hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1535b486ba4435dd7a498a04855bbcb01acdf90b | 1,260 | cpp | C++ | Generator/Generator/Util.cpp | Snowapril/Procedural-Terrain-Estimator | b0eb13fd04e5f4c7d2ea73ca5fa9bd8a83cf2825 | [
"MIT"
] | 36 | 2018-08-14T13:40:19.000Z | 2022-03-22T05:32:24.000Z | Generator/Generator/Util.cpp | Snowapril/Procedural-Terrain-Estimator | b0eb13fd04e5f4c7d2ea73ca5fa9bd8a83cf2825 | [
"MIT"
] | 3 | 2018-09-14T14:14:08.000Z | 2021-03-14T16:05:31.000Z | Generator/Generator/Util.cpp | Snowapril/Procedural-Terrain-Estimator | b0eb13fd04e5f4c7d2ea73ca5fa9bd8a83cf2825 | [
"MIT"
] | 9 | 2018-08-26T04:14:17.000Z | 2020-12-24T18:05:20.000Z | #include "Util.hpp"
namespace Util
{
Rect::Rect()
{
}
Rect::Rect(glm::vec2 lt, glm::vec2 rb)
: leftTop(lt), rightBottom(rb)
{
}
Rect::Rect(float left, float top, float right, float bottom)
: leftTop(left, top), rightBottom(right, bottom)
{
}
Rect::Rect(const Rect & other)
{
this->leftTop = other.leftTop;
this->rightBottom = other.rightBottom;
}
Rect & Rect::operator=(const Rect & other)
{
if (&other == this)
return *this;
this->leftTop = other.leftTop;
this->rightBottom = other.rightBottom;
return *this;
}
Rect::Rect(Rect && other)
{
this->leftTop = std::move(other.leftTop);
this->rightBottom = std::move(other.rightBottom);
}
Rect & Rect::operator=(Rect && other)
{
if (&other == this)
return *this;
this->leftTop = std::move(other.leftTop);
this->rightBottom = std::move(other.rightBottom);
return *this;
}
glm::vec2 Rect::getScale(void) const
{
return rightBottom - leftTop;
}
glm::vec2 Rect::getLeftTop(void) const
{
return leftTop;
}
glm::vec2 Rect::getRightBottom(void) const
{
return rightBottom;
}
void Rect::setLeftTop(glm::vec2 newValue)
{
leftTop = newValue;
}
void Rect::setRightBottom(glm::vec2 newValue)
{
rightBottom = newValue;
}
} | 16.363636 | 61 | 0.646825 | Snowapril |
153b4d03588d0f7d218505b06ee88747a530261b | 1,613 | hpp | C++ | src/algorithm/algorithmBase.hpp | TheSonOfDeimos/network-routing-optimization | 7030b5cf333f19ab68952b6841463f4cfd664895 | [
"MIT"
] | null | null | null | src/algorithm/algorithmBase.hpp | TheSonOfDeimos/network-routing-optimization | 7030b5cf333f19ab68952b6841463f4cfd664895 | [
"MIT"
] | null | null | null | src/algorithm/algorithmBase.hpp | TheSonOfDeimos/network-routing-optimization | 7030b5cf333f19ab68952b6841463f4cfd664895 | [
"MIT"
] | null | null | null | #ifndef ALGORITHM_BASE_HPP
#define ALGORITHM_BASE_HPP
#include <unordered_map>
#include <vector>
#include "types.hpp"
struct Cell
{
// Relative values
double ping; // ms
double packetLoss; // amount of lost packets in % per 100 packets
double speed; // Mbit/sec
// Absolute values
double bandwidth; // Mbit/sec
dataVolume_t bufferVolume; // Mb
double cost = -1;
std::vector<hostAddress_t> path = {};
};
// On Input
using ConnectMatrix_t = std::unordered_map<hostAddress_t, std::unordered_map<hostAddress_t, Cell>>;
struct Route
{
double cost;
std::vector<hostAddress_t> path;
hostAddress_t source;
hostAddress_t destination;
};
// On Output
using RouteTable_t = std::vector<Route>;
class AlgorithmBase
{
public:
virtual ~AlgorithmBase() = default;
RouteTable_t buildRoutes(const ConnectMatrix_t& matrix);
protected:
ConnectMatrix_t buildNext(const ConnectMatrix_t& startMatrix, const ConnectMatrix_t& prevMatrix);
virtual status_t adoptStartMatrix(ConnectMatrix_t& startMatrix) = 0;
virtual status_t isPathPossible(hostAddress_t startLineAddr, const std::pair<hostAddress_t, Cell>& startElement, hostAddress_t prevLineAddr, const std::pair<hostAddress_t, Cell>& prevElement) = 0;
virtual status_t appentToNextMatrix(hostAddress_t startLineAddr, const std::pair<hostAddress_t, Cell>& startElement, hostAddress_t prevLineAddr, const std::pair<hostAddress_t, Cell>& prevElement, ConnectMatrix_t& nextMatrix) = 0;
virtual RouteTable_t mergeMatrixToRouteTable(const std::vector<ConnectMatrix_t>& matrixVec) = 0;
};
#endif
| 29.87037 | 233 | 0.748915 | TheSonOfDeimos |
153e6da54c1f05c705466f21ca50f1461c872217 | 3,066 | cpp | C++ | reader/android-reader/jni/NativeFormats/fbreader/src/formats/PluginCollection.cpp | liufeiit/itmarry | 9d48eac9ebf02d857658b3c9f70dab2321a3362b | [
"MIT"
] | 1 | 2015-01-22T19:51:03.000Z | 2015-01-22T19:51:03.000Z | reader/android-reader/jni/NativeFormats/fbreader/src/formats/PluginCollection.cpp | liufeiit/itmarry | 9d48eac9ebf02d857658b3c9f70dab2321a3362b | [
"MIT"
] | null | null | null | reader/android-reader/jni/NativeFormats/fbreader/src/formats/PluginCollection.cpp | liufeiit/itmarry | 9d48eac9ebf02d857658b3c9f70dab2321a3362b | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2004-2013 Geometer Plus <contact@geometerplus.com>
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <AndroidUtil.h>
#include <JniEnvelope.h>
#include <ZLibrary.h>
#include <ZLFile.h>
#include "FormatPlugin.h"
#include "../library/Book.h"
#include "fb2/FB2Plugin.h"
#include "html/HtmlPlugin.h"
#include "txt/TxtPlugin.h"
//#include "pdb/PdbPlugin.h"
//#include "tcr/TcrPlugin.h"
#include "oeb/OEBPlugin.h"
//#include "chm/CHMPlugin.h"
#include "rtf/RtfPlugin.h"
//#include "openreader/OpenReaderPlugin.h"
#include "doc/DocPlugin.h"
PluginCollection *PluginCollection::ourInstance = 0;
PluginCollection &PluginCollection::Instance() {
if (ourInstance == 0) {
ourInstance = new PluginCollection();
ourInstance->myPlugins.push_back(new FB2Plugin());
ourInstance->myPlugins.push_back(new HtmlPlugin());
ourInstance->myPlugins.push_back(new TxtPlugin());
// ourInstance->myPlugins.push_back(new PluckerPlugin());
// ourInstance->myPlugins.push_back(new PalmDocPlugin());
// ourInstance->myPlugins.push_back(new MobipocketPlugin());
// ourInstance->myPlugins.push_back(new EReaderPlugin());
// ourInstance->myPlugins.push_back(new ZTXTPlugin());
// ourInstance->myPlugins.push_back(new TcrPlugin());
// ourInstance->myPlugins.push_back(new CHMPlugin());
ourInstance->myPlugins.push_back(new OEBPlugin());
ourInstance->myPlugins.push_back(new RtfPlugin());
ourInstance->myPlugins.push_back(new DocPlugin());
// ourInstance->myPlugins.push_back(new OpenReaderPlugin());
}
return *ourInstance;
}
void PluginCollection::deleteInstance() {
if (ourInstance != 0) {
delete ourInstance;
ourInstance = 0;
}
}
PluginCollection::PluginCollection() {
JNIEnv *env = AndroidUtil::getEnv();
jobject instance = AndroidUtil::StaticMethod_PluginCollection_Instance->call();
myJavaInstance = env->NewGlobalRef(instance);
env->DeleteLocalRef(instance);
}
PluginCollection::~PluginCollection() {
JNIEnv *env = AndroidUtil::getEnv();
env->DeleteGlobalRef(myJavaInstance);
}
shared_ptr<FormatPlugin> PluginCollection::pluginByType(const std::string &fileType) const {
for (std::vector<shared_ptr<FormatPlugin> >::const_iterator it = myPlugins.begin(); it != myPlugins.end(); ++it) {
if (fileType == (*it)->supportedFileType()) {
return *it;
}
}
return 0;
}
bool PluginCollection::isLanguageAutoDetectEnabled() {
return true;
}
| 32.273684 | 115 | 0.742988 | liufeiit |
15408cbedb0f32036560f6b4a2ef5e0bb19323ab | 8,233 | cpp | C++ | generated/src/DatabaseAsyncClient.cpp | automyinc/vnx-examples | 492423bb8c8447f641e5691f45575056cab396df | [
"MIT"
] | null | null | null | generated/src/DatabaseAsyncClient.cpp | automyinc/vnx-examples | 492423bb8c8447f641e5691f45575056cab396df | [
"MIT"
] | null | null | null | generated/src/DatabaseAsyncClient.cpp | automyinc/vnx-examples | 492423bb8c8447f641e5691f45575056cab396df | [
"MIT"
] | null | null | null |
// AUTO GENERATED by vnxcppcodegen
#include <example/package.hxx>
#include <example/DatabaseAsyncClient.hxx>
#include <vnx/Input.h>
#include <vnx/Output.h>
namespace example {
DatabaseAsyncClient::DatabaseAsyncClient(const std::string& service_name)
: AsyncClient::AsyncClient(vnx::Hash64(service_name))
{
}
DatabaseAsyncClient::DatabaseAsyncClient(vnx::Hash64 service_addr)
: AsyncClient::AsyncClient(service_addr)
{
}
uint64_t DatabaseAsyncClient::add_user(const ::std::string& name, const std::function<void()>& _callback) {
std::shared_ptr<vnx::Binary> _argument_data = vnx::Binary::create();
vnx::BinaryOutputStream _stream_out(_argument_data.get());
vnx::TypeOutput _out(&_stream_out);
const vnx::TypeCode* _type_code = vnx::get_type_code(vnx::Hash64(0x2741180fbb8f23a1ull));
{
vnx::write(_out, name, _type_code, _type_code->fields[0].code.data());
}
_out.flush();
_argument_data->type_code = _type_code;
const uint64_t _request_id = vnx_request(_argument_data);
vnx_queue_add_user[_request_id] = _callback;
vnx_num_pending++;
return _request_id;
}
uint64_t DatabaseAsyncClient::add_user_balance(const ::std::string& name, const ::vnx::float64_t& value, const std::function<void()>& _callback) {
std::shared_ptr<vnx::Binary> _argument_data = vnx::Binary::create();
vnx::BinaryOutputStream _stream_out(_argument_data.get());
vnx::TypeOutput _out(&_stream_out);
const vnx::TypeCode* _type_code = vnx::get_type_code(vnx::Hash64(0x3d6e042d45e04326ull));
{
char* const _buf = _out.write(8);
vnx::write_value(_buf + 0, value);
vnx::write(_out, name, _type_code, _type_code->fields[0].code.data());
}
_out.flush();
_argument_data->type_code = _type_code;
const uint64_t _request_id = vnx_request(_argument_data);
vnx_queue_add_user_balance[_request_id] = _callback;
vnx_num_pending++;
return _request_id;
}
uint64_t DatabaseAsyncClient::get_user(const ::std::string& name, const std::function<void(::std::shared_ptr<const ::example::User>)>& _callback) {
std::shared_ptr<vnx::Binary> _argument_data = vnx::Binary::create();
vnx::BinaryOutputStream _stream_out(_argument_data.get());
vnx::TypeOutput _out(&_stream_out);
const vnx::TypeCode* _type_code = vnx::get_type_code(vnx::Hash64(0x3e6f70937269a136ull));
{
vnx::write(_out, name, _type_code, _type_code->fields[0].code.data());
}
_out.flush();
_argument_data->type_code = _type_code;
const uint64_t _request_id = vnx_request(_argument_data);
vnx_queue_get_user[_request_id] = _callback;
vnx_num_pending++;
return _request_id;
}
uint64_t DatabaseAsyncClient::get_user_balance(const ::std::string& name, const std::function<void(::vnx::float64_t)>& _callback) {
std::shared_ptr<vnx::Binary> _argument_data = vnx::Binary::create();
vnx::BinaryOutputStream _stream_out(_argument_data.get());
vnx::TypeOutput _out(&_stream_out);
const vnx::TypeCode* _type_code = vnx::get_type_code(vnx::Hash64(0xe625a8cfd51e9a9eull));
{
vnx::write(_out, name, _type_code, _type_code->fields[0].code.data());
}
_out.flush();
_argument_data->type_code = _type_code;
const uint64_t _request_id = vnx_request(_argument_data);
vnx_queue_get_user_balance[_request_id] = _callback;
vnx_num_pending++;
return _request_id;
}
uint64_t DatabaseAsyncClient::handle(const ::std::shared_ptr<const ::example::Transaction>& sample, const std::function<void()>& _callback) {
std::shared_ptr<vnx::Binary> _argument_data = vnx::Binary::create();
vnx::BinaryOutputStream _stream_out(_argument_data.get());
vnx::TypeOutput _out(&_stream_out);
const vnx::TypeCode* _type_code = vnx::get_type_code(vnx::Hash64(0xa9a81442632b020eull));
{
vnx::write(_out, sample, _type_code, _type_code->fields[0].code.data());
}
_out.flush();
_argument_data->type_code = _type_code;
const uint64_t _request_id = vnx_request(_argument_data);
vnx_queue_handle_example_Transaction[_request_id] = _callback;
vnx_num_pending++;
return _request_id;
}
uint64_t DatabaseAsyncClient::subtract_user_balance(const ::std::string& name, const ::vnx::float64_t& value, const std::function<void()>& _callback) {
std::shared_ptr<vnx::Binary> _argument_data = vnx::Binary::create();
vnx::BinaryOutputStream _stream_out(_argument_data.get());
vnx::TypeOutput _out(&_stream_out);
const vnx::TypeCode* _type_code = vnx::get_type_code(vnx::Hash64(0xe58127da78610817ull));
{
char* const _buf = _out.write(8);
vnx::write_value(_buf + 0, value);
vnx::write(_out, name, _type_code, _type_code->fields[0].code.data());
}
_out.flush();
_argument_data->type_code = _type_code;
const uint64_t _request_id = vnx_request(_argument_data);
vnx_queue_subtract_user_balance[_request_id] = _callback;
vnx_num_pending++;
return _request_id;
}
void DatabaseAsyncClient::vnx_purge_request(uint64_t _request_id) {
vnx_num_pending -= vnx_queue_add_user.erase(_request_id);
vnx_num_pending -= vnx_queue_add_user_balance.erase(_request_id);
vnx_num_pending -= vnx_queue_get_user.erase(_request_id);
vnx_num_pending -= vnx_queue_get_user_balance.erase(_request_id);
vnx_num_pending -= vnx_queue_handle_example_Transaction.erase(_request_id);
vnx_num_pending -= vnx_queue_subtract_user_balance.erase(_request_id);
}
void DatabaseAsyncClient::vnx_callback_switch(uint64_t _request_id, std::shared_ptr<const vnx::Binary> _data) {
vnx::BinaryInputStream _stream_in(_data.get());
vnx::TypeInput _in(&_stream_in);
const vnx::TypeCode* _return_type = _data->type_code;
if(_return_type->type_hash == vnx::Hash64(0x73df74b7d405f6b0ull)) {
auto _iter = vnx_queue_add_user.find(_request_id);
if(_iter != vnx_queue_add_user.end()) {
if(_iter->second) {
_iter->second();
}
vnx_queue_add_user.erase(_iter);
vnx_num_pending--;
}
}
else if(_return_type->type_hash == vnx::Hash64(0xce8eb9027f2289c3ull)) {
auto _iter = vnx_queue_add_user_balance.find(_request_id);
if(_iter != vnx_queue_add_user_balance.end()) {
if(_iter->second) {
_iter->second();
}
vnx_queue_add_user_balance.erase(_iter);
vnx_num_pending--;
}
}
else if(_return_type->type_hash == vnx::Hash64(0x36d19b92367474d9ull)) {
::std::shared_ptr<const ::example::User> _ret_0;
{
const char* const _buf = _in.read(_return_type->total_field_size);
if(_return_type->is_matched) {
}
for(const vnx::TypeField* _field : _return_type->ext_fields) {
switch(_field->native_index) {
case 0: vnx::read(_in, _ret_0, _return_type, _field->code.data()); break;
default: vnx::skip(_in, _return_type, _field->code.data());
}
}
}
auto _iter = vnx_queue_get_user.find(_request_id);
if(_iter != vnx_queue_get_user.end()) {
if(_iter->second) {
_iter->second(_ret_0);
}
vnx_queue_get_user.erase(_iter);
vnx_num_pending--;
}
}
else if(_return_type->type_hash == vnx::Hash64(0x50b361140a464af7ull)) {
::vnx::float64_t _ret_0 = 0;
{
const char* const _buf = _in.read(_return_type->total_field_size);
if(_return_type->is_matched) {
{
const vnx::TypeField* const _field = _return_type->field_map[0];
if(_field) {
vnx::read_value(_buf + _field->offset, _ret_0, _field->code.data());
}
}
}
for(const vnx::TypeField* _field : _return_type->ext_fields) {
switch(_field->native_index) {
default: vnx::skip(_in, _return_type, _field->code.data());
}
}
}
auto _iter = vnx_queue_get_user_balance.find(_request_id);
if(_iter != vnx_queue_get_user_balance.end()) {
if(_iter->second) {
_iter->second(_ret_0);
}
vnx_queue_get_user_balance.erase(_iter);
vnx_num_pending--;
}
}
else if(_return_type->type_hash == vnx::Hash64(0xa6ede797ad62d986ull)) {
auto _iter = vnx_queue_handle_example_Transaction.find(_request_id);
if(_iter != vnx_queue_handle_example_Transaction.end()) {
if(_iter->second) {
_iter->second();
}
vnx_queue_handle_example_Transaction.erase(_iter);
vnx_num_pending--;
}
}
else if(_return_type->type_hash == vnx::Hash64(0x602e1ee9204ea132ull)) {
auto _iter = vnx_queue_subtract_user_balance.find(_request_id);
if(_iter != vnx_queue_subtract_user_balance.end()) {
if(_iter->second) {
_iter->second();
}
vnx_queue_subtract_user_balance.erase(_iter);
vnx_num_pending--;
}
}
}
} // namespace example
| 35.951965 | 151 | 0.742014 | automyinc |
1541882e8f26b9db462bbbfd8af139cdfb2b074a | 2,618 | cpp | C++ | graph-source-code/41-E/189438.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/41-E/189438.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/41-E/189438.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include<iostream>
#include<sstream>
#include<string>
#include<cstdlib>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cctype>
#include<set>
#include<bitset>
#include<algorithm>
#include<list>
#include<utility>
#include<functional>
#include <deque>
#include <numeric>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <ctime>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
using namespace std;
#define deb(a) cout<<" -> "<<#a<<" "<<a<<endl;
#define oo (1<<30)
#define PI 3.141592653589793
#define pi 2*acos(0)
#define ERR 1e-5
#define PRE 1e-8
#define popcount(a) (__builtin_popcount(a))
#define SZ(a) ((int)a.size())
#define PB push_back
#define LL long long
#define ISS istringstream
#define OSS ostringstream
#define SS stringstream
#define VS vector<string>
#define VI vector<int>
#define VD vector<double>
#define VLL vector<long long>
#define SII set<int>::iterator
#define SI set<int>
#define mem(a,b) memset(a,b,sizeof(a))
#define memc(a,b) memcpy(a,b,sizeof(b))
#define fi(i,a,b) for(i=a;i<b;i++)
#define fd(i,a,b) for(i=a;i>b;i--)
#define fii(a,b) for(i=a;i<b;i++)
#define fdi(a,b) for(i=a;i>b;i--)
#define fij(a,b) for(j=a;j<b;j++)
#define fdj(a,b) for(j=a;j>b;j--)
#define fik(a,b) for(k=a;k<b;k++)
#define fdk(a,b) for(k=a;k>b;k--)
#define fil(a,b) for(l=a;l<b;l++)
#define fdl(a,b) for(l=a;l>b;l--)
#define ri(i,a) for(i=0;i<a;i++)
#define rd(i,a) for(i=a;i>-1;i--)
#define rii(a) for(i=0;i<a;i++)
#define rdi(a) for(i=a;i>-1;i--)
#define rij(a) for(j=0;j<a;j++)
#define rdj(a) for(j=a;j>-1;j--)
#define rik(a) for(k=0;k<a;k++)
#define rdk(a) for(k=a;k>-1;k--)
#define ril(a) for(l=0;l<a;l++)
#define rdl(a) for(l=a;i>-1;l--)
#define EQ(a,b) (fabs(a-b)<ERR)
#define all(a) (a).begin(),(a).end()
#define CROSS(a,b,c,d) ((b.x-a.x)*(d.y-c.y)-(d.x-c.x)*(b.y-a.y))
#define sqr(a) ((a)*(a))
#define p2(a) (1LL<<a)
int main()
{
//freopen("in.in","r",stdin);
//freopen("ou.in","w",stdout);
int i,j,n;
while(cin>>n)
{
if(n&1)printf("%d\n",(n/2)*(n+1)/2);
else printf("%d\n",(n*n)/4);
for(i=1;i<=n/2;i++)
for(j=n/2+1;j<=n;j++) printf("%d %d\n",i,j);
}
return 0;
}
| 25.417476 | 66 | 0.52903 | AmrARaouf |
1543c74cb3eacc8e390d23bac942a89f68c54a53 | 2,118 | cpp | C++ | base-3.15.5-pre1/src/ca/legacy/pcas/generic/casAsyncPVAttachIOI.cpp | osteffen/epics | 20556240f157c6b812d66e900d119e0db3bce391 | [
"OML"
] | null | null | null | base-3.15.5-pre1/src/ca/legacy/pcas/generic/casAsyncPVAttachIOI.cpp | osteffen/epics | 20556240f157c6b812d66e900d119e0db3bce391 | [
"OML"
] | null | null | null | base-3.15.5-pre1/src/ca/legacy/pcas/generic/casAsyncPVAttachIOI.cpp | osteffen/epics | 20556240f157c6b812d66e900d119e0db3bce391 | [
"OML"
] | null | null | null |
/*************************************************************************\
* Copyright (c) 2002 The University of Chicago, as Operator of Argonne
* National Laboratory.
* Copyright (c) 2002 The Regents of the University of California, as
* Operator of Los Alamos National Laboratory.
* EPICS BASE is distributed subject to a Software License Agreement found
* in file LICENSE that is included with this distribution.
\*************************************************************************/
/*
* Author Jeffrey O. Hill
* johill@lanl.gov
* 505 665 1831
*/
#include "errlog.h"
#define epicsExportSharedSymbols
#include "casAsyncPVAttachIOI.h"
casAsyncPVAttachIOI::casAsyncPVAttachIOI (
casAsyncPVAttachIO & intf, const casCtx & ctx ) :
casAsyncIOI ( ctx ), msg ( *ctx.getMsg() ),
asyncPVAttachIO ( intf ), retVal ( S_cas_badParameter )
{
ctx.getServer()->incrementIOInProgCount ();
ctx.getClient()->installAsynchIO ( *this );
}
caStatus casAsyncPVAttachIOI::postIOCompletion ( const pvAttachReturn & retValIn )
{
this->retVal = retValIn;
return this->insertEventQueue ();
}
caStatus casAsyncPVAttachIOI::cbFuncAsyncIO (
epicsGuard < casClientMutex > & guard )
{
caStatus status;
// uninstall here in case the channel is deleted
// further down the call stack
this->client.uninstallAsynchIO ( *this );
this->client.getCAS().decrementIOInProgCount ();
if ( this->msg.m_cmmd == CA_PROTO_CREATE_CHAN ) {
casCtx tmpCtx;
tmpCtx.setMsg ( this->msg, 0 );
tmpCtx.setServer ( & this->client.getCAS() );
tmpCtx.setClient ( & this->client );
status = this->client.createChanResponse ( guard,
tmpCtx, this->retVal );
}
else {
errPrintf ( S_cas_invalidAsynchIO, __FILE__, __LINE__,
" - client request type = %u", this->msg.m_cmmd );
status = S_cas_invalidAsynchIO;
}
if ( status == S_cas_sendBlocked ) {
this->client.getCAS().incrementIOInProgCount ();
this->client.installAsynchIO ( *this );
}
return status;
}
| 31.147059 | 82 | 0.617564 | osteffen |
1543f151890790f43a3431f95a01f790cc536799 | 4,869 | hpp | C++ | include/opengm/minimizer/to_quadratic_minimizer.hpp | DerThorsten/opengm3 | 23af324a0fde1357eb9745d69798686f0476e1f1 | [
"MIT"
] | null | null | null | include/opengm/minimizer/to_quadratic_minimizer.hpp | DerThorsten/opengm3 | 23af324a0fde1357eb9745d69798686f0476e1f1 | [
"MIT"
] | null | null | null | include/opengm/minimizer/to_quadratic_minimizer.hpp | DerThorsten/opengm3 | 23af324a0fde1357eb9745d69798686f0476e1f1 | [
"MIT"
] | null | null | null | #pragma once
#include <queue>
#include <algorithm>
#include "opengm/minimizer/minimizer_base.hpp"
#include "opengm/minimizer/bp.hpp"
#include "opengm/minimizer/utils/label_fuser.hpp"
#include "opengm/factors_of_variables.hpp"
namespace opengm{
template<class GM>
class SelfFusion;
namespace detail_self_fusion{
template<class GM>
class ToQuadraticMinimizerVisitor: public MinimizerCallbackBase<GM>{
public:
using gm_type = GM;
using minimizer_base_type = MinimizerBase<gm_type>;
using self_fusion_type = SelfFusion<gm_type>;
using base_type = MinimizerCallbackBase<gm_type>;
ToQuadraticMinimizerVisitor(self_fusion_type & self_fusion, base_type * outer_visitor)
: m_self_fusion(self_fusion),
m_outer_callback(outer_visitor)
{
}
void begin(minimizer_base_type * minimizer){
if(m_outer_callback != nullptr){
return m_outer_callback->begin(&m_self_fusion);
}
}
void end(minimizer_base_type * minimizer){
if(m_outer_callback != nullptr){
return m_outer_callback->end(&m_self_fusion);
}
}
bool operator()(minimizer_base_type * minimizer){
if(m_outer_callback != nullptr){
return m_outer_callback->operator()(&m_self_fusion);
}
return true;
}
private:
self_fusion_type & m_self_fusion;
base_type * m_outer_callback;
};
}
template<class GM>
class SelfFusion : public MinimizerCrtpBase<GM, SelfFusion<GM> >{
public:
friend class detail_self_fusion::ToQuadraticMinimizerVisitor<GM>;
using gm_type = GM;
using base_type = MinimizerBase<GM>;
using value_type = typename GM::value_type;
using label_type = typename GM::label_type;
using labels_vector_type = typename base_type::labels_vector_type;
using minimizer_callback_base_ptr_type = typename base_type::minimizer_callback_base_ptr_type;
using base_type::minimize;
using quadratic_gm_type = typename ToQuadratic<gm_type>::quadratic_gm_type;
using quadratic_gm_minimizer_factory_base_type = MinimizerFactoryBase<quadratic_gm_type>;
using quadratic_gm_minimizer_factory_ptr_type = std::shared_ptr<quadratic_gm_minimizer_factory_base_type>;
private:
using inner_callback_type = detail_self_fusion::ToQuadraticMinimizerVisitor<gm_type>;
public:
struct settings_type : public SolverSettingsBase{
quadratic_gm_minimizer_factory_ptr_type minimizer_factory;
};
SelfFusion(const GM & gm, const settings_type & settings = settings_type())
: m_gm(gm),
m_settings(settings),
m_energy(),
m_labels(gm.num_variables(),0),
m_outer_callback(nullptr),
m_starting_point_passed(false),
{
if(!m_settings.minimizer_factory)
{
m_settings.minimizer_factory = std::make_shared<default_minimizer_factory_type>();
}
}
std::string name() const override{
return "SelfFusion";
}
const gm_type & gm() const override{
return m_gm;
}
const labels_vector_type & best_labels()override{
return m_labels;
}
const labels_vector_type & current_labels() override{
return m_labels;
}
value_type best_energy() override{
return m_energy;
}
value_type current_energy() override {
return m_energy;
}
bool can_start_from_starting_point() override{
return true;
}
void set_starting_point(const label_type * labels)override{
m_starting_point_passed = true;
m_labels.assign(labels, labels + m_gm.num_variables());
}
void minimize(minimizer_callback_base_ptr_type minimizer_callback_base_ptr)override{
// evaluate energy st. callbacks report correct energy
m_energy = m_gm.evaluate(m_labels);
auto callback = callback_wrapper(this, minimizer_callback_base_ptr);
auto quadratic_gm to_quadratic(m_gm);
auto quadratic_gm_minimizer = m_settings.minimizer_factory->create(quadratic_gm);
if(m_starting_point_passed && minimizer->can_start_from_starting_point())
{
// todo, we need to create the labels for the quadratic gm
//quadratic_gm_minimizer->set_starting_point(m_labels);
}
if(minimizer_callback_base_ptr != nullptr)
{
inner_callback_type inner_callback(*this, minimizer_callback_base_ptr);
quadratic_gm_minimizer->minimize(&inner_callback);
}
else
{
quadratic_gm_minimizer->minimize();
}
}
private:
const GM & m_gm;
settings_type m_settings;
value_type m_energy;
std::vector<label_type> m_labels;
bool m_starting_point_passed;
};
} | 27.201117 | 110 | 0.678168 | DerThorsten |
15461aed26d76d9755aa4d227a623daeb78f8290 | 1,895 | cc | C++ | src/player_mc.cc | tczajka/flippo-veoveo | 6ebd612c4b85cb910264169164f1cdb1a2252a3d | [
"MIT"
] | 5 | 2019-01-19T14:18:20.000Z | 2022-01-23T16:58:45.000Z | src/player_mc.cc | tczajka/flippo-veoveo | 6ebd612c4b85cb910264169164f1cdb1a2252a3d | [
"MIT"
] | null | null | null | src/player_mc.cc | tczajka/flippo-veoveo | 6ebd612c4b85cb910264169164f1cdb1a2252a3d | [
"MIT"
] | null | null | null | #include "player_mc.h"
#include "logging.h"
#include <algorithm>
Move PlayerMc::choose_move(const Position &position,
const PlaySettings &settings) {
const int rounds_left = (num_squares - position.move_number() + 1) / 2;
const Timestamp end_time = settings.start_time + settings.time_left / rounds_left;
std::vector<MoveOption> move_options;
{
Bitboard valid_moves = position.valid_moves();
while (valid_moves) {
const Move move = first_square(valid_moves);
MoveOption move_option;
move_option.move = move;
move_options.push_back(move_option);
valid_moves = remove_first_square(valid_moves);
}
}
std::int64_t num_simulations = 0;
std::int64_t num_rounds = 0;
while (num_rounds == 0 || current_time() < end_time) {
for (MoveOption &move_option : move_options) {
Position pos2;
position.make_move(move_option.move, pos2);
move_option.total_score -= simulate(pos2);
++num_simulations;
}
++num_rounds;
}
std::sort(move_options.begin(), move_options.end(),
[](const MoveOption &a, const MoveOption &b) {
return a.total_score > b.total_score;
});
log_info("Simulations %ld\n", num_simulations);
log_info("Best moves:");
for (std::size_t i=0; i < move_options.size() && i < 3; ++i) {
log_info(" %s (%.3f)", move_to_string(move_options[i].move).c_str(),
static_cast<double>(move_options[i].total_score) / num_rounds);
}
log_info("\n");
return move_options.begin()->move;
}
int PlayerMc::simulate(const Position &position) {
Position pos2 = position;
int rounds = 0;
while (!pos2.finished()) {
const Move move = random_generator.get_square(pos2.valid_moves());
pos2.make_move(move, pos2);
++rounds;
}
const int score = pos2.final_score();
return (rounds & 1) ? -score : score;
}
| 30.564516 | 84 | 0.653298 | tczajka |
154632a790b78b66114a87c2d618220eabca37d4 | 2,019 | cc | C++ | tools/to_tuple_generator/to_tuple_generator.cc | cflaviu/cista | d7fab2dcfdf1b7665e9f8b4d6eeefa4a9f89046b | [
"MIT"
] | 843 | 2019-01-03T11:33:00.000Z | 2022-03-27T08:09:46.000Z | tools/to_tuple_generator/to_tuple_generator.cc | cflaviu/cista | d7fab2dcfdf1b7665e9f8b4d6eeefa4a9f89046b | [
"MIT"
] | 58 | 2019-01-03T20:32:02.000Z | 2022-01-31T17:25:42.000Z | tools/to_tuple_generator/to_tuple_generator.cc | cflaviu/cista | d7fab2dcfdf1b7665e9f8b4d6eeefa4a9f89046b | [
"MIT"
] | 63 | 2019-01-04T03:00:04.000Z | 2022-03-30T20:01:22.000Z | #include <iostream>
#include <sstream>
#include <string>
std::string var_list(unsigned num, bool address_of) {
std::stringstream ss;
for (int i = 0; i < num; ++i) {
if (address_of) {
ss << "&";
}
ss << "p" << (i + 1);
if (i != num - 1) {
ss << ", ";
}
}
return ss.str();
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "usage: " << argv[0] << " [max members]\n";
return 1;
}
auto const max_members = std::stoi(argv[1]);
std::cout << R"(
#pragma once
#include <tuple>
#include "cista/reflection/arity.h"
namespace cista {
template <typename T>
constexpr auto to_tuple_works_v =
std::is_aggregate_v<T> &&
#if !defined(_MSC_VER) || defined(NDEBUG)
std::is_standard_layout_v < T>&&
#endif
!std::is_polymorphic_v<T>;
template <typename T>
inline auto to_tuple(T& t) {
constexpr auto const a = arity<T>();
static_assert(a <= )"
<< max_members << R"(, "Max. supported members: )" << max_members
<< R"(");)"
<< R"(
if constexpr (a == 0) {
return std::tie();
})";
for (auto i = 1U; i <= max_members; ++i) {
std::cout << R"( else if constexpr (a == )" << i << R"() {
auto& [)" << var_list(i, false)
<< R"(] = t;
return std::tie()"
<< var_list(i, false) << R"();
})";
}
std::cout << "\n}\n";
std::cout << R"(
template <typename T>
inline auto to_ptr_tuple(T& t) {
constexpr auto const a = arity<T>();
static_assert(a <= )"
<< max_members << R"(, "Max. supported members: )" << max_members
<< R"(");)"
<< R"(
if constexpr (a == 0) {
return std::make_tuple();
})";
for (auto i = 1U; i <= max_members; ++i) {
std::cout << R"( else if constexpr (a == )" << i << R"() {
auto& [)" << var_list(i, false)
<< R"(] = t;
return std::make_tuple()"
<< var_list(i, true) << R"();
})";
}
std::cout << "\n}";
std::cout << R"(
} // namespace cista
)";
} | 22.685393 | 77 | 0.500248 | cflaviu |
15493dd3688367e4c6172ace7644878b6bf49c85 | 362 | cpp | C++ | Email/Mapi/MapiGPF.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | 67 | 2018-03-02T10:50:02.000Z | 2022-03-23T18:20:29.000Z | Email/Mapi/MapiGPF.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | null | null | null | Email/Mapi/MapiGPF.cpp | BartoszMilewski/CodeCoop | 7d29f53ccf65b0d29ea7d6781a74507b52c08d0d | [
"MIT"
] | 9 | 2018-03-01T16:38:28.000Z | 2021-03-02T16:17:09.000Z | // ---------------------------
// (c) Reliable Software, 2005
// ---------------------------
#include "precompiled.h"
#include "MapiGPF.h"
#include "OutputSink.h"
char const Err [] = "Unexpected error in MAPI code during a call to ";
void Mapi::HandleGPF (std::string const & where)
{
std::string msg = Err + where + ".";
TheOutput.Display (msg.c_str ());
}
| 24.133333 | 70 | 0.560773 | BartoszMilewski |
15496d77cbaff3b88198a2bd763cc54cdfe91d50 | 5,292 | cpp | C++ | coast/modules/WorkerPoolManager/WorkerPoolManagerModulePoolManager.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/WorkerPoolManager/WorkerPoolManagerModulePoolManager.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/WorkerPoolManager/WorkerPoolManagerModulePoolManager.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "WorkerPoolManagerModulePoolManager.h"
#include "SystemLog.h"
#include "Tracer.h"
//---- WorkerPoolManagerModuleWorker -----------------------------------------------
WorkerPoolManagerModuleWorker::WorkerPoolManagerModuleWorker(const char *name)
: WorkerThread(name)
{
StartTrace(WorkerPoolManagerModuleWorker.WorkerPoolManagerModuleWorker);
}
WorkerPoolManagerModuleWorker::~WorkerPoolManagerModuleWorker()
{
StartTrace(WorkerPoolManagerModuleWorker.~WorkerPoolManagerModuleWorker);
}
// one time initialization
void WorkerPoolManagerModuleWorker::DoInit(ROAnything workerInit)
{
StartTrace(WorkerPoolManagerModuleWorker.DoInit);
fWorkerInitCfg = workerInit.DeepClone();
}
void WorkerPoolManagerModuleWorker::DoProcessWorkload()
{
StartTrace(WorkerPoolManagerModuleWorker.DoProcessWorkload);
if ( CheckRunningState( eWorking ) ) {
Anything *pMessages;
Mutex *pMx;
Mutex::ConditionType *pCond;
pMx = (Mutex *)fWork["mutex"].AsIFAObject();
pCond = (Mutex::ConditionType *)fWork["condition"].AsIFAObject();
pMessages = (Anything *)fWork["messages"].AsIFAObject(0L);
Assert(pMessages != NULL);
Assert(pMx != NULL);
Assert(pCond != NULL);
TraceAny(*pMessages, "Arguments passed to me");
TraceAny(fWorkerInitCfg, "My initial config:");
{
// here we should do something fancier then copying input to output :-)
LockUnlockEntry me(*pMx);
Anything *pResult = (Anything *)fWork["results"].AsIFAObject(0L);
(*pResult)["Got"] = (*pMessages).AsString();
(*pResult)["WorkerInitialConfig"] = fWorkerInitCfg;
}
// signal that we finished working
pCond->Signal();
}
}
// passing of the work
void WorkerPoolManagerModuleWorker::DoWorkingHook(ROAnything workerConfig)
{
StartTrace(WorkerPoolManagerModuleWorker.DoWorkingHook);
// It is essential to copy the worker's config into a instance variable.
// And it is essential to DeepClone that data for thread safety reasons too.
fWork = workerConfig.DeepClone();
}
void WorkerPoolManagerModuleWorker::DoTerminationRequestHook(ROAnything)
{
StartTrace(WorkerPoolManagerModuleWorker.DoTerminationRequestHook);
}
void WorkerPoolManagerModuleWorker::DoTerminatedHook()
{
StartTrace(WorkerPoolManagerModuleWorker.DoTerminatedHook);
}
//---- WorkerPoolManagerModulePoolManager ------------------------------------------------
WorkerPoolManagerModulePoolManager::WorkerPoolManagerModulePoolManager(String name)
: WorkerPoolManager(name)
, fRequests(0)
{
StartTrace(WorkerPoolManagerModulePoolManager.WorkerPoolManagerModulePoolManager);
}
WorkerPoolManagerModulePoolManager::~WorkerPoolManagerModulePoolManager()
{
StartTrace(WorkerPoolManagerModulePoolManager.~WorkerPoolManagerModulePoolManager);
Terminate(5L);
Anything dummy;
DoDeletePool(dummy);
}
bool WorkerPoolManagerModulePoolManager::Init(const ROAnything config)
{
StartTrace(WorkerPoolManagerModulePoolManager.Init);
bool bRet = false;
long concurrentQueries = 5L;
String strInterfacesPathName;
if (config.IsDefined("Workers")) {
concurrentQueries = config["Workers"].AsLong(5L);
}
long usePoolStorage = 0L;
u_long poolStorageSize = 1000L;
u_long numOfPoolBucketSizes = 20L;
Trace("Initializing worker pool with " << concurrentQueries << " possible parallel queries");
Anything workerInitCfg;
workerInitCfg = config["WorkerInitialConfig"].DeepClone();
TraceAny(workerInitCfg, "WorkerInitialConfig for Pool: " << workerInitCfg.SlotName(0L));
// initialize the base class
if (WorkerPoolManager::Init(concurrentQueries, usePoolStorage, poolStorageSize, numOfPoolBucketSizes, workerInitCfg) == 0) {
Trace("WorkerPoolManager::Init successful");
bRet = true;
}
return bRet;
}
void WorkerPoolManagerModulePoolManager::DoAllocPool(ROAnything args)
{
StartTrace(WorkerPoolManagerModulePoolManager.DoAllocPool);
// create the pool of worker threads
fRequests = new WorkerPoolManagerModuleWorker[GetPoolSize()];
}
WorkerThread *WorkerPoolManagerModulePoolManager::DoGetWorker(long i)
{
StartTrace(WorkerPoolManagerModulePoolManager.DoGetWorker);
// accessor for one specific worker
if (fRequests) {
return &(fRequests[i]);
}
return 0;
}
void WorkerPoolManagerModulePoolManager::DoDeletePool(ROAnything args)
{
StartTrace(WorkerPoolManagerModulePoolManager.DoDeletePool);
// cleanup of the sub-class specific stuff
// CAUTION: this cleanup method may be called repeatedly..
if (fRequests) {
delete [ ] fRequests;
fRequests = 0;
}
}
void WorkerPoolManagerModulePoolManager::Enter(Anything &args)
{
// make this function block the caller until the worker has finished working
// to achieve this we create a Mutex and Condition to wait on
Mutex mx(args["server"].AsString());
Mutex::ConditionType cond;
args["mutex"] = (IFAObject *)&mx;
args["condition"] = (IFAObject *)&cond;
{
LockUnlockEntry me(mx);
WorkerPoolManager::Enter(args, -1L);
// wait on the worker to finish its work and start it with waiting on the condition
cond.Wait(mx);
}
}
| 31.879518 | 125 | 0.76455 | zer0infinity |
1549b420441803622cc3c33c638505f312d94f28 | 49,088 | cpp | C++ | src/3rdparty/khtml/src/css/css_renderstyledeclarationimpl.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/css/css_renderstyledeclarationimpl.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/css/css_renderstyledeclarationimpl.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | /**
* css_renderstyledeclarationimpl.cpp
*
* Copyright 2004 Zack Rusin <zack@kde.org>
* Copyright 2004,2005 Apple Computer, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "css_renderstyledeclarationimpl.h"
#include "rendering/render_style.h"
#include "rendering/render_object.h"
#include "cssproperties.h"
#include "cssvalues.h"
#include <dom/dom_exception.h>
using namespace DOM;
using namespace khtml;
// List of all properties we know how to compute, omitting shorthands.
static const int computedProperties[] = {
CSS_PROP_BACKGROUND_COLOR,
CSS_PROP_BACKGROUND_CLIP,
CSS_PROP_BACKGROUND_IMAGE,
CSS_PROP_BACKGROUND_REPEAT,
CSS_PROP_BACKGROUND_ATTACHMENT,
CSS_PROP_BACKGROUND_ORIGIN,
CSS_PROP_BACKGROUND_POSITION,
CSS_PROP_BACKGROUND_POSITION_X,
CSS_PROP_BACKGROUND_POSITION_Y,
CSS_PROP_BACKGROUND_SIZE,
CSS_PROP_BORDER_COLLAPSE,
CSS_PROP_BORDER_SPACING,
CSS_PROP__KHTML_BORDER_HORIZONTAL_SPACING,
CSS_PROP__KHTML_BORDER_VERTICAL_SPACING,
CSS_PROP_BORDER_TOP_RIGHT_RADIUS,
CSS_PROP_BORDER_BOTTOM_RIGHT_RADIUS,
CSS_PROP_BORDER_BOTTOM_LEFT_RADIUS,
CSS_PROP_BORDER_TOP_LEFT_RADIUS,
CSS_PROP_BORDER_TOP_COLOR,
CSS_PROP_BORDER_RIGHT_COLOR,
CSS_PROP_BORDER_BOTTOM_COLOR,
CSS_PROP_BORDER_LEFT_COLOR,
CSS_PROP_BORDER_TOP_STYLE,
CSS_PROP_BORDER_RIGHT_STYLE,
CSS_PROP_BORDER_BOTTOM_STYLE,
CSS_PROP_BORDER_LEFT_STYLE,
CSS_PROP_BORDER_TOP_WIDTH,
CSS_PROP_BORDER_RIGHT_WIDTH,
CSS_PROP_BORDER_BOTTOM_WIDTH,
CSS_PROP_BORDER_LEFT_WIDTH,
CSS_PROP_BOTTOM,
CSS_PROP_BOX_SIZING,
CSS_PROP_CAPTION_SIDE,
CSS_PROP_CLEAR,
CSS_PROP_COLOR,
CSS_PROP_CURSOR,
CSS_PROP_DIRECTION,
CSS_PROP_DISPLAY,
CSS_PROP_EMPTY_CELLS,
CSS_PROP_FLOAT,
CSS_PROP_FONT_FAMILY,
CSS_PROP_FONT_SIZE,
CSS_PROP_FONT_STYLE,
CSS_PROP_FONT_VARIANT,
CSS_PROP_FONT_WEIGHT,
CSS_PROP_HEIGHT,
CSS_PROP_LEFT,
CSS_PROP_LETTER_SPACING,
CSS_PROP_LINE_HEIGHT,
CSS_PROP_LIST_STYLE_IMAGE,
CSS_PROP_LIST_STYLE_POSITION,
CSS_PROP_LIST_STYLE_TYPE,
CSS_PROP_MARGIN_TOP,
CSS_PROP_MARGIN_RIGHT,
CSS_PROP_MARGIN_BOTTOM,
CSS_PROP_MARGIN_LEFT,
CSS_PROP__KHTML_MARQUEE_DIRECTION,
CSS_PROP__KHTML_MARQUEE_INCREMENT,
CSS_PROP__KHTML_MARQUEE_REPETITION,
CSS_PROP__KHTML_MARQUEE_STYLE,
CSS_PROP_MAX_HEIGHT,
CSS_PROP_MAX_WIDTH,
CSS_PROP_MIN_HEIGHT,
CSS_PROP_MIN_WIDTH,
CSS_PROP_OPACITY,
CSS_PROP_ORPHANS,
CSS_PROP_OUTLINE_STYLE,
CSS_PROP_OVERFLOW,
CSS_PROP_OVERFLOW_X,
CSS_PROP_OVERFLOW_Y,
CSS_PROP_PADDING_TOP,
CSS_PROP_PADDING_RIGHT,
CSS_PROP_PADDING_BOTTOM,
CSS_PROP_PADDING_LEFT,
CSS_PROP_PAGE_BREAK_AFTER,
CSS_PROP_PAGE_BREAK_BEFORE,
CSS_PROP_PAGE_BREAK_INSIDE,
CSS_PROP_POSITION,
CSS_PROP_RIGHT,
CSS_PROP_TABLE_LAYOUT,
CSS_PROP_TEXT_ALIGN,
CSS_PROP_TEXT_DECORATION,
CSS_PROP_TEXT_INDENT,
CSS_PROP_TEXT_OVERFLOW,
CSS_PROP_TEXT_SHADOW,
CSS_PROP_TEXT_TRANSFORM,
CSS_PROP_TOP,
CSS_PROP_UNICODE_BIDI,
CSS_PROP_VERTICAL_ALIGN,
CSS_PROP_VISIBILITY,
CSS_PROP_WHITE_SPACE,
CSS_PROP_WIDOWS,
CSS_PROP_WIDTH,
CSS_PROP_WORD_SPACING,
CSS_PROP_Z_INDEX
};
const unsigned numComputedProperties = sizeof(computedProperties) / sizeof(computedProperties[0]);
static CSSPrimitiveValueImpl *valueForLength(const Length &length, int max)
{
if (length.isPercent()) {
return new CSSPrimitiveValueImpl(length.percent(), CSSPrimitiveValue::CSS_PERCENTAGE);
} else {
return new CSSPrimitiveValueImpl(length.minWidth(max), CSSPrimitiveValue::CSS_PX);
}
}
static CSSPrimitiveValueImpl *valueForLength2(const Length &length)
{
if (length.isPercent()) {
return new CSSPrimitiveValueImpl(length.percent(), CSSPrimitiveValue::CSS_PERCENTAGE);
} else {
return new CSSPrimitiveValueImpl(length.value(), CSSPrimitiveValue::CSS_PX);
}
}
static CSSValueImpl *valueForBorderStyle(EBorderStyle style)
{
switch (style) {
case khtml::BNATIVE:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_NATIVE);
case khtml::BNONE:
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
case khtml::BHIDDEN:
return new CSSPrimitiveValueImpl(CSS_VAL_HIDDEN);
case khtml::INSET:
return new CSSPrimitiveValueImpl(CSS_VAL_INSET);
case khtml::GROOVE:
return new CSSPrimitiveValueImpl(CSS_VAL_GROOVE);
case khtml::RIDGE:
return new CSSPrimitiveValueImpl(CSS_VAL_RIDGE);
case khtml::OUTSET:
return new CSSPrimitiveValueImpl(CSS_VAL_OUTSET);
case khtml::DOTTED:
return new CSSPrimitiveValueImpl(CSS_VAL_DOTTED);
case khtml::DASHED:
return new CSSPrimitiveValueImpl(CSS_VAL_DASHED);
case khtml::SOLID:
return new CSSPrimitiveValueImpl(CSS_VAL_SOLID);
case khtml::DOUBLE:
return new CSSPrimitiveValueImpl(CSS_VAL_DOUBLE);
}
Q_ASSERT(0);
return nullptr;
}
static CSSValueImpl *valueForBorderRadii(BorderRadii radii)
{
CSSPrimitiveValueImpl *h = valueForLength2(radii.horizontal);
CSSPrimitiveValueImpl *v = valueForLength2(radii.vertical);
return new CSSPrimitiveValueImpl(new PairImpl(h, v));
}
static CSSValueImpl *valueForTextAlign(ETextAlign align)
{
switch (align) {
case khtml::TAAUTO:
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
case khtml::LEFT:
return new CSSPrimitiveValueImpl(CSS_VAL_LEFT);
case khtml::RIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL_RIGHT);
case khtml::CENTER:
return new CSSPrimitiveValueImpl(CSS_VAL_CENTER);
case khtml::JUSTIFY:
return new CSSPrimitiveValueImpl(CSS_VAL_JUSTIFY);
case khtml::KHTML_LEFT:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_LEFT);
case khtml::KHTML_RIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_RIGHT);
case khtml::KHTML_CENTER:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_CENTER);
}
Q_ASSERT(0);
return nullptr;
}
DOMString khtml::stringForListStyleType(EListStyleType type)
{
switch (type) {
case khtml::LDISC:
return "disc";
case khtml::LCIRCLE:
return "circle";
case khtml::LSQUARE:
return "square";
case khtml::LBOX:
return "box";
case khtml::LDIAMOND:
return "-khtml-diamond";
case khtml::LDECIMAL:
return "decimal";
case khtml::DECIMAL_LEADING_ZERO:
return "decimal-leading-zero";
case khtml::ARABIC_INDIC:
return "-khtml-arabic-indic";
case khtml::LAO:
return "-khtml-lao";
case khtml::PERSIAN:
return "-khtml-persian";
case khtml::URDU:
return "-khtml-urdu";
case khtml::THAI:
return "-khtml-thai";
case khtml::TIBETAN:
return "-khtml-tibetan";
case khtml::LOWER_ROMAN:
return "lower-roman";
case khtml::UPPER_ROMAN:
return "upper-roman";
case khtml::HEBREW:
return "hebrew";
case khtml::ARMENIAN:
return "armenian";
case khtml::GEORGIAN:
return "georgian";
case khtml::CJK_IDEOGRAPHIC:
return "cjk-ideographic";
case khtml::JAPANESE_FORMAL:
return "-khtml-japanese-formal";
case khtml::JAPANESE_INFORMAL:
return "-khtml-japanese-informal";
case khtml::SIMP_CHINESE_FORMAL:
return "-khtml-simp-chinese-formal";
case khtml::SIMP_CHINESE_INFORMAL:
return "-khtml-simp-chinese-informal";
case khtml::TRAD_CHINESE_FORMAL:
return "-khtml-trad-chinese-formal";
case khtml::TRAD_CHINESE_INFORMAL:
return "-khtml-trad-chinese-informal";
case khtml::LOWER_GREEK:
return "lower-greek";
case khtml::UPPER_GREEK:
return "-khtml-upper-greek";
case khtml::LOWER_ALPHA:
return "lower-alpha";
case khtml::UPPER_ALPHA:
return "upper-alpha";
case khtml::LOWER_LATIN:
return "lower-latin";
case khtml::UPPER_LATIN:
return "upper-latin";
case khtml::HIRAGANA:
return "hiragana";
case khtml::KATAKANA:
return "katakana";
case khtml::HIRAGANA_IROHA:
return "hiragana-iroha";
case khtml::KATAKANA_IROHA:
return "katakana_iroha";
case khtml::LNONE:
return "none";
}
Q_ASSERT(0);
return "";
}
static CSSPrimitiveValueImpl *valueForColor(QColor color)
{
if (color.isValid()) {
return new CSSPrimitiveValueImpl(color.rgba());
} else {
return new CSSPrimitiveValueImpl(khtml::transparentColor);
}
}
static CSSValueImpl *valueForShadow(const ShadowData *shadow)
{
if (!shadow) {
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
}
CSSValueListImpl *list = new CSSValueListImpl(CSSValueListImpl::Comma);
for (const ShadowData *s = shadow; s; s = s->next) {
CSSPrimitiveValueImpl *x = new CSSPrimitiveValueImpl(s->x, CSSPrimitiveValue::CSS_PX);
CSSPrimitiveValueImpl *y = new CSSPrimitiveValueImpl(s->y, CSSPrimitiveValue::CSS_PX);
CSSPrimitiveValueImpl *blur = new CSSPrimitiveValueImpl(s->blur, CSSPrimitiveValue::CSS_PX);
CSSPrimitiveValueImpl *color = valueForColor(s->color);
list->append(new ShadowValueImpl(x, y, blur, color));
}
return list;
}
static CSSValueImpl *getPositionOffsetValue(RenderObject *renderer, int propertyID)
{
if (!renderer) {
return nullptr;
}
RenderStyle *style = renderer->style();
if (!style) {
return nullptr;
}
Length l;
switch (propertyID) {
case CSS_PROP_LEFT:
l = style->left();
break;
case CSS_PROP_RIGHT:
l = style->right();
break;
case CSS_PROP_TOP:
l = style->top();
break;
case CSS_PROP_BOTTOM:
l = style->bottom();
break;
default:
return nullptr;
}
if (renderer->isPositioned()) {
return valueForLength(l, renderer->contentWidth());
}
if (renderer->isRelPositioned())
// FIXME: It's not enough to simply return "auto" values for one offset if the other side is defined.
// In other words if left is auto and right is not auto, then left's computed value is negative right.
// So we should get the opposite length unit and see if it is auto.
{
return valueForLength(l, renderer->contentWidth());
}
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
}
RenderStyleDeclarationImpl::RenderStyleDeclarationImpl(DOM::NodeImpl *node)
: CSSStyleDeclarationImpl(nullptr), m_node(node)
{
//qCDebug(KHTML_LOG) << "Render Style Declaration created";
}
RenderStyleDeclarationImpl::~RenderStyleDeclarationImpl()
{
//qCDebug(KHTML_LOG) << "Render Style Declaration destroyed";
}
DOM::DOMString RenderStyleDeclarationImpl::cssText() const
{
DOMString result;
for (unsigned i = 0; i < numComputedProperties; i++) {
if (i != 0) {
result += " ";
}
result += getPropertyName(computedProperties[i]);
result += ": ";
result += getPropertyValue(computedProperties[i]);
result += ";";
}
return result;
}
void RenderStyleDeclarationImpl::setCssText(DOM::DOMString)
{
// ### report that this sucka is read only
}
CSSValueImpl *RenderStyleDeclarationImpl::getPropertyCSSValue(int propertyID) const
{
NodeImpl *node = m_node.get();
if (!node) {
return nullptr;
}
// Make sure our layout is up to date before we allow a query on these attributes.
DocumentImpl *docimpl = node->document();
if (docimpl) {
docimpl->updateLayout();
}
RenderStyle *style = node->computedStyle();
if (!style) {
return nullptr;
}
RenderObject *renderer = node->renderer(); // can be NULL
// temporary(?) measure to handle with missing render object
// check how we can better deal with it on a case-by-case basis
#define RETURN_NULL_ON_NULL(ptr) if(ptr == 0) return 0;
switch (propertyID) {
case CSS_PROP_BACKGROUND_COLOR:
return valueForColor(style->backgroundColor());
case CSS_PROP_BACKGROUND_CLIP:
switch (style->backgroundLayers()->backgroundClip()) {
case BGBORDER:
return new CSSPrimitiveValueImpl(CSS_VAL_BORDER_BOX);
case BGPADDING:
return new CSSPrimitiveValueImpl(CSS_VAL_PADDING_BOX);
case BGCONTENT:
return new CSSPrimitiveValueImpl(CSS_VAL_CONTENT_BOX);
}
Q_ASSERT(0);
break;
case CSS_PROP_BACKGROUND_IMAGE:
if (style->backgroundImage())
return new CSSPrimitiveValueImpl(style->backgroundImage()->url(),
CSSPrimitiveValue::CSS_URI);
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
case CSS_PROP_BACKGROUND_REPEAT:
switch (style->backgroundRepeat()) {
case khtml::REPEAT:
return new CSSPrimitiveValueImpl(CSS_VAL_REPEAT);
case khtml::REPEAT_X:
return new CSSPrimitiveValueImpl(CSS_VAL_REPEAT_X);
case khtml::REPEAT_Y:
return new CSSPrimitiveValueImpl(CSS_VAL_REPEAT_Y);
case khtml::NO_REPEAT:
return new CSSPrimitiveValueImpl(CSS_VAL_NO_REPEAT);
default:
Q_ASSERT(0);
}
break;
case CSS_PROP_BACKGROUND_ATTACHMENT:
switch (style->backgroundAttachment()) {
case khtml::BGASCROLL:
return new CSSPrimitiveValueImpl(CSS_VAL_SCROLL);
case khtml::BGAFIXED:
return new CSSPrimitiveValueImpl(CSS_VAL_FIXED);
case khtml::BGALOCAL:
return new CSSPrimitiveValueImpl(CSS_VAL_LOCAL);
default:
Q_ASSERT(0);
}
break;
case CSS_PROP_BACKGROUND_ORIGIN:
switch (style->backgroundLayers()->backgroundOrigin()) {
case BGBORDER:
return new CSSPrimitiveValueImpl(CSS_VAL_BORDER_BOX);
case BGPADDING:
return new CSSPrimitiveValueImpl(CSS_VAL_PADDING_BOX);
case BGCONTENT:
return new CSSPrimitiveValueImpl(CSS_VAL_CONTENT_BOX);
}
Q_ASSERT(0);
break;
case CSS_PROP_BACKGROUND_POSITION: {
RETURN_NULL_ON_NULL(renderer);
CSSValueListImpl *values = new CSSValueListImpl(CSSValueListImpl::Space);
values->append(valueForLength(style->backgroundXPosition(), renderer->contentWidth()));
values->append(valueForLength(style->backgroundYPosition(), renderer->contentHeight()));
return values;
}
case CSS_PROP_BACKGROUND_POSITION_X:
RETURN_NULL_ON_NULL(renderer);
return valueForLength(style->backgroundXPosition(), renderer->contentWidth());
case CSS_PROP_BACKGROUND_POSITION_Y:
RETURN_NULL_ON_NULL(renderer);
return valueForLength(style->backgroundYPosition(), renderer->contentHeight());
case CSS_PROP_BACKGROUND_SIZE: {
const EBackgroundSizeType backgroundSizeType = style->backgroundLayers()->backgroundSize().type;
switch (backgroundSizeType) {
case BGSCONTAIN:
return new CSSPrimitiveValueImpl(CSS_VAL_CONTAIN);
case BGSCOVER:
return new CSSPrimitiveValueImpl(CSS_VAL_COVER);
case BGSLENGTH: {
const BGSize bgSize = style->backgroundLayers()->backgroundSize();
CSSValueListImpl *values = new CSSValueListImpl(CSSValueListImpl::Space);
switch (bgSize.width.type()) {
case Auto:
values->append(new CSSPrimitiveValueImpl(CSS_VAL_AUTO));
break;
case Percent:
values->append(new CSSPrimitiveValueImpl(bgSize.width.percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
break;
default:
values->append(new CSSPrimitiveValueImpl(bgSize.width.value(), CSSPrimitiveValue::CSS_PX));
}
switch (bgSize.height.type()) {
case Auto:
values->append(new CSSPrimitiveValueImpl(CSS_VAL_AUTO));
break;
case Percent:
values->append(new CSSPrimitiveValueImpl(bgSize.height.percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
break;
default:
values->append(new CSSPrimitiveValueImpl(bgSize.height.value(), CSSPrimitiveValue::CSS_PX));
}
return values;
}
default:
Q_ASSERT(0);
}
break;
}
case CSS_PROP_BORDER_COLLAPSE:
if (style->borderCollapse()) {
return new CSSPrimitiveValueImpl(CSS_VAL_COLLAPSE);
} else {
return new CSSPrimitiveValueImpl(CSS_VAL_SEPARATE);
}
case CSS_PROP_BORDER_SPACING: {
CSSValueListImpl *values = new CSSValueListImpl(CSSValueListImpl::Space);
values->append(new CSSPrimitiveValueImpl(style->borderHorizontalSpacing(), CSSPrimitiveValue::CSS_PX));
values->append(new CSSPrimitiveValueImpl(style->borderVerticalSpacing(), CSSPrimitiveValue::CSS_PX));
return values;
}
case CSS_PROP__KHTML_BORDER_HORIZONTAL_SPACING:
return new CSSPrimitiveValueImpl(style->borderHorizontalSpacing(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP__KHTML_BORDER_VERTICAL_SPACING:
return new CSSPrimitiveValueImpl(style->borderVerticalSpacing(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP_BORDER_TOP_RIGHT_RADIUS:
return valueForBorderRadii(style->borderTopRightRadius());
case CSS_PROP_BORDER_BOTTOM_RIGHT_RADIUS:
return valueForBorderRadii(style->borderBottomRightRadius());
case CSS_PROP_BORDER_BOTTOM_LEFT_RADIUS:
return valueForBorderRadii(style->borderBottomLeftRadius());
case CSS_PROP_BORDER_TOP_LEFT_RADIUS:
return valueForBorderRadii(style->borderTopLeftRadius());
case CSS_PROP_BORDER_TOP_COLOR:
return valueForColor(style->borderTopColor());
case CSS_PROP_BORDER_RIGHT_COLOR:
return valueForColor(style->borderRightColor());
case CSS_PROP_BORDER_BOTTOM_COLOR:
return valueForColor(style->borderBottomColor());
case CSS_PROP_BORDER_LEFT_COLOR:
return valueForColor(style->borderLeftColor());
case CSS_PROP_BORDER_TOP_STYLE:
return valueForBorderStyle(style->borderTopStyle());
case CSS_PROP_BORDER_RIGHT_STYLE:
return valueForBorderStyle(style->borderRightStyle());
case CSS_PROP_BORDER_BOTTOM_STYLE:
return valueForBorderStyle(style->borderBottomStyle());
case CSS_PROP_BORDER_LEFT_STYLE:
return valueForBorderStyle(style->borderLeftStyle());
case CSS_PROP_BORDER_TOP_WIDTH:
return new CSSPrimitiveValueImpl(style->borderTopWidth(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP_BORDER_RIGHT_WIDTH:
return new CSSPrimitiveValueImpl(style->borderRightWidth(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP_BORDER_BOTTOM_WIDTH:
return new CSSPrimitiveValueImpl(style->borderBottomWidth(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP_BORDER_LEFT_WIDTH:
return new CSSPrimitiveValueImpl(style->borderLeftWidth(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP_BOTTOM:
RETURN_NULL_ON_NULL(renderer);
return getPositionOffsetValue(renderer, CSS_PROP_BOTTOM);
case CSS_PROP_BOX_SIZING:
if (style->boxSizing() == BORDER_BOX) {
return new CSSPrimitiveValueImpl(CSS_VAL_BORDER_BOX);
} else {
return new CSSPrimitiveValueImpl(CSS_VAL_CONTENT_BOX);
}
case CSS_PROP_CAPTION_SIDE:
switch (style->captionSide()) {
case CAPLEFT:
return new CSSPrimitiveValueImpl(CSS_VAL_LEFT);
case CAPRIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL_RIGHT);
case CAPTOP:
return new CSSPrimitiveValueImpl(CSS_VAL_TOP);
case CAPBOTTOM:
return new CSSPrimitiveValueImpl(CSS_VAL_BOTTOM);
}
Q_ASSERT(0);
break;
case CSS_PROP_CLEAR:
switch (style->clear()) {
case CNONE:
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
case CLEFT:
return new CSSPrimitiveValueImpl(CSS_VAL_LEFT);
case CRIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL_RIGHT);
case CBOTH:
return new CSSPrimitiveValueImpl(CSS_VAL_BOTH);
}
Q_ASSERT(0);
break;
case CSS_PROP_CLIP:
break;
case CSS_PROP_COLOR:
return valueForColor(style->color());
case CSS_PROP_CONTENT:
break;
case CSS_PROP_COUNTER_INCREMENT:
break;
case CSS_PROP_COUNTER_RESET:
break;
case CSS_PROP_CURSOR:
switch (style->cursor()) {
case CURSOR_AUTO:
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
case CURSOR_DEFAULT:
return new CSSPrimitiveValueImpl(CSS_VAL_DEFAULT);
case CURSOR_NONE:
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
case CURSOR_CONTEXT_MENU:
return new CSSPrimitiveValueImpl(CSS_VAL_CONTEXT_MENU);
case CURSOR_HELP:
return new CSSPrimitiveValueImpl(CSS_VAL_HELP);
case CURSOR_POINTER:
return new CSSPrimitiveValueImpl(CSS_VAL_POINTER);
case CURSOR_PROGRESS:
return new CSSPrimitiveValueImpl(CSS_VAL_PROGRESS);
case CURSOR_WAIT:
return new CSSPrimitiveValueImpl(CSS_VAL_WAIT);
case CURSOR_CELL:
return new CSSPrimitiveValueImpl(CSS_VAL_CELL);
case CURSOR_CROSS:
return new CSSPrimitiveValueImpl(CSS_VAL_CROSSHAIR);
case CURSOR_TEXT:
return new CSSPrimitiveValueImpl(CSS_VAL_TEXT);
case CURSOR_VERTICAL_TEXT:
return new CSSPrimitiveValueImpl(CSS_VAL_VERTICAL_TEXT);
case CURSOR_ALIAS:
return new CSSPrimitiveValueImpl(CSS_VAL_ALIAS);
case CURSOR_COPY:
return new CSSPrimitiveValueImpl(CSS_VAL_COPY);
case CURSOR_MOVE:
return new CSSPrimitiveValueImpl(CSS_VAL_MOVE);
case CURSOR_NO_DROP:
return new CSSPrimitiveValueImpl(CSS_VAL_NO_DROP);
case CURSOR_NOT_ALLOWED:
return new CSSPrimitiveValueImpl(CSS_VAL_NOT_ALLOWED);
case CURSOR_E_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_E_RESIZE);
case CURSOR_N_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_N_RESIZE);
case CURSOR_NE_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_NE_RESIZE);
case CURSOR_NW_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_NW_RESIZE);
case CURSOR_S_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_S_RESIZE);
case CURSOR_SE_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_SE_RESIZE);
case CURSOR_SW_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_SW_RESIZE);
case CURSOR_W_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_W_RESIZE);
case CURSOR_EW_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_EW_RESIZE);
case CURSOR_NS_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_NS_RESIZE);
case CURSOR_NESW_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_NESW_RESIZE);
case CURSOR_NWSE_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_NWSE_RESIZE);
case CURSOR_COL_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_COL_RESIZE);
case CURSOR_ROW_RESIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_ROW_RESIZE);
case CURSOR_ALL_SCROLL:
return new CSSPrimitiveValueImpl(CSS_VAL_ALL_SCROLL);
}
Q_ASSERT(0);
break;
case CSS_PROP_DIRECTION:
switch (style->direction()) {
case LTR:
return new CSSPrimitiveValueImpl(CSS_VAL_LTR);
case RTL:
return new CSSPrimitiveValueImpl(CSS_VAL_RTL);
}
Q_ASSERT(0);
break;
case CSS_PROP_DISPLAY:
switch (style->display()) {
case INLINE:
return new CSSPrimitiveValueImpl(CSS_VAL_INLINE);
case BLOCK:
return new CSSPrimitiveValueImpl(CSS_VAL_BLOCK);
case LIST_ITEM:
return new CSSPrimitiveValueImpl(CSS_VAL_LIST_ITEM);
case RUN_IN:
return new CSSPrimitiveValueImpl(CSS_VAL_RUN_IN);
case COMPACT:
return new CSSPrimitiveValueImpl(CSS_VAL_COMPACT);
case INLINE_BLOCK:
return new CSSPrimitiveValueImpl(CSS_VAL_INLINE_BLOCK);
case TABLE:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE);
case INLINE_TABLE:
return new CSSPrimitiveValueImpl(CSS_VAL_INLINE_TABLE);
case TABLE_ROW_GROUP:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_ROW_GROUP);
case TABLE_HEADER_GROUP:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_HEADER_GROUP);
case TABLE_FOOTER_GROUP:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_FOOTER_GROUP);
case TABLE_ROW:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_ROW);
case TABLE_COLUMN_GROUP:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_COLUMN_GROUP);
case TABLE_COLUMN:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_COLUMN);
case TABLE_CELL:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_CELL);
case TABLE_CAPTION:
return new CSSPrimitiveValueImpl(CSS_VAL_TABLE_CAPTION);
case NONE:
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
}
Q_ASSERT(0);
break;
case CSS_PROP_EMPTY_CELLS:
switch (style->emptyCells()) {
case SHOW:
return new CSSPrimitiveValueImpl(CSS_VAL_SHOW);
case HIDE:
return new CSSPrimitiveValueImpl(CSS_VAL_HIDE);
}
Q_ASSERT(0);
break;
case CSS_PROP_FLOAT: {
switch (style->floating()) {
case FNONE:
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
case FLEFT:
return new CSSPrimitiveValueImpl(CSS_VAL_LEFT);
case FRIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL_RIGHT);
case FLEFT_ALIGN:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_LEFT);
case FRIGHT_ALIGN:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_RIGHT);
}
Q_ASSERT(0);
break;
}
case CSS_PROP_FONT_FAMILY: {
FontDef def = style->htmlFont().getFontDef();
return new CSSPrimitiveValueImpl(DOMString(def.family), CSSPrimitiveValue::CSS_STRING);
}
case CSS_PROP_FONT_SIZE: {
FontDef def = style->htmlFont().getFontDef();
return new CSSPrimitiveValueImpl(def.size, CSSPrimitiveValue::CSS_PX);
}
case CSS_PROP_FONT_STYLE: {
// FIXME: handle oblique
FontDef def = style->htmlFont().getFontDef();
if (def.italic) {
return new CSSPrimitiveValueImpl(CSS_VAL_ITALIC);
} else {
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
}
}
case CSS_PROP_FONT_VARIANT: {
FontDef def = style->htmlFont().getFontDef();
if (def.smallCaps) {
return new CSSPrimitiveValueImpl(CSS_VAL_SMALL_CAPS);
} else {
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
}
}
case CSS_PROP_FONT_WEIGHT: {
// FIXME: this does not reflect the full range of weights
// that can be expressed with CSS
FontDef def = style->htmlFont().getFontDef();
switch (def.weight) {
case QFont::Light:
return new CSSPrimitiveValueImpl(CSS_VAL_300);
case QFont::Normal:
//return new CSSPrimitiveValueImpl(CSS_VAL_400);
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
case QFont::DemiBold:
return new CSSPrimitiveValueImpl(CSS_VAL_600);
case QFont::Bold:
//return new CSSPrimitiveValueImpl(CSS_VAL_700);
return new CSSPrimitiveValueImpl(CSS_VAL_BOLD);
case QFont::Black:
return new CSSPrimitiveValueImpl(CSS_VAL_900);
default:
// Should not happen
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
}
}
case CSS_PROP_HEIGHT:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->contentHeight(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->height());
case CSS_PROP_LEFT:
RETURN_NULL_ON_NULL(renderer);
return getPositionOffsetValue(renderer, CSS_PROP_LEFT);
case CSS_PROP_LETTER_SPACING:
if (style->letterSpacing() == 0) {
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
}
return new CSSPrimitiveValueImpl(style->letterSpacing(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP_LINE_HEIGHT: {
// Note: internally a specified <number> value gets encoded as a percentage,
// so the isPercent() case corresponds to the <number> case;
// values < 0 are used to mark "normal"; and specified %%
// get computed down to px by the time they get to RenderStyle
// already
Length length(style->lineHeight());
if (length.isNegative()) {
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
}
if (length.isPercent()) {
//XXX: merge from webcore the computedStyle/specifiedStyle distinction in rendering/font.h
float computedSize = style->htmlFont().getFontDef().size;
return new CSSPrimitiveValueImpl((int)(length.percent() * computedSize) / 100, CSSPrimitiveValue::CSS_PX);
} else {
return new CSSPrimitiveValueImpl(length.value(), CSSPrimitiveValue::CSS_PX);
}
}
case CSS_PROP_LIST_STYLE_IMAGE:
if (style->listStyleImage()) {
return new CSSPrimitiveValueImpl(style->listStyleImage()->url(), CSSPrimitiveValue::CSS_URI);
}
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
case CSS_PROP_LIST_STYLE_POSITION:
switch (style->listStylePosition()) {
case OUTSIDE:
return new CSSPrimitiveValueImpl(CSS_VAL_OUTSIDE);
case INSIDE:
return new CSSPrimitiveValueImpl(CSS_VAL_INSIDE);
}
Q_ASSERT(0);
break;
case CSS_PROP_LIST_STYLE_TYPE:
return new CSSPrimitiveValueImpl(stringForListStyleType(style->listStyleType()), CSSPrimitiveValue::CSS_STRING);
case CSS_PROP_MARGIN_TOP:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->marginTop(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->marginTop());
case CSS_PROP_MARGIN_RIGHT:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->marginRight(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->marginRight());
case CSS_PROP_MARGIN_BOTTOM:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->marginBottom(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->marginBottom());
case CSS_PROP_MARGIN_LEFT:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->marginLeft(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->marginLeft());
case CSS_PROP__KHTML_MARQUEE:
// FIXME: unimplemented
break;
case CSS_PROP__KHTML_MARQUEE_DIRECTION:
switch (style->marqueeDirection()) {
case MFORWARD:
return new CSSPrimitiveValueImpl(CSS_VAL_FORWARDS);
case MBACKWARD:
return new CSSPrimitiveValueImpl(CSS_VAL_BACKWARDS);
case MAUTO:
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
case MUP:
return new CSSPrimitiveValueImpl(CSS_VAL_UP);
case MDOWN:
return new CSSPrimitiveValueImpl(CSS_VAL_DOWN);
case MLEFT:
return new CSSPrimitiveValueImpl(CSS_VAL_LEFT);
case MRIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL_RIGHT);
}
Q_ASSERT(0);
return nullptr;
case CSS_PROP__KHTML_MARQUEE_INCREMENT:
RETURN_NULL_ON_NULL(renderer);
return valueForLength(style->marqueeIncrement(), renderer->contentWidth());
case CSS_PROP__KHTML_MARQUEE_REPETITION:
if (style->marqueeLoopCount() < 0) {
return new CSSPrimitiveValueImpl(CSS_VAL_INFINITE);
}
return new CSSPrimitiveValueImpl(style->marqueeLoopCount(), CSSPrimitiveValue::CSS_NUMBER);
case CSS_PROP__KHTML_MARQUEE_SPEED:
// FIXME: unimplemented
break;
case CSS_PROP__KHTML_MARQUEE_STYLE:
switch (style->marqueeBehavior()) {
case MNONE:
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
case MSCROLL:
return new CSSPrimitiveValueImpl(CSS_VAL_SCROLL);
case MSLIDE:
return new CSSPrimitiveValueImpl(CSS_VAL_SLIDE);
case MALTERNATE:
return new CSSPrimitiveValueImpl(CSS_VAL_ALTERNATE);
case MUNFURL:
return new CSSPrimitiveValueImpl(CSS_VAL_UNFURL);
}
Q_ASSERT(0);
return nullptr;
case CSS_PROP_MAX_HEIGHT:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->availableHeight(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_MAX_WIDTH:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->maxWidth(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_MIN_HEIGHT:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->contentHeight(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_MIN_WIDTH:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->minWidth(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_OPACITY:
return new CSSPrimitiveValueImpl(style->opacity(), CSSPrimitiveValue::CSS_NUMBER);
case CSS_PROP_ORPHANS:
return new CSSPrimitiveValueImpl(style->orphans(), CSSPrimitiveValue::CSS_NUMBER);
case CSS_PROP_OUTLINE_COLOR:
break;
case CSS_PROP_OUTLINE_OFFSET:
break;
case CSS_PROP_OUTLINE_STYLE:
if (style->outlineStyleIsAuto()) {
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
}
return valueForBorderStyle(style->outlineStyle());
case CSS_PROP_OUTLINE_WIDTH:
break;
case CSS_PROP_OVERFLOW:
case CSS_PROP_OVERFLOW_X:
case CSS_PROP_OVERFLOW_Y: {
EOverflow overflow;
switch (propertyID) {
case CSS_PROP_OVERFLOW_X:
overflow = style->overflowX();
break;
case CSS_PROP_OVERFLOW_Y:
overflow = style->overflowY();
break;
default:
overflow = qMax(style->overflowX(), style->overflowY());
}
switch (overflow) {
case OVISIBLE:
return new CSSPrimitiveValueImpl(CSS_VAL_VISIBLE);
case OHIDDEN:
return new CSSPrimitiveValueImpl(CSS_VAL_HIDDEN);
case OSCROLL:
return new CSSPrimitiveValueImpl(CSS_VAL_SCROLL);
case OAUTO:
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
case OMARQUEE:
return new CSSPrimitiveValueImpl(CSS_VAL_MARQUEE);
}
Q_ASSERT(0);
return nullptr;
}
case CSS_PROP_PADDING_TOP:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->paddingTop(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->paddingTop());
case CSS_PROP_PADDING_RIGHT:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->paddingRight(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->paddingRight());
case CSS_PROP_PADDING_BOTTOM:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->paddingBottom(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->paddingBottom());
case CSS_PROP_PADDING_LEFT:
if (renderer) {
return new CSSPrimitiveValueImpl(renderer->paddingLeft(), CSSPrimitiveValue::CSS_PX);
}
return valueForLength2(style->paddingLeft());
case CSS_PROP_PAGE_BREAK_AFTER:
switch (style->pageBreakAfter()) {
case PBAUTO:
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
case PBALWAYS:
return new CSSPrimitiveValueImpl(CSS_VAL_ALWAYS);
case PBAVOID:
return new CSSPrimitiveValueImpl(CSS_VAL_AVOID);
case PBLEFT:
return new CSSPrimitiveValueImpl(CSS_VAL_LEFT);
case PBRIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL_RIGHT);
}
Q_ASSERT(0);
break;
case CSS_PROP_PAGE_BREAK_BEFORE:
switch (style->pageBreakBefore()) {
case PBAUTO:
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
case PBALWAYS:
return new CSSPrimitiveValueImpl(CSS_VAL_ALWAYS);
case PBAVOID:
return new CSSPrimitiveValueImpl(CSS_VAL_AVOID);
case PBLEFT:
return new CSSPrimitiveValueImpl(CSS_VAL_LEFT);
case PBRIGHT:
return new CSSPrimitiveValueImpl(CSS_VAL_RIGHT);
}
Q_ASSERT(0);
break;
case CSS_PROP_PAGE_BREAK_INSIDE:
if (style->pageBreakInside()) {
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
} else {
return new CSSPrimitiveValueImpl(CSS_VAL_AVOID);
}
Q_ASSERT(0);
break;
case CSS_PROP_POSITION:
switch (style->position()) {
case PSTATIC:
return new CSSPrimitiveValueImpl(CSS_VAL_STATIC);
case PRELATIVE:
return new CSSPrimitiveValueImpl(CSS_VAL_RELATIVE);
case PABSOLUTE:
return new CSSPrimitiveValueImpl(CSS_VAL_ABSOLUTE);
case PFIXED:
return new CSSPrimitiveValueImpl(CSS_VAL_FIXED);
}
Q_ASSERT(0);
break;
case CSS_PROP_QUOTES:
break;
case CSS_PROP_RIGHT:
RETURN_NULL_ON_NULL(renderer);
return getPositionOffsetValue(renderer, CSS_PROP_RIGHT);
case CSS_PROP_SIZE:
break;
case CSS_PROP_TABLE_LAYOUT:
switch (style->tableLayout()) {
case TAUTO:
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
case TFIXED:
return new CSSPrimitiveValueImpl(CSS_VAL_FIXED);
}
Q_ASSERT(0);
break;
case CSS_PROP_TEXT_ALIGN:
return valueForTextAlign(style->textAlign());
case CSS_PROP_TEXT_DECORATION: {
QString string;
if (style->textDecoration() & khtml::UNDERLINE) {
string += "underline";
}
if (style->textDecoration() & khtml::OVERLINE) {
if (string.length() > 0) {
string += " ";
}
string += "overline";
}
if (style->textDecoration() & khtml::LINE_THROUGH) {
if (string.length() > 0) {
string += " ";
}
string += "line-through";
}
if (style->textDecoration() & khtml::BLINK) {
if (string.length() > 0) {
string += " ";
}
string += "blink";
}
if (string.length() == 0) {
string = "none";
}
return new CSSPrimitiveValueImpl(DOMString(string), CSSPrimitiveValue::CSS_STRING);
}
case CSS_PROP_TEXT_INDENT:
RETURN_NULL_ON_NULL(renderer);
return valueForLength(style->textIndent(), renderer->contentWidth());
case CSS_PROP_TEXT_SHADOW:
return valueForShadow(style->textShadow());
case CSS_PROP_TEXT_TRANSFORM:
switch (style->textTransform()) {
case CAPITALIZE:
return new CSSPrimitiveValueImpl(CSS_VAL_CAPITALIZE);
case UPPERCASE:
return new CSSPrimitiveValueImpl(CSS_VAL_UPPERCASE);
case LOWERCASE:
return new CSSPrimitiveValueImpl(CSS_VAL_LOWERCASE);
case TTNONE:
return new CSSPrimitiveValueImpl(CSS_VAL_NONE);
}
Q_ASSERT(0);
break;
case CSS_PROP_TOP:
RETURN_NULL_ON_NULL(renderer);
return getPositionOffsetValue(renderer, CSS_PROP_TOP);
case CSS_PROP_UNICODE_BIDI:
switch (style->unicodeBidi()) {
case UBNormal:
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
case Embed:
return new CSSPrimitiveValueImpl(CSS_VAL_EMBED);
case Override:
return new CSSPrimitiveValueImpl(CSS_VAL_BIDI_OVERRIDE);
}
Q_ASSERT(0);
break;
case CSS_PROP_VERTICAL_ALIGN: {
switch (style->verticalAlign()) {
case BASELINE:
return new CSSPrimitiveValueImpl(CSS_VAL_BASELINE);
case MIDDLE:
return new CSSPrimitiveValueImpl(CSS_VAL_MIDDLE);
case SUB:
return new CSSPrimitiveValueImpl(CSS_VAL_SUB);
case SUPER:
return new CSSPrimitiveValueImpl(CSS_VAL_SUPER);
case TEXT_TOP:
return new CSSPrimitiveValueImpl(CSS_VAL_TEXT_TOP);
case TEXT_BOTTOM:
return new CSSPrimitiveValueImpl(CSS_VAL_TEXT_BOTTOM);
case TOP:
return new CSSPrimitiveValueImpl(CSS_VAL_TOP);
case BOTTOM:
return new CSSPrimitiveValueImpl(CSS_VAL_BOTTOM);
case BASELINE_MIDDLE:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_BASELINE_MIDDLE);
case LENGTH:
RETURN_NULL_ON_NULL(renderer);
return valueForLength(style->verticalAlignLength(), renderer->contentWidth());
}
Q_ASSERT(0);
break;
}
case CSS_PROP_VISIBILITY:
switch (style->visibility()) {
case khtml::VISIBLE:
return new CSSPrimitiveValueImpl(CSS_VAL_VISIBLE);
case khtml::HIDDEN:
return new CSSPrimitiveValueImpl(CSS_VAL_HIDDEN);
case khtml::COLLAPSE:
return new CSSPrimitiveValueImpl(CSS_VAL_COLLAPSE);
}
Q_ASSERT(0);
break;
case CSS_PROP_WHITE_SPACE: {
switch (style->whiteSpace()) {
case NORMAL:
return new CSSPrimitiveValueImpl(CSS_VAL_NORMAL);
case PRE:
return new CSSPrimitiveValueImpl(CSS_VAL_PRE);
case PRE_WRAP:
return new CSSPrimitiveValueImpl(CSS_VAL_PRE_WRAP);
case PRE_LINE:
return new CSSPrimitiveValueImpl(CSS_VAL_PRE_LINE);
case NOWRAP:
return new CSSPrimitiveValueImpl(CSS_VAL_NOWRAP);
case KHTML_NOWRAP:
return new CSSPrimitiveValueImpl(CSS_VAL__KHTML_NOWRAP);
}
Q_ASSERT(0);
break;
}
case CSS_PROP_WIDOWS:
return new CSSPrimitiveValueImpl(style->widows(), CSSPrimitiveValue::CSS_NUMBER);
case CSS_PROP_WIDTH:
if (renderer)
return new CSSPrimitiveValueImpl(renderer->contentWidth(),
CSSPrimitiveValue::CSS_PX);
return valueForLength2(style->width());
case CSS_PROP_WORD_SPACING:
return new CSSPrimitiveValueImpl(style->wordSpacing(), CSSPrimitiveValue::CSS_PX);
case CSS_PROP_Z_INDEX:
if (style->hasAutoZIndex()) {
return new CSSPrimitiveValueImpl(CSS_VAL_AUTO);
}
return new CSSPrimitiveValueImpl(style->zIndex(), CSSPrimitiveValue::CSS_NUMBER);
case CSS_PROP_BACKGROUND:
break;
case CSS_PROP_BORDER:
break;
case CSS_PROP_BORDER_COLOR:
break;
case CSS_PROP_BORDER_STYLE:
break;
case CSS_PROP_BORDER_TOP:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->borderTop(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_BORDER_RIGHT:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->borderRight(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_BORDER_BOTTOM:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->borderBottom(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_BORDER_LEFT:
RETURN_NULL_ON_NULL(renderer);
return new CSSPrimitiveValueImpl(renderer->borderLeft(),
CSSPrimitiveValue::CSS_PX);
break;
case CSS_PROP_BORDER_WIDTH:
break;
case CSS_PROP_FONT:
break;
case CSS_PROP_LIST_STYLE:
break;
case CSS_PROP_MARGIN:
break;
case CSS_PROP_OUTLINE:
break;
case CSS_PROP_PADDING:
break;
case CSS_PROP_SCROLLBAR_BASE_COLOR:
break;
case CSS_PROP_SCROLLBAR_FACE_COLOR:
break;
case CSS_PROP_SCROLLBAR_SHADOW_COLOR:
break;
case CSS_PROP_SCROLLBAR_HIGHLIGHT_COLOR:
break;
case CSS_PROP_SCROLLBAR_3DLIGHT_COLOR:
break;
case CSS_PROP_SCROLLBAR_DARKSHADOW_COLOR:
break;
case CSS_PROP_SCROLLBAR_TRACK_COLOR:
break;
case CSS_PROP_SCROLLBAR_ARROW_COLOR:
break;
case CSS_PROP__KHTML_FLOW_MODE:
break;
case CSS_PROP__KHTML_USER_INPUT:
break;
case CSS_PROP_TEXT_OVERFLOW:
if (style->textOverflow()) {
return new CSSPrimitiveValueImpl(CSS_VAL_ELLIPSIS);
} else {
return new CSSPrimitiveValueImpl(CSS_VAL_CLIP);
}
break;
default:
qCWarning(KHTML_LOG) << "Unhandled property:" << getPropertyName(propertyID);
//Q_ASSERT( 0 );
break;
}
return nullptr;
}
#undef RETURN_NULL_ON_NULL
DOMString RenderStyleDeclarationImpl::getPropertyValue(int propertyID) const
{
CSSValueImpl *value = getPropertyCSSValue(propertyID);
if (value) {
DOMString val = value->cssText();
delete value;
return val;
}
return "";
}
bool RenderStyleDeclarationImpl::getPropertyPriority(int) const
{
// All computed styles have a priority of false (not "important").
return false;
}
void RenderStyleDeclarationImpl::removeProperty(int, DOM::DOMString *)
{
// ### emit error since we're read-only
}
bool RenderStyleDeclarationImpl::removePropertiesInSet(const int *, unsigned)
{
// ### emit error since we're read-only
return false;
}
bool RenderStyleDeclarationImpl::setProperty(int, const DOM::DOMString &, bool, int &ec)
{
ec = DOMException::NO_MODIFICATION_ALLOWED_ERR;
return false;
}
bool RenderStyleDeclarationImpl::setProperty(int, const DOM::DOMString &, bool)
{
// ### emit error since we're read-only
return false;
}
void RenderStyleDeclarationImpl::setProperty(int, int, bool)
{
// ### emit error since we're read-only
}
void RenderStyleDeclarationImpl::setLengthProperty(int, const DOM::DOMString &, bool,
bool)
{
// ### emit error since we're read-only
}
void RenderStyleDeclarationImpl::setProperty(const DOMString &)
{
// ### emit error since we're read-only
}
unsigned long RenderStyleDeclarationImpl::length() const
{
return numComputedProperties;
}
DOM::DOMString RenderStyleDeclarationImpl::item(unsigned long i) const
{
if (i >= numComputedProperties) {
return DOMString();
}
return getPropertyName(computedProperties[i]);
}
CSSProperty RenderStyleDeclarationImpl::property(int id) const
{
CSSProperty prop;
prop.m_id = id;
prop.m_important = false;
CSSValueImpl *v = getPropertyCSSValue(id);
if (!v) {
v = new CSSPrimitiveValueImpl;
}
prop.setValue(v);
return prop;
}
| 35.90929 | 126 | 0.658939 | afarcat |
154c8ece419e263864e17e4c9f137c97bf481c64 | 1,955 | cpp | C++ | Source/Untitled_DeckRPG/Core/SummonerSaveData.cpp | JeffereyAEL/UntitledDeckRPG | e2935641957ba01645fdb0112eda5386b80fb919 | [
"Artistic-2.0"
] | null | null | null | Source/Untitled_DeckRPG/Core/SummonerSaveData.cpp | JeffereyAEL/UntitledDeckRPG | e2935641957ba01645fdb0112eda5386b80fb919 | [
"Artistic-2.0"
] | null | null | null | Source/Untitled_DeckRPG/Core/SummonerSaveData.cpp | JeffereyAEL/UntitledDeckRPG | e2935641957ba01645fdb0112eda5386b80fb919 | [
"Artistic-2.0"
] | null | null | null | #include "SummonerSaveData.h"
#include "Untitled_DeckRPG/Externals/DefinedDebugHelpers.h"
#include "Untitled_DeckRPG/InstanceClasses/StorableInstanceClasses/ArmorInstance.h"
#include "Untitled_DeckRPG/InstanceClasses/StorableInstanceClasses/SummonInstance.h"
USummonerSaveData::USummonerSaveData() {
Name = "UNINSTANTIATED_PLAYER";
Inventory = TArray<FStorableInstanceConfig>();
bValidSave = false;
}
void USummonerSaveData::SetPlayerData(FSummonerPersistentData summoner) {
for (auto storable_instance : summoner.Inventory)
{
Inventory.Add(storable_instance->Config);
}
Name = summoner.Name;
// TODO: add in deck save functionality
bValidSave = true;
}
FSummonerPersistentData USummonerSaveData::GetPlayerData(APlayerController* controller) const {
FSummonerPersistentData temp_data{};
temp_data.Name = Name;
for (auto config : Inventory)
{
UStorableInstance* new_instance = nullptr;
switch(config.StorableType)
{
case StorableType_Armor:
new_instance = NewObject<UStorableInstance>(controller,
UArmorInstance::StaticClass());
break;
case StorableType_Summon:
new_instance = NewObject<UStorableInstance>(controller,
USummonInstance::StaticClass());
break;
default:
break;
}
if (!IsValid(new_instance))
{
#if WITH_EDITOR
SCREENMSGT("Storable Instance construction from GetData() failed", 10);
#endif
return FSummonerPersistentData{};
}
if (config.StorableType != StorableType_None)
new_instance->PostConstruction(config.AssetIDString,
config.Level, config.Rank);
temp_data.Inventory.Add(new_instance);
}
return temp_data;
}
void USummonerSaveData::PostConstruction(FSummonerPersistentData data) {
SetPlayerData(data);
}
| 32.04918 | 95 | 0.679795 | JeffereyAEL |
155143521decbd3e38477d5c3dec7bdc2dd834df | 2,089 | cpp | C++ | Modules/ModelFit/src/Common/mitkModelGenerator.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/ModelFit/src/Common/mitkModelGenerator.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/ModelFit/src/Common/mitkModelGenerator.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkModelGenerator.h"
#include "mitkIModelFitProvider.h"
#include "usModuleContext.h"
#include "usGetModuleContext.h"
mitk::IModelFitProvider* mitk::ModelGenerator::GetProviderService(const ModelClassIDType& id)
{
mitk::IModelFitProvider* result = nullptr;
std::string filter = "(" + mitk::IModelFitProvider::PROP_MODEL_CLASS_ID() + "=" + id + ")";
std::vector<us::ServiceReference<mitk::IModelFitProvider> > providerRegisters = us::GetModuleContext()->GetServiceReferences<mitk::IModelFitProvider>(filter);
if (!providerRegisters.empty())
{
if (providerRegisters.size() > 1)
{
MITK_WARN << "Multiple provider for class id'"<<id<<"' found. Using just one.";
}
result = us::GetModuleContext()->GetService<mitk::IModelFitProvider>(providerRegisters.front());
}
return result;
};
mitk::ModelGenerator::ModelGenerator()
= default;
mitk::ModelGenerator::~ModelGenerator()
= default;
mitk::ModelFactoryBase::Pointer mitk::ModelGenerator::GetModelFactory(const ModelClassIDType& id)
{
mitk::ModelFactoryBase::Pointer factory = nullptr;
auto service = GetProviderService(id);
if (service)
{
factory = service->GenerateFactory();
}
return factory;
}
mitk::ModelParameterizerBase::Pointer mitk::ModelGenerator::GenerateModelParameterizer(
const modelFit::ModelFitInfo& fit)
{
mitk::ModelParameterizerBase::Pointer result = nullptr;
mitk::ModelFactoryBase::Pointer factory = GetModelFactory(fit.functionClassID);
if (factory.IsNotNull())
{
result = factory->CreateParameterizer(&fit);
}
return result;
}
| 27.12987 | 160 | 0.696027 | wyyrepo |
1551a3b4d48a4f71fbfb4378aa467e1f43408517 | 14,407 | cpp | C++ | libraries/model/test/src/ModelTransformerTest.cpp | awf/ELL | 25c94a1422efc41d5560db11b136f9d8f957ad41 | [
"MIT"
] | 2,094 | 2016-09-28T05:55:24.000Z | 2019-05-04T19:06:36.000Z | libraries/model/test/src/ModelTransformerTest.cpp | awesomemachinelearning/ELL | cb897e3aec148a1e9bd648012b5f53ab9d0dd20c | [
"MIT"
] | 213 | 2017-06-30T12:53:40.000Z | 2019-05-03T06:35:38.000Z | libraries/model/test/src/ModelTransformerTest.cpp | awesomemachinelearning/ELL | cb897e3aec148a1e9bd648012b5f53ab9d0dd20c | [
"MIT"
] | 301 | 2017-03-24T08:40:00.000Z | 2019-05-02T21:22:28.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: ModelTransformerTest.cpp (model_test)
// Authors: Chuck Jacobs
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "ModelTransformerTest.h"
#include <model_testing/include/ModelTestUtilities.h>
#include <model/include/InputNode.h>
#include <model/include/Model.h>
#include <model/include/OutputNode.h>
#include <nodes/include/BinaryOperationNode.h>
#include <nodes/include/UnaryOperationNode.h>
#include <testing/include/testing.h>
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace ell;
using namespace ell::model;
using namespace ell::nodes;
using namespace ell::testing;
// prototypes of sub-tests
void TestCopySubmodel_Full(const Model& model);
void TestCopySubmodel_Prefix(const Model& model);
void TestCopySubmodel_DoublePrefix(const Model& model);
void TestCopySubmodelOnto_InPlace();
void TestCopySubmodelOnto_OutOfPlace();
void TestCopySubmodelOnto_PrefixInPlace();
void TestCopySubmodelOnto_PrefixOutOfPlace();
template <bool useDestModel>
void TestCopySubmodelOnto_MidsectionInPlace();
template <bool useDestModel>
void TestCopySubmodelOnto_MidsectionOutOfPlace();
void TestTransformSubmodelOnto_CopyInPlace();
void TestTransformSubmodelOnto_CopyOutOfPlace();
void TestTransformSubmodelOnto_CopyPrefixInPlace();
void TestTransformSubmodelOnto_CopyPrefixOutOfPlace();
void TestTransformSubmodelOnto_ModifyInPlace();
void TestTransformSubmodelOnto_ModifyOutOfPlace();
void TestTransformSubmodelInPlace_Copy();
void TestTransformSubmodelInPlace_CopyPrefix();
void TestTransformSubmodelInPlace_Modify();
namespace
{
const std::vector<const OutputPortBase*> noOutput = {};
} // namespace
// Transform functions
void CopyNode(const Node& node, ModelTransformer& transformer)
{
transformer.CopyNode(node);
}
class ModifyFirstDebugNode
{
public:
void operator()(const Node& node, ModelTransformer& transformer)
{
auto debugNode = dynamic_cast<const DebugNode<double, int>*>(&node);
if (debugNode == nullptr || _didModify)
{
transformer.CopyNode(node);
}
else
{
const auto& newInputs = transformer.GetCorrespondingInputs(debugNode->input);
auto newNode = transformer.AddNode<DebugNode<double, int>>(newInputs, 101);
transformer.MapNodeOutput(debugNode->output, newNode->output);
_didModify = true;
}
}
private:
bool _didModify = false;
};
// Tests
void
TestCopySubmodel()
{
// Tests the function:
//
// Model ModelTransformer::CopySubmodel(const Submodel& submodel, const TransformContext& context);
auto model = GetLinearDebugNodeModel(8); // in -> n1 -> n2 -> ... -> n8:out
FailOnException(TestCopySubmodel_Full, model);
FailOnException(TestCopySubmodel_Prefix, model);
FailOnException(TestCopySubmodel_DoublePrefix, model);
}
void TestCopySubmodelOnto()
{
// Tests the functions:
//
// Model ModelTransformer::CopySubmodelOnto(const Submodel& submodel, Model& destModel, const std::vector<const OutputPortBase*>& onto, const TransformContext& context);
// Model ModelTransformer::CopySubmodelOnto(const Submodel& submodel, const std::vector<const OutputPortBase*>& onto, const TransformContext& context);
FailOnException(TestCopySubmodelOnto_InPlace);
FailOnException(TestCopySubmodelOnto_OutOfPlace);
FailOnException(TestCopySubmodelOnto_PrefixInPlace);
FailOnException(TestCopySubmodelOnto_PrefixOutOfPlace);
FailOnException(TestCopySubmodelOnto_MidsectionInPlace<true>);
FailOnException(TestCopySubmodelOnto_MidsectionInPlace<false>);
FailOnException(TestCopySubmodelOnto_MidsectionOutOfPlace<true>);
FailOnException(TestCopySubmodelOnto_MidsectionOutOfPlace<false>);
}
void TestTransformSubmodelOnto()
{
// Tests the function:
//
// Submodel ModelTransformer::TransformSubmodelOnto(const Submodel& submodel, Model& destModel, const std::vector<const OutputPortBase*>& onto,
// const TransformContext& context, const NodeTransformFunction& transformFunction);
FailOnException(TestTransformSubmodelOnto_CopyInPlace);
FailOnException(TestTransformSubmodelOnto_CopyOutOfPlace);
FailOnException(TestTransformSubmodelOnto_CopyPrefixInPlace);
FailOnException(TestTransformSubmodelOnto_CopyPrefixOutOfPlace);
FailOnException(TestTransformSubmodelOnto_ModifyInPlace);
FailOnException(TestTransformSubmodelOnto_ModifyOutOfPlace);
}
void TestTransformSubmodelInPlace()
{
// Tests the function:
//
// Submodel ModelTransformer::TransformSubmodelOnto(const Submodel& submodel, const std::vector<const OutputPortBase*>& onto,
// const TransformContext& context, const NodeTransformFunction& transformFunction);
FailOnException(TestTransformSubmodelInPlace_Copy);
FailOnException(TestTransformSubmodelInPlace_CopyPrefix);
FailOnException(TestTransformSubmodelInPlace_Modify);
}
// Individual tests
void TestCopySubmodel_Full(const Model& model)
{
TransformContext context;
ModelTransformer transformer;
Submodel submodel(model);
auto newModel = transformer.CopySubmodel(submodel, context);
ProcessTest("TestCopySubmodel_Full", newModel.Size() == static_cast<int>(model.Size()));
}
void TestCopySubmodel_Prefix(const Model& model)
{
TransformContext context;
ModelTransformer transformer;
std::vector<const OutputPortBase*> outputs = { &FindDebugNode(model, 3)->output }; // in -> n1 -> n2 -> n3:out
Submodel submodel(outputs);
auto newModel = transformer.CopySubmodel(submodel, context);
ProcessTest("TestCopySubmodel_Prefix", newModel.Size() == 4);
}
void TestCopySubmodel_DoublePrefix(const Model& model)
{
TransformContext context;
ModelTransformer transformer;
std::vector<const OutputPortBase*> outputs = { &FindDebugNode(model, 3)->output, &FindDebugNode(model, 5)->output }; // in -> n1 -> n2 -> n3 -> n4 -> n5:out
Submodel submodel(outputs);
auto newModel = transformer.CopySubmodel(submodel, context);
ProcessTest("TestCopySubmodel_DoublePrefix", newModel.Size() == 6);
}
void TestCopySubmodelOnto_InPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
// Copy the submodel onto itself (should be a no-op)
Submodel fullSubmodel(srcModel);
transformer.CopySubmodelOnto(fullSubmodel, srcModel, noOutput, context);
ProcessTest("TestCopySubmodelOnto_InPlace", srcModel.Size() == oldSize);
}
void TestCopySubmodelOnto_OutOfPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
Model destModel;
TransformContext context;
ModelTransformer transformer;
Submodel submodel(srcModel);
transformer.CopySubmodelOnto(submodel, destModel, noOutput, context);
ProcessTest("TestCopySubmodelOnto_OutOfPlace", destModel.Size() == oldSize);
}
void TestCopySubmodelOnto_PrefixInPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
auto branchPoint = &FindDebugNode(srcModel, 1)->output;
Submodel submodel({ branchPoint });
transformer.CopySubmodelOnto(submodel, srcModel, noOutput, context);
ProcessTest("TestCopySubmodelOnto_PrefixInPlace", srcModel.Size() == oldSize);
}
void TestCopySubmodelOnto_PrefixOutOfPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
Model destModel;
TransformContext context;
ModelTransformer transformer;
auto branchPoint = &FindDebugNode(srcModel, 1)->output;
Submodel submodel({ branchPoint });
transformer.CopySubmodelOnto(submodel, destModel, noOutput, context);
ProcessTest("TestCopySubmodelOnto_PrefixOutOfPlace", destModel.Size() == 2);
}
template <bool useDestModel>
void TestCopySubmodelOnto_MidsectionInPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
auto midsectionInput = &FindDebugNode(srcModel, 2)->input;
auto midsectionOutput = &FindDebugNode(srcModel, 3)->output;
auto onto = &FindDebugNode(srcModel, 1)->output;
Submodel submodel({ midsectionInput }, { midsectionOutput });
if (useDestModel)
{
transformer.CopySubmodelOnto(submodel, srcModel, { onto }, context);
}
else
{
transformer.CopySubmodelOnto(submodel, { onto }, context);
}
auto newNode2 = FindDebugNode(srcModel, 2);
ProcessTest("TestCopySubmodelOnto_MidsectionInPlace", (srcModel.Size() == oldSize) && ((&newNode2->input.GetReferencedPort()) == onto));
}
template <bool useDestModel>
void TestCopySubmodelOnto_MidsectionOutOfPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto destModel = GetLinearDebugNodeModel(1);
auto oldSize = destModel.Size();
TransformContext context;
ModelTransformer transformer;
auto midsectionInput = &FindDebugNode(srcModel, 2)->input;
auto midsectionOutput = &FindDebugNode(srcModel, 3)->output;
auto onto = &FindDebugNode(destModel, 1)->output;
Submodel submodel({ midsectionInput }, { midsectionOutput });
if (useDestModel)
{
transformer.CopySubmodelOnto(submodel, destModel, { onto }, context);
}
else
{
transformer.CopySubmodelOnto(submodel, { onto }, context);
}
auto newNode2 = FindDebugNode(destModel, 2);
ProcessTest("TestCopySubmodelOnto_MidsectionOutOfPlace", (destModel.Size() == oldSize + 2) && ((&newNode2->input.GetReferencedPort()) == onto));
}
void TestTransformSubmodelOnto_CopyInPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
Submodel submodel(srcModel);
transformer.TransformSubmodelOnto(submodel, srcModel, noOutput, context, CopyNode);
ProcessTest("TestTransformSubmodelOnto_CopyInPlace", srcModel.Size() == oldSize);
}
void TestTransformSubmodelOnto_CopyOutOfPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
Model destModel;
TransformContext context;
ModelTransformer transformer;
Submodel submodel(srcModel);
transformer.TransformSubmodelOnto(submodel, destModel, noOutput, context, CopyNode);
ProcessTest("TestTransformSubmodelOnto_CopyOutOfPlace", destModel.Size() == oldSize);
}
void TestTransformSubmodelOnto_CopyPrefixInPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
auto branchPoint = &FindDebugNode(srcModel, 1)->output;
Submodel submodel({ branchPoint });
transformer.TransformSubmodelOnto(submodel, srcModel, noOutput, context, CopyNode);
ProcessTest("TestTransformSubmodelOnto_CopyPrefixInPlace", srcModel.Size() == oldSize);
}
void TestTransformSubmodelOnto_CopyPrefixOutOfPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
Model destModel;
TransformContext context;
ModelTransformer transformer;
auto branchPoint = &FindDebugNode(srcModel, 1)->output;
Submodel submodel({ branchPoint });
transformer.TransformSubmodelOnto(submodel, destModel, noOutput, context, CopyNode);
ProcessTest("TestTransformSubmodelOnto_CopyPrefixOutOfPlace", destModel.Size() == 2);
}
void TestTransformSubmodelOnto_ModifyInPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
Submodel submodel(srcModel);
// transforms first debug node to have an ID of 101, then copies the rest
auto oldNode1 = FindDebugNode(srcModel, 1);
transformer.TransformSubmodelOnto(submodel, srcModel, noOutput, context, ModifyFirstDebugNode());
auto newNode1 = FindDebugNode(srcModel, 101);
ProcessTest("TestTransformSubmodelOnto_ModifyInPlace", (srcModel.Size() == 2 * oldSize - 1) && ((&oldNode1->input.GetReferencedPort()) == (&newNode1->input.GetReferencedPort())));
}
void TestTransformSubmodelOnto_ModifyOutOfPlace()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
Model destModel;
TransformContext context;
ModelTransformer transformer;
Submodel submodel(srcModel);
transformer.TransformSubmodelOnto(submodel, destModel, noOutput, context, ModifyFirstDebugNode());
ProcessTest("TestTransformSubmodelOnto_ModifyOutOfPlace", destModel.Size() == oldSize);
}
void TestTransformSubmodelInPlace_Copy()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
Submodel submodel(srcModel);
transformer.TransformSubmodelOnto(submodel, srcModel, noOutput, context, CopyNode);
ProcessTest("TestTransformSubmodelInPlace_Copy", srcModel.Size() == oldSize);
}
void TestTransformSubmodelInPlace_CopyPrefix()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
auto branchPoint = &FindDebugNode(srcModel, 1)->output;
Submodel submodel({ branchPoint });
transformer.TransformSubmodelOnto(submodel, srcModel, noOutput, context, CopyNode);
ProcessTest("TestTransformSubmodelInPlace_CopyPrefix", srcModel.Size() == oldSize);
}
void TestTransformSubmodelInPlace_Modify()
{
auto srcModel = GetLinearDebugNodeModel(4);
auto oldSize = srcModel.Size();
TransformContext context;
ModelTransformer transformer;
Submodel submodel(srcModel);
auto oldNode1 = FindDebugNode(srcModel, 1);
transformer.TransformSubmodelOnto(submodel, srcModel, noOutput, context, ModifyFirstDebugNode());
auto newNode1 = FindDebugNode(srcModel, 101);
ProcessTest("TestTransformSubmodelInPlace_Modify", (srcModel.Size() == 2 * oldSize - 1) && ((&oldNode1->input.GetReferencedPort()) == (&newNode1->input.GetReferencedPort())));
}
| 34.549161 | 183 | 0.737905 | awf |
1553b6502b5cd6d959357abb9c636bef0377971d | 3,206 | cpp | C++ | Vorlesungsbeispiele/MRT2_VL-8_Ampel_mit_OPC_UA/src/Ampel_Behaviors.cpp | zmanjiyani/PLT_MRT_ARM-RPi2 | da77ab8ddf652a12ae6a6647c993daa2f94b39fb | [
"MIT"
] | 4 | 2015-11-11T14:02:17.000Z | 2021-11-29T16:07:38.000Z | Vorlesungsbeispiele/MRT2_VL-8_Ampel_mit_OPC_UA/src/Ampel_Behaviors.cpp | zmanjiyani/PLT_MRT_ARM-RPi2 | da77ab8ddf652a12ae6a6647c993daa2f94b39fb | [
"MIT"
] | 6 | 2019-04-20T14:48:58.000Z | 2020-08-26T15:13:02.000Z | Vorlesungsbeispiele/MRT2_VL-8_Ampel_mit_OPC_UA/src/Ampel_Behaviors.cpp | zmanjiyani/PLT_MRT_ARM-RPi2 | da77ab8ddf652a12ae6a6647c993daa2f94b39fb | [
"MIT"
] | 9 | 2016-01-10T15:14:28.000Z | 2021-10-13T22:45:19.000Z | /*
* Copyright (c) 2018 <copyright holder> <email>
*
* 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 "Ampel_Behaviors.h"
#include "Ampel.h"
void behavior_red(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
a->setRedLight(true);
a->setYellowLight(false);
a->setGreenLight(false);
}
void behavior_redtogreen(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
a->setRedLight(true);
a->setYellowLight(true);
a->setGreenLight(false);
}
void behavior_green(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
a->setRedLight(false);
a->setYellowLight(false);
a->setGreenLight(true);
}
void behavior_greentored(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
a->setRedLight(false);
a->setYellowLight(true);
a->setGreenLight(false);
}
void behavior_offline_check(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
a->setRedLight(false);
a->setYellowLight(true);
a->setGreenLight(false);
}
void behavior_offline(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
a->setRedLight(false);
a->setYellowLight(false);
a->setGreenLight(false);
}
bool guard_hasController(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
return a->hasController();
}
bool guard_hasNoController(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
return !(a->hasController());
}
bool guard_greenPhaseRequested(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
return (a->getPhaseCommand() == PHASE_GREEN);
}
bool guard_redPhaseRequested(const AutomatonElement& ae, const string& ActionID)
{
Ampel *a = static_cast<Ampel*>(ae.getHandle());
return (a->getPhaseCommand() == PHASE_RED);
}
| 31.431373 | 82 | 0.720524 | zmanjiyani |
1554aa5fb694fc3d5d0af6be1c7a5efb573e25f1 | 3,530 | cpp | C++ | Program07/courseClassDriver.cpp | jeremysteph/pancake-day | 8a875b8aa1e003493587a48056ee070285b966cf | [
"CC0-1.0"
] | 1 | 2020-09-27T07:53:59.000Z | 2020-09-27T07:53:59.000Z | Program07/courseClassDriver.cpp | jeremysteph/pancake-day | 8a875b8aa1e003493587a48056ee070285b966cf | [
"CC0-1.0"
] | null | null | null | Program07/courseClassDriver.cpp | jeremysteph/pancake-day | 8a875b8aa1e003493587a48056ee070285b966cf | [
"CC0-1.0"
] | null | null | null | #include "courseClassDriver.h"
#include <fstream>
int main(){
vector<Course> schedule;
char cinput[512];
string input;
cout << "Class Scheduler";
do{
cout << ': ';
cin.getline(cinput, 512);
input = cinput;
size_t size = wordCount(input);
if (size != 0){
string parsed[size];
parseInput(parsed, input, size);
string cmd = parsed[0];
if (cmd == "add") add(schedule, parsed, size);
else if (cmd == "clear") clear(schedule);
else if (cmd == "export"){
if (size == 2)exportSchedule(schedule, parsed[1]);
}
else if (cmd == "import"){
if (size == 2) importSchedule(schedule, parsed[1]);
}
else if (cmd == "remove"){
if (size == 3)remove(schedule, parsed[1], parsed[2]);
}
else if (cmd == "validate") validate(schedule);
else if (cmd == "quit"){}
else cout << "invalid command" << endl;
}
} while (input != "quit");
return 0;
}
void help(){
cout << "add <days> <start time> <end time> <course code> <section> <instructor>\n" << endl;
cout << "clear\n Delete all courses from the current schedule\n" << endl;
cout << "export <file name>\n Save the contents of schedule to text file\n" << endl;
cout << "import <file name>\n Read the contents of a schedule text file\n" << endl;
cout << "remove <course code> <section>\n" << endl;
cout << "validate\n Check the current schedule to determine whether any instructor is teaching courses at the same time\n" << endl;
cout << "quit" << endl;
}
void add(vector<Course>& s, const string* parsed, size_t size){
DaysOfWeek dow(parsed[1]);
DigitalTime start;
istringstream st, en;
st.str(parsed[2]);
start.input(st);
DigitalTime end;
en.str(parsed[3]);
end.input(en);
TimeInterval time(start, end);
s.push_back(Course(parsed[4], parsed[5], dow, time, parsed[6]));
}
void clear(vector<Course>& sch){
sch.clear();
}
void exportSchedule(const vector<Course>& s, string fileName){
ofstream outputs;
outputs.open(fileName.c_str());
vector<Course>::size_type sz = s.size();
for (unsigned int i = 0; i < sz; ++i){
s[i].output(outputs);
}
outputs.close();
}
void importSchedule(vector<Course>& s, string fileName){
ifstream input;
string line;
input.open(fileName.c_str());
while (getline(input, line)){
size_t size = wordCount(line);
string parsed[size];
parseInput(parsed, line, size);
add(s, parsed, size);
}
input.close();
}
void remove(vector<Course>& s, string courseCode, string sections){
vector<Course>::size_type sz = s.size();
for (unsigned int i = 0; i < sz; ++i){
if (s[i].getCourse() == courseCode && s[i].getSection() == sections)s.erase(s.begin() + (i));
}
}
void validate(const vector<Course>& s){
vector<Course>::size_type sz = s.size();
for (unsigned int i = 0; i < sz; ++i){
Course c = s[i];
for (unsigned int j = i + 1; j < sz; ++j){
if (s[j] == c) {
cout << "ERROR!\n";
c.output(cout);
cout << "overlaps with\n";
s[j].output(cout);
cout << endl;
}
}
}
}
void parseInput(string* parse, string input, size_t size){
string str = input;
char *pch, *cstr;
cstr = new char[input.size() + 1];
strcpy(cstr, input.c_str());
int index = 0;
pch = strtok(cstr, " <>");
while (pch != NULL)
{
parse[index] = pch;
++index;
pch = strtok(NULL, " <>");
}
}
int wordCount(string input){
int words = 1;
for (unsigned int i = 0; i < input.size(); ++i){
if (input[i] == ' ') ++words;
}
return words;
} | 27.795276 | 134 | 0.602266 | jeremysteph |
15570b15cfb1f385581154f9f946421bde72901b | 81 | cpp | C++ | TinyEngine/src/Platform/OpenGL/ImGuiBuildOpenGL.cpp | LongerZrLong/TinyEngine | c5b0d57e9724c765967ce091c503f81673d74986 | [
"Apache-2.0"
] | null | null | null | TinyEngine/src/Platform/OpenGL/ImGuiBuildOpenGL.cpp | LongerZrLong/TinyEngine | c5b0d57e9724c765967ce091c503f81673d74986 | [
"Apache-2.0"
] | null | null | null | TinyEngine/src/Platform/OpenGL/ImGuiBuildOpenGL.cpp | LongerZrLong/TinyEngine | c5b0d57e9724c765967ce091c503f81673d74986 | [
"Apache-2.0"
] | null | null | null | #define IMGUI_IMPL_OPENGL_LOADER_GLAD
#include <backends/imgui_impl_opengl3.cpp>
| 27 | 42 | 0.876543 | LongerZrLong |
155b56a25b7e733e6451d8aac8f3dd63c9019ea8 | 30,956 | cpp | C++ | src/filesystemmodel.cpp | Jawez/FileManager | 6d90f5f8b1757cd0d86ea0f81a7968b0dbb181aa | [
"MIT"
] | 10 | 2021-09-10T02:07:50.000Z | 2022-03-27T08:35:08.000Z | src/filesystemmodel.cpp | Jawez/FileManager | 6d90f5f8b1757cd0d86ea0f81a7968b0dbb181aa | [
"MIT"
] | null | null | null | src/filesystemmodel.cpp | Jawez/FileManager | 6d90f5f8b1757cd0d86ea0f81a7968b0dbb181aa | [
"MIT"
] | 3 | 2021-09-15T14:05:16.000Z | 2022-03-19T11:33:27.000Z | #include "filesystemmodel.h"
#include "progressdialog.h"
#include "settings.h"
#include <QtDebug>
#include <QFuture>
#include <QFileInfo>
#include <QModelIndex>
#include <QApplication>
#include <QProgressDialog>
#include <QtConcurrent>
#include <QMessageBox>
#include <QPushButton>
#include <QMimeData>
#include <QUrl>
#define MAX_COLUMN_NUMBER 6
FileSystemModel::FileSystemModel()
{
// connect(qApp->clipboard(), &QClipboard::changed, this, &FileSystemModel::onClipboardChanged);
// init mime info for cut, copy ...
modelMimeData = nullptr;
modelMimeAct = Qt::IgnoreAction;
}
FileSystemModel::~FileSystemModel()
{
this->cleanMimeData();
}
// handle shortcut info
QVariant FileSystemModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.model() != this)
return QVariant();
if (role == Qt::SizeHintRole) {
// qDebug() << QFileSystemModel::data(index, Qt::SizeHintRole).toSize(); // QSize(-1, -1)
return QSize(-1, ITEM_DEFAULT_HEIGHT);
}
if (role == Qt::EditRole || role == Qt::DisplayRole) {
QFileInfo info = fileInfo(index);
switch (index.column()) {
case 0: // displayName
if (info.isShortcut()) {
// qDebug() << QString("displayName %1").arg(info.completeBaseName());
return QVariant(info.completeBaseName());
}
break;
case 1: // size
if (info.isShortcut()) {
QFileInfo *shortcut = new QFileInfo(info.absoluteFilePath());
// qDebug() << QString("size %1").arg(shortcut->size());
return QVariant(shortcut->size());
}
break;
case 2: // type
break;
case 3: // time
// if (info.isShortcut()) {
// QFileInfo *shortcut = new QFileInfo(info.absoluteFilePath());
//// qDebug() << QString("time %1").arg(shortcut->birthTime());
// return QVariant(shortcut->birthTime());
// }
break;
}
}
return QFileSystemModel::data(index, role);
}
// handle translation
QVariant FileSystemModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role) {
case Qt::DecorationRole:
if (section == 0) {
// ### TODO oh man this is ugly and doesn't even work all the way!
// it is still 2 pixels off
QImage pixmap(16, 1, QImage::Format_ARGB32_Premultiplied);
pixmap.fill(Qt::transparent);
return pixmap;
}
break;
case Qt::TextAlignmentRole:
return Qt::AlignLeft;
}
if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
return QAbstractItemModel::headerData(section, orientation, role);
QString returnValue;
switch (section) {
case 0: returnValue = tr("Name");
break;
case 1: returnValue = tr("Size");
break;
case 2: returnValue =
#ifdef Q_OS_MAC
tr("Kind", "Match OS X Finder");
#else
tr("Type", "All other platforms");
#endif
break;
// Windows - Type
// OS X - Kind
// Konqueror - File Type
// Nautilus - Type
case 3: returnValue = tr("Date Modified");
break;
case 4: returnValue = tr("Row");
break;
case 5: returnValue = tr("Date Created");
break;
case 6: returnValue = tr("Number");
break;
default: return QVariant();
}
return returnValue;
}
static bool dirIsDotAndDotDot(const QString &dir)
{
return (dir == "." || dir == "..");
}
// handle drag data
QMimeData *FileSystemModel::mimeData(const QModelIndexList &indexes) const
{
QList<QUrl> urls;
QList<QModelIndex>::const_iterator it = indexes.begin();
for (; it != indexes.end(); ++it) {
if ((*it).column() == 0) {
// handle special index, for example ".", ".." and Drive
qDebug() << QString("mime name %1").arg((*it).data().toString());
// displayName
QString fileName = (*it).data().toString();
if (dirIsDotAndDotDot(fileName)) {
qDebug() << QString(".. continue");
continue;
}
// type
if ((*it).siblingAtColumn(2).data().toString() == "Drive") {
qDebug() << QString("Drive continue");
continue;
}
// // QFileSystemModel::filePath() with .lnk for file shortcut, no .lnk for dir shortcut
// urls << QUrl::fromLocalFile(filePath(*it));
// QFileInfo::filePath() with .lnk for all shortcuts
QString path = this->fileInfo(*it).filePath();
QFileInfo info(path);
if (info.isShortcut() && !info.exists()) {
qDebug() << QString("isShortcut not exists continue");
// showShortcutWarning(*it); // can not show message box when drag drop
continue;
}
urls << QUrl::fromLocalFile(path);
qDebug() << QString("mime %1").arg(path);
}
}
QMimeData *data = new QMimeData();
data->setUrls(urls);
return data;
}
// handle drop data
bool FileSystemModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent)
{
Q_UNUSED(row);
Q_UNUSED(column);
if (!parent.isValid() || isReadOnly())
return false;
// move target by default
action = Qt::MoveAction;
qDebug() << QString("modelDropMimeData action %1").arg(action);
#if USE_CUSTOM_DROP
QString to = QDir::fromNativeSeparators(QString("%1/").arg(filePath(parent)));
handleMimeDataPrivate(data, action, to, true);
return true;
#else
bool success = true;
QString to = filePath(parent) + QDir::separator();
QList<QUrl> urls = data->urls();
QList<QUrl>::const_iterator it = urls.constBegin();
switch (action) {
case Qt::CopyAction:
for (; it != urls.constEnd(); ++it) {
QString path = (*it).toLocalFile();
qDebug() << QString("drop %1").arg(path);
success = QFile::copy(path, to + QFileInfo(path).fileName()) && success;
}
break;
case Qt::LinkAction:
for (; it != urls.constEnd(); ++it) {
QString path = (*it).toLocalFile();
qDebug() << QString("drop %1").arg(path);
success = QFile::link(path, to + QFileInfo(path).fileName()) && success;
}
break;
case Qt::MoveAction:
for (; it != urls.constEnd(); ++it) {
QString path = (*it).toLocalFile();
qDebug() << QString("drop %1").arg(path);
success = QFile::rename(path, to + QFileInfo(path).fileName()) && success;
}
break;
default:
return false;
}
return success;
#endif // USE_CUSTOM_DROP
}
void FileSystemModel::refreshDir(const QString &dir)
{
// qDebug() << QString("refreshDir %1").arg(dir);
if (dir.isEmpty())
return;
if (QFileInfo(dir).isDir() && !QFileInfo(dir).isShortcut()) {
QString root = this->rootPath();
this->setRootPath(dir);
this->setRootPath(root);
}
}
QStringList FileSystemModel::dirEntryList(const QString &path)
{
QStringList list;
// QStringList filter;
// QDirIterator it(path, filter, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
QDirIterator it(path, QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs | QDir::System/* | QDir::Hidden*/, QDirIterator::Subdirectories);
list << QFileInfo(path).absoluteFilePath();
while (it.hasNext())
list << it.next();
// qDebug() << QString("dirEntryList list %1: ").arg(list.count()) << list;
return list;
}
static bool isSamePath(const QString &path1, const QString &path2)
{
return (QDir::fromNativeSeparators(path1) == QDir::fromNativeSeparators(path2));
}
bool FileSystemModel::moveTarget(const QString &srcPath, const QString &to, const QString &targetPath)
{
// cut
bool result = QFile::rename(srcPath, targetPath);
if (!result) {
qDebug() << QString("rename failed, try to copy");
// try to copy target, then remove old file
result = copyTarget(srcPath, to, targetPath);
if (result) {
this->remove(this->index(srcPath)); // remove old file
} else {
if (this->index(targetPath).isValid())
this->remove(this->index(targetPath)); // remove target if copy failed
}
}
qDebug() << QString("move target result %1").arg(result);
return result;
}
// this function will block when copy large file
bool FileSystemModel::copyTarget(const QString &srcPath, const QString &to, const QString &targetPath)
{
bool result = false;
QFileInfo info(srcPath);
if (!info.exists())
return false;
// handle target
if (info.isDir() && !info.isShortcut()) {
// list all sub target
QStringList srcList = dirEntryList(info.absoluteFilePath());
if (srcList.isEmpty()) {
return false;
}
QStringList targetList = srcList;
targetList.replaceInStrings(info.absoluteFilePath(), targetPath); // replace src dir to target dir
// mkdir or copy
for (int i = 0; i < targetList.count(); i++) {
QString copyResult;
QFileInfo srcInfo(srcList.at(i));
if (srcInfo.isDir() && !srcInfo.isShortcut()) {
bool result = QDir().mkpath(targetList.at(i));
copyResult = QString("mkpath %1 %2").arg(result).arg(targetList.at(i));
} else {
bool result = QFile::copy(srcList.at(i), targetList.at(i));
copyResult = QString("copy %1 %2->%3").arg(result).arg(srcList.at(i), targetList.at(i));
copyResult += QString("; %1 %2").arg(srcInfo.isDir(), !srcInfo.isShortcut());
}
// qDebug() << copyResult;
}
result = QFileInfo::exists(targetPath);
} else {
// copy
result = QFile::copy(srcPath, targetPath);
}
qDebug() << QString("copy target result %1").arg(result);
return result;
}
bool FileSystemModel::handleTargetConcurrent(const QString &srcPath, const QString &to, const QString &targetPath,
Qt::DropAction action, QWidget *dialog)
{
bool result = false;
ProgressDialog *progress = (ProgressDialog *)dialog;
// qDebug() << QString("handleTargetConcurrent action %1").arg(action);
QFuture<bool> future;
switch (action) {
case Qt::MoveAction:
future = QtConcurrent::run(this, &FileSystemModel::moveTarget, srcPath, to, targetPath);
break;
case Qt::CopyAction:
future = QtConcurrent::run(this, &FileSystemModel::copyTarget, srcPath, to, targetPath);
break;
default:
return false;
}
while (future.isRunning()) {
QCoreApplication::processEvents();
if (progress) {
if (progress->isCancel()) {
progress->waitStop(tr("Please wait for a moment..."));
}
}
}
result = future.result();
// qDebug() << QString("future result %1").arg(result);
if (progress) {
if (progress->wasCanceled()) {
progress->cancel();
qDebug() << QString("cancel progress");
}
}
return result;
}
bool FileSystemModel::deleteTarget(const QString &fileName)
{
bool result = false;
QFileInfo info(fileName);
qDebug() << QString("deleteTarget %1, %2").arg(info.exists()).arg(info.absolutePath());
if (info.exists() || info.isShortcut()) {
QString path = info.absolutePath();
result = QFile::moveToTrash(fileName);
qDebug() << QString("delete %1 result %2").arg(fileName).arg(result);
#if DISABLE_FILE_WATCHER
this->refreshDir(path);
#endif
}
return result;
}
void FileSystemModel::cleanMimeData()
{
qDebug() << QString("clean mimeData");
if (modelMimeData != nullptr) {
delete modelMimeData;
modelMimeData = nullptr;
}
modelMimeAct = Qt::IgnoreAction;
}
void FileSystemModel::setMimeData(const QModelIndexList &indexes, Qt::DropAction action)
{
if (indexes.isEmpty())
return;
if (action != Qt::MoveAction && action != Qt::CopyAction/* && action != Qt::LinkAction*/) {
qDebug() << QString("set mimeData action %1 error, return").arg(action);
return;
}
modelMimeData = this->mimeData(indexes);
modelMimeAct = action;
qApp->clipboard()->setMimeData(this->mimeData(indexes), QClipboard::Clipboard);
}
Qt::DropAction FileSystemModel::getMimeAct()
{
return modelMimeAct;
}
void FileSystemModel::handleMimeData(const QString &to, Qt::DropAction action)
{
const QMimeData *data = qApp->clipboard()->mimeData(QClipboard::Clipboard);
if (data == nullptr || data->urls().isEmpty()){ // data always not null
qDebug() << "no mimeData";
return;
}
if (modelMimeData == nullptr || data->urls() != modelMimeData->urls()) {
qDebug() << "mimeData changed: " << data << modelMimeData;
action = Qt::CopyAction;
}
if (action == Qt::IgnoreAction)
action = modelMimeAct;
if (action == Qt::IgnoreAction)
handleMimeDataPrivate(data, Qt::CopyAction, to);
else
handleMimeDataPrivate(data, action, to);
}
// private
bool FileSystemModel::handleMimeDataPrivate(const QMimeData *data, Qt::DropAction action, const QString &to, bool isDrop)
{
qDebug() << QString("handleMimeDataPrivate action %1, to %2").arg(action).arg(to);
if (action != Qt::MoveAction && action != Qt::CopyAction && action != Qt::LinkAction) {
return false;
}
if (data == nullptr)
return false;
if (to.isEmpty())
return false;
QList<QUrl> urls = data->urls();
qDebug() << QString("urls nums %1, to %2").arg(urls.count()).arg(to);
if (urls.isEmpty())
return false;
int currFile = 0;
int numFiles = urls.count();
bool showProgress = false; // !isDrop;
ProgressDialog *progress = nullptr;
bool handleResult = false;
QList<QUrl>::const_iterator it = urls.constBegin();
for (; it != urls.constEnd(); ++it) {
QString srcPath = (*it).toLocalFile();
QString targetPath = srcPath;
QFileInfo info(srcPath);
QString labelText = tr("Handling file number %1 of %2...").arg(currFile).arg(numFiles);
if (showProgress) {
// update progress dialog
progress->setProgress(labelText, currFile);
QCoreApplication::processEvents();
if (progress->wasCanceled()) {
qDebug() << QString("wasCanceled");
break;
}
}
bool result = false;
switch (action) {
case Qt::MoveAction: {
targetPath = to + info.fileName(); // with .lnk for all shortcuts
if (isSamePath(srcPath, targetPath)) {
qDebug() << QString("move path not change %1").arg(targetPath);
continue;
}
// not allow move parent folder to child folder
if (info.isDir() && targetPath.contains(srcPath + "/")) {
qDebug() << QString("targetPath %1 contain srcPath %2").arg(targetPath, srcPath);
continue;
}
if (!showProgress) {
if (!showMoveConfirmBox(data, to)) {
qDebug() << QString("user cancel move");
return false;
}
// qDebug() << QString("user confirm continue");
showProgress = true;
// init progress dialog
progress = new ProgressDialog("", tr("Abort"), 0, numFiles, Qt::ApplicationModal);
progress->setProgress(labelText, currFile);
}
// target already exist, not handle shortcut(can not ensure whether shortcut exist)
if (QFileInfo::exists(targetPath)) {
if (!showReplaceBox(targetPath))
continue;
}
#if !DISABLE_FILE_WATCHER
// remove model watcher
if (this->removeDirWatcher(srcPath))
#endif
{
// result = moveTarget(srcPath, to, targetPath);
result = handleTargetConcurrent(srcPath, to, targetPath, action, progress);
}
break;
}
case Qt::CopyAction: {
targetPath = QDir::fromNativeSeparators(to + info.fileName());
// target already exist, not handle shortcut(can not ensure whether shortcut exist)
if (QFileInfo::exists(targetPath)) {
qDebug() << QString("src %1, target %2").arg(srcPath, targetPath);
// not the same path, alert user
if (!isSamePath(srcPath, targetPath)) {
if (!showReplaceBox(targetPath))
continue;
}
}
// rename when targetPath exist
// if targetPath exist, then srcPath must equal to targetPath now(isSamePath(srcPath, targetPath))
for (int i = 1; QFileInfo::exists(targetPath); i++) {
QString name;
//: system file name
if (info.completeSuffix().isEmpty()) // dir or special file
name = tr("%1 - copy (%2)").arg(info.baseName()).arg(i);
else
name = tr("%1 - copy (%2).%3").arg(info.baseName()).arg(i).arg(info.completeSuffix());
targetPath = to + name;
}
if (!showProgress) {
showProgress = true;
progress = new ProgressDialog("", tr("Abort"), 0, numFiles, Qt::ApplicationModal);
progress->setProgress(labelText, currFile);
}
// result = copyTarget(srcPath, to, targetPath);
result = handleTargetConcurrent(srcPath, to, targetPath, action, progress);
break;
}
case Qt::LinkAction: {
// get symLinkTarget
if (info.isShortcut()) {
srcPath = info.symLinkTarget();
info.setFile(srcPath);
}
targetPath = to + info.fileName() + QString(" - shortcut.lnk");
// rename
for (int i = 1; QFileInfo::exists(targetPath); i++) {
QString name;
//: system file name
name = tr("%1 - shortcut (%2).lnk").arg(info.fileName()).arg(i); // example:text.txt - shortcut (1)
targetPath = to + name;
}
if (!showProgress) {
showProgress = true;
progress = new ProgressDialog("", tr("Abort"), 0, numFiles, Qt::ApplicationModal);
progress->setProgress(labelText, currFile);
}
// link
result = QFile::link(srcPath, targetPath);
break;
}
default:
qDebug() << QString("action error, break");
break;
}
currFile++;
#if DISABLE_FILE_WATCHER
// refresh dir
this->refreshDir(to);
QString from = info.absolutePath();
if (!isSamePath(to, from))
this->refreshDir(from);
#endif
qDebug() << QString("%1 to %2, result %3").arg(srcPath, targetPath).arg(result);
if (result) {
if (isDrop)
emit dropCompleted(to, targetPath);
else
emit pasteCompleted(to, targetPath);
handleResult = true;
}
}
if (showProgress && !progress->wasCanceled() && currFile >= numFiles) {
QString labelText = tr("Handling file number %1 of %1...").arg(numFiles);
progress->setProgress(labelText, numFiles);
}
if (action == Qt::MoveAction && handleResult) {
this->cleanMimeData();
qApp->clipboard()->clear(QClipboard::Clipboard);
}
if (progress) {
progress->deleteLater();
}
return handleResult;
}
void FileSystemModel::onClipboardChanged(QClipboard::Mode mode)
{
qDebug() << QString("onClipboardChanged %1").arg(mode);
// qDebug() << "data changed: " << qApp->clipboard()->mimeData(QClipboard::Clipboard) << modelMimeData;
// qDebug() << qApp->clipboard()->mimeData(QClipboard::Clipboard)->formats();
// qDebug() << qApp->clipboard()->mimeData(QClipboard::Clipboard)->text();
// qDebug() << qApp->clipboard()->mimeData(QClipboard::Clipboard)->urls();
}
// return false if cancel clicked
bool FileSystemModel::showMoveConfirmBox(const QMimeData *data, const QString &to)
{
QString allSrcPath;
QList<QUrl> urls = data->urls();
foreach (QUrl url, urls) {
QString path = url.toLocalFile();
allSrcPath.append(QString("\"%1\"<br>").arg(QDir::toNativeSeparators(path)));
}
const QString message = tr("<p>Move the following <b>%1</b> targets to \"%2\":</p>"
"%3")
.arg(urls.count()).arg(QDir::toNativeSeparators(to), allSrcPath);
QMessageBox msgBox;
//: message box for move targets
msgBox.setWindowTitle(tr("Move targets"));
msgBox.setText(message);
// msgBox.setIcon(QMessageBox::Information); // setIcon() will cause a beep when it shows
QPushButton *yesButton = msgBox.addButton(tr("&Yes"), QMessageBox::ActionRole);
QPushButton *noButton = msgBox.addButton(tr("&No"), QMessageBox::ActionRole);
msgBox.setDefaultButton(yesButton);
msgBox.setEscapeButton(noButton);
int ret = msgBox.exec();
// qDebug() << QString("msgBox ret %1").arg(ret);
if (msgBox.clickedButton() == yesButton) {
} else if (msgBox.clickedButton() == noButton) {
qDebug() << QString("user canceled the move");
return false;
}
return true;
}
bool FileSystemModel::showReplaceBox(const QString &path)
{
bool replace = false;
const QString message = tr("<p>Target already existed.</p>"
"<p>\"%1\"</p>"
"<p>Do you want to replace the old one?</p>")
.arg(path);
QMessageBox msgBox;
//: message box for replace old files for copy
msgBox.setWindowTitle(tr("Replace or skip"));
msgBox.setText(message);
msgBox.setIcon(QMessageBox::Information);
QPushButton *yesButton = msgBox.addButton(tr("&Yes"), QMessageBox::ActionRole);
QPushButton *noButton = msgBox.addButton(tr("&No"), QMessageBox::ActionRole);
msgBox.setDefaultButton(yesButton);
msgBox.setEscapeButton(noButton);
int ret = msgBox.exec();
if (msgBox.clickedButton() == yesButton) {
this->deleteTarget(path);
replace = true;
} else if (msgBox.clickedButton() == noButton) {
}
return replace;
}
void FileSystemModel::showShortcutInfo(const QModelIndex &index)
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Shortcut info"));
QString path = QDir::toNativeSeparators(QString("%1/%2").arg(this->fileInfo(index).absolutePath(), this->fileName(index)));
QString message = QDir::toNativeSeparators(this->fileInfo(index).symLinkTarget());
if (this->fileInfo(index).exists()) {
// msgBox.setIcon(QMessageBox::Information);
message = tr("<p><b>Shortcut:</b></p>%1"
"<p>Target exists:</p>%2").arg(path, message);
} else {
msgBox.setIcon(QMessageBox::Information);
message = tr("<p><b>Invalid shortcut:</b></p>%1"
"<p>Target not exists:</p>%2").arg(path, message);
}
msgBox.setText(message);
QPushButton *deleteButton = msgBox.addButton(tr("&Delete Shortcut"), QMessageBox::ActionRole);
QPushButton *okButton = msgBox.addButton(tr("&Ok"), QMessageBox::ActionRole);
// QPushButton *okButton = msgBox.addButton(QMessageBox::Ok);
msgBox.setDefaultButton(deleteButton);
msgBox.setEscapeButton(okButton);
int ret = msgBox.exec();
if (msgBox.clickedButton() == deleteButton) {
QString path = this->fileInfo(index).absoluteFilePath();
this->deleteTarget(path);
} else if (msgBox.clickedButton() == okButton) {
}
}
void FileSystemModel::showShortcutWarning(const QModelIndex &index) const
{
if (this->fileInfo(index).exists() || !this->fileInfo(index).isShortcut()) {
qDebug() << QString("target exist or is not shortcut, no warning");
return;
} else {
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Invalid shortcut"));
QString path = QDir::toNativeSeparators(QString("%1/%2").arg(this->fileInfo(index).absolutePath(), this->fileName(index)));
QString target = QDir::toNativeSeparators(this->fileInfo(index).symLinkTarget());
msgBox.setIcon(QMessageBox::Information);
QString message = tr("<p><b>Invalid shortcut:</b></p>%1"
"<p>Target not exists:</p>%2").arg(path, target);
msgBox.setText(message);
QPushButton *okButton = msgBox.addButton(tr("&Ok"), QMessageBox::ActionRole);
msgBox.setDefaultButton(okButton);
msgBox.exec();
}
}
static void displayNotificationMessage(const QString &title, const QString &text, QMessageBox::Icon icon)
{
QMessageBox msgBox;
msgBox.setWindowTitle(title);
msgBox.setText(text);
msgBox.setIcon(icon);
msgBox.addButton(FileSystemModel::tr("&Ok"), QMessageBox::ActionRole);
msgBox.exec();
}
static void displayFolderInUseMessage(const QString &dir)
{
const QString message =
FileSystemModel::tr("<p>Operation failed, some folders or files in this folder have been opened in another program.</p>"
"<p>Please close these folders or files and try again.</p>"
"%1")
.arg(dir);
displayNotificationMessage(FileSystemModel::tr("Folder is in use"),
message,
QMessageBox::Information);
}
// use QFileSystemModel::setData() remove watcher, then rename to srcName
bool FileSystemModel::removeDirWatcher(const QString &dir)
{
if (dir.isEmpty()) {
return false;
}
QFileInfo info(dir);
if (info.isDir() && !info.isShortcut()) {
QString name = info.fileName();
// rename to .../_name
QString tempName = QString("_%1").arg(name);
QString tempPath = QString("%1/%2").arg(info.absolutePath(), tempName);
// prevent tempName already exist, rename to .../i_name
for (int i = 1; QFileInfo::exists(tempPath); i++) {
tempName = QString("%1_%2").arg(i).arg(name);
tempPath = QString("%1/%2").arg(info.absolutePath(), tempName);
}
if (QFileSystemModel::setData(this->index(dir), QVariant(tempName))) {
qDebug() << QString("setData success %1->%2").arg(name, tempName);
// rename to .../name(restore the srcName)
if (QFile::rename(tempPath, dir)) {
qDebug() << QString("rename success %1").arg(dir);
return true;
}
}
} else {
return true; // return true if it is not a dir
}
displayFolderInUseMessage(dir);
return false;
}
static void displayRenameFailedMessage(const QString &newName, const QString &hint)
{
const QString message = FileSystemModel::tr("<b>The name \"%1\" cannot be used.</b>").arg(newName);
displayNotificationMessage(FileSystemModel::tr("Rename failed"),
QString("%1<br>%2").arg(message).arg(hint),
QMessageBox::Information);
}
// rename target
bool FileSystemModel::setData(const QModelIndex &idx, const QVariant &value, int role)
{
// data check in QFileSystemModel::setData()
if (!idx.isValid()
|| idx.column() != 0
|| role != Qt::EditRole
|| (flags(idx) & Qt::ItemIsEditable) == 0) {
return false;
}
QString newName = value.toString();
QString oldName = idx.data().toString();
if (newName == oldName)
return true;
const QString parentPath = filePath(parent(idx));
if (newName.isEmpty() || QDir::toNativeSeparators(newName).contains(QDir::separator())) {
QString hint = tr("<p>Invalid filename.</p>"
"<p>Try using another name, with fewer characters or no punctuation marks(can't use %1).</p>")
.arg("\\ / : * ? \" < > |"); // \ / : * ? " < > |
displayRenameFailedMessage(newName, hint);
return false;
}
// make sure target not exist
QString srcPath = QString("%1/%2").arg(parentPath, oldName);
QString targetPath = QString("%1/%2").arg(parentPath, newName);
if (QFileInfo::exists(targetPath)) {
QString hint = tr("<p>Filename already exists.</p><p>Try using another name.</p>");
displayRenameFailedMessage(newName, hint);
return false;
}
// qDebug() << QString("FileSystemModel setData");
#if DISABLE_FILE_WATCHER
// bool result = QFileSystemModel::setData(idx, value, role);
bool result = QDir(parentPath).rename(oldName, newName);
qDebug() << QString("setData result %1").arg(result);
if (result) {
const QString parentPath = filePath(parent(idx));
// used to update the view of the proxy model, file model's view auto update
this->refreshDir(parentPath);
} else {
QString hint = tr("<p>Please makesure the target is closed.</p>"
"<p>Try using another name, with fewer characters or no punctuation marks(can't use \\/:*?\"<>|).</p>");
displayRenameFailedMessage(newName, hint);
}
return result;
#else
QString tempName = QString("_%1").arg(newName);
QString tempPath = QString("%1/%2").arg(parentPath, tempName);
// prevent tempName already exist, rename to .../i_name
for (int i = 1; QFileInfo::exists(tempPath); i++) {
tempName = QString("%1_%2").arg(i).arg(newName);
tempPath = QString("%1/%2").arg(parentPath, tempName);
}
// rename to tempName, then rename to targetName
if (QFileSystemModel::setData(idx, QVariant(tempName), role)) {
bool result = QDir(parentPath).rename(tempName, newName);
qDebug() << QString("rename %1, %2->%3").arg(result).arg(tempName, newName);
// if rename failed, then restore the oldName
if (!result) {
QDir(parentPath).rename(tempName, oldName);
}
return result;
}
return false;
#endif // DISABLE_FILE_WATCHER
}
| 33.79476 | 147 | 0.579758 | Jawez |
155b65b8b11b38d1533ce920aa6cba640c56b6b0 | 1,555 | cpp | C++ | src/KthSmallestElementInABST.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | src/KthSmallestElementInABST.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | src/KthSmallestElementInABST.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "KthSmallestElementInABST.hpp"
#include <stack>
using namespace std;
int KthSmallestElementInABST::kthSmallest(TreeNode *root, int k) {
return kthSmallestRecursive(root, k);
}
int KthSmallestElementInABST::kthSmallestBinarySearch(TreeNode *root, int k) {
int n = countNodes(root->left);
if (k <= n)
return kthSmallestBinarySearch(root->left, k);
else if (k > n + 1)
return kthSmallestBinarySearch(root->right, k - n - 1);
return root->val;
}
int KthSmallestElementInABST::countNodes(TreeNode *root) {
if (root == nullptr)
return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
int KthSmallestElementInABST::kthSmallestIterative(TreeNode *root, int k) {
stack<TreeNode *> s;
TreeNode *cur = root;
while (!s.empty() || cur) {
if (cur) {
s.push(cur);
cur = cur->left;
} else {
cur = s.top();
s.pop();
k--;
if (k == 0) return cur->val;
cur = cur->right;
}
}
return -1;
}
int KthSmallestElementInABST::kthSmallestRecursive(TreeNode *root, int k) {
int ret = 0;
kthSmallestRecursive_helper(root, k, ret);
return ret;
}
void KthSmallestElementInABST::kthSmallestRecursive_helper(TreeNode *root, int &k, int &ret) {
if (root->left) kthSmallestRecursive_helper(root->left, k, ret);
k--;
if (k == 0) {
ret = root->val;
return;
}
if (root->right) kthSmallestRecursive_helper(root->right, k, ret);
} | 24.68254 | 94 | 0.607717 | yanzhe-chen |
155e22c12319b959134dee88fd481c9bc4cecef7 | 84,027 | cxx | C++ | net/winnet/enum.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/winnet/enum.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/winnet/enum.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1991 Microsoft Corporation
Module Name:
enum.cxx
Abstract:
Contains the entry points for the WinNet Enum API supported by the
Multi-Provider Router. The following functions are in this file:
WNetOpenEnumW
WNetEnumResourceW
WNetCloseEnum
MprOpenEnumConnect
MprOpenEnumNetwork
MprEnumConnect
MprEnumNetwork
MprProviderEnum
MprCopyResource
MprCopyProviderEnum
MprProviderOpen
MprOpenRemember
MprEnumRemembered
MprMultiStrBuffSize
Author:
Dan Lafferty (danl) 14-Oct-1991
Environment:
User Mode -Win32
Notes:
Revision History:
14-Oct-1991 danl
created
21-Sep-1992 KeithMo
Handle odd-sized buffers.
02-Nov-1992 danl
Fail with NO_NETWORK if there are no providers.
02-Mar-1995 anirudhs
Add support for RESOURCE_CONTEXT.
17-Jul-1995 anirudhs
Add recognition (but not true support) of RESOURCE_RECENT.
Clean up code for detecting top-level enum.
03-Aug-1995 anirudhs
WNetEnumResourceW: Allow a *lpcCount of 0.
15-Sep-1995 anirudhs
MprEnumRemembered: Fail after all resources have been enumerated.
24-Sep-1995 anirudhs
Add support for customization of the RESOURCE_CONTEXT enumeration
based on policy settings.
11-Apr-1996 anirudhs
Use CRoutedOperation in one case of WNetOpenEnumW.
16-Mar-1999 jschwart
Add support for RESOURCE_SHAREABLE
05-May-1999 jschwart
Make provider addition/removal dynamic
--*/
//
// INCLUDES
//
#include "precomp.hxx"
#include <memory.h> // memcpy
#include <lmcons.h> // needed for netlib.h
#include <regstr.h> // Registry keys and value names
//
// EXTERNALS
//
extern DWORD GlobalNumActiveProviders;
extern HMODULE hDLL;
//
// DATA STRUCTURES
//
//
// "Manually" align headers and put pointers first in ENUM
// structures to avoid Win64 alignment faults. Keep Key as
// the first field in the header so MPR knows where to check
// to see what type of enum it is.
//
typedef struct _CONNECT_HEADER
{
DWORD Key;
DWORD ReturnRoot;
DWORD dwNumProviders;
DWORD dwNumActiveProviders;
}
CONNECT_HEADER, *LPCONNECT_HEADER;
typedef struct _CONNECT_ENUM
{
HANDLE ProviderEnumHandle;
HINSTANCE hProviderDll; // Refcount the provider DLL
PF_NPEnumResource pfEnumResource;
PF_NPCloseEnum pfCloseEnum;
DWORD State;
}
CONNECT_ENUM, *LPCONNECT_ENUM;
typedef struct _NETWORK_HEADER
{
DWORD Key;
DWORD dwNumProviders;
DWORD dwNumActiveProviders;
DWORD dwPad;
}
NETWORK_HEADER, *LPNETWORK_HEADER;
typedef struct _NETWORK_ENUM
{
HINSTANCE hProviderDll;
LPNETRESOURCE lpnr;
DWORD State;
}
NETWORK_ENUM, *LPNETWORK_ENUM;
typedef struct _ENUM_HANDLE
{
DWORD Key;
DWORD dwPad;
HANDLE EnumHandle;
HINSTANCE hProviderDll;
PF_NPEnumResource pfEnumResource;
PF_NPCloseEnum pfCloseEnum;
}
ENUM_HANDLE, *LPENUM_HANDLE;
typedef struct _REMEMBER_HANDLE
{
DWORD Key;
DWORD dwPad;
HKEY ConnectKey;
DWORD KeyIndex;
DWORD ConnectionType;
}
REMEMBER_HANDLE, *LPREMEMBER_HANDLE;
//
// CONSTANTS
//
#define DONE 1
#define MORE_ENTRIES 2
#define NOT_OPENED 3
#define CONNECT_TABLE_KEY 0x6e6e4f63 // "cOnn"
#define STATE_TABLE_KEY 0x74417473 // "stAt"
#define PROVIDER_ENUM_KEY 0x764f7270 // "prOv"
#define REMEMBER_KEY 0x626D4572 // "rEmb"
#define REGSTR_PATH_NETWORK_POLICIES \
REGSTR_PATH_POLICIES L"\\" REGSTR_KEY_NETWORK
//
// Macros for rounding a value up/down to a WCHAR boundary.
// Note: These macros assume that sizeof(WCHAR) is a power of 2.
//
#define ROUND_DOWN(x) ((x) & ~(sizeof(WCHAR) - 1))
#define ROUND_UP(x) (((x) + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1))
//
// LOCAL FUNCTION PROTOTYPES
//
DWORD
MprCopyProviderEnum(
IN LPNETRESOURCEW ProviderBuffer,
IN OUT LPDWORD EntryCount,
IN OUT LPBYTE *TempBufPtr,
IN OUT LPDWORD BytesLeft
);
DWORD
MprCopyResource(
IN OUT LPBYTE *BufPtr,
IN const NETRESOURCEW *Resource,
IN OUT LPDWORD BytesLeft
);
DWORD
MprEnumNetwork(
IN OUT LPNETWORK_HEADER StateTable,
IN OUT LPDWORD NumEntries,
IN OUT LPVOID lpBuffer,
IN OUT LPDWORD lpBufferSize
);
DWORD
MprEnumConnect(
IN OUT LPCONNECT_HEADER ConnectEnumHeader,
IN OUT LPDWORD NumEntries,
IN OUT LPVOID lpBuffer,
IN OUT LPDWORD lpBufferSize
);
DWORD
MprOpenEnumNetwork(
OUT LPHANDLE lphEnum
);
DWORD
MprOpenEnumConnect(
IN DWORD dwScope,
IN DWORD dwType,
IN DWORD dwUsage,
IN LPNETRESOURCE lpNetResource,
OUT LPHANDLE lphEnum
);
DWORD
MprProviderEnum(
IN LPENUM_HANDLE EnumHandlePtr,
IN OUT LPDWORD lpcCount,
IN LPVOID lpBuffer,
IN OUT LPDWORD lpBufferSize
);
DWORD
MprOpenRemember(
IN DWORD dwType,
OUT LPHANDLE lphRemember
);
DWORD
MprEnumRemembered(
IN OUT LPREMEMBER_HANDLE RememberInfo,
IN OUT LPDWORD NumEntries,
IN OUT LPBYTE lpBuffer,
IN OUT LPDWORD lpBufferSize
);
DWORD
MprMultiStrBuffSize(
IN LPTSTR lpString1,
IN LPTSTR lpString2,
IN LPTSTR lpString3,
IN LPTSTR lpString4,
IN LPTSTR lpString5
) ;
class CProviderOpenEnum : public CRoutedOperation
{
public:
CProviderOpenEnum(
DWORD dwScope,
DWORD dwType,
DWORD dwUsage,
LPNETRESOURCEW lpNetResource,
LPHANDLE lphEnum
) :
CRoutedOperation(DBGPARM("ProviderOpenEnum")
PROVIDERFUNC(OpenEnum)),
_dwScope (dwScope ),
_dwType (dwType ),
_dwUsage (dwUsage ),
_lpNetResource(lpNetResource),
_lphEnum (lphEnum )
{ }
protected:
DWORD GetResult(); // overrides CRoutedOperation implementation
private:
DWORD _dwScope;
DWORD _dwType;
DWORD _dwUsage;
LPNETRESOURCEW _lpNetResource;
LPHANDLE _lphEnum;
HANDLE _ProviderEnumHandle; // Enum handle returned by provider
DECLARE_CROUTED
};
DWORD
WNetOpenEnumW (
IN DWORD dwScope,
IN DWORD dwType,
IN DWORD dwUsage,
IN LPNETRESOURCEW lpNetResource,
OUT LPHANDLE lphEnum
)
/*++
Routine Description:
This API is used to open an enumeration of network resources or existing
connections. It must be called to obtain a valid handle for enumeration.
NOTE:
For GlobalNet Enum, the caller must get a new handle for each level that
is desired. For the other scopes, the caller gets a single handle and
with that can enumerate all resources.
Arguments:
dwScope - Determines the scope of the enumeration. This can be one of:
RESOURCE_CONNECTED - All Currently connected resources.
RESOURCE_GLOBALNET - All resources on the network.
RESOURCE_REMEMBERED - All persistent connections.
RESOURCE_RECENT - Same as RESOURCE_REMEMBERED (supported for Win95
semi-compatibility)
RESOURCE_CONTEXT - The resources associated with the user's current
and default network context (as defined by the providers).
RESOURCE_SHAREABLE - All shareable resources on the given server
dwType - Used to specify the type of resources on interest. This is a
bitmask which may be any combination of:
RESOURCETYPE_DISK - All disk resources
RESOURCETYPE_PRINT - All print resources
If this is 0. all types of resources are returned. If a provider does
not have the capability to distinguish between print and disk
resources at a level, it may return all resources.
dwUsage - Used to specify the usage of resources of interest. This is a
bitmask which may be any combination of:
RESOURCEUSAGE_CONNECTABLE - all connectable resources.
RESOURCEUSAGE_CONTAINER - all container resources.
The bitmask may be 0 to match all.
lpNetResource - This specifies the container to perform the enumeration.
If it is NULL, the logical root of the network is assumed, and the
router is responsible for obtaining the information for return.
lphEnum - If the Open was successful, this will contain a handle that
can be used for future calls to WNetEnumResource.
Return Value:
WN_SUCCESS - Indicates the operation was successful.
WN_NOT_CONTAINER - Indicates that lpNetResource does not point to a
container.
WN_BAD_VALUE - Invalid dwScope or dwType, or bad combination of parameters
is specified.
WN_NO_NETWORK - network is not present.
--*/
{
DWORD status = WN_SUCCESS;
//
// dwScope MUST be set to either GLOBALNET or CONNECTED or REMEMBERED
// or RECENT or CONTEXT or SHAREABLE.
// This is verified in the switch statement below.
//
//
// dwType is a bit mask that can have any combination of the DISK
// or PRINT bits set. Or it can be the value 0.
//
if (dwType & ~(RESOURCETYPE_DISK | RESOURCETYPE_PRINT)) {
status = WN_BAD_VALUE;
goto CleanExit;
}
//
// dwUsage is a bit mask that can have any combination of the CONNECTABLE
// or CONTAINER bits set. Or it can be the value 0. This field is
// ignored if dwScope is not RESOURCE_GLOBALNET.
//
if (dwScope == RESOURCE_GLOBALNET) {
if (dwUsage & ~(RESOURCEUSAGE_ALL)) {
status = WN_BAD_VALUE;
goto CleanExit;
}
}
//
// Make sure the user passed in a valid OUT parameter
//
__try
{
PROBE_FOR_WRITE((LPDWORD)lphEnum);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
status = WN_BAD_POINTER;
}
if (status != WN_SUCCESS)
{
goto CleanExit;
}
//
// Check to see if it is a top-level enum request.
//
if (lpNetResource == NULL
||
(IS_EMPTY_STRING(lpNetResource->lpProvider) &&
IS_EMPTY_STRING(lpNetResource->lpRemoteName))
||
dwScope == RESOURCE_SHAREABLE)
{
//
// lpNetResource is NULL or represents no resource or this is
// a request for shareable resources.
// This is a top-level enum request, therefore, the MPR must provide
// the information.
//
switch(dwScope) {
case RESOURCE_CONNECTED:
case RESOURCE_CONTEXT:
case RESOURCE_SHAREABLE:
{
MprCheckProviders();
CProviderSharedLock PLock;
INIT_IF_NECESSARY(NETWORK_LEVEL,status);
if (MprNetIsAvailable()) {
status = MprOpenEnumConnect(dwScope,
dwType,
dwUsage,
lpNetResource,
lphEnum);
}
else
status = WN_NO_NETWORK ;
break;
}
case RESOURCE_GLOBALNET:
{
MprCheckProviders();
CProviderSharedLock PLock;
INIT_IF_NECESSARY(NETWORK_LEVEL,status);
if (MprNetIsAvailable()) {
status = MprOpenEnumNetwork(lphEnum);
}
else
status = WN_NO_NETWORK ;
break;
}
case RESOURCE_REMEMBERED:
case RESOURCE_RECENT:
MPR_LOG(TRACE,"OpenEnum RESOURCE_REMEMBERED\n",0);
status = MprOpenRemember(dwType, lphEnum);
break;
default:
status = WN_BAD_VALUE;
break;
}
}
else {
//
// Request is for one of the providers. It should be for a
// GLOBALNET enumeration. It is not allowed to request any
// other type of enumeration with a pointer to a resource
// buffer.
//
if (dwScope != RESOURCE_GLOBALNET) {
status = WN_BAD_VALUE;
goto CleanExit;
}
CProviderOpenEnum ProviderOpenEnum(
dwScope,
dwType,
dwUsage,
lpNetResource,
lphEnum);
status = ProviderOpenEnum.Perform(TRUE);
}
CleanExit:
if (status != WN_SUCCESS) {
SetLastError(status);
}
return(status);
}
DWORD
WNetEnumResourceW (
IN HANDLE hEnum,
IN OUT LPDWORD lpcCount,
OUT LPVOID lpBuffer,
IN OUT LPDWORD lpBufferSize
)
/*++
Routine Description:
This function is used to obtain an array of NETRESOURCE structures each
of which describes a network resource.
Arguments:
hEnum - This is a handle that was obtained from an WNetOpenEnum call.
lpcCount - Specifies the number of entries requested. -1 indicates
as many entries as possible are requested. If the operation is
successful, this location will receive the number of entries
actually read.
lpBuffer - A pointer to the buffer to receive the enumeration result,
which are returned as an array of NETRESOURCE entries. The buffer
is valid until the next call using hEnum.
lpBufferSize - This specifies the size of the buffer passed to the function
call. It will contain the required buffer size if WN_MORE_DATA is
returned.
Return Value:
WN_SUCCESS - Indicates that the call is successful, and that the caller
should continue to call WNetEnumResource to continue the enumeration.
WN_NO_MORE_ENTRIES - Indicates that the enumeration completed successfully.
The following return codes indicate an error occured and GetLastError
may be used to obtain another copy of the error code:
WN_MORE_DATA - Indicates that the buffer is too small for even one
entry.
WN_BAD_HANDLE - hEnum is not a valid handle.
WN_NO_NETWORK - The Network is not present. This condition is checked
for before hEnum is tested for validity.
History:
12-Feb-1992 Johnl Removed requirement that buffersize must be at
least as large as NETRESOURCEW (bug 5790)
--*/
{
DWORD status = WN_SUCCESS;
//
// Screen the parameters as best we can.
//
//
// Probe the handle
//
__try {
*(volatile DWORD *)hEnum;
}
__except(EXCEPTION_EXECUTE_HANDLER) {
status = GetExceptionCode();
if (status != EXCEPTION_ACCESS_VIOLATION) {
MPR_LOG(ERROR,"WNetEnumResource:Unexpected Exception 0x%lx\n",status);
}
status = WN_BAD_HANDLE;
}
__try {
PROBE_FOR_WRITE(lpcCount);
if (IS_BAD_BYTE_BUFFER(lpBuffer, lpBufferSize)) {
status = WN_BAD_POINTER;
}
}
__except (EXCEPTION_EXECUTE_HANDLER) {
status = GetExceptionCode();
if (status != EXCEPTION_ACCESS_VIOLATION) {
MPR_LOG(ERROR,"WNetEnumResource:Unexpected Exception 0x%lx\n",status);
}
status = WN_BAD_POINTER;
}
if (status != WN_SUCCESS) {
goto CleanExit;
}
switch(*(LPDWORD)hEnum){
case CONNECT_TABLE_KEY:
//
// Call on Providers to enumerate connections.
//
status = MprEnumConnect(
(LPCONNECT_HEADER)hEnum, // key is part of structure
lpcCount,
lpBuffer,
lpBufferSize);
break;
case STATE_TABLE_KEY:
//
// Enumerate the top level NetResource structure maintained by
// the router.
//
status = MprEnumNetwork(
(LPNETWORK_HEADER)hEnum,
lpcCount,
lpBuffer,
lpBufferSize);
break;
case PROVIDER_ENUM_KEY:
//
// Call on providers to enumerate resources on the network.
//
status = MprProviderEnum(
(LPENUM_HANDLE)hEnum, // key is part of structure
lpcCount,
lpBuffer,
lpBufferSize);
break;
case REMEMBER_KEY:
//
// Enumerate the connections in the current user section of the
// registry.
//
status = MprEnumRemembered(
(LPREMEMBER_HANDLE)hEnum,
lpcCount,
(LPBYTE)lpBuffer,
lpBufferSize);
break;
default:
status = WN_BAD_HANDLE;
}
CleanExit:
if(status != WN_SUCCESS) {
SetLastError(status);
}
return(status);
}
DWORD
WNetCloseEnum (
IN HANDLE hEnum
)
/*++
Routine Description:
Closes an enumeration handle that is owned by the router.
In cases where the router is acting as a proxy for a single provider,
an attempt is made to return any error information from this provider
back to the user. This makes the router as transparent as possible.
Arguments:
hEnum - This must be a handle obtained from a call to WNetOpenEnum.
Return Value:
WN_SUCCESS - The operation was successful.
WN_NO_NETWORK - The Network is not present. This condition is checked
before hEnum is tested for validity.
WN_BAD_HANDLE - hEnum is not a valid handle.
--*/
{
DWORD status = WN_SUCCESS;
DWORD i;
//
// Probe the handle
//
__try {
*(volatile DWORD *)hEnum;
}
__except(EXCEPTION_EXECUTE_HANDLER) {
status = GetExceptionCode();
if (status != EXCEPTION_ACCESS_VIOLATION) {
MPR_LOG(ERROR,"WNetCloseEnum:Unexpected Exception 0x%lx\n",status);
}
status = WN_BAD_HANDLE;
}
if (status != WN_SUCCESS) {
SetLastError(WN_BAD_HANDLE);
return(status);
}
//
// Use hEnum as a pointer and check the DWORD value at its location.
// If it contains a CONNECT_TABLE_KEY, we must close all handles to
// the providers before freeing the memory for the table.
// If it is a STATE_TABLE_KEY, we just free the memory.
//
switch(*(LPDWORD)hEnum){
case CONNECT_TABLE_KEY:
{
LPCONNECT_HEADER connectEnumHeader;
LPCONNECT_ENUM connectEnumTable;
connectEnumHeader = (LPCONNECT_HEADER)hEnum;
connectEnumTable = (LPCONNECT_ENUM)(connectEnumHeader + 1);
//
// Close all the open provider handles
//
MPR_LOG(TRACE,"Closing Connection Enum Handles from Providers\n",0);
for(i = 0; i < connectEnumHeader->dwNumProviders; i++) {
if((connectEnumTable[i].State != NOT_OPENED) &&
(connectEnumTable[i].pfCloseEnum != NULL))
{
status = connectEnumTable[i].pfCloseEnum(
connectEnumTable[i].ProviderEnumHandle);
if(status != WN_SUCCESS) {
//
// Because we are closing many handles at once, the failure
// is noted for debug purposes only.
//
MPR_LOG(ERROR,"WNetCloseEnum:(connect-provider #%d) failed\n",i);
MPR_LOG(ERROR,"WNetCloseEnum: error code = %d\n",status);
//
// Error information is returned if there is only one
// provider.
//
if (connectEnumHeader->dwNumProviders != 1) {
status = WN_SUCCESS;
}
}
//
// If this fires, the logic in MprOpenEnumConnect is wrong
//
ASSERT(connectEnumTable[i].hProviderDll != NULL);
FreeLibrary(connectEnumTable[i].hProviderDll);
}
else
{
//
// If this fires, the logic in MprOpenEnumConnect is wrong
// and we're not releasing a refcounted provider DLL
//
ASSERT(connectEnumTable[i].hProviderDll == NULL);
}
}
//
// Free the Table Memory
//
if (LocalFree(hEnum)) {
MPR_LOG(ERROR,"WNetCloseEnum:LocalFree(connect) failed %d\n",
GetLastError());
}
if (status != WN_SUCCESS)
{
SetLastError(status);
}
return(status);
}
case STATE_TABLE_KEY:
{
LPNETWORK_HEADER StateTableHeader;
LPNETWORK_ENUM StateTable;
//
// Free the State Table Memory.
//
MPR_LOG(TRACE,"Free State Table for Network Enum\n",0);
StateTableHeader = (LPNETWORK_HEADER)hEnum;
StateTable = (LPNETWORK_ENUM)(StateTableHeader + 1);
for (i = 0; i < StateTableHeader->dwNumProviders; i++)
{
if (StateTable[i].hProviderDll != NULL)
{
FreeLibrary(StateTable[i].hProviderDll);
LocalFree(StateTable[i].lpnr);
}
else
{
//
// If this fires, MprOpenEnumNetwork is causing a mem leak
//
ASSERT(StateTable[i].lpnr == NULL);
}
}
if (LocalFree(hEnum)) {
MPR_LOG(ERROR,"WNetCloseEnum:LocalFree(network) failed %d\n",
GetLastError());
}
return(WN_SUCCESS);
}
case PROVIDER_ENUM_KEY:
{
LPENUM_HANDLE enumHandle;
//
// Close the providers enumeration handle, and free the
// ENUM_HANDLE structure.
//
MPR_LOG(TRACE,"Closing Provider Enum Handle\n",0);
enumHandle = (LPENUM_HANDLE)hEnum;
ASSERT(enumHandle->pfCloseEnum != NULL);
status = (enumHandle->pfCloseEnum)(enumHandle->EnumHandle);
ASSERT(enumHandle->hProviderDll != NULL);
FreeLibrary(enumHandle->hProviderDll);
if (LocalFree(enumHandle) != 0) {
MPR_LOG(ERROR,"WNetCloseEnum:LocalFree(provider) failed %d\n",
GetLastError());
}
//
// Check the status returned from the Provider's CloseEnum
//
if(status != WN_SUCCESS) {
MPR_LOG(ERROR,"WNetCloseEnum:(provider) failed %d\n",status);
SetLastError(status);
}
return(status);
}
case REMEMBER_KEY:
{
LPREMEMBER_HANDLE rememberHandle;
rememberHandle = (LPREMEMBER_HANDLE)hEnum;
//
// Close the RegistryKey Handle associated with this handle.
//
if (rememberHandle->ConnectKey != NULL) {
RegCloseKey(rememberHandle->ConnectKey);
}
//
// Free up the memory for the handle.
//
if (LocalFree(rememberHandle) != 0) {
MPR_LOG(ERROR,"WNetCloseEnum:LocalFree(remember) failed %d\n",
GetLastError());
}
return(WN_SUCCESS);
}
default:
SetLastError(WN_BAD_HANDLE);
return(WN_BAD_HANDLE);
}
}
DWORD
MprOpenEnumConnect(
IN DWORD dwScope,
IN DWORD dwType,
IN DWORD dwUsage,
IN LPNETRESOURCE lpNetResource,
OUT LPHANDLE lphEnum
)
/*++
Routine Description:
This function handles the opening of connection enumerations and context
enumerations. It does this by sending an OpenEnum to all Providers, and
storing the returned handles in a table. The handle that is returned is
a pointer to this table.
The first DWORD in the table is a key that will help to identify a
correct table. The second DWORD is a Boolean value that tells whether
a NETRESOURCE structure representing the root of the network needs to be
returned in the enumeration.
Arguments:
dwScope - RESOURCE_CONNECTED, RESOURCE_CONTEXT, or RESOURCE_SHAREABLE
dwType -
dwUsage -
lpNetResource -
lphEnum - This is a pointer to a location where the handle for
the connection enumeration is to be stored.
Return Value:
WN_SUCCESS - The operation was successful.
WN_OUT_OF_MEMORY - The memory allocation for the handle was unsuccessful.
--*/
{
DWORD i;
DWORD status;
LPCONNECT_HEADER connectEnumHeader;
LPCONNECT_ENUM connectEnumTable;
LPPROVIDER provider;
BOOL fcnSupported = FALSE; // Is fcn supported by a provider?
BOOL atLeastOne=FALSE;
BOOL bDynamicEntries = TRUE; // Whether to show dynamic entries
// in the net neighborhood
HKEY hkPolicies = NULL;
ASSERT(dwScope == RESOURCE_CONNECTED
||
dwScope == RESOURCE_CONTEXT
||
dwScope == RESOURCE_SHAREABLE);
ASSERT_INITIALIZED(NETWORK);
//
// If there are no providers, return NO_NETWORK
//
if (GlobalNumActiveProviders == 0) {
return(WN_NO_NETWORK);
}
//
// Allocate the handle table with enough room for a header.
//
connectEnumHeader = (LPCONNECT_HEADER) LocalAlloc(
LPTR,
sizeof(CONNECT_HEADER) +
sizeof(CONNECT_ENUM) * GlobalNumProviders
);
if (connectEnumHeader == NULL) {
MPR_LOG(ERROR,"MprOpenEnumConnect:LocalAlloc Failed %d\n",GetLastError());
return(WN_OUT_OF_MEMORY);
}
//
// Initialize the key used in the connect table.
//
connectEnumHeader->Key = CONNECT_TABLE_KEY;
connectEnumHeader->ReturnRoot = FALSE;
connectEnumHeader->dwNumProviders = GlobalNumProviders;
connectEnumHeader->dwNumActiveProviders = GlobalNumActiveProviders;
connectEnumTable = (LPCONNECT_ENUM)(connectEnumHeader + 1);
//
// Check the policy on whether dynamic entries are to be shown in the
// network neighborhood. By default, they are shown.
//
if (dwScope == RESOURCE_CONTEXT)
{
if (MprOpenKey(
HKEY_CURRENT_USER,
REGSTR_PATH_NETWORK_POLICIES,
&hkPolicies,
KEY_READ))
{
bDynamicEntries = ! (MprGetKeyNumberValue(
hkPolicies,
REGSTR_VAL_NOWORKGROUPCONTENTS,
FALSE));
}
else
{
hkPolicies = NULL;
}
}
//
// Initialize all state flags for providers to the NOT_OPENED state, so
// we won't try to enumerate or close their handles unless we actually
// got handles from them.
// Initialize handles for the network providers by calling them with
// OpenEnum.
//
for(i=0; i<GlobalNumProviders; i++) {
connectEnumTable[i].State = NOT_OPENED;
provider = GlobalProviderInfo + i;
if ((provider->InitClass & NETWORK_TYPE) &&
(provider->OpenEnum != NULL)) {
if (dwScope == RESOURCE_CONTEXT)
{
DWORD dwCaps = provider->GetCaps(WNNC_ENUMERATION);
if (dwCaps & WNNC_ENUM_GLOBAL)
{
// A browsing network is present, so show root,
// even if network is down, and even if ENUM_CONTEXT
// isn't supported.
connectEnumHeader->ReturnRoot = TRUE;
}
if ((dwCaps & WNNC_ENUM_CONTEXT) == 0)
{
// This provider can't show hood entries, so skip it.
continue;
}
}
else if (dwScope == RESOURCE_SHAREABLE)
{
DWORD dwCaps = provider->GetCaps(WNNC_ENUMERATION);
if ((dwCaps & WNNC_ENUM_SHAREABLE) == 0)
{
// This provider can't show shareable resources, so skip it.
continue;
}
}
fcnSupported = TRUE;
if (bDynamicEntries)
{
//
// Refcount the provider
//
connectEnumTable[i].hProviderDll = LoadLibraryEx(provider->DllName,
NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (connectEnumTable[i].hProviderDll == NULL)
{
status = GetLastError();
//
// This can happen under extreme low memory conditions. The
// loader can sometimes return ERROR_MOD_NOT_FOUND in this case.
//
MPR_LOG2(ERROR,
"MprOpenEnumConnect: LoadLibraryEx on %ws FAILED %d\n",
provider->DllName,
status);
ASSERT(status == ERROR_NOT_ENOUGH_MEMORY || status == ERROR_MOD_NOT_FOUND);
continue;
}
connectEnumTable[i].pfEnumResource = provider->EnumResource;
connectEnumTable[i].pfCloseEnum = provider->CloseEnum;
status = provider->OpenEnum(
dwScope, // Scope
dwType, // Type
dwUsage, // Usage
(dwScope == RESOURCE_SHAREABLE ? lpNetResource : NULL), // NetResource
&(connectEnumTable[i].ProviderEnumHandle)); // hEnum
if (status != WN_SUCCESS) {
MPR_LOG(ERROR,"MprOpenEnumConnect:OpenEnum Failed %d\n",status);
MPR_LOG(ERROR,
"That was for the %ws Provider\n",
provider->Resource.lpProvider);
FreeLibrary(connectEnumTable[i].hProviderDll);
connectEnumTable[i].hProviderDll = NULL;
connectEnumTable[i].pfEnumResource = NULL;
connectEnumTable[i].pfCloseEnum = NULL;
}
else {
//
// At least one provider has returned a handle.
//
atLeastOne = TRUE;
//
// Set the state to MORE_ENTRIES, so we later enumerate from the
// handle and/or close it.
//
connectEnumTable[i].State = MORE_ENTRIES;
MPR_LOG(TRACE,"MprOpenEnumConnect: OpenEnum Handle = 0x%lx\n",
connectEnumTable[i].ProviderEnumHandle);
}
}
else
{
// Succeed the WNetOpenEnum but leave this provider as NOT_OPENED
atLeastOne = TRUE;
}
}
}
if (connectEnumHeader->ReturnRoot)
{
// Able to show the root object. Check the policy on whether
// to show it.
connectEnumHeader->ReturnRoot = ! (MprGetKeyNumberValue(
hkPolicies,
REGSTR_VAL_NOENTIRENETWORK,
FALSE));
fcnSupported = TRUE;
atLeastOne = TRUE;
}
if (hkPolicies)
{
RegCloseKey(hkPolicies);
}
if (fcnSupported == FALSE) {
//
// No providers in the list support the API function. Therefore,
// we assume that no networks are installed.
// Note that in this case, atLeastOne will always be FALSE.
//
status = WN_NOT_SUPPORTED;
}
//
// return the handle (pointer to connectEnumTable);
//
*lphEnum = connectEnumHeader;
if (atLeastOne == FALSE) {
//
// If none of the providers returned a handle, then return the
// status from the last provider.
//
*lphEnum = NULL;
LocalFree( connectEnumHeader);
return(status);
}
return(WN_SUCCESS);
}
DWORD
MprOpenEnumNetwork(
OUT LPHANDLE lphEnum
)
/*++
Routine Description:
This function handles the opening of net resource enumerations.
It does this by allocating a table of Provider State Flags and returning
a handle to that table. The state flags (or for each provider) will
be set to MORE_ENTRIES. Later, when enumerations take place, the state
for each provider is changed to DONE after the buffer is successfully
loaded with the the NETRESOURCE info for that provider.
Arguments:
lphEnum - This is a pointer to a location where the handle for
the network resource enumeration is to be stored.
Return Value:
WN_SUCCESS - The operation was successful.
WN_OUT_OF_MEMORY - The memory allocation for the handle was unsuccessful.
--*/
{
LPNETWORK_ENUM stateTable;
LPNETWORK_HEADER stateTableHeader;
DWORD i;
ASSERT_INITIALIZED(NETWORK);
//
// If there are no providers, return NO_NETWORK
//
if (GlobalNumActiveProviders == 0) {
return(WN_NO_NETWORK);
}
//
// Allocate the state table.
//
stateTableHeader = (LPNETWORK_HEADER) LocalAlloc(
LPTR,
sizeof(NETWORK_HEADER) +
sizeof(NETWORK_ENUM) * GlobalNumProviders
);
if (stateTableHeader == NULL) {
MPR_LOG(ERROR,"MprOpenEnumNetwork:LocalAlloc Failed %d\n",GetLastError());
return(WN_OUT_OF_MEMORY);
}
stateTableHeader->Key = STATE_TABLE_KEY;
stateTableHeader->dwNumProviders = GlobalNumProviders;
stateTableHeader->dwNumActiveProviders = GlobalNumActiveProviders;
stateTable = (LPNETWORK_ENUM)(stateTableHeader + 1);
//
// Initialize state flags for all network providers to the MORE_ENTRIES state.
//
for(i = 0; i < GlobalNumProviders; i++) {
if (GlobalProviderInfo[i].InitClass & NETWORK_TYPE)
{
if (GlobalProviderInfo[i].Handle != NULL)
{
stateTable[i].hProviderDll = LoadLibraryEx(GlobalProviderInfo[i].DllName,
NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (stateTable[i].hProviderDll == NULL)
{
DWORD status = GetLastError();
//
// This can happen under extreme low memory conditions. The
// loader can sometimes return ERROR_MOD_NOT_FOUND in this case.
//
MPR_LOG1(ERROR,
"MprOpenEnumNetwork: LoadLibraryEx on %ws FAILED\n",
GlobalProviderInfo[i].DllName);
ASSERT(status == ERROR_NOT_ENOUGH_MEMORY || status == ERROR_MOD_NOT_FOUND);
}
else
{
LPBYTE lpTempBuffer;
DWORD dwSize = 0;
DWORD dwStatus;
//
// Figure out how much space we'll need for the NETRESOURCE.
// It needs to be copied since the provider (and its resource)
// may go away between now and the WNetEnumResource call.
//
dwStatus = MprCopyResource(NULL,
&GlobalProviderInfo[i].Resource,
&dwSize);
ASSERT(dwStatus == WN_MORE_DATA);
stateTable[i].lpnr = (LPNETRESOURCE)LocalAlloc(LPTR, dwSize);
if (stateTable[i].lpnr == NULL)
{
MPR_LOG0(ERROR, "MprOpenEnumNetwork: LocalAlloc FAILED\n");
//
// Rather than fail silently in this case, bail out
//
for (UINT j = 0; j <= i; j++)
{
if (stateTable[j].hProviderDll)
{
FreeLibrary(stateTable[j].hProviderDll);
stateTable[j].hProviderDll = NULL;
stateTable[j].State = MORE_ENTRIES;
}
LocalFree(stateTable[j].lpnr);
}
LocalFree(stateTableHeader);
return(WN_OUT_OF_MEMORY);
}
else
{
lpTempBuffer = (LPBYTE)stateTable[i].lpnr;
dwStatus = MprCopyResource(&lpTempBuffer,
&GlobalProviderInfo[i].Resource,
&dwSize);
ASSERT(dwStatus == WN_SUCCESS);
}
}
}
stateTable[i].State = MORE_ENTRIES;
}
else {
stateTable[i].State = DONE;
}
}
//
// return the handle (pointer to stateTable);
//
*lphEnum = stateTableHeader;
return(WN_SUCCESS);
}
DWORD
MprEnumConnect(
IN OUT LPCONNECT_HEADER ConnectEnumHeader,
IN OUT LPDWORD NumEntries,
IN OUT LPVOID lpBuffer,
IN OUT LPDWORD lpBufferSize
)
/*++
Routine Description:
This function looks in the ConnectEnumTable for the next provider that
has MORE_ENTRIES. It begins requesting Enum Data from that provider -
each time copying data that is returned from the provider enum into the
users enum buffer (lpBuffer). This continues until we finish, or
we reach the requested number of elements, or the user buffer is full.
Each time we enumerate a provider to completion, that provider is
marked as DONE.
Note, for a context enumeration, the first NETRESOURCE returned in the
enumeration is a constant NETRESOURCE representing the root of the
network. This is done to make it easy for the shell to display a
"Rest of Network" object in a "Network Neighborhood" view.
Arguments:
ConnectEnumHeader - This is a pointer to a CONNECT_HEADER structure
followed by an array of CONNECT_ENUM structures. The ReturnRoot
member of the header tells whether the root object needs to be
returned at the start of the enumeration. On exit, if the root
object has been returned, the ReturnRoot member is set to FALSE.
NumEntries - On entry this points to the maximum number of entries
that the user desires to receive. On exit it points to the
number of entries that were placed in the users buffer.
lpBuffer - This is a pointer to the users buffer in which the
enumeration data is to be placed.
lpBufferSize - This is the size (in bytes) of the users buffer. It will
be set to the size of the required buffer size of WN_MORE_DATA is
returned.
Return Value:
WN_SUCCESS - This indicates that the call is returning some entries.
However, the enumeration is not complete due to one of the following:
1) There was not enough buffer space.
2) The requested number of entries was reached.
3) There is no more data to enumerate - the next call will
return WN_NO_MORE_ENTRIES.
WN_MORE_DATA - This indicates that the buffer was not large enough
to receive one enumeration entry.
WN_NO_MORE_ENTRIES - This indicates that there are no more entries
to enumerate. No data is returned with this return code.
WN_NO_NETWORK - If there are no providers loaded.
Note:
--*/
{
DWORD i; // provider index
DWORD status=WN_NO_MORE_ENTRIES;
DWORD entriesRead=0; // number of entries read into the buffer.
LPBYTE tempBufPtr; // pointer to top of remaining free buffer space.
LPNETRESOURCEW providerBuffer; // buffer for data returned from provider
DWORD bytesLeft; // Numer of bytes left in the buffer
DWORD entryCount; // number of entries read from provider
LPCONNECT_ENUM ConnectEnumTable = (LPCONNECT_ENUM) (ConnectEnumHeader + 1);
// Start of array
//
// If there are no providers, return NO_NETWORK
//
if (ConnectEnumHeader->dwNumActiveProviders == 0) {
return(WN_NO_NETWORK);
}
bytesLeft = ROUND_DOWN(*lpBufferSize);
tempBufPtr = (LPBYTE) lpBuffer;
//
// Check to see if there are any flags in state table that indicate
// MORE_ENTRIES. If not, we want to return WN_NO_MORE_ENTRIES.
//
for(i = 0; i < ConnectEnumHeader->dwNumProviders; i++) {
if(ConnectEnumTable[i].State == MORE_ENTRIES) {
break;
}
}
if ( (i == ConnectEnumHeader->dwNumProviders) && (! ConnectEnumHeader->ReturnRoot) ) {
*NumEntries = 0;
return(WN_NO_MORE_ENTRIES);
}
//
// If no entries are requested, we have nothing to do
//
if (*NumEntries == 0) {
return WN_SUCCESS;
}
//
// Allocate a buffer for the provider to return data in.
// The buffer size must equal the number of bytes left in the
// user buffer.
// (We can't have the provider write data directly to the caller's
// buffer because NPEnumResource is not required to place strings
// at the end of the buffer -- only at the end of the array of
// NETRESOURCEs.)
//
providerBuffer = (LPNETRESOURCEW) LocalAlloc(LPTR, bytesLeft);
if (providerBuffer == NULL) {
MPR_LOG(ERROR,"MprEnumConnect:LocalAlloc Failed %d\n",
GetLastError());
*NumEntries = 0;
return(WN_OUT_OF_MEMORY);
}
//
// Copy the root-of-network resource if required.
//
if (ConnectEnumHeader->ReturnRoot)
{
NETRESOURCEW RootResource = {
RESOURCE_GLOBALNET, // dwScope
RESOURCETYPE_ANY, // dwType
RESOURCEDISPLAYTYPE_ROOT, // dwDisplayType
RESOURCEUSAGE_CONTAINER, // dwUsage
NULL, // lpLocalName
NULL, // lpRemoteName
g_wszEntireNetwork, // lpComment
NULL // lpProvider
};
status = MprCopyResource(&tempBufPtr, &RootResource, &bytesLeft);
if (status == WN_SUCCESS)
{
entriesRead = 1;
ConnectEnumHeader->ReturnRoot = FALSE;
}
else
{
if (status == WN_MORE_DATA)
{
//
// Not even enough room for one NETRESOURCE
//
*lpBufferSize = bytesLeft;
}
goto CleanExit;
}
}
//
// Loop until we have copied from all Providers or until the
// the maximum number of entries has been reached.
//
for ( ; i < ConnectEnumHeader->dwNumProviders && entriesRead < *NumEntries; i++)
{
if (ConnectEnumTable[i].State != MORE_ENTRIES)
{
//
// Skip providers that don't have more entries
//
continue;
}
if (ConnectEnumTable[i].hProviderDll == NULL) {
//
// If the provider has not been initialized because it is
// not "ACTIVE", then skip it.
//
ConnectEnumTable[i].State = DONE;
status = WN_SUCCESS;
continue;
}
//
// Adjust the entry count for any entries that have been read
// so far.
//
entryCount = *NumEntries - entriesRead;
//
// Call the provider to get the enumerated data
//
status = ConnectEnumTable[i].pfEnumResource(
ConnectEnumTable[i].ProviderEnumHandle,
&entryCount,
providerBuffer,
&bytesLeft ); // (note, the provider updates
// bytesLeft only if it returns
// WN_MORE_DATA)
switch (status)
{
case WN_SUCCESS:
MPR_LOG(TRACE,"EnumResourceHandle = 0x%lx\n",
ConnectEnumTable[i].ProviderEnumHandle);
status = MprCopyProviderEnum(
providerBuffer,
&entryCount,
&tempBufPtr,
&bytesLeft);
entriesRead += entryCount;
if (status != WN_SUCCESS) {
//
// An internal error occured - for some reason the
// buffer space left in the user buffer was smaller
// than the buffer space that the provider filled in.
// The best we can do in this case is return what data
// we have. WARNING: the data that didn't make it
// will become lost since the provider thinks it
// enumerated successfully, but we couldn't do anything
// with it.
//
MPR_LOG(ERROR,
"MprEnumConnect:MprCopyProviderEnum Internal Error %d\n",
status);
if(entriesRead > 0) {
status = WN_SUCCESS;
}
goto CleanExit;
}
//
// We successfully placed all the received data from
// that provider into the user buffer. In this case,
// if we haven't reached the requested number of entries,
// we want to loop around and ask the same provider
// to enumerate more. This time the provider should
// indicate why it quit last time - either there are
// no more entries, or we ran out of buffer space.
//
break;
case WN_NO_MORE_ENTRIES:
//
// This Provider has completed its enumeration, mark it
// as done and increment to the next provider. We don't
// want to return NO_MORE_ENTRIES status. That should
// only be returned by the check at beginning or end
// of this function.
//
ConnectEnumTable[i].State = DONE;
status = WN_SUCCESS;
break;
case WN_MORE_DATA:
//
// This provider has more data, but there is not enough
// room left in the user buffer to place any more data
// from this provider. We don't want to go on to the
// next provider until we're finished with this one. So
// if we have any entries at all to return, we send back
// a SUCCESS status. Otherwise, the WN_MORE_DATA status
// is appropriate.
//
if(entriesRead > 0) {
status = WN_SUCCESS;
}
else
{
//
// If 0 entries were read, then the provider should
// have set bytesLeft with the required buffer size
//
*lpBufferSize = ROUND_UP(bytesLeft);
}
goto CleanExit;
break;
default:
//
// We received an unexpected error from the Provider Enum
// call.
//
MPR_LOG(ERROR,"MprEnumConnect:ProviderEnum Error %d\n",status);
if(entriesRead > 0) {
//
// If we have received data so far, ignore this error
// and move on to the next provider. This provider will
// be left in the MORE_ENTRIES state, so that on some other
// pass - when all other providers are done, this error
// will be returned.
//
status = WN_SUCCESS;
}
else{
//
// No entries have been read so far. We can return
// immediately with the error.
//
goto CleanExit;
}
} // end switch (status)
} // end for (each provider)
//
// If we looped through all providers and they are all DONE.
// If there were no connections, then return proper error code.
//
if ((entriesRead == 0) && (status == WN_SUCCESS)) {
status = WN_NO_MORE_ENTRIES;
}
CleanExit:
//
// Update the number of entries to be returned to user.
//
*NumEntries = entriesRead;
LocalFree(providerBuffer);
return(status);
}
DWORD
MprEnumNetwork(
IN OUT LPNETWORK_HEADER StateTableHeader,
IN OUT LPDWORD NumEntries,
IN OUT LPVOID lpBuffer,
IN OUT LPDWORD lpBufferSize
)
/*++
Routine Description:
This function Looks in the state table for the next provider that has
MORE_ENTRIES. It begins by copying the NETRESOURCE info for that one.
This continues until we finish, or we reach the requested number of
elements, or the buffer is full. Each time we copy a complete structure,
we mark that provider as DONE.
Arguments:
StateTable - This is a pointer to the state table that is managed by
the handle used in this request. The state table is a table of
flags used to indicate the enumeration state for a given
provider. These flags are in the same order as the provider
information in the GlobalProviderInfo Array. The state can be
either DONE or MORE_ENTRIES.
NumEntries - On entry this points to the maximum number of entries
that the user desires to receive. On exit it points to the
number of entries that were placed in the users buffer.
lpBuffer - This is a pointer to the users buffer in which the
enumeration data is to be placed.
lpBufferSize - This is the size (in bytes) of the users buffer.
Return Value:
WN_SUCCESS - This indicates that the call is returning some entries.
However, the enumeration is not complete due to one of the following:
1) There was not enough buffer space.
2) The requested number of entries was reached.
3) There is no more data to enumerate - the next call will
return WN_NO_MORE_ENTRIES.
WN_MORE_DATA - This indicates that the buffer was not large enough
to receive one enumeration entry.
WN_NO_MORE_ENTRIES - This indicates that there are no more entries
to enumerate. No data is returned with this return code.
Note:
CAUTION: "DONE" entries may appear anywhere in the statetable.
You cannot always rely on the fact that all of the entries
after a MORE_ENTRIES entry are also in the MORE_ENTRIES state.
This is because a provider that would not pass back a handle
at open time will be marked as DONE so that it gets skipped
at Enum Time.
--*/
{
DWORD i;
DWORD status;
DWORD entriesRead=0; // number of entries read into the buffer.
LPBYTE tempBufPtr; // pointer to top of remaining free buffer space.
DWORD bytesLeft; // num bytes left in free buffer space
LPNETWORK_ENUM StateTable = (LPNETWORK_ENUM)(StateTableHeader + 1);
//
// If there are no providers, return NO_NETWORK
//
if (StateTableHeader->dwNumActiveProviders == 0) {
return(WN_NO_NETWORK);
}
bytesLeft = ROUND_DOWN(*lpBufferSize);
tempBufPtr = (LPBYTE) lpBuffer;
//
// Check to see if there are any flags in state table that indicate
// MORE_ENTRIES. If not, we want to return WN_NO_MORE_ENTRIES.
//
for(i = 0; i < StateTableHeader->dwNumProviders; i++) {
if(StateTable[i].State == MORE_ENTRIES) {
break;
}
}
if ( i >= StateTableHeader->dwNumProviders ) {
*NumEntries = 0;
return(WN_NO_MORE_ENTRIES);
}
//
// Loop until we have copied from all Providers or until the
// the maximum number of entries has been reached.
//
for(; (i < StateTableHeader->dwNumProviders) && (entriesRead < *NumEntries); i++)
{
if (StateTable[i].State == MORE_ENTRIES) {
if (StateTable[i].hProviderDll == NULL)
{
//
// If the provider is not ACTIVE, skip it.
//
StateTable[i].State = DONE;
}
else
{
status = MprCopyResource(
&tempBufPtr,
StateTable[i].lpnr,
&bytesLeft);
if (status == WN_SUCCESS)
{
StateTable[i].State = DONE;
entriesRead++;
}
else
{
//
// The buffer must be full - so exit.
// If no entries are being returned, we will indicate
// that the buffer was not large enough for even one entry.
//
*NumEntries = entriesRead;
if (entriesRead > 0) {
return(WN_SUCCESS);
}
else {
*lpBufferSize = ROUND_UP(bytesLeft);
return(WN_MORE_DATA);
}
}
}
} // EndIf (state == MORE_ENTRIES)
} // EndFor (each provider)
//
// Update the number of entries to be returned to user
//
*NumEntries = entriesRead;
return(WN_SUCCESS);
}
DWORD
MprProviderEnum(
IN LPENUM_HANDLE EnumHandlePtr,
IN OUT LPDWORD lpcCount,
IN LPVOID lpBuffer,
IN OUT LPDWORD lpBufferSize
)
/*++
Routine Description:
This function calls the provider (identified by the EnumHandlePtr)
with a WNetEnumResource request. Aside from the EnumHandlePtr, all the
rest of the parameters are simply passed thru to the provider.
Arguments:
EnumHandlePtr - This is a pointer to an ENUM_HANDLE structure which
contains a pointer to the provider structure and the handle for
that provider's enumeration.
lpcCount - A pointer to a value that on entry contains the requested
number of elements to enumerate. On exit this contains the
actual number of elements enumerated.
lpBuffer - A pointer to the users buffer that the enumeration data
is to be placed into.
lpBufferSize - The number of bytes of free space in the user's buffer.
Return Value:
This function can return any return code that WNetEnumResource()
can return.
--*/
{
DWORD status;
ASSERT(EnumHandlePtr->pfEnumResource != NULL);
//
// Call the provider listed in the ENUM_HANDLE structure and ask it
// to enumerate.
//
status = EnumHandlePtr->pfEnumResource(
EnumHandlePtr->EnumHandle,
lpcCount,
lpBuffer,
lpBufferSize);
if (status == WN_SUCCESS) {
MPR_LOG(TRACE,"EnumResourceHandle = 0x%lx\n",
EnumHandlePtr->EnumHandle);
}
return(status);
}
DWORD
MprCopyResource(
IN OUT LPBYTE *BufPtr,
IN const NETRESOURCEW *Resource,
IN OUT LPDWORD BytesLeft
)
/*++
Routine Description:
This function copies a single NETRESOURCE structure into a buffer.
The structure gets copied to the top of the buffer, and the strings
that the structure references are copied to the bottom of the
buffer. So any remaining free buffer space is left in the middle.
Upon successful return from this function, BufPtr will point to
the top of this remaining free space, and BytesLeft will be updated
to indicate how many bytes of free space are remaining.
If there is not enough room in the buffer to copy the Resource and its
strings, an error is returned, and BufPtr is not changed.
Arguments:
BufPtr - This is a pointer to a location that upon entry, contains a
pointer to the buffer that the copied data is to be placed into.
Upon exit, this pointer location points to the next free location
in the buffer.
Resource - This points to the Resource Structure that is to be copied
into the buffer.
BytesLeft - This points to a location to where a count of the remaining
free bytes in the buffer is stored. This is updated on exit to
indicate the adjusted number of free bytes left in the buffer.
If the buffer is not large enough, and WN_MORE_DATA is returned, then
the size of the buffer required to fit all the data is returned in
this field.
Return Value:
WN_SUCCESS - The operation was successful
WN_MORE_DATA - The buffer was not large enough to contain the
Resource structure an its accompanying strings.
Note:
History:
02-Apr-1992 JohnL
Changed error return code to WN_MORE_DATA, added code to set the
required buffer size if WN_MORE_DATA is returned.
--*/
{
LPTSTR startOfFreeBuf;
LPTSTR endOfFreeBuf;
LPNETRESOURCEW newResource;
//
// The buffer must be at least large enough to hold a resource structure.
//
if (*BytesLeft < sizeof(NETRESOURCEW)) {
*BytesLeft = MprMultiStrBuffSize( Resource->lpRemoteName,
Resource->lpLocalName,
Resource->lpComment,
Resource->lpProvider,
NULL ) + sizeof(NETRESOURCEW) ;
return(WN_MORE_DATA);
}
//
// Copy the Resource structure into the beginning of the buffer.
//
newResource = (LPNETRESOURCEW) *BufPtr;
memcpy(newResource, Resource, sizeof(NETRESOURCEW));
startOfFreeBuf = (LPTSTR)((PCHAR)newResource + sizeof(NETRESOURCEW));
endOfFreeBuf = (LPTSTR)((LPBYTE)newResource + *BytesLeft);
//
// If a REMOTE_NAME string is to be copied, copy that and update the
// pointer in the structure.
//
if (Resource->lpRemoteName != NULL) {
//
// If we must copy the remote name,
//
if (!NetpCopyStringToBuffer(
Resource->lpRemoteName, // pointer to string
wcslen(Resource->lpRemoteName), // num chars in string
startOfFreeBuf, // start of open space
&endOfFreeBuf, // end of open space
&newResource->lpRemoteName)) { // where string pointer goes
*BytesLeft = MprMultiStrBuffSize( Resource->lpRemoteName,
Resource->lpLocalName,
Resource->lpComment,
Resource->lpProvider,
NULL ) ;
goto ErrorMoreData ;
}
}
else{
newResource->lpRemoteName = NULL;
}
//
// If a LOCAL_NAME string is to be copied, copy that and update the
// pointer in the structure.
//
if( ((Resource->dwScope == RESOURCE_CONNECTED) ||
(Resource->dwScope == RESOURCE_REMEMBERED))
&&
(Resource->lpLocalName != NULL) ) {
//
// If we must copy the local name,
//
if (!NetpCopyStringToBuffer(
Resource->lpLocalName, // pointer to string
wcslen(Resource->lpLocalName), // num chars in string
startOfFreeBuf, // start of open space
&endOfFreeBuf, // end of open space
&newResource->lpLocalName)) // where string pointer goes
{
goto ErrorMoreData ;
}
}
else{
newResource->lpLocalName = NULL;
}
//
// If a COMMENT string is to be copied, copy that and update the
// pointer in the structure.
//
if (Resource->lpComment != NULL) {
//
// If we must copy the comment string,
//
if (!NetpCopyStringToBuffer(
Resource->lpComment, // pointer to string
wcslen(Resource->lpComment), // num chars in string
startOfFreeBuf, // start of open space
&endOfFreeBuf, // end of open space
&newResource->lpComment)) // where string pointer goes
{
goto ErrorMoreData ;
}
}
else{
newResource->lpComment = NULL;
}
//
// If a PROVIDER string is to be copied, copy that and update the
// pointer in the structure.
//
if (Resource->lpProvider != NULL) {
//
// If we must copy the provider name,
//
if (!NetpCopyStringToBuffer(
Resource->lpProvider, // pointer to string
wcslen(Resource->lpProvider), // num chars in string
startOfFreeBuf, // start of open space
&endOfFreeBuf, // end of open space
&newResource->lpProvider)) // where string pointer goes
{
goto ErrorMoreData ;
}
}
else{
newResource->lpProvider = NULL;
}
//
// Update the returned information
//
*BufPtr = (LPBYTE)startOfFreeBuf;
*BytesLeft = (DWORD) ((LPBYTE) endOfFreeBuf - (LPBYTE) startOfFreeBuf);
return (WN_SUCCESS);
//
// This is reached when we couldn't fill the buffer because the given
// buffer size is too small. We therefore need to set the required
// buffer size before returning.
ErrorMoreData:
*BytesLeft = MprMultiStrBuffSize( Resource->lpRemoteName,
Resource->lpLocalName,
Resource->lpComment,
Resource->lpProvider,
NULL ) + sizeof(NETRESOURCEW) ;
return (WN_MORE_DATA);
}
DWORD
MprCopyProviderEnum(
IN LPNETRESOURCEW ProviderBuffer,
IN OUT LPDWORD EntryCount,
IN OUT LPBYTE *TempBufPtr,
IN OUT LPDWORD BytesLeft
)
/*++
Routine Description:
This function moves the enumerated NETRESOURCE structures that are
returned from a provider to a buffer that can be returned to the user.
The buffer that is returned to the user may contain enum data from
several providers. Because, we don't know how strings are packed in
the buffer that is returned from the provider, we must simply walk
through each structure and copy the information into the user buffer
in a format that we do know about. Then the amount of free space
left in the user buffer can be determined so that enum data from
another provider can be added to it.
Arguments:
ProviderBuffer - This is a pointer to the top of an array of NETRESOURCE
structures that is returned from one of the providers.
EntryCount - This points to the number of elements in the array that
was returned from the provider. On exit, this points to the number
of elements that was successfully copied. This should always be
the same as the number of elements passed in.
TempBufPtr - This is a pointer to the top of the free space in the user
buffer.
BytesLeft - Upon entry, this contains the number of free space bytes
in the user buffer. Upon exit, this contains the updated number
of free space bytes in the user buffer.
Return Value:
WN_SUCCESS - The operation was successful
WN_OUT_OF_MEMORY - The buffer was not large enough to contain all of
data the provider returned. This should never happen.
Note:
--*/
{
DWORD i;
DWORD status;
DWORD entriesRead=0;
//
// Loop for each element in the array of NetResource Structures.
//
for(i=0; i<*EntryCount; i++,ProviderBuffer++) {
status = MprCopyResource(
TempBufPtr,
ProviderBuffer,
BytesLeft);
if (status != WN_SUCCESS) {
MPR_LOG(ERROR,"MprCopyProviderEnum: Buffer Size Mismatch\n",0);
//
// The buffer must be full - this should never happen since
// the amount of data placed in the ProviderBuffer is limited
// by the number of bytes left in the user buffer.
//
ASSERT(0);
*EntryCount = entriesRead;
return(status);
}
entriesRead++;
}
*EntryCount = entriesRead;
return(WN_SUCCESS);
}
//===================================================================
// CProviderOpenEnum - open an enumeration by a provider
//===================================================================
DWORD
CProviderOpenEnum::ValidateRoutedParameters(
LPCWSTR * ppProviderName,
LPCWSTR * ppRemoteName,
LPCWSTR * ppLocalName
)
{
//
// Let the base class validate any specified provider name.
// Note: This must be done before setting _lpNetResource to NULL!
//
*ppProviderName = _lpNetResource->lpProvider;
//
// Check to see if a top level enumeration for the provider is requested.
// (This is different from a top level MPR enumeration.)
// A top level enum is signified by a net resource with either a special
// bit set in the dwUsage field, or a provider name but no remote name.
//
if ((_lpNetResource->dwUsage & RESOURCEUSAGE_RESERVED) ||
IS_EMPTY_STRING(_lpNetResource->lpRemoteName))
{
//
// Top level enum. Don't pass the net resource to the provider.
//
ASSERT(! IS_EMPTY_STRING(_lpNetResource->lpProvider));
_lpNetResource = NULL;
}
else
{
//
// Use the remote name as a hint to pick the provider order.
//
*ppRemoteName = _lpNetResource->lpRemoteName;
}
*ppLocalName = NULL;
return WN_SUCCESS;
}
DWORD
CProviderOpenEnum::TestProvider(
const PROVIDER * pProvider
)
{
ASSERT(MPR_IS_INITIALIZED(NETWORK));
if ((pProvider->GetCaps(WNNC_ENUMERATION) & WNNC_ENUM_GLOBAL) == 0)
{
return WN_NOT_SUPPORTED;
}
return ( pProvider->OpenEnum(
_dwScope,
_dwType,
_dwUsage,
_lpNetResource,
&_ProviderEnumHandle) );
}
DWORD
CProviderOpenEnum::GetResult()
{
//
// Let the base class try the providers until one responds
// CRoutedOperation::GetResult calls INIT_IF_NECESSARY
//
DWORD status = CRoutedOperation::GetResult();
if (status != WN_SUCCESS)
{
return status;
}
MPR_LOG(TRACE,"CProviderOpenEnum: OpenEnum Handle = 0x%lx\n",
_ProviderEnumHandle);
//
// Allocate memory to store the handle.
//
LPENUM_HANDLE enumHandleStruct =
(ENUM_HANDLE *) LocalAlloc(LPTR, sizeof(ENUM_HANDLE));
if (enumHandleStruct == NULL)
{
//
// If we can't allocate memory to store the handle
// away, then we must close it, and change the status
// to indicate a memory failure.
//
MPR_LOG(ERROR,"CProviderOpenEnum: LocalAlloc failed %d\n",
GetLastError());
LastProvider()->CloseEnum(_ProviderEnumHandle);
status = WN_OUT_OF_MEMORY;
}
else
{
//
// Store the handle in the ENUM_HANDLE structure and
// return the pointer to that structure as a handle
// for the user.
//
enumHandleStruct->Key = PROVIDER_ENUM_KEY;
//
// Refcount the provider
//
enumHandleStruct->hProviderDll = LoadLibraryEx(LastProvider()->DllName,
NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (enumHandleStruct->hProviderDll == NULL)
{
status = GetLastError();
//
// This can happen under extreme low memory conditions. The
// loader can sometimes return ERROR_MOD_NOT_FOUND in this case.
//
MPR_LOG2(ERROR,
"MprOpenEnumConnect: LoadLibraryEx on %ws FAILED %d\n",
LastProvider()->DllName,
status);
ASSERT(status == ERROR_NOT_ENOUGH_MEMORY || status == ERROR_MOD_NOT_FOUND);
LastProvider()->CloseEnum(_ProviderEnumHandle);
LocalFree(enumHandleStruct);
}
else
{
enumHandleStruct->pfEnumResource = LastProvider()->EnumResource;
enumHandleStruct->pfCloseEnum = LastProvider()->CloseEnum;
enumHandleStruct->EnumHandle = _ProviderEnumHandle;
*_lphEnum = enumHandleStruct;
}
}
return status;
}
DWORD
MprOpenRemember(
IN DWORD dwType,
OUT LPHANDLE lphRemember
)
/*++
Routine Description:
Arguments:
Return Value:
Note:
--*/
{
LPREMEMBER_HANDLE rememberInfo;
rememberInfo = (REMEMBER_HANDLE *) LocalAlloc(LPTR, sizeof(REMEMBER_HANDLE));
if (rememberInfo == NULL) {
MPR_LOG(ERROR,"MprOpenRemember:LocalAlloc Failed %d\n",GetLastError());
return(WN_OUT_OF_MEMORY);
}
rememberInfo->Key = REMEMBER_KEY;
rememberInfo->KeyIndex = 0;
rememberInfo->ConnectionType = dwType;
//
// Open the key to the connection information in the current user
// section of the registry.
//
// NOTE: If this fails, we must assume that there is no connection
// information stored. This is not an error condition.
// In this case, we store a NULL for the handle so that we know
// the situation. Each time EnumResource is called, we can try
// to open the key again.
//
if (!MprOpenKey(
HKEY_CURRENT_USER,
CONNECTION_KEY_NAME,
&(rememberInfo->ConnectKey),
DA_READ)) {
MPR_LOG(ERROR,"MprOpenRemember: MprOpenKey Failed\n",0);
rememberInfo->ConnectKey = NULL;
}
*lphRemember = (HANDLE)rememberInfo;
return(WN_SUCCESS);
}
DWORD
MprEnumRemembered(
IN OUT LPREMEMBER_HANDLE RememberInfo,
IN OUT LPDWORD NumEntries,
IN OUT LPBYTE lpBuffer,
IN OUT LPDWORD lpBufferSize
)
/*++
Routine Description:
Arguments:
RememberInfo - This is a pointer to REMEMBER_HANDLE data structure
that contains the context information for this enumeration handle.
NumEntries - On entry this points to the maximum number of entries
that the user desires to receive. On exit it points to the
number of entries that were placed in the users buffer.
lpBuffer - This is a pointer to the users buffer in which the
enumeration data is to be placed.
lpBufferSize - This is the size (in bytes) of the users buffer.
Return Value:
WN_SUCCESS - The call was successful, and some entries were returned.
However, there are still more entries to be enumerated.
WN_NO_MORE_ENTRIES - This function has no data to return because
there was no further connection information in the registry.
WN_CONNOT_OPEN_PROFILE - This function could open a key to the
connection information, but could not get any information about
that key.
WN_MORE_DATA - The caller's buffer was too small for even one entry.
Note:
History:
Changed to return "status" instead of WN_SUCCESS
--*/
{
DWORD status = WN_SUCCESS ;
LPTSTR userName;
NETRESOURCEW netResource;
LPBYTE tempBufPtr;
DWORD bytesLeft;
DWORD entriesRead = 0;
DWORD numSubKeys;
DWORD maxSubKeyLen;
DWORD maxValueLen;
if ((RememberInfo->ConnectKey == NULL) && (RememberInfo->KeyIndex == 0)) {
//
// If we failed to open the key at Open-time, attempt to open it
// now. This registry key is closed when the CloseEnum function is
// called.
//
if (!MprOpenKey(
HKEY_CURRENT_USER,
CONNECTION_KEY_NAME,
&(RememberInfo->ConnectKey),
DA_READ)) {
//
// We couldn't open the key. So we must assume that it doesn't
// exist because there if no connection information stored.
//
MPR_LOG(ERROR,"MprEnumRemembered: MprOpenKey Failed\n",0);
RememberInfo->ConnectKey = NULL;
return(WN_NO_MORE_ENTRIES);
}
}
//
// Find out the size of the largest key name.
//
if(!MprGetKeyInfo(
RememberInfo->ConnectKey,
NULL,
&numSubKeys,
&maxSubKeyLen,
NULL,
&maxValueLen)) {
MPR_LOG(ERROR,"MprEnumRemembered: MprGetKeyInfo Failed\n",0);
return(WN_CANNOT_OPEN_PROFILE);
}
//
// If we've already enumerated all the subkeys, there are no more entries.
//
if (RememberInfo->KeyIndex >= numSubKeys) {
return(WN_NO_MORE_ENTRIES);
}
tempBufPtr = lpBuffer;
bytesLeft = ROUND_DOWN(*lpBufferSize);
tempBufPtr = lpBuffer;
netResource.lpComment = NULL;
netResource.dwScope = RESOURCE_REMEMBERED;
netResource.dwUsage = 0;
netResource.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
//
// MprReadConnectionInfo may access the providers
//
MprCheckProviders();
CProviderSharedLock PLock;
while(
(RememberInfo->KeyIndex < numSubKeys) &&
(entriesRead < *NumEntries) &&
(bytesLeft > sizeof(NETRESOURCE))
)
{
//
// Get the connection info from the key and stuff it into
// a NETRESOURCE structure.
//
BOOL fMatch = FALSE;
DWORD ProviderFlags; // ignored
DWORD DeferFlags; // ignored
if(!MprReadConnectionInfo(
RememberInfo->ConnectKey,
NULL,
RememberInfo->KeyIndex,
&ProviderFlags,
&DeferFlags,
&userName,
&netResource,
NULL,
maxSubKeyLen)) {
//
// NOTE: The ReadConnectionInfo call could return FALSE
// if it failed in a memory allocation.
//
if (entriesRead == 0) {
status = WN_NO_MORE_ENTRIES;
}
else {
status = WN_SUCCESS;
}
break;
}
else
{
if ((netResource.dwType == RememberInfo->ConnectionType) ||
(RememberInfo->ConnectionType == RESOURCETYPE_ANY)) {
fMatch = TRUE;
}
}
//
// Copy the new netResource information into the user's
// buffer. Each time this function is called, the tempBufPtr
// gets updated to point to the next free space in the user's
// buffer.
//
if ( fMatch )
{
status = MprCopyResource(
&tempBufPtr,
&netResource,
&bytesLeft);
if (status != WN_SUCCESS) {
if (entriesRead == 0) {
*lpBufferSize = ROUND_UP(bytesLeft);
status = WN_MORE_DATA;
}
else {
status = WN_SUCCESS;
}
break;
}
entriesRead++;
}
//
// Free the allocated memory resources.
//
LocalFree(netResource.lpLocalName);
LocalFree(netResource.lpRemoteName);
LocalFree(netResource.lpProvider);
if (userName != NULL) {
LocalFree(userName);
}
(RememberInfo->KeyIndex)++;
}
*NumEntries = entriesRead;
return(status);
}
DWORD
MprMultiStrBuffSize(
IN LPTSTR lpString1,
IN LPTSTR lpString2,
IN LPTSTR lpString3,
IN LPTSTR lpString4,
IN LPTSTR lpString5
)
/*++
Routine Description:
This function is a worker function that simply determines the total
storage requirements needed by the passed set of strings. Any of the
strings maybe NULL in which case the string will be ignored.
The NULL terminator is added into the total memory requirements.
Arguments:
lpString1 -> 5 - Pointers to valid strings or NULL.
Return Value:
The count of bytes required to store the passed strings.
Note:
--*/
{
DWORD cbRequired = 0 ;
if ( lpString1 != NULL )
{
cbRequired += (wcslen( lpString1 ) + 1) * sizeof(TCHAR);
}
if ( lpString2 != NULL )
{
cbRequired += (wcslen( lpString2 ) + 1) * sizeof(TCHAR) ;
}
if ( lpString3 != NULL )
{
cbRequired += (wcslen( lpString3 ) + 1) * sizeof(TCHAR) ;
}
if ( lpString4 != NULL )
{
cbRequired += (wcslen( lpString4 ) + 1) * sizeof(TCHAR) ;
}
if ( lpString5 != NULL )
{
cbRequired += (wcslen( lpString5 ) + 1) * sizeof(TCHAR) ;
}
return cbRequired ;
}
BOOL
MprNetIsAvailable(
VOID)
/*++
Routine Description:
This function checks if the net is available by calling the GetCaps
of each provider to make sure it is started.
Arguments:
none
Return Value:
TRUE is yes, FALSE otherwise
Note:
--*/
{
DWORD status = WN_SUCCESS;
LPDWORD index;
DWORD indexArray[DEFAULT_MAX_PROVIDERS];
DWORD numProviders, i;
LPPROVIDER provider;
DWORD dwResult ;
//
// Find the list of providers to call for this request.
// If there are no active providers, MprFindCallOrder returns
// WN_NO_NETWORK.
//
index = indexArray;
status = MprFindCallOrder(
NULL,
&index,
&numProviders,
NETWORK_TYPE);
if (status != WN_SUCCESS)
return(FALSE);
//
// Loop through the list of providers, making sure at least one
// is started
//
ASSERT(MPR_IS_INITIALIZED(NETWORK));
for (i=0; i<numProviders; i++)
{
//
// Call the appropriate providers API entry point
//
provider = GlobalProviderInfo + index[i];
if (provider->GetCaps != NULL)
{
dwResult = provider->GetCaps( WNNC_START );
if (dwResult != 0)
{
if (index != indexArray)
LocalFree(index);
return (TRUE) ;
}
}
}
//
// If memory was allocated by MprFindCallOrder, free it.
//
if (index != indexArray)
LocalFree(index);
return(FALSE);
}
| 30.510893 | 99 | 0.542219 | npocmaka |
1560267c0994b59b55989bff706b1eb9fbdaaa4f | 343 | cpp | C++ | _code/pack-indexing/benchmark_1.erb.cpp | ldionne/ldionne.github.io | 9391dd54f00bd61046d60dbfeab31b13e8803d43 | [
"MIT"
] | null | null | null | _code/pack-indexing/benchmark_1.erb.cpp | ldionne/ldionne.github.io | 9391dd54f00bd61046d60dbfeab31b13e8803d43 | [
"MIT"
] | null | null | null | _code/pack-indexing/benchmark_1.erb.cpp | ldionne/ldionne.github.io | 9391dd54f00bd61046d60dbfeab31b13e8803d43 | [
"MIT"
] | null | null | null | // Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.
#include <cstddef>
#include <tuple>
#include <utility>
#include "<%= header %>"
<% (0..input_size-1).each do |n| %>
using T_<%= n %> = nth_element<
<%= n %>,
<%= (1..input_size).map { |i| "int" }.join(', ') %>
>;
<% end %>
| 21.4375 | 61 | 0.55102 | ldionne |
156166db872cb216b7cb2401c9b9af4fb738f355 | 7,212 | cpp | C++ | engine/source/engine/core/file-system/FileSystem.cpp | yhyu13/Engine2021 | 6ded548caa45bf980d88e09bed59431b61f5337e | [
"MIT"
] | null | null | null | engine/source/engine/core/file-system/FileSystem.cpp | yhyu13/Engine2021 | 6ded548caa45bf980d88e09bed59431b61f5337e | [
"MIT"
] | null | null | null | engine/source/engine/core/file-system/FileSystem.cpp | yhyu13/Engine2021 | 6ded548caa45bf980d88e09bed59431b61f5337e | [
"MIT"
] | null | null | null | #include "engine-precompiled-header.h"
#include "FileSystem.h"
#include "../exception/EngineException.h"
void longmarch::FileSystem::RegisterProtocol(const std::string& name, const fs::path& path)
{
s_pathProtocol[name] = path;
}
fs::path longmarch::FileSystem::ResolveSingleBackSlash(const std::string& path)
{
auto _path = path;
std::replace(_path.begin(), _path.end(), '\\', '/');
return fs::path(_path).make_preferred();
}
fs::path longmarch::FileSystem::ResolveProtocol(const fs::path& _path)
{
const auto& string_path = _path.string();
auto pos_1 = string_path.find('$', 0);
auto pos_2 = string_path.find(':', 1);
if (pos_1 != 0 || pos_2 == std::string::npos)
{
if (!string_path.empty())
{
PRINT("Path protocol cannot be resolve : " + string_path);
}
return _path;
}
pos_2 += 1; // Protocol includes the ':' char
const auto& root = string_path.substr(0, pos_2);
fs::path relative_path = string_path.substr(pos_2);
if (auto it = s_pathProtocol.find(root); it != s_pathProtocol.end())
{
auto result = it->second;
if (!relative_path.empty())
{
result = result / relative_path.make_preferred();
}
return result.make_preferred();
}
else
{
ENGINE_EXCEPT(L"Path protocol is not registered : " + str2wstr(string_path));
return _path;
}
}
fs::path longmarch::FileSystem::Absolute(const fs::path& path)
{
std::error_code ec;
fs::path result = Absolute(path, ec);
ENGINE_EXCEPT_IF(ec, L"ToAbsolute failed with " + wStr(ec));
return result.make_preferred();
}
fs::path longmarch::FileSystem::Absolute(const fs::path& p, std::error_code& ec)
{
ec.clear();
#if defined(WIN32) || defined(WINDOWS_APP)
if (p.empty()) {
return Absolute(CWD(ec), ec) / "";
}
ULONG size = ::GetFullPathNameW(p.wstring().c_str(), 0, 0, 0);
if (size) {
std::vector<wchar_t> buf(size, 0);
ULONG s2 = GetFullPathNameW(p.wstring().c_str(), size, buf.data(), nullptr);
if (s2 && s2 < size) {
fs::path result = fs::path(std::wstring(buf.data(), s2));
if (p.filename() == ".") {
result /= ".";
}
return result;
}
}
ec = std::error_code(::GetLastError(), std::system_category());
return fs::path();
#else
fs::path base = current_path(ec);
fs::path absoluteBase = base.is_absolute() ? base : absolute(base, ec);
if (!ec) {
if (p.empty()) {
return absoluteBase / p;
}
if (p.has_root_name()) {
if (p.has_root_directory()) {
return p;
}
else {
return p.root_name() / absoluteBase.root_directory() / absoluteBase.relative_path() / p.relative_path();
}
}
else {
if (p.has_root_directory()) {
return absoluteBase.root_name() / p;
}
else {
return absoluteBase / p;
}
}
}
ec = std::error_code(errno, std::system_category());
return fs::path();
#endif
}
fs::path longmarch::FileSystem::CWD()
{
std::error_code ec;
auto result = CWD(ec);
ENGINE_EXCEPT_IF(ec, L"Current Path failed with " + wStr(ec));
return result;
}
bool longmarch::FileSystem::ExistCheck(const fs::path& path, bool throwOnNotExist)
{
if (fs::exists(path))
{
return true;
}
else
{
if (throwOnNotExist)
{
ENGINE_EXCEPT(L"Path does not exist : " + path.wstring());
}
return false;
}
}
fs::path longmarch::FileSystem::CWD(std::error_code& ec)
{
ec.clear();
#if defined(WIN32) || defined(WINDOWS_APP)
DWORD pathlen = ::GetCurrentDirectoryW(0, 0);
std::unique_ptr<wchar_t[]> buffer(new wchar_t[pathlen + 1]);
if (::GetCurrentDirectoryW(pathlen, buffer.get()) == 0) {
ec = std::error_code(::GetLastError(), std::system_category());
return fs::path();
}
return fs::path(std::wstring(buffer.get()), fs::path::native_format);
#else
size_t pathlen = static_cast<size_t>(std::max(int(::pathconf(".", _PC_PATH_MAX)), int(PATH_MAX)));
std::unique_ptr<char[]> buffer(new char[pathlen + 1]);
if (::getcwd(buffer.get(), pathlen) == NULL) {
ec = std::error_code(errno, std::system_category());
return fs::path();
}
return fs::path(buffer.get());
#endif
}
std::ifstream& longmarch::FileSystem::OpenIfstream(const fs::path& _file, FileType type)
{
auto file = FileSystem::ResolveProtocol(_file).string();
atomic_flag_guard lock(s_IfFlag);
if (auto it = s_FileIStreamMap.find(file); it != s_FileIStreamMap.end())
{
// Rewind
it->second.clear();
it->second.seekg(0);
return it->second;
}
else
{
switch (type)
{
case longmarch::FileSystem::FileType::OPEN_BINARY:
s_FileIStreamMap[file] = std::ifstream(file, std::ifstream::in | std::ifstream::binary);
break;
case longmarch::FileSystem::FileType::OPEN_TEXT:
s_FileIStreamMap[file] = std::ifstream(file, std::ifstream::in);
break;
}
return s_FileIStreamMap[file];
}
}
void longmarch::FileSystem::CloseIfstream(const fs::path& _file)
{
auto file = FileSystem::ResolveProtocol(_file).string();
atomic_flag_guard lock(s_IfFlag);
if (auto it = s_FileIStreamMap.find(file); it != s_FileIStreamMap.end())
{
it->second.close();
s_FileIStreamMap.erase(it);
}
}
std::ofstream& longmarch::FileSystem::OpenOfstream(const fs::path& _file, FileType type)
{
auto file = FileSystem::ResolveProtocol(_file).string();
atomic_flag_guard lock(s_OfFlag);
if (auto it = s_FileOStreamMap.find(file); it != s_FileOStreamMap.end())
{
// Rewind
it->second.clear();
it->second.seekp(0);
return it->second;
}
else
{
switch (type)
{
case longmarch::FileSystem::FileType::OPEN_BINARY:
s_FileOStreamMap[file] = std::ofstream(file, std::ofstream::out | std::ofstream::binary);
break;
case longmarch::FileSystem::FileType::OPEN_TEXT:
s_FileOStreamMap[file] = std::ofstream(file, std::ofstream::out);
break;
}
return s_FileOStreamMap[file];
}
}
void longmarch::FileSystem::CloseOfstream(const fs::path& _file)
{
auto file = FileSystem::ResolveProtocol(_file).string();
atomic_flag_guard lock(s_OfFlag);
if (auto it = s_FileOStreamMap.find(file); it != s_FileOStreamMap.end())
{
it->second.close();
s_FileOStreamMap.erase(it);
}
}
Json::Value longmarch::FileSystem::GetNewJsonCPP(const fs::path& _file)
{
auto file = FileSystem::ResolveProtocol(_file).string();
Json::Value doc;
auto& stream = OpenIfstream(file, longmarch::FileSystem::FileType::OPEN_BINARY);
ENGINE_TRY_CATCH({ stream >> doc; });
CloseIfstream(file);
return doc;
}
Json::Value& longmarch::FileSystem::GetCachedJsonCPP(const fs::path& _file)
{
auto file = FileSystem::ResolveProtocol(_file).string();
atomic_flag_guard lock(s_jsonFlag);
if (auto it = s_jsonCPPParserMap.find(file); it == s_jsonCPPParserMap.end())
{
Json::Value doc;
auto& stream = OpenIfstream(file, longmarch::FileSystem::FileType::OPEN_BINARY);
ENGINE_TRY_CATCH({ stream >> doc; });
CloseIfstream(file);
s_jsonCPPParserMap[file] = std::move(doc);
}
return s_jsonCPPParserMap[file];
}
void longmarch::FileSystem::RemoveCachedJsonCPP(const fs::path& _file)
{
auto file = FileSystem::ResolveProtocol(_file).string();
atomic_flag_guard lock(s_jsonFlag);
s_jsonCPPParserMap.erase(file);
} | 28.062257 | 109 | 0.660288 | yhyu13 |
1561dfb9a7429631b23844559f81a32a111a73c8 | 7,259 | cc | C++ | mojo/public/cpp/bindings/lib/control_message_proxy.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | mojo/public/cpp/bindings/lib/control_message_proxy.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | mojo/public/cpp/bindings/lib/control_message_proxy.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/public/cpp/bindings/lib/control_message_proxy.h"
#include <stddef.h>
#include <stdint.h>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "mojo/public/cpp/bindings/lib/message_builder.h"
#include "mojo/public/cpp/bindings/lib/serialization.h"
#include "mojo/public/cpp/bindings/lib/validation_util.h"
#include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h"
namespace mojo {
namespace internal {
namespace {
bool ValidateControlResponse(Message* message) {
ValidationContext validation_context(
message->data(), message->data_num_bytes(), message->handles()->size(),
message, "ControlResponseValidator");
if (!ValidateMessageIsResponse(message, &validation_context))
return false;
switch (message->header()->name) {
case interface_control::kRunMessageId:
return ValidateMessagePayload<
interface_control::internal::RunResponseMessageParams_Data>(
message, &validation_context);
}
return false;
}
using RunCallback =
base::Callback<void(interface_control::RunResponseMessageParamsPtr)>;
class RunResponseForwardToCallback : public MessageReceiver {
public:
explicit RunResponseForwardToCallback(const RunCallback& callback)
: callback_(callback) {}
bool Accept(Message* message) override;
private:
RunCallback callback_;
DISALLOW_COPY_AND_ASSIGN(RunResponseForwardToCallback);
};
bool RunResponseForwardToCallback::Accept(Message* message) {
if (!ValidateControlResponse(message))
return false;
interface_control::internal::RunResponseMessageParams_Data* params =
reinterpret_cast<
interface_control::internal::RunResponseMessageParams_Data*>(
message->mutable_payload());
interface_control::RunResponseMessageParamsPtr params_ptr;
SerializationContext context;
Deserialize<interface_control::RunResponseMessageParamsDataView>(
params, ¶ms_ptr, &context);
callback_.Run(std::move(params_ptr));
return true;
}
void SendRunMessage(MessageReceiverWithResponder* receiver,
interface_control::RunInputPtr input_ptr,
const RunCallback& callback) {
SerializationContext context;
auto params_ptr = interface_control::RunMessageParams::New();
params_ptr->input = std::move(input_ptr);
size_t size = PrepareToSerialize<interface_control::RunMessageParamsDataView>(
params_ptr, &context);
RequestMessageBuilder builder(interface_control::kRunMessageId, size);
interface_control::internal::RunMessageParams_Data* params = nullptr;
Serialize<interface_control::RunMessageParamsDataView>(
params_ptr, builder.buffer(), ¶ms, &context);
MessageReceiver* responder = new RunResponseForwardToCallback(callback);
if (!receiver->AcceptWithResponder(builder.message(), responder))
delete responder;
}
Message ConstructRunOrClosePipeMessage(
interface_control::RunOrClosePipeInputPtr input_ptr) {
SerializationContext context;
auto params_ptr = interface_control::RunOrClosePipeMessageParams::New();
params_ptr->input = std::move(input_ptr);
size_t size = PrepareToSerialize<
interface_control::RunOrClosePipeMessageParamsDataView>(params_ptr,
&context);
MessageBuilder builder(interface_control::kRunOrClosePipeMessageId, size);
interface_control::internal::RunOrClosePipeMessageParams_Data* params =
nullptr;
Serialize<interface_control::RunOrClosePipeMessageParamsDataView>(
params_ptr, builder.buffer(), ¶ms, &context);
return std::move(*builder.message());
}
void SendRunOrClosePipeMessage(
MessageReceiverWithResponder* receiver,
interface_control::RunOrClosePipeInputPtr input_ptr) {
Message message(ConstructRunOrClosePipeMessage(std::move(input_ptr)));
bool ok = receiver->Accept(&message);
ALLOW_UNUSED_LOCAL(ok);
}
void RunVersionCallback(
const base::Callback<void(uint32_t)>& callback,
interface_control::RunResponseMessageParamsPtr run_response) {
uint32_t version = 0u;
if (run_response->output && run_response->output->is_query_version_result())
version = run_response->output->get_query_version_result()->version;
callback.Run(version);
}
void RunClosure(const base::Closure& callback,
interface_control::RunResponseMessageParamsPtr run_response) {
callback.Run();
}
} // namespace
ControlMessageProxy::ControlMessageProxy(MessageReceiverWithResponder* receiver)
: receiver_(receiver) {
}
ControlMessageProxy::~ControlMessageProxy() = default;
void ControlMessageProxy::QueryVersion(
const base::Callback<void(uint32_t)>& callback) {
auto input_ptr = interface_control::RunInput::New();
input_ptr->set_query_version(interface_control::QueryVersion::New());
SendRunMessage(receiver_, std::move(input_ptr),
base::Bind(&RunVersionCallback, callback));
}
void ControlMessageProxy::RequireVersion(uint32_t version) {
auto require_version = interface_control::RequireVersion::New();
require_version->version = version;
auto input_ptr = interface_control::RunOrClosePipeInput::New();
input_ptr->set_require_version(std::move(require_version));
SendRunOrClosePipeMessage(receiver_, std::move(input_ptr));
}
void ControlMessageProxy::FlushForTesting() {
if (encountered_error_)
return;
auto input_ptr = interface_control::RunInput::New();
input_ptr->set_flush_for_testing(interface_control::FlushForTesting::New());
base::RunLoop run_loop;
run_loop_quit_closure_ = run_loop.QuitClosure();
SendRunMessage(
receiver_, std::move(input_ptr),
base::Bind(&RunClosure,
base::Bind(&ControlMessageProxy::RunFlushForTestingClosure,
base::Unretained(this))));
run_loop.Run();
}
void ControlMessageProxy::SendDisconnectReason(uint32_t custom_reason,
const std::string& description) {
Message message =
ConstructDisconnectReasonMessage(custom_reason, description);
bool ok = receiver_->Accept(&message);
ALLOW_UNUSED_LOCAL(ok);
}
void ControlMessageProxy::RunFlushForTestingClosure() {
DCHECK(!run_loop_quit_closure_.is_null());
base::ResetAndReturn(&run_loop_quit_closure_).Run();
}
void ControlMessageProxy::OnConnectionError() {
encountered_error_ = true;
if (!run_loop_quit_closure_.is_null())
RunFlushForTestingClosure();
}
// static
Message ControlMessageProxy::ConstructDisconnectReasonMessage(
uint32_t custom_reason,
const std::string& description) {
auto send_disconnect_reason = interface_control::SendDisconnectReason::New();
send_disconnect_reason->custom_reason = custom_reason;
send_disconnect_reason->description = description;
auto input_ptr = interface_control::RunOrClosePipeInput::New();
input_ptr->set_send_disconnect_reason(std::move(send_disconnect_reason));
return ConstructRunOrClosePipeMessage(std::move(input_ptr));
}
} // namespace internal
} // namespace mojo
| 35.237864 | 80 | 0.754236 | google-ar |
1565deb91bc1982bd223bb56933b1b9c4ef510ca | 2,438 | cpp | C++ | src/utilities_gui/dlgDeviceInfo.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | src/utilities_gui/dlgDeviceInfo.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | src/utilities_gui/dlgDeviceInfo.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | #include "dlgDeviceInfo.h"
#include "IConnection.h"
using namespace lime;
dlgDeviceInfo::dlgDeviceInfo(wxWindow* parent, wxWindowID id, const wxString &title, const wxPoint& pos, const wxSize& size, long styles)
:
dlgDeviceInfo_view( parent, id, title, pos, size, styles)
{
ctrPort = nullptr;
dataPort = nullptr;
}
void dlgDeviceInfo::Initialize(IConnection* pCtrPort, IConnection* pDataPort)
{
ctrPort = pCtrPort;
dataPort = pDataPort;
}
void dlgDeviceInfo::OnGetInfo( wxCommandEvent& event )
{
if (ctrPort != nullptr && ctrPort->IsOpen() == true)
{
auto info = ctrPort->GetDeviceInfo();
lblDeviceCtr->SetLabel(info.deviceName);
lblExpansionCtr->SetLabel(info.expansionName);
lblFirmwareCtr->SetLabel(info.firmwareVersion);
lblHardwareCtr->SetLabel(info.hardwareVersion);
lblProtocolCtr->SetLabel(info.protocolVersion);
lblGatewareCtr->SetLabel(info.gatewareVersion);
lblGatewareRevCtr->SetLabel(info.gatewareRevision);
lblGatewareTargetCtr->SetLabel(info.gatewareTargetBoard);
}
else
{
lblDeviceCtr->SetLabel(_("???"));
lblExpansionCtr->SetLabel(_("???"));
lblFirmwareCtr->SetLabel(_("???"));
lblHardwareCtr->SetLabel(_("???"));
lblProtocolCtr->SetLabel(_("???"));
lblGatewareCtr->SetLabel(_("???"));
lblGatewareRevCtr->SetLabel(_("???"));
lblGatewareTargetCtr->SetLabel(_("???"));
}
if (dataPort != nullptr && dataPort->IsOpen() == true)
{
auto info = dataPort->GetDeviceInfo();
lblDeviceData->SetLabel(info.deviceName);
lblExpansionData->SetLabel(info.expansionName);
lblFirmwareData->SetLabel(info.firmwareVersion);
lblHardwareData->SetLabel(info.hardwareVersion);
lblProtocolData->SetLabel(info.protocolVersion);
lblGatewareData->SetLabel(info.gatewareVersion);
lblGatewareRevData->SetLabel(info.gatewareRevision);
lblGatewareTargetData->SetLabel(info.gatewareTargetBoard);
}
else
{
lblDeviceData->SetLabel(_("???"));
lblExpansionData->SetLabel(_("???"));
lblFirmwareData->SetLabel(_("???"));
lblHardwareData->SetLabel(_("???"));
lblProtocolData->SetLabel(_("???"));
lblGatewareData->SetLabel(_("???"));
lblGatewareRevData->SetLabel(_("???"));
lblGatewareTargetData->SetLabel(_("???"));
}
}
| 34.828571 | 137 | 0.650123 | bastille-attic |
15666c1629f120c191effc359b9b9077625f9551 | 800 | hpp | C++ | src/Animation.hpp | darkbitsorg/db-08_green_grappler | f009228edb2eb1a943ab6d5801a78a5d00ac9e43 | [
"BSD-2-Clause-NetBSD",
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2018-06-12T13:35:31.000Z | 2018-06-12T13:35:31.000Z | src/Animation.hpp | darkbitsorg/db-08_green_grappler | f009228edb2eb1a943ab6d5801a78a5d00ac9e43 | [
"BSD-2-Clause-NetBSD",
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | src/Animation.hpp | darkbitsorg/db-08_green_grappler | f009228edb2eb1a943ab6d5801a78a5d00ac9e43 | [
"BSD-2-Clause-NetBSD",
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "Blending.hpp"
class Animation
{
public:
Animation(const std::string& aFilename);
Animation(const std::string& aFilename, int aNumberOfFrames);
~Animation();
BITMAP *getFrame(int aFrame) const;
int getFrameCount() const;
int getFrameWidth() const;
int getFrameHeight() const;
void drawFrame(BITMAP *aBuffer, int aFrame, int aX, int aY, bool aHFlip = false, bool aVFlip = false, Blending aBlending = Blending_None) const;
//void drawFrame(BITMAP *dest, int frame, int x, int y, bool aHFlip, int aFillColor) const;
void drawRotatedFrame(BITMAP *aBuffer, int aFrame, int aX, int aY, int aAngle, bool aVFlip = false) const;
protected:
void privFillFramesList(BITMAP *aAllFrames, int aCount);
int myFrameWidth;
int myFrameHeight;
std::vector<BITMAP *> myFrames;
}; | 30.769231 | 145 | 0.74875 | darkbitsorg |
d07e1c8ebab0aaa06780ab9769ca1e6429b57c7a | 3,831 | cpp | C++ | test/test_service_script_runner.cpp | ProjectDecibel/open_sysadmin | beee92e72a0c3afa3aeb396855aa42c96e8989a8 | [
"Apache-2.0"
] | 14 | 2017-05-31T19:38:25.000Z | 2022-01-19T20:56:32.000Z | test/test_service_script_runner.cpp | ProjectDecibel/open_sysadmin | beee92e72a0c3afa3aeb396855aa42c96e8989a8 | [
"Apache-2.0"
] | 26 | 2017-06-07T14:05:07.000Z | 2020-01-29T20:06:34.000Z | test/test_service_script_runner.cpp | ProjectDecibel/open_sysadmin | beee92e72a0c3afa3aeb396855aa42c96e8989a8 | [
"Apache-2.0"
] | 9 | 2017-05-31T21:09:59.000Z | 2021-05-14T15:11:18.000Z | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <log4cxx/logger.h>
#include <fstream>
#include <string>
#include "ServiceScriptRunner.h"
#include "decibel/messaging/Reactor.h"
namespace dm = decibel::messaging;
namespace
{
log4cxx::LoggerPtr spLogger(log4cxx::Logger::getLogger("test_service_script_runner"));
}
TEST(ServiceScriptRunnering, Basic)
{
dm::Reactor r;
ServiceScriptRunner runner(&r, {"./argdumper.py"});
int calledback = 0;
runner.Run({"key", "key2", "key3"}).thenValue([&r, &calledback](auto /*unused*/)
{
calledback++;
r.Stop();
}).thenError(
folly::tag_t<ExternalRunnerError>{},
[](const auto&)
{
FAIL() << "Should not have errored out";
});
r.Start();
ASSERT_EQ(1, calledback);
}
TEST(ServiceScriptRunnering, ActualOutput)
{
dm::Reactor r;
ServiceScriptRunner runner(&r, {"./argdumper.py"});
int calledback = 0;
runner.Run({"key", "key2", "key3"}).thenValue([&r, &calledback](auto /*unused*/)
{
calledback++;
r.Stop();
}).thenError(
folly::tag_t<ExternalRunnerError>{},
[](const auto&)
{
FAIL() << "Should not have errored out";
});
r.Start();
ASSERT_EQ(1, calledback);
std::ifstream ifs("argdumper");
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
ASSERT_STREQ("key key2 key3\n", content.c_str());
}
TEST(ServiceScriptRunnering, WithServiceArgs)
{
dm::Reactor r;
ServiceScriptRunner runner(&r, {"./argdumper.py", "key0", "more", "args"});
int calledback = 0;
runner.Run({}).thenValue([&r, &calledback](auto /*unused*/)
{
calledback++;
r.Stop();
}).thenError(
folly::tag_t<ExternalRunnerError>{},
[](const auto&)
{
FAIL() << "Should not have errored out";
});
r.Start();
ASSERT_EQ(1, calledback);
std::ifstream ifs("argdumper");
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
ASSERT_STREQ("key0 more args\n", content.c_str());
}
TEST(ServiceScriptRunnering, FailedOutput)
{
dm::Reactor r;
ServiceScriptRunner runner(&r, {"./argdumper.py"});
int calledback = 0;
// argdumper knows to exit with a bad status when receiving "failme" as it's first argument
runner.Run({"failme", "key2", "key3"}).thenValue([](auto /*unused*/)
{
FAIL() << "Should have errored out";
}).thenError(
folly::tag_t<ExternalRunnerError>{},
[&r, &calledback](const auto&)
{
calledback++;
r.Stop();
});
r.Start();
ASSERT_EQ(1, calledback);
}
TEST(ServiceScriptRunnering, Detaching)
{
dm::Reactor r;
ServiceScriptRunner runner(&r, {"./argdumper.py"}, HookOptions::RunOptions::DETACH);
int calledback = 0;
runner.Run({"key", "key2", "key3"}).thenValue([&r, &calledback](auto /*unused*/)
{
calledback++;
r.Stop();
}).thenError(
folly::tag_t<ExternalRunnerError>{},
[](const auto&)
{
FAIL() << "Should not have errored out";
});
r.Start();
ASSERT_EQ(1, calledback);
}
TEST(ServiceScriptRunnering, Ignoring)
{
dm::Reactor r;
ServiceScriptRunner runner(&r, {"./argdumper.py"}, HookOptions::RunOptions::IGNORE);
int calledback = 0;
runner.Run({"failme", "key2", "key3"}).thenValue([&r, &calledback](auto /*unused*/)
{
calledback++;
r.Stop();
}).thenError(
folly::tag_t<ExternalRunnerError>{},
[](const auto&)
{
FAIL() << "Should not have errored out";
});
r.Start();
ASSERT_EQ(1, calledback);
}
| 27.170213 | 95 | 0.577656 | ProjectDecibel |
d07f1345f740ee7dc5b9c3cac249451815e8ef7f | 884 | cpp | C++ | CCC/Stage1/01-Done/ccc01j4s2.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | 1 | 2017-10-01T00:51:39.000Z | 2017-10-01T00:51:39.000Z | CCC/Stage1/01-Done/ccc01j4s2.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | CCC/Stage1/01-Done/ccc01j4s2.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | #include <cstdio>
using namespace std;
int s[20][20];
int main()
{
int a,b;
scanf("%d%d",&a,&b);
int x=10,y=10;
int sx,sy,bx,by;
sx=sy=20;
bx=by=0;
char d='l';
for(int i=a;i!=b+1;i++)
{
if(x>bx) bx=x;
if(x<sx) sx=x;
if(y>by) by=y;
if(y<sy) sy=y;
s[x][y]=i;
if(d=='d')
{
if(!s[x][y+1])
{
d='r';
y++;
continue;
}
x++;
}
else if(d=='r')
{
if(!s[x-1][y])
{
d='u';
x--;
continue;
}
y++;
}
else if(d=='u')
{
if(!s[x][y-1])
{
d='l';
y--;
continue;
}
x--;
}
else if(d=='l')
{
if(!s[x+1][y])
{
d='d';
x++;
continue;
}
y--;
}
}
for(int i=sx;i<=bx;i++)
{
for(int j=sy;j<=by;j++)
if(s[i][j])
printf("%2d ",s[i][j]);
else
printf(" ");
printf("\n");
}
return 0;
}
| 11.945946 | 26 | 0.350679 | zzh8829 |
d0845ae57df5832bf5abee62d80c587935440cdd | 842 | hpp | C++ | src/PyOmega_h.hpp | overfelt/omega_h | dfc19cc3ea0e183692ca6c548dda39f7892301b5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/PyOmega_h.hpp | overfelt/omega_h | dfc19cc3ea0e183692ca6c548dda39f7892301b5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/PyOmega_h.hpp | overfelt/omega_h | dfc19cc3ea0e183692ca6c548dda39f7892301b5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #ifndef OMEGA_H_PY_HPP
#define OMEGA_H_PY_HPP
#include <Omega_h_config.h>
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include <pybind11/pybind11.h>
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
namespace py = pybind11;
namespace Omega_h {
class Library;
extern std::unique_ptr<Library> pybind11_global_library;
void pybind11_c(py::module& module);
void pybind11_array(py::module& module);
void pybind11_comm(py::module& module);
void pybind11_library(py::module& module);
void pybind11_mesh(py::module& module);
void pybind11_build(py::module& module);
void pybind11_adapt(py::module& module);
void pybind11_file(py::module& module);
void pybind11_class(py::module& module);
#ifdef OMEGA_H_USE_DOLFIN
void pybind11_dolfin(py::module& module);
#endif
} // namespace Omega_h
#endif
| 22.756757 | 56 | 0.785036 | overfelt |
d08693adac956c086209f971c0833bea9b328291 | 709 | cpp | C++ | C++Codes/Reverse Stack.cpp | aardhyakumar/Hacktoberfest-20 | 20ae70f8b55cfe3130f16fa5a6b14996b6bb5f27 | [
"MIT"
] | 4 | 2020-10-16T05:53:21.000Z | 2020-10-18T13:31:31.000Z | C++Codes/Reverse Stack.cpp | aardhyakumar/Hacktoberfest-20 | 20ae70f8b55cfe3130f16fa5a6b14996b6bb5f27 | [
"MIT"
] | 5 | 2020-09-20T14:46:05.000Z | 2021-10-09T16:40:55.000Z | C++Codes/Reverse Stack.cpp | aardhyakumar/Hacktoberfest-20 | 20ae70f8b55cfe3130f16fa5a6b14996b6bb5f27 | [
"MIT"
] | 16 | 2020-10-16T05:53:24.000Z | 2021-10-16T18:38:23.000Z | //C++ Program to reverse a stack without recursion
#include<bits/stdc++.h>
using namespace std;
void insertatbottom (stack<int> &st,int ele){
if(st.empty()){
st.push(ele);
return;
}
int topele=st.top();
st.pop();
insertatbottom(st,ele);
st.push(topele);
}
void reverse(stack <int> &st){
if(st.empty()){
return ;
}
int ele=st.top();
st.pop();
reverse(st);
insertatbottom(st,ele);
}
int main(){
stack<int> st;
int n;
cin>>n;
for(int i=0;i<n;i++){
int x;
cin>>x;
st.push(x);
}
reverse(st);
while(!st.empty()){
cout<<st.top()<<endl;
st.pop();
}
return 0;
}
| 14.770833 | 50 | 0.503526 | aardhyakumar |
d08b8e2a8ad801809986736704fa00845719af08 | 651 | cpp | C++ | EU4toV2/Source/Mappers/FlagColorMapper.cpp | Clonefusion/EU4toVic2 | d39157b8317152da4ca138a69d78b6335bb27eb3 | [
"MIT"
] | 2 | 2020-01-02T16:07:51.000Z | 2020-01-12T17:55:13.000Z | EU4toV2/Source/Mappers/FlagColorMapper.cpp | Clonefusion/EU4toVic2 | d39157b8317152da4ca138a69d78b6335bb27eb3 | [
"MIT"
] | 3 | 2020-01-12T19:44:56.000Z | 2020-01-17T05:40:41.000Z | EU4toV2/Source/Mappers/FlagColorMapper.cpp | Clonefusion/EU4toVic2 | d39157b8317152da4ca138a69d78b6335bb27eb3 | [
"MIT"
] | 1 | 2020-01-12T17:55:40.000Z | 2020-01-12T17:55:40.000Z | #include "FlagColorMapper.h"
#include "ParserHelpers.h"
mappers::FlagColorMapper::FlagColorMapper(std::istream& theStream)
{
registerKeyword(std::regex("flag_color"), [this](const std::string& sourceGov, std::istream& theStream)
{
commonItems::Color theColor(theStream);
flagColorMapping.push_back(theColor);
});
registerKeyword(std::regex("[a-z0-9\\_]+"), commonItems::ignoreItem);
parseStream(theStream);
}
std::optional<commonItems::Color> mappers::FlagColorMapper::getFlagColorByIndex(int index) const
{
if ((flagColorMapping.empty()) || (index >= flagColorMapping.size())) return std::nullopt;
return flagColorMapping[index];
}
| 29.590909 | 104 | 0.746544 | Clonefusion |
d08bcbe2295669bca55f9ce7b4d73e403cb92586 | 5,437 | cpp | C++ | src/my_arm/RobotDartAdapter.cpp | Tadinu/my_arm | ac4fb295ddad7c7ee999a03d2e7d229802b64226 | [
"BSD-3-Clause"
] | 4 | 2021-02-20T15:59:42.000Z | 2022-03-25T04:04:21.000Z | src/my_arm/RobotDartAdapter.cpp | Tadinu/my_arm | ac4fb295ddad7c7ee999a03d2e7d229802b64226 | [
"BSD-3-Clause"
] | 1 | 2021-04-14T04:12:48.000Z | 2021-04-14T04:12:48.000Z | src/my_arm/RobotDartAdapter.cpp | Tadinu/my_arm | ac4fb295ddad7c7ee999a03d2e7d229802b64226 | [
"BSD-3-Clause"
] | 2 | 2019-10-29T12:41:16.000Z | 2021-03-22T16:38:27.000Z | #include <functional> // std::bind
#include <QThread>
#include <QVector3D>
#include "Rviz/VMarker.h"
#include "RobotDartAdapter.h"
RobotDartAdapter* RobotDartAdapter::_instance = nullptr;
RobotDartAdapter* RobotDartAdapter::getInstance()
{
if(_instance == nullptr) {
_instance = new RobotDartAdapter();
}
return _instance;
}
#define UPDATE_VOXEL_MESH_USING_LOCAL_TIMER
RobotDartAdapter::RobotDartAdapter():
_pMutex(new QMutex(QMutex::Recursive))
{
}
RobotDartAdapter::~RobotDartAdapter()
{
_pMutex->tryLock(500);
_pMutex->unlock(); // futile if tryLock() failed!
delete _pMutex;
}
void RobotDartAdapter::deleteInstance()
{
delete _instance;
_instance = nullptr;
}
void RobotDartAdapter::initDart(int argc, char* argv[])
{
#if 1 // Ducta
// load a skeleton file
// create and initialize the world
dart::simulation::WorldPtr myWorld
= dart::utils::SkelParser::readWorld(
DART_DATA_PATH"skel/softBodies.skel");
assert(myWorld != nullptr);
#endif
// Create Left Leg skeleton
dart::dynamics::SkeletonPtr LeftLegSkel = dart::dynamics::Skeleton::create();
double mass = 1.0;
// BodyNode 1: Left Hip Yaw (LHY)
dart::dynamics::BodyNode::Properties body;
body.mName = "LHY";
dart::dynamics::ShapePtr shape(
new dart::dynamics::BoxShape(Eigen::Vector3d(0.3, 0.3, 1.0)));
body.mInertia.setMass(mass);
dart::dynamics::RevoluteJoint::Properties joint;
joint.mName = "LHY";
joint.mAxis = Eigen::Vector3d(0.0, 0.0, 1.0);
joint.mPositionLowerLimits[0] = -dart::math::constantsd::pi();
joint.mPositionUpperLimits[0] = dart::math::constantsd::pi();
// You can get the newly created Joint and BodyNode pointers like this
std::pair<dart::dynamics::Joint*, dart::dynamics::BodyNode*> pair =
LeftLegSkel->createJointAndBodyNodePair<dart::dynamics::RevoluteJoint>(
nullptr, joint, body);
pair.second->createShapeNodeWith<
dart::dynamics::VisualAspect,
dart::dynamics::CollisionAspect,
dart::dynamics::DynamicsAspect>(shape);
dart::dynamics::BodyNode* parent = pair.second;
// BodyNode 2: Left Hip Roll (LHR) whose parent is: LHY
body = dart::dynamics::BodyNode::Properties(); // create a fresh properties container
body.mName = "LHR";
shape = dart::dynamics::ShapePtr(
new dart::dynamics::BoxShape(Eigen::Vector3d(0.3, 0.3, 1.0)));
joint.mName = "LHR";
joint.mT_ParentBodyToJoint = Eigen::Translation3d(0.0, 0.0, 0.5);
// You can get the specific type of Joint Pointer instead of just a basic Joint pointer
std::pair<dart::dynamics::RevoluteJoint*, dart::dynamics::BodyNode*> pair1 =
LeftLegSkel->createJointAndBodyNodePair<dart::dynamics::RevoluteJoint>(
parent, joint, body);
pair1.first->setAxis(Eigen::Vector3d(1.0, 0.0, 0.0));
auto shapeNode1 = pair1.second->createShapeNodeWith<
dart::dynamics::VisualAspect,
dart::dynamics::CollisionAspect,
dart::dynamics::DynamicsAspect>(shape);
shapeNode1->setRelativeTranslation(Eigen::Vector3d(0.0, 0.0, 0.5));
pair1.second->setLocalCOM(shapeNode1->getRelativeTranslation());
pair1.second->setMass(mass);
// BodyNode 3: Left Hip Pitch (LHP) whose parent is: LHR
body = dart::dynamics::BodyNode::Properties(); // create a fresh properties container
body.mName = "LHP";
shape = dart::dynamics::ShapePtr(
new dart::dynamics::BoxShape(Eigen::Vector3d(0.3, 0.3, 1.0)));
joint.mName = "LHP";
joint.mAxis = Eigen::Vector3d(0.0, 1.0, 0.0);
joint.mT_ParentBodyToJoint = Eigen::Translation3d(0.0, 0.0, 1.0);
// Or you can completely ignore the return value of this function
std::pair<dart::dynamics::RevoluteJoint*, dart::dynamics::BodyNode*> pair2 =
LeftLegSkel->createJointAndBodyNodePair<dart::dynamics::RevoluteJoint>(
LeftLegSkel->getBodyNode(1), joint, body);
auto shapeNode2 = pair2.second->createShapeNodeWith<
dart::dynamics::VisualAspect,
dart::dynamics::CollisionAspect,
dart::dynamics::DynamicsAspect>(shape);
shapeNode2->setRelativeTranslation(Eigen::Vector3d(0.0, 0.0, 0.5));
pair2.second->setLocalCOM(shapeNode2->getRelativeTranslation());
pair2.second->setMass(mass);
// Window stuff
MyWindow window(LeftLegSkel);
window.setWorld(myWorld);
glutInit(&argc, argv);
window.initWindow(640, 480, "Skeleton example");
glutMainLoop();
}
// ###########################################################################################
void MyWindow::draw()
{
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
drawSkeleton(skel.get());
}
void MyWindow::keyboard(unsigned char _key, int _x, int _y)
{
static bool inverse = false;
static const double dDOF = 0.1;
switch (_key) {
case '-': {
inverse = !inverse;
} break;
case '1':
case '2':
case '3': {
std::size_t dofIdx = _key - 49;
Eigen::VectorXd pose = skel->getPositions();
pose(dofIdx) = pose(dofIdx) + (inverse ? -dDOF : dDOF);
skel->setPositions(pose);
std::cout << "Updated pose DOF " << dofIdx << ": " << pose.transpose()
<< std::endl;
glutPostRedisplay();
} break;
default:
Win3D::keyboard(_key, _x, _y);
}
glutPostRedisplay();
}
| 33.770186 | 94 | 0.654405 | Tadinu |
d09770577356886cd5c4943211a2ffbd93526df9 | 8,231 | cc | C++ | onnxruntime/test/common/path_test.cc | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 6,036 | 2019-05-07T06:03:57.000Z | 2022-03-31T17:59:54.000Z | onnxruntime/test/common/path_test.cc | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 5,730 | 2019-05-06T23:04:55.000Z | 2022-03-31T23:55:56.000Z | onnxruntime/test/common/path_test.cc | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 1,566 | 2019-05-07T01:30:07.000Z | 2022-03-31T17:06:50.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/common/path.h"
#include "gtest/gtest.h"
#include "core/common/optional.h"
#include "test/util/include/asserts.h"
namespace onnxruntime {
namespace test {
TEST(PathTest, Parse) {
auto check_parse =
[](const std::string& path_string,
const std::string& expected_root,
const std::vector<std::string>& expected_components) {
Path p{};
ASSERT_STATUS_OK(Path::Parse(ToPathString(path_string), p));
std::vector<PathString> expected_components_ps{};
std::transform(
expected_components.begin(), expected_components.end(),
std::back_inserter(expected_components_ps),
[](const std::string& s) { return ToPathString(s); });
EXPECT_EQ(p.GetComponents(), expected_components_ps);
EXPECT_EQ(p.GetRootPathString(), ToPathString(expected_root));
};
check_parse(
"i/am/relative",
"", {"i", "am", "relative"});
#ifdef _WIN32
check_parse(
"/i/am/rooted",
R"(\)", {"i", "am", "rooted"});
check_parse(
R"(\\server\share\i\am\rooted)",
R"(\\server\share\)", {"i", "am", "rooted"});
check_parse(
R"(C:\i\am\rooted)",
R"(C:\)", {"i", "am", "rooted"});
check_parse(
R"(C:i\am\relative)",
"C:", {"i", "am", "relative"});
#else // POSIX
check_parse(
"/i/am/rooted",
"/", {"i", "am", "rooted"});
check_parse(
"//root_name/i/am/rooted",
"//root_name/", {"i", "am", "rooted"});
#endif
}
TEST(PathTest, ParseFailure) {
auto check_parse_failure =
[](const std::string& path_string) {
Path p{};
EXPECT_FALSE(Path::Parse(ToPathString(path_string), p).IsOK());
};
#ifdef _WIN32
check_parse_failure(R"(\\server_name_no_separator)");
check_parse_failure(R"(\\server_name_no_share_name\)");
check_parse_failure(R"(\\server_name\share_name_no_root_dir)");
#else // POSIX
check_parse_failure("//root_name_no_root_dir");
#endif
}
TEST(PathTest, IsEmpty) {
auto check_empty =
[](const std::string& path_string, bool is_empty) {
Path p{};
ASSERT_STATUS_OK(Path::Parse(ToPathString(path_string), p));
EXPECT_EQ(p.IsEmpty(), is_empty);
};
check_empty("", true);
check_empty(".", false);
check_empty("/", false);
}
TEST(PathTest, IsAbsoluteOrRelative) {
auto check_abs_or_rel =
[](const std::string& path_string, bool is_absolute) {
Path p{};
ASSERT_STATUS_OK(Path::Parse(ToPathString(path_string), p));
EXPECT_EQ(p.IsAbsolute(), is_absolute);
EXPECT_EQ(p.IsRelative(), !is_absolute);
};
check_abs_or_rel("relative", false);
check_abs_or_rel("", false);
#ifdef _WIN32
check_abs_or_rel(R"(\root_relative)", false);
check_abs_or_rel(R"(\)", false);
check_abs_or_rel("C:drive_relative", false);
check_abs_or_rel("C:", false);
check_abs_or_rel(R"(C:\absolute)", true);
check_abs_or_rel(R"(C:\)", true);
#else // POSIX
check_abs_or_rel("/absolute", true);
check_abs_or_rel("/", true);
#endif
}
TEST(PathTest, ParentPath) {
auto check_parent =
[](const std::string path_string, const std::string& expected_parent_path_string) {
Path p{}, p_expected_parent{};
ASSERT_STATUS_OK(Path::Parse(ToPathString(path_string), p));
ASSERT_STATUS_OK(Path::Parse(ToPathString(expected_parent_path_string), p_expected_parent));
EXPECT_EQ(p.ParentPath().ToPathString(), p_expected_parent.ToPathString());
};
check_parent("a/b", "a");
check_parent("/a/b", "/a");
check_parent("", "");
check_parent("/", "/");
}
TEST(PathTest, Normalize) {
auto check_normalize =
[](const std::string& path_string,
const std::string& expected_normalized_path_string) {
Path p{}, p_expected_normalized{};
ASSERT_STATUS_OK(Path::Parse(ToPathString(path_string), p));
ASSERT_STATUS_OK(Path::Parse(ToPathString(expected_normalized_path_string), p_expected_normalized));
EXPECT_EQ(p.Normalize().ToPathString(), p_expected_normalized.ToPathString());
};
check_normalize("/a/b/./c/../../d/../e", "/a/e");
check_normalize("a/b/./c/../../d/../e", "a/e");
check_normalize("/../a/../../b", "/b");
check_normalize("../a/../../b", "../../b");
check_normalize("/a/..", "/");
check_normalize("a/..", ".");
check_normalize("", "");
check_normalize("/", "/");
check_normalize(".", ".");
}
TEST(PathTest, Append) {
auto check_append =
[](const std::string& a, const std::string& b, const std::string& expected_ab) {
Path p_a{}, p_b{}, p_expected_ab{};
ASSERT_STATUS_OK(Path::Parse(ToPathString(a), p_a));
ASSERT_STATUS_OK(Path::Parse(ToPathString(b), p_b));
ASSERT_STATUS_OK(Path::Parse(ToPathString(expected_ab), p_expected_ab));
EXPECT_EQ(p_a.Append(p_b).ToPathString(), p_expected_ab.ToPathString());
};
check_append("/a/b", "c/d", "/a/b/c/d");
check_append("/a/b", "/c/d", "/c/d");
check_append("a/b", "c/d", "a/b/c/d");
check_append("a/b", "/c/d", "/c/d");
#ifdef _WIN32
check_append(R"(C:\a\b)", R"(c\d)", R"(C:\a\b\c\d)");
check_append(R"(C:\a\b)", R"(\c\d)", R"(C:\c\d)");
check_append(R"(C:\a\b)", R"(D:c\d)", R"(D:c\d)");
check_append(R"(C:\a\b)", R"(D:\c\d)", R"(D:\c\d)");
check_append(R"(C:a\b)", R"(c\d)", R"(C:a\b\c\d)");
check_append(R"(C:a\b)", R"(\c\d)", R"(C:\c\d)");
check_append(R"(C:a\b)", R"(D:c\d)", R"(D:c\d)");
check_append(R"(C:a\b)", R"(D:\c\d)", R"(D:\c\d)");
#else // POSIX
check_append("//root_0/a/b", "c/d", "//root_0/a/b/c/d");
check_append("//root_0/a/b", "/c/d", "/c/d");
check_append("//root_0/a/b", "//root_1/c/d", "//root_1/c/d");
#endif
}
TEST(PathTest, RelativePath) {
auto check_relative =
[](const std::string& src,
const std::string& dst,
const std::string& expected_rel) {
Path p_src, p_dst, p_expected_rel, p_rel;
ASSERT_STATUS_OK(Path::Parse(ToPathString(src), p_src));
ASSERT_STATUS_OK(Path::Parse(ToPathString(dst), p_dst));
ASSERT_STATUS_OK(Path::Parse(ToPathString(expected_rel), p_expected_rel));
ASSERT_STATUS_OK(RelativePath(p_src, p_dst, p_rel));
EXPECT_EQ(p_rel.ToPathString(), p_expected_rel.ToPathString());
};
check_relative(
"/a/b/c/d/e", "/a/b/c/d/e/f/g/h",
"f/g/h");
check_relative(
"/a/b/c/d/e", "/a/b/f/g/h/i",
"../../../f/g/h/i");
check_relative(
"a/b/../c/../d", "e/./f/../g/h",
"../../e/g/h");
}
TEST(PathTest, RelativePathFailure) {
auto check_relative_failure =
[](const std::string& src,
const std::string& dst) {
Path p_src, p_dst, p_rel;
ASSERT_STATUS_OK(Path::Parse(ToPathString(src), p_src));
ASSERT_STATUS_OK(Path::Parse(ToPathString(dst), p_dst));
EXPECT_FALSE(RelativePath(p_src, p_dst, p_rel).IsOK());
};
check_relative_failure("/rooted", "relative");
check_relative_failure("relative", "/rooted");
#ifdef _WIN32
check_relative_failure("C:/a", "D:/a");
#else // POSIX
check_relative_failure("//root_0/a", "//root_1/a");
#endif
}
#if !defined(ORT_NO_EXCEPTIONS)
TEST(PathTest, Concat) {
auto check_concat =
[](const optional<std::string>& a, const std::string& b, const std::string& expected_a, bool expect_throw = false) {
Path p_a{}, p_expected_a{};
if (a.has_value()) {
ASSERT_STATUS_OK(Path::Parse(ToPathString(*a), p_a));
}
ASSERT_STATUS_OK(Path::Parse(ToPathString(expected_a), p_expected_a));
if (expect_throw) {
EXPECT_THROW(p_a.Concat(ToPathString(b)).ToPathString(), OnnxRuntimeException);
} else {
EXPECT_EQ(p_a.Concat(ToPathString(b)).ToPathString(), p_expected_a.ToPathString());
}
};
check_concat({"/a/b"}, "c", "/a/bc");
check_concat({"a/b"}, "cd", "a/bcd");
check_concat({""}, "cd", "cd");
check_concat({}, "c", "c");
#ifdef _WIN32
check_concat({"a/b"}, R"(c\d)", "", true /* expect_throw */);
#else
check_concat({"a/b"}, "c/d", "", true /* expect_throw */);
#endif
}
#endif
} // namespace test
} // namespace onnxruntime
| 32.027237 | 122 | 0.609039 | lchang20 |
d0982a59d0d971819899a90827717e5692dc5c3d | 4,353 | cpp | C++ | es-core/src/hardware/boards/odroidadvancego2/OdroidAdvanceGo2PowerEventReader.cpp | AdoPi/custom-es-fork | 49d23b57173612531fdf0f1c996592fb161df779 | [
"MIT"
] | null | null | null | es-core/src/hardware/boards/odroidadvancego2/OdroidAdvanceGo2PowerEventReader.cpp | AdoPi/custom-es-fork | 49d23b57173612531fdf0f1c996592fb161df779 | [
"MIT"
] | null | null | null | es-core/src/hardware/boards/odroidadvancego2/OdroidAdvanceGo2PowerEventReader.cpp | AdoPi/custom-es-fork | 49d23b57173612531fdf0f1c996592fb161df779 | [
"MIT"
] | null | null | null | //
// Created by bkg2k on 01/11/2020.
//
#include "OdroidAdvanceGo2PowerEventReader.h"
#include <utils/Log.h>
#include <linux/input.h>
#include <fcntl.h>
#include <poll.h>
#include <utils/datetime/DateTime.h>
#include <MainRunner.h>
OdroidAdvanceGo2PowerEventReader::OdroidAdvanceGo2PowerEventReader(HardwareMessageSender& messageSender)
: mSender(messageSender)
, mFileHandle(0)
, mWaitFor(WaitFor::Press)
{
}
OdroidAdvanceGo2PowerEventReader::~OdroidAdvanceGo2PowerEventReader()
{
StopReader();
}
void OdroidAdvanceGo2PowerEventReader::StartReader()
{
LOG(LogDebug) << "[OdroidAdvanceGo2] Power button manager requested to start.";
Start("OAG2Power");
}
void OdroidAdvanceGo2PowerEventReader::StopReader()
{
LOG(LogDebug) << "[OdroidAdvanceGo2] Power button manager requested to stop.";
Stop();
}
void OdroidAdvanceGo2PowerEventReader::Break()
{
if (mFileHandle >= 0)
{
LOG(LogDebug) << "[OdroidAdvanceGo2] Breaking power button thread.";
// Close handle to force the 'read' to fail and exit
int fd = mFileHandle;
mFileHandle = -1;
close(fd);
}
}
void OdroidAdvanceGo2PowerEventReader::Run()
{
LOG(LogInfo) << "[OdroidAdvanceGo2] Running background power button manager.";
while(IsRunning())
{
mFileHandle = open(sInputEventPath, O_RDONLY);
if (mFileHandle < 0)
{
LOG(LogError) << "[OdroidAdvanceGo2] Error opening " << sInputEventPath << ". Retry in 5s...";
sleep(5);
continue;
}
input_event pressEvent {};
while(IsRunning())
{
// Poll
struct pollfd poller { .fd = mFileHandle, .events = POLLIN, .revents = 0 };
if (poll(&poller, 1, 100) != 1 || (poller.revents & POLLIN) == 0)
{
// If the button is pressed at least 2000ms
// Just send the message and ignore release event.
if (mWaitFor == WaitFor::Release)
{
timeval now {};
gettimeofday(&now, nullptr);
long start = (pressEvent.time.tv_usec / 1000) + (pressEvent.time.tv_sec * 1000);
long stop = (now.tv_usec / 1000) + (now.tv_sec * 1000);
long elapsed = stop - start;
if (elapsed >= 2000)
{
mSender.Send(BoardType::OdroidAdvanceGo2, MessageTypes::PowerButtonPressed, (int)elapsed);
mWaitFor = WaitFor::Ignore; // Ignore releasing the button
}
}
continue;
}
// Read event
struct input_event event {};
if (read(mFileHandle, &event, sizeof(event)) != sizeof(event))
{
// Error while the file handle is ok means a true read error
if (mFileHandle >= 0)
{
LOG(LogError) << "[OdroidAdvanceGo2] Error reading " << sInputEventPath << ". Retrying";
close(mFileHandle);
continue;
}
// If file handle NOK, we're instructed to quit
LOG(LogInfo) << "[OdroidAdvanceGo2] Power event reader ordered to stop.";
break;
}
// Power button pressed?
if ((event.type == 1) && (event.code == sPowerKeyCode))
switch(mWaitFor)
{
case WaitFor::Press:
{
if (event.value == 1) // Really pressed?
{
mWaitFor = WaitFor::Release;
pressEvent = event;
}
break;
}
case WaitFor::Release:
{
if (event.value == 0) // Really released
{
long start = (pressEvent.time.tv_usec / 1000) + (pressEvent.time.tv_sec * 1000);
long stop = (event.time.tv_usec / 1000) + (event.time.tv_sec * 1000);
long elapsed = stop - start;
if (elapsed > 20) // Debouncing
mSender.Send(BoardType::OdroidAdvanceGo2, MessageTypes::PowerButtonPressed, (int)elapsed);
}
break;
}
case WaitFor::Ignore: mWaitFor = WaitFor::Press; break;
}
}
}
}
void OdroidAdvanceGo2PowerEventReader::Suspend()
{
{ LOG(LogInfo) << "[OdroidAdvanceGo2] SUSPEND!"; }
mWaitFor = WaitFor::Ignore; // Ignore next event when waking up!
if (system("/usr/sbin/pm-suspend") != 0) // Suspend mode
LOG(LogError) << "[OdroidAdvanceGo2] Suspend failed!";
{ LOG(LogInfo) << "[OdroidAdvanceGo2] WAKEUP!"; }
mSender.Send(BoardType::OdroidAdvanceGo2, MessageTypes::Resume);
}
| 30.229167 | 106 | 0.603032 | AdoPi |
d0984ce12fba9d44a5f9652de6f3ed8bf5961eea | 180 | cpp | C++ | 1-basic-env/test/main.cpp | OuyangWenyu/hydrocpp | 9587e63c7125ee42b2523b361161876e8083be2e | [
"MIT"
] | null | null | null | 1-basic-env/test/main.cpp | OuyangWenyu/hydrocpp | 9587e63c7125ee42b2523b361161876e8083be2e | [
"MIT"
] | null | null | null | 1-basic-env/test/main.cpp | OuyangWenyu/hydrocpp | 9587e63c7125ee42b2523b361161876e8083be2e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
char a[10],b[10];
cin.getline(a,10,',');
cin.getline(b,10,',');
cout<<a<<endl;
cout<<b<<endl;
}
| 16.363636 | 27 | 0.516667 | OuyangWenyu |
d098be9aa5cc0bbae5d74812e0b06555c30a4f98 | 3,141 | cpp | C++ | dev/Gems/LmbrCentral/Code/Source/Audio/EditorAudioEnvironmentComponent.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/LmbrCentral/Code/Source/Audio/EditorAudioEnvironmentComponent.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/LmbrCentral/Code/Source/Audio/EditorAudioEnvironmentComponent.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "EditorAudioEnvironmentComponent.h"
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Serialization/SerializeContext.h>
namespace LmbrCentral
{
//=========================================================================
void EditorAudioEnvironmentComponent::Reflect(AZ::ReflectContext* context)
{
auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<EditorAudioEnvironmentComponent, EditorComponentBase>()
->Version(1)
->Field("Environment name", &EditorAudioEnvironmentComponent::m_defaultEnvironment)
;
if (auto editContext = serializeContext->GetEditContext())
{
editContext->Class<EditorAudioEnvironmentComponent>("Audio Environment", "The Audio Environment component provides access to features of the Audio Translation Layer (ATL) environments to apply environmental effects such as reverb or echo")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Audio")
->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/AudioEnvironment.svg")
->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/AudioEnvironment.png")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-audio-environment.html")
->DataElement("AudioControl", &EditorAudioEnvironmentComponent::m_defaultEnvironment, "Default Environment", "Name of the default ATL Environment control to use")
;
}
}
}
//=========================================================================
EditorAudioEnvironmentComponent::EditorAudioEnvironmentComponent()
{
m_defaultEnvironment.m_propertyType = AzToolsFramework::AudioPropertyType::Environment;
}
//=========================================================================
void EditorAudioEnvironmentComponent::BuildGameEntity(AZ::Entity* gameEntity)
{
gameEntity->CreateComponent<AudioEnvironmentComponent>(m_defaultEnvironment.m_controlName);
}
} // namespace LmbrCentral
| 51.491803 | 255 | 0.638013 | jeikabu |
d09b484c3891610d00f88f07c71dd9ec2b30e928 | 1,456 | hpp | C++ | lib/hsa/hsaInputData.hpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 19 | 2018-12-14T00:51:52.000Z | 2022-02-20T02:43:50.000Z | lib/hsa/hsaInputData.hpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 487 | 2018-12-13T00:59:53.000Z | 2022-02-07T16:12:56.000Z | lib/hsa/hsaInputData.hpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | 5 | 2019-05-09T19:52:19.000Z | 2021-03-27T20:13:21.000Z | #ifndef HSA_INPUT_DATA_H
#define HSA_INPUT_DATA_H
#include "Config.hpp" // for Config
#include "buffer.h" // for Buffer
#include "bufferContainer.hpp" // for bufferContainer
#include "hsa/hsa.h" // for hsa_signal_t
#include "hsaCommand.hpp" // for hsaCommand
#include "hsaDeviceInterface.hpp" // for hsaDeviceInterface
#include <stdint.h> // for int32_t
#include <string> // for string
class hsaInputData : public hsaCommand {
public:
hsaInputData(kotekan::Config& config, const std::string& unique_name,
kotekan::bufferContainer& host_buffers, hsaDeviceInterface& device);
virtual ~hsaInputData();
int wait_on_precondition(int gpu_frame_id) override;
hsa_signal_t execute(int gpu_frame_id, hsa_signal_t precede_signal) override;
void finalize_frame(int frame_id) override;
private:
int32_t network_buffer_id;
int32_t network_buffer_precondition_id;
int32_t network_buffer_finalize_id;
Buffer* network_buf;
int32_t input_frame_len;
// TODO maybe factor these into a CHIME command object class?
int32_t _num_local_freq;
int32_t _num_elements;
int32_t _samples_per_data_set;
float _delay_max_fraction;
// Random delay in seconds
double _random_delay;
// Apply a random delay to spread out the power load if set to true.
bool _enable_delay;
const double _sample_arrival_rate = 390625.0;
};
#endif
| 29.12 | 85 | 0.719093 | eschnett |
d09b53ec757d32a45deced598650f5491bba8ebc | 1,777 | cpp | C++ | aws-cpp-sdk-inspector2/source/model/FreeTrialInfoError.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-inspector2/source/model/FreeTrialInfoError.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-inspector2/source/model/FreeTrialInfoError.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/inspector2/model/FreeTrialInfoError.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Inspector2
{
namespace Model
{
FreeTrialInfoError::FreeTrialInfoError() :
m_accountIdHasBeenSet(false),
m_code(FreeTrialInfoErrorCode::NOT_SET),
m_codeHasBeenSet(false),
m_messageHasBeenSet(false)
{
}
FreeTrialInfoError::FreeTrialInfoError(JsonView jsonValue) :
m_accountIdHasBeenSet(false),
m_code(FreeTrialInfoErrorCode::NOT_SET),
m_codeHasBeenSet(false),
m_messageHasBeenSet(false)
{
*this = jsonValue;
}
FreeTrialInfoError& FreeTrialInfoError::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("accountId"))
{
m_accountId = jsonValue.GetString("accountId");
m_accountIdHasBeenSet = true;
}
if(jsonValue.ValueExists("code"))
{
m_code = FreeTrialInfoErrorCodeMapper::GetFreeTrialInfoErrorCodeForName(jsonValue.GetString("code"));
m_codeHasBeenSet = true;
}
if(jsonValue.ValueExists("message"))
{
m_message = jsonValue.GetString("message");
m_messageHasBeenSet = true;
}
return *this;
}
JsonValue FreeTrialInfoError::Jsonize() const
{
JsonValue payload;
if(m_accountIdHasBeenSet)
{
payload.WithString("accountId", m_accountId);
}
if(m_codeHasBeenSet)
{
payload.WithString("code", FreeTrialInfoErrorCodeMapper::GetNameForFreeTrialInfoErrorCode(m_code));
}
if(m_messageHasBeenSet)
{
payload.WithString("message", m_message);
}
return payload;
}
} // namespace Model
} // namespace Inspector2
} // namespace Aws
| 19.527473 | 105 | 0.732696 | perfectrecall |
d09e5531a56c0a361bfc05b6729b921e25a84cc6 | 2,515 | cpp | C++ | tests/android/app/src/main/cpp/miniaudio_async_test.cpp | ondesly/audio_engine | 37e68f9e5be3f36b77aac6574e90d2150aef0f6d | [
"BSD-2-Clause"
] | null | null | null | tests/android/app/src/main/cpp/miniaudio_async_test.cpp | ondesly/audio_engine | 37e68f9e5be3f36b77aac6574e90d2150aef0f6d | [
"BSD-2-Clause"
] | null | null | null | tests/android/app/src/main/cpp/miniaudio_async_test.cpp | ondesly/audio_engine | 37e68f9e5be3f36b77aac6574e90d2150aef0f6d | [
"BSD-2-Clause"
] | null | null | null | //
// miniaudio_async_test.cpp
// audio_engine
//
// Created by Dmitrii Torkhov <dmitriitorkhov@gmail.com> on 03.09.2021.
// Copyright © 2021 Dmitrii Torkhov. All rights reserved.
//
#include <iostream>
#include <miniaudio.h>
#include "miniaudio_async_test.h"
oo::audio::miniaudio_async_test::miniaudio_async_test() {
m_service_thread = std::make_unique<std::thread>([&]() {
ma_device_config device_config;
device_config = ma_device_config_init(ma_device_type_playback);
device_config.playback.format = ma_format_f32;
device_config.playback.channels = 2;
device_config.sampleRate = 44100;
device_config.dataCallback = [](ma_device *device, void *output,
const void *,
ma_uint32 frame_count) {
std::cout << "callback" << std::endl;
};
ma_device device;
auto result = ma_device_init(nullptr, &device_config, &device);
if (result != MA_SUCCESS) {
return;
}
char command;
while (true) {
if (m_queue.pop(command)) {
switch (command) {
case 'a':
result = ma_device_start(&device);
if (result != MA_SUCCESS) {
return;
}
break;
case 'o':
result = ma_device_stop(&device);
if (result != MA_SUCCESS) {
return;
}
break;
default:
break;
}
} else {
std::unique_lock<std::mutex> lock(m_mutex);
if (m_is_done) {
break;
} else {
using namespace std::chrono_literals;
m_condition.wait_for(lock, 100ms);
}
}
}
ma_device_uninit(&device);
});
}
oo::audio::miniaudio_async_test::~miniaudio_async_test() {
{
std::lock_guard<std::mutex> lock(m_mutex);
m_is_done = true;
m_condition.notify_all();
}
m_service_thread->join();
}
void oo::audio::miniaudio_async_test::start() {
m_queue.push('a');
m_condition.notify_one();
}
void oo::audio::miniaudio_async_test::stop() {
m_queue.push('o');
m_condition.notify_one();
} | 28.908046 | 72 | 0.496223 | ondesly |
d09f30e7fb44a15afb588553d1edd6613e1e65ec | 942 | cpp | C++ | src/matrix.cpp | sraaphorst/nibac | 288fcc4012065cf8b15dab4fc5f0c829b2b4a65c | [
"Apache-2.0"
] | null | null | null | src/matrix.cpp | sraaphorst/nibac | 288fcc4012065cf8b15dab4fc5f0c829b2b4a65c | [
"Apache-2.0"
] | 9 | 2018-05-06T20:27:49.000Z | 2018-10-24T23:28:24.000Z | src/matrix.cpp | sraaphorst/nibac | 288fcc4012065cf8b15dab4fc5f0c829b2b4a65c | [
"Apache-2.0"
] | null | null | null | /**
* matrix.h
*
* By Sebastian Raaphorst, 2003 - 2018.
*/
#include "common.h"
#include "matrix.h"
namespace vorpal::nibac {
template<class T>
void matrix_2d(T ***matrix, int n, int m) {
(*matrix) = new T *[n];
for (int i = 0; i < n; ++i)
(*matrix)[i] = new T[m];
}
template<class T>
void matrix_3d(T ****matrix, int n, int m, int p) {
(*matrix) = new T **[n];
for (int i = 0; i < n; ++i)
matrix_2d(&((*matrix)[i]), m, p);
}
template<class T>
void matrix_free_2d(T ***matrix, int n, int m) {
for (int i = 0; i < n; ++i)
delete[] (*matrix)[i];
delete[] (*matrix);
*matrix = 0;
}
template<class T>
void matrix_free_3d(T ****matrix, int n, int m, int p) {
for (int i = 0; i < n; ++i)
matrix_free_2d(&((*matrix)[i]), m, p);
delete[] (*matrix);
*matrix = 0;
}
}; | 23.55 | 60 | 0.46603 | sraaphorst |
d0a2185b3868089cf0490fa9942ed3649c49d8d9 | 3,749 | hpp | C++ | include/ouchilib/crypto/algorithm/mugi.hpp | ouchiminh/ouchilib | de1bab0aa75c9e567ce06d76c95bc330dffbf52e | [
"MIT"
] | 1 | 2019-06-11T05:22:54.000Z | 2019-06-11T05:22:54.000Z | include/ouchilib/crypto/algorithm/mugi.hpp | ouchiminh/ouchilib | de1bab0aa75c9e567ce06d76c95bc330dffbf52e | [
"MIT"
] | 1 | 2019-10-30T14:33:37.000Z | 2019-10-31T15:01:09.000Z | include/ouchilib/crypto/algorithm/mugi.hpp | ouchiminh/ouchilib | de1bab0aa75c9e567ce06d76c95bc330dffbf52e | [
"MIT"
] | null | null | null | #pragma once
#include <type_traits>
#include "ouchilib/math/gf.hpp"
#include "ouchilib/math/matrix.hpp"
#include "../common.hpp"
#include "aes.hpp"
namespace ouchi::crypto {
struct mugi {
static constexpr unsigned vec_size = 16;
using result_type = std::uint64_t;
mugi() = default;
mugi(memory_view<vec_size> key, memory_view<vec_size> iv)
: a_{ detail::pack<std::uint64_t>(key.data),
detail::pack<std::uint64_t>(key.data+8),
(rotl(detail::pack<std::uint64_t>(key.data), 7)) ^ (rotr(detail::pack<std::uint64_t>(key.data+8), 7)) ^ c[0] }
, b_{}
{
constexpr std::uint64_t zero[16] = {};
for (auto i = 0u; i < 16; ++i) {
rho(zero);
b_[15-i] = a_[0];
}
a_[0] ^= detail::pack<std::uint64_t>(iv.data);
a_[1] ^= detail::pack<std::uint64_t>(iv.data + 8);
a_[2] ^= rotl(detail::pack<std::uint64_t>(iv.data), 7) ^
rotr(detail::pack<std::uint64_t>(iv.data + 8), 7) ^ c[0];
for (auto i = 0u; i < 16; ++i) rho(zero);
for (auto i = 0u; i < 16; ++i) update();
}
~mugi()
{
secure_memset(a_, 0);
secure_memset(b_, 0);
}
result_type operator()() noexcept
{
auto cp = a_[2];
update();
return cp;
}
void discard(size_t n) noexcept
{
for (auto i = 0ull; i < n; ++i) (void)operator()();
}
private:
std::uint64_t a_[3];
std::uint64_t b_[16];
static constexpr std::uint64_t c[3] = {
0x6A09E667F3BCC908,0xBB67AE8584CAA73B,0x3C6EF372FE94F82B
};
void update() noexcept
{
std::uint64_t at[3] = { a_[0], a_[1], a_[2] };
rho(b_); lambda(at);
}
void rho(const std::uint64_t (&b)[16]) noexcept
{
std::uint64_t a0 = a_[0], a1 = a_[1];
a_[0] = a_[1];
a_[1] = a_[2] ^ F(a_[1], b[4]) ^ c[1];
a_[2] = a0 ^ F(a1, rotl(b[10], 17)) ^ c[2];
}
void lambda(const std::uint64_t (&a)[3]) noexcept
{
std::uint64_t bt[16];
std::memcpy(bt, b_, sizeof(bt));
for (auto i :{ 1,2,3,5,6,7,8,9,11,12,13,14,15 }) {
b_[i] = bt[i - 1];
}
b_[0] = bt[15] ^ a[0];
b_[4] = bt[3] ^ bt[7];
b_[10] = bt[9] ^ rotl(bt[13], 32);
}
std::uint64_t F(std::uint64_t x, std::uint64_t b) const noexcept
{
std::uint8_t o[8] = {};
detail::unpack(x ^ b, o);
for (auto& i : o) { i = (std::uint8_t)aes128::subchar(i); }
std::uint32_t ph = detail::pack<std::uint32_t>(o);
std::uint32_t pl = detail::pack<std::uint32_t>(o + 4);
auto qh = M(ph), ql = M(pl);
return
(((ql >> 24) & 0xFFull) << 56) |
(((ql >> 16) & 0xFFull) << 48) |
(((qh >> 8) & 0xFFull) << 40) |
(((qh >> 0) & 0xFFull) << 32) |
(((qh >> 24) & 0xFFull) << 24) |
(((qh >> 16) & 0xFFull) << 16) |
(((ql >> 8) & 0xFFull) << 8) |
((ql >> 0) & 0xFFull);
}
std::uint32_t M(std::uint32_t x) const noexcept
{
using gf256 = ouchi::math::gf<unsigned char, 0x1b>;
constexpr ouchi::math::fl_matrix<gf256, 4, 4> m{
gf256{0x02},gf256{0x03},gf256{0x01},gf256{0x01},
gf256{0x01},gf256{0x02},gf256{0x03},gf256{0x01},
gf256{0x01},gf256{0x01},gf256{0x02},gf256{0x03},
gf256{0x03},gf256{0x01},gf256{0x01},gf256{0x02}
};
ouchi::math::fl_matrix<gf256, 4, 1> xm({
gf256{(x >> 24)&0xff},
gf256{(x >> 16)&0xff},
gf256{(x >> 8)&0xff},
gf256{(x >> 0)&0xff}
});
auto r = m * xm;
return detail::pack<std::uint32_t>(r.data());
}
};
}
| 32.042735 | 123 | 0.486263 | ouchiminh |
d0a23b9cbdba85704b8ff417427ebfafaf0b160e | 1,289 | cpp | C++ | may20/pizzav2.cpp | HectorFuentes/COP1334C | 1092278e1c6381d1e49a97a4065f2a2cd8b81e5d | [
"MIT"
] | null | null | null | may20/pizzav2.cpp | HectorFuentes/COP1334C | 1092278e1c6381d1e49a97a4065f2a2cd8b81e5d | [
"MIT"
] | null | null | null | may20/pizzav2.cpp | HectorFuentes/COP1334C | 1092278e1c6381d1e49a97a4065f2a2cd8b81e5d | [
"MIT"
] | null | null | null | /*pizza.cpp
Michelle Levine
May 20, 2015
This program prompts the user for some information about a pizza.
The slice area and cost are calculated and displayed.
*/
//preprocessor directives
#include<iostream>
#include<iomanip>
#include<cmath> //needed for the pow function
using namespace std;
int main()
{
//Declare and initialize variables and constants
float radius = 0.0, pizzaCost = 0.0, pizzaArea = 0.0, sliceCost = 0.0, sliceArea = 0.0;
int numSlices = 0;
const float PI = 3.14;
//Intro
cout<<"WELCOME TO THE BROWARD PIZZERIA!!\n\n";
//Prompt for radius
cout<<"Enter the radius of the pizza(in): ";
cin>>radius;
//Prompt for pizzaCost
cout<<"\nEnter the total cost of the pizza : $";
cin>>pizzaCost;
//Prompt for numSlices
cout<<"\nEnter the number of slices in the pizza: ";
cin>>numSlices;
//Calculate pizzaArea
pizzaArea = PI * pow(radius,2); //radius ^ 2
//Calculate sliceArea
sliceArea = pizzaArea / numSlices;
//Calculate sliceCost
sliceCost = pizzaCost / numSlices;
//Display sliceArea and sliceCost
cout<<"************************************\n";
cout<<fixed<<showpoint<<setprecision(2);
cout<<"\nArea of a single slice of pizza:\t"<<sliceArea<<" sq. in.\n";
cout<<"Cost of a single slice of pizza:\t$"<<sliceCost<<endl;
return 0;
}
| 24.320755 | 88 | 0.683476 | HectorFuentes |
d0a6ee74af41a1e3569b0f16700d167741d4e428 | 48,868 | cpp | C++ | VirtualBox-5.0.0/src/VBox/Frontends/VBoxSDL/Framebuffer.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | 1 | 2015-04-30T14:18:45.000Z | 2015-04-30T14:18:45.000Z | VirtualBox-5.0.0/src/VBox/Frontends/VBoxSDL/Framebuffer.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | VirtualBox-5.0.0/src/VBox/Frontends/VBoxSDL/Framebuffer.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | /* $Id: Framebuffer.cpp $ */
/** @file
*
* VBox frontends: VBoxSDL (simple frontend based on SDL):
* Implementation of VBoxSDLFB (SDL framebuffer) class
*/
/*
* Copyright (C) 2006-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <VBox/com/com.h>
#include <VBox/com/array.h>
#include <VBox/com/string.h>
#include <VBox/com/Guid.h>
#include <VBox/com/ErrorInfo.h>
#include <VBox/com/VirtualBox.h>
#include <iprt/stream.h>
#include <iprt/env.h>
#ifdef RT_OS_OS2
# undef RT_MAX
// from <iprt/cdefs.h>
# define RT_MAX(Value1, Value2) ((Value1) >= (Value2) ? (Value1) : (Value2))
#endif
using namespace com;
#define LOG_GROUP LOG_GROUP_GUI
#include <VBox/err.h>
#include <VBox/log.h>
#include "VBoxSDL.h"
#include "Framebuffer.h"
#include "Ico64x01.h"
#if defined(RT_OS_WINDOWS) || defined(RT_OS_LINUX)
#include <SDL_syswm.h> /* for SDL_GetWMInfo() */
#endif
#if defined(VBOX_WITH_XPCOM)
NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VBoxSDLFB, IFramebuffer)
NS_DECL_CLASSINFO(VBoxSDLFB)
NS_IMPL_THREADSAFE_ISUPPORTS2_CI(VBoxSDLFBOverlay, IFramebufferOverlay, IFramebuffer)
NS_DECL_CLASSINFO(VBoxSDLFBOverlay)
#endif
#ifdef VBOX_SECURELABEL
/* function pointers */
extern "C"
{
DECLSPEC int (SDLCALL *pTTF_Init)(void);
DECLSPEC TTF_Font* (SDLCALL *pTTF_OpenFont)(const char *file, int ptsize);
DECLSPEC SDL_Surface* (SDLCALL *pTTF_RenderUTF8_Solid)(TTF_Font *font, const char *text, SDL_Color fg);
DECLSPEC SDL_Surface* (SDLCALL *pTTF_RenderUTF8_Blended)(TTF_Font *font, const char *text, SDL_Color fg);
DECLSPEC void (SDLCALL *pTTF_CloseFont)(TTF_Font *font);
DECLSPEC void (SDLCALL *pTTF_Quit)(void);
}
#endif /* VBOX_SECURELABEL */
static bool gfSdlInitialized = false; /**< if SDL was initialized */
static SDL_Surface *gWMIcon = NULL; /**< the application icon */
static RTNATIVETHREAD gSdlNativeThread = NIL_RTNATIVETHREAD; /**< the SDL thread */
//
// Constructor / destructor
//
VBoxSDLFB::VBoxSDLFB()
{
}
HRESULT VBoxSDLFB::FinalConstruct()
{
return 0;
}
void VBoxSDLFB::FinalRelease()
{
return;
}
/**
* SDL framebuffer constructor. It is called from the main
* (i.e. SDL) thread. Therefore it is safe to use SDL calls
* here.
* @param fFullscreen flag whether we start in fullscreen mode
* @param fResizable flag whether the SDL window should be resizable
* @param fShowSDLConfig flag whether we print out SDL settings
* @param fKeepHostRes flag whether we switch the host screen resolution
* when switching to fullscreen or not
* @param iFixedWidth fixed SDL width (-1 means not set)
* @param iFixedHeight fixed SDL height (-1 means not set)
*/
HRESULT VBoxSDLFB::init(uint32_t uScreenId,
bool fFullscreen, bool fResizable, bool fShowSDLConfig,
bool fKeepHostRes, uint32_t u32FixedWidth,
uint32_t u32FixedHeight, uint32_t u32FixedBPP,
bool fUpdateImage)
{
int rc;
LogFlow(("VBoxSDLFB::VBoxSDLFB\n"));
mScreenId = uScreenId;
mfUpdateImage = fUpdateImage;
mScreen = NULL;
#ifdef VBOX_WITH_SDL13
mWindow = 0;
mTexture = 0;
#endif
mSurfVRAM = NULL;
mfInitialized = false;
mfFullscreen = fFullscreen;
mfKeepHostRes = fKeepHostRes;
mTopOffset = 0;
mfResizable = fResizable;
mfShowSDLConfig = fShowSDLConfig;
mFixedSDLWidth = u32FixedWidth;
mFixedSDLHeight = u32FixedHeight;
mFixedSDLBPP = u32FixedBPP;
mCenterXOffset = 0;
mCenterYOffset = 0;
/* Start with standard screen dimensions. */
mGuestXRes = 640;
mGuestYRes = 480;
mPtrVRAM = NULL;
mBitsPerPixel = 0;
mBytesPerLine = 0;
mfSameSizeRequested = false;
#ifdef VBOX_SECURELABEL
mLabelFont = NULL;
mLabelHeight = 0;
mLabelOffs = 0;
#endif
mfUpdates = false;
rc = RTCritSectInit(&mUpdateLock);
AssertMsg(rc == VINF_SUCCESS, ("Error from RTCritSectInit!\n"));
resizeGuest();
Assert(mScreen);
mfInitialized = true;
#ifdef RT_OS_WINDOWS
HRESULT hr = CoCreateFreeThreadedMarshaler(this, //GetControllingUnknown(),
&m_pUnkMarshaler.p);
Log(("CoCreateFreeThreadedMarshaler hr %08X\n", hr));
#endif
return 0;
}
VBoxSDLFB::~VBoxSDLFB()
{
LogFlow(("VBoxSDLFB::~VBoxSDLFB\n"));
if (mSurfVRAM)
{
SDL_FreeSurface(mSurfVRAM);
mSurfVRAM = NULL;
}
mScreen = NULL;
#ifdef VBOX_SECURELABEL
if (mLabelFont)
pTTF_CloseFont(mLabelFont);
if (pTTF_Quit)
pTTF_Quit();
#endif
RTCritSectDelete(&mUpdateLock);
}
bool VBoxSDLFB::init(bool fShowSDLConfig)
{
LogFlow(("VBoxSDLFB::init\n"));
/* memorize the thread that inited us, that's the SDL thread */
gSdlNativeThread = RTThreadNativeSelf();
#ifdef RT_OS_WINDOWS
/* default to DirectX if nothing else set */
if (!RTEnvExist("SDL_VIDEODRIVER"))
{
_putenv("SDL_VIDEODRIVER=directx");
// _putenv("SDL_VIDEODRIVER=windib");
}
#endif
#ifdef VBOXSDL_WITH_X11
/* On some X servers the mouse is stuck inside the bottom right corner.
* See http://wiki.clug.org.za/wiki/QEMU_mouse_not_working */
RTEnvSet("SDL_VIDEO_X11_DGAMOUSE", "0");
#endif
int rc = SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE);
if (rc != 0)
{
RTPrintf("SDL Error: '%s'\n", SDL_GetError());
return false;
}
gfSdlInitialized = true;
const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo();
Assert(videoInfo);
if (videoInfo)
{
/* output what SDL is capable of */
if (fShowSDLConfig)
RTPrintf("SDL capabilities:\n"
" Hardware surface support: %s\n"
" Window manager available: %s\n"
" Screen to screen blits accelerated: %s\n"
" Screen to screen colorkey blits accelerated: %s\n"
" Screen to screen alpha blits accelerated: %s\n"
" Memory to screen blits accelerated: %s\n"
" Memory to screen colorkey blits accelerated: %s\n"
" Memory to screen alpha blits accelerated: %s\n"
" Color fills accelerated: %s\n"
" Video memory in kilobytes: %d\n"
" Optimal bpp mode: %d\n"
"SDL video driver: %s\n",
videoInfo->hw_available ? "yes" : "no",
videoInfo->wm_available ? "yes" : "no",
videoInfo->blit_hw ? "yes" : "no",
videoInfo->blit_hw_CC ? "yes" : "no",
videoInfo->blit_hw_A ? "yes" : "no",
videoInfo->blit_sw ? "yes" : "no",
videoInfo->blit_sw_CC ? "yes" : "no",
videoInfo->blit_sw_A ? "yes" : "no",
videoInfo->blit_fill ? "yes" : "no",
videoInfo->video_mem,
videoInfo->vfmt->BitsPerPixel,
RTEnvGet("SDL_VIDEODRIVER"));
}
if (12320 == g_cbIco64x01)
{
gWMIcon = SDL_AllocSurface(SDL_SWSURFACE, 64, 64, 24, 0xff, 0xff00, 0xff0000, 0);
/** @todo make it as simple as possible. No PNM interpreter here... */
if (gWMIcon)
{
memcpy(gWMIcon->pixels, g_abIco64x01+32, g_cbIco64x01-32);
SDL_WM_SetIcon(gWMIcon, NULL);
}
}
return true;
}
/**
* Terminate SDL
*
* @remarks must be called from the SDL thread!
*/
void VBoxSDLFB::uninit()
{
if (gfSdlInitialized)
{
AssertMsg(gSdlNativeThread == RTThreadNativeSelf(), ("Wrong thread! SDL is not threadsafe!\n"));
SDL_QuitSubSystem(SDL_INIT_VIDEO);
if (gWMIcon)
{
SDL_FreeSurface(gWMIcon);
gWMIcon = NULL;
}
}
}
/**
* Returns the current framebuffer width in pixels.
*
* @returns COM status code
* @param width Address of result buffer.
*/
STDMETHODIMP VBoxSDLFB::COMGETTER(Width)(ULONG *width)
{
LogFlow(("VBoxSDLFB::GetWidth\n"));
if (!width)
return E_INVALIDARG;
*width = mGuestXRes;
return S_OK;
}
/**
* Returns the current framebuffer height in pixels.
*
* @returns COM status code
* @param height Address of result buffer.
*/
STDMETHODIMP VBoxSDLFB::COMGETTER(Height)(ULONG *height)
{
LogFlow(("VBoxSDLFB::GetHeight\n"));
if (!height)
return E_INVALIDARG;
*height = mGuestYRes;
return S_OK;
}
/**
* Return the current framebuffer color depth.
*
* @returns COM status code
* @param bitsPerPixel Address of result variable
*/
STDMETHODIMP VBoxSDLFB::COMGETTER(BitsPerPixel)(ULONG *bitsPerPixel)
{
LogFlow(("VBoxSDLFB::GetBitsPerPixel\n"));
if (!bitsPerPixel)
return E_INVALIDARG;
/* get the information directly from the surface in use */
Assert(mSurfVRAM);
*bitsPerPixel = (ULONG)(mSurfVRAM ? mSurfVRAM->format->BitsPerPixel : 0);
return S_OK;
}
/**
* Return the current framebuffer line size in bytes.
*
* @returns COM status code.
* @param lineSize Address of result variable.
*/
STDMETHODIMP VBoxSDLFB::COMGETTER(BytesPerLine)(ULONG *bytesPerLine)
{
LogFlow(("VBoxSDLFB::GetBytesPerLine\n"));
if (!bytesPerLine)
return E_INVALIDARG;
/* get the information directly from the surface */
Assert(mSurfVRAM);
*bytesPerLine = (ULONG)(mSurfVRAM ? mSurfVRAM->pitch : 0);
return S_OK;
}
STDMETHODIMP VBoxSDLFB::COMGETTER(PixelFormat) (BitmapFormat_T *pixelFormat)
{
if (!pixelFormat)
return E_POINTER;
*pixelFormat = BitmapFormat_BGR;
return S_OK;
}
/**
* Returns by how many pixels the guest should shrink its
* video mode height values.
*
* @returns COM status code.
* @param heightReduction Address of result variable.
*/
STDMETHODIMP VBoxSDLFB::COMGETTER(HeightReduction)(ULONG *heightReduction)
{
if (!heightReduction)
return E_POINTER;
#ifdef VBOX_SECURELABEL
*heightReduction = mLabelHeight;
#else
*heightReduction = 0;
#endif
return S_OK;
}
/**
* Returns a pointer to an alpha-blended overlay used for displaying status
* icons above the framebuffer.
*
* @returns COM status code.
* @param aOverlay The overlay framebuffer.
*/
STDMETHODIMP VBoxSDLFB::COMGETTER(Overlay)(IFramebufferOverlay **aOverlay)
{
if (!aOverlay)
return E_POINTER;
/* Not yet implemented */
*aOverlay = 0;
return S_OK;
}
/**
* Returns handle of window where framebuffer context is being drawn
*
* @returns COM status code.
* @param winId Handle of associated window.
*/
STDMETHODIMP VBoxSDLFB::COMGETTER(WinId)(LONG64 *winId)
{
if (!winId)
return E_POINTER;
#ifdef RT_OS_DARWIN
if (mWinId == NULL) /* (In case it failed the first time.) */
mWinId = (intptr_t)VBoxSDLGetDarwinWindowId();
#endif
*winId = mWinId;
return S_OK;
}
STDMETHODIMP VBoxSDLFB::COMGETTER(Capabilities)(ComSafeArrayOut(FramebufferCapabilities_T, aCapabilities))
{
if (ComSafeArrayOutIsNull(aCapabilities))
return E_POINTER;
com::SafeArray<FramebufferCapabilities_T> caps;
if (mfUpdateImage)
{
caps.resize(1);
caps[0] = FramebufferCapabilities_UpdateImage;
}
else
{
/* No caps to return. */
}
caps.detachTo(ComSafeArrayOutArg(aCapabilities));
return S_OK;
}
/**
* Notify framebuffer of an update.
*
* @returns COM status code
* @param x Update region upper left corner x value.
* @param y Update region upper left corner y value.
* @param w Update region width in pixels.
* @param h Update region height in pixels.
* @param finished Address of output flag whether the update
* could be fully processed in this call (which
* has to return immediately) or VBox should wait
* for a call to the update complete API before
* continuing with display updates.
*/
STDMETHODIMP VBoxSDLFB::NotifyUpdate(ULONG x, ULONG y,
ULONG w, ULONG h)
{
/*
* The input values are in guest screen coordinates.
*/
LogFlow(("VBoxSDLFB::NotifyUpdate: x = %d, y = %d, w = %d, h = %d\n",
x, y, w, h));
#ifdef VBOXSDL_WITH_X11
/*
* SDL does not allow us to make this call from any other thread than
* the main SDL thread (which initialized the video mode). So we have
* to send an event to the main SDL thread and process it there. For
* sake of simplicity, we encode all information in the event parameters.
*/
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.code = mScreenId;
event.user.type = SDL_USER_EVENT_UPDATERECT;
// 16 bit is enough for coordinates
event.user.data1 = (void*)(uintptr_t)(x << 16 | y);
event.user.data2 = (void*)(uintptr_t)(w << 16 | h);
PushNotifyUpdateEvent(&event);
#else /* !VBOXSDL_WITH_X11 */
update(x, y, w, h, true /* fGuestRelative */);
#endif /* !VBOXSDL_WITH_X11 */
return S_OK;
}
STDMETHODIMP VBoxSDLFB::NotifyUpdateImage(ULONG aX,
ULONG aY,
ULONG aWidth,
ULONG aHeight,
ComSafeArrayIn(BYTE, aImage))
{
LogFlow(("NotifyUpdateImage: %d,%d %dx%d\n", aX, aY, aWidth, aHeight));
com::SafeArray<BYTE> image(ComSafeArrayInArg(aImage));
/* Copy to mSurfVRAM. */
SDL_Rect srcRect;
SDL_Rect dstRect;
srcRect.x = 0;
srcRect.y = 0;
srcRect.w = (uint16_t)aWidth;
srcRect.h = (uint16_t)aHeight;
dstRect.x = (int16_t)aX;
dstRect.y = (int16_t)aY;
dstRect.w = (uint16_t)aWidth;
dstRect.h = (uint16_t)aHeight;
const uint32_t Rmask = 0x00FF0000, Gmask = 0x0000FF00, Bmask = 0x000000FF, Amask = 0;
SDL_Surface *surfSrc = SDL_CreateRGBSurfaceFrom(image.raw(), aWidth, aHeight, 32, aWidth * 4,
Rmask, Gmask, Bmask, Amask);
if (surfSrc)
{
RTCritSectEnter(&mUpdateLock);
if (mfUpdates)
SDL_BlitSurface(surfSrc, &srcRect, mSurfVRAM, &dstRect);
RTCritSectLeave(&mUpdateLock);
SDL_FreeSurface(surfSrc);
}
return NotifyUpdate(aX, aY, aWidth, aHeight);
}
extern ComPtr<IDisplay> gpDisplay;
STDMETHODIMP VBoxSDLFB::NotifyChange(ULONG aScreenId,
ULONG aXOrigin,
ULONG aYOrigin,
ULONG aWidth,
ULONG aHeight)
{
LogRel(("NotifyChange: %d %d,%d %dx%d\n",
aScreenId, aXOrigin, aYOrigin, aWidth, aHeight));
ComPtr<IDisplaySourceBitmap> pSourceBitmap;
if (!mfUpdateImage)
gpDisplay->QuerySourceBitmap(aScreenId, pSourceBitmap.asOutParam());
RTCritSectEnter(&mUpdateLock);
/* Disable screen updates. */
mfUpdates = false;
if (mfUpdateImage)
{
mGuestXRes = aWidth;
mGuestYRes = aHeight;
mPtrVRAM = NULL;
mBitsPerPixel = 0;
mBytesPerLine = 0;
}
else
{
/* Save the new bitmap. */
mpPendingSourceBitmap = pSourceBitmap;
}
RTCritSectLeave(&mUpdateLock);
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.type = SDL_USER_EVENT_NOTIFYCHANGE;
event.user.code = mScreenId;
PushSDLEventForSure(&event);
RTThreadYield();
return S_OK;
}
/**
* Returns whether we like the given video mode.
*
* @returns COM status code
* @param width video mode width in pixels
* @param height video mode height in pixels
* @param bpp video mode bit depth in bits per pixel
* @param supported pointer to result variable
*/
STDMETHODIMP VBoxSDLFB::VideoModeSupported(ULONG width, ULONG height, ULONG bpp, BOOL *supported)
{
if (!supported)
return E_POINTER;
/* are constraints set? */
if ( ( (mMaxScreenWidth != ~(uint32_t)0)
&& (width > mMaxScreenWidth))
|| ( (mMaxScreenHeight != ~(uint32_t)0)
&& (height > mMaxScreenHeight)))
{
/* nope, we don't want that (but still don't freak out if it is set) */
#ifdef DEBUG
printf("VBoxSDL::VideoModeSupported: we refused mode %dx%dx%d\n", width, height, bpp);
#endif
*supported = false;
}
else
{
/* anything will do */
*supported = true;
}
return S_OK;
}
STDMETHODIMP VBoxSDLFB::GetVisibleRegion(BYTE *aRectangles, ULONG aCount,
ULONG *aCountCopied)
{
PRTRECT rects = (PRTRECT)aRectangles;
if (!rects)
return E_POINTER;
/// @todo
NOREF(aCount);
NOREF(aCountCopied);
return S_OK;
}
STDMETHODIMP VBoxSDLFB::SetVisibleRegion(BYTE *aRectangles, ULONG aCount)
{
PRTRECT rects = (PRTRECT)aRectangles;
if (!rects)
return E_POINTER;
/// @todo
NOREF(aCount);
return S_OK;
}
STDMETHODIMP VBoxSDLFB::ProcessVHWACommand(BYTE *pCommand)
{
return E_NOTIMPL;
}
STDMETHODIMP VBoxSDLFB::Notify3DEvent(ULONG uType, ComSafeArrayIn(BYTE, aData))
{
return E_NOTIMPL;
}
//
// Internal public methods
//
/* This method runs on the main SDL thread. */
void VBoxSDLFB::notifyChange(ULONG aScreenId)
{
/* Disable screen updates. */
RTCritSectEnter(&mUpdateLock);
if (!mfUpdateImage && mpPendingSourceBitmap.isNull())
{
/* Do nothing. Change event already processed. */
RTCritSectLeave(&mUpdateLock);
return;
}
/* Release the current bitmap and keep the pending one. */
mpSourceBitmap = mpPendingSourceBitmap;
mpPendingSourceBitmap.setNull();
RTCritSectLeave(&mUpdateLock);
if (mpSourceBitmap.isNull())
{
mPtrVRAM = NULL;
mBitsPerPixel = 32;
mBytesPerLine = mGuestXRes * 4;
}
else
{
BYTE *pAddress = NULL;
ULONG ulWidth = 0;
ULONG ulHeight = 0;
ULONG ulBitsPerPixel = 0;
ULONG ulBytesPerLine = 0;
BitmapFormat_T bitmapFormat = BitmapFormat_Opaque;
mpSourceBitmap->QueryBitmapInfo(&pAddress,
&ulWidth,
&ulHeight,
&ulBitsPerPixel,
&ulBytesPerLine,
&bitmapFormat);
if ( mGuestXRes == ulWidth
&& mGuestYRes == ulHeight
&& mBitsPerPixel == ulBitsPerPixel
&& mBytesPerLine == ulBytesPerLine
&& mPtrVRAM == pAddress
)
{
mfSameSizeRequested = true;
}
else
{
mfSameSizeRequested = false;
}
mGuestXRes = ulWidth;
mGuestYRes = ulHeight;
mPtrVRAM = pAddress;
mBitsPerPixel = ulBitsPerPixel;
mBytesPerLine = ulBytesPerLine;
}
resizeGuest();
gpDisplay->InvalidateAndUpdateScreen(aScreenId);
}
/**
* Method that does the actual resize of the guest framebuffer and
* then changes the SDL framebuffer setup.
*/
void VBoxSDLFB::resizeGuest()
{
LogFlowFunc (("mGuestXRes: %d, mGuestYRes: %d\n", mGuestXRes, mGuestYRes));
AssertMsg(gSdlNativeThread == RTThreadNativeSelf(),
("Wrong thread! SDL is not threadsafe!\n"));
RTCritSectEnter(&mUpdateLock);
const uint32_t Rmask = 0x00FF0000, Gmask = 0x0000FF00, Bmask = 0x000000FF, Amask = 0;
/* first free the current surface */
if (mSurfVRAM)
{
SDL_FreeSurface(mSurfVRAM);
mSurfVRAM = NULL;
}
if (mPtrVRAM)
{
/* Create a source surface from the source bitmap. */
mSurfVRAM = SDL_CreateRGBSurfaceFrom(mPtrVRAM, mGuestXRes, mGuestYRes, mBitsPerPixel,
mBytesPerLine, Rmask, Gmask, Bmask, Amask);
LogFlow(("VBoxSDL:: using the source bitmap\n"));
}
else
{
mSurfVRAM = SDL_CreateRGBSurface(SDL_SWSURFACE, mGuestXRes, mGuestYRes, mBitsPerPixel,
Rmask, Gmask, Bmask, Amask);
LogFlow(("VBoxSDL:: using SDL_SWSURFACE\n"));
}
LogFlow(("VBoxSDL:: created VRAM surface %p\n", mSurfVRAM));
if (mfSameSizeRequested)
{
mfSameSizeRequested = false;
LogFlow(("VBoxSDL:: the same resolution requested, skipping the resize.\n"));
}
else
{
/* now adjust the SDL resolution */
resizeSDL();
}
/* Enable screen updates. */
mfUpdates = true;
RTCritSectLeave(&mUpdateLock);
repaint();
}
/**
* Sets SDL video mode. This is independent from guest video
* mode changes.
*
* @remarks Must be called from the SDL thread!
*/
void VBoxSDLFB::resizeSDL(void)
{
LogFlow(("VBoxSDL:resizeSDL\n"));
/*
* We request a hardware surface from SDL so that we can perform
* accelerated system memory to VRAM blits. The way video handling
* works it that on the one hand we have the screen surface from SDL
* and on the other hand we have a software surface that we create
* using guest VRAM memory for linear modes and using SDL allocated
* system memory for text and non linear graphics modes. We never
* directly write to the screen surface but always use SDL blitting
* functions to blit from our system memory surface to the VRAM.
* Therefore, SDL can take advantage of hardware acceleration.
*/
int sdlFlags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
#ifndef RT_OS_OS2 /* doesn't seem to work for some reason... */
if (mfResizable)
sdlFlags |= SDL_RESIZABLE;
#endif
if (mfFullscreen)
sdlFlags |= SDL_FULLSCREEN;
/*
* Now we have to check whether there are video mode restrictions
*/
SDL_Rect **modes;
/* Get available fullscreen/hardware modes */
modes = SDL_ListModes(NULL, sdlFlags);
Assert(modes != NULL);
/* -1 means that any mode is possible (usually non fullscreen) */
if (modes != (SDL_Rect **)-1)
{
/*
* according to the SDL documentation, the API guarantees that
* the modes are sorted from larger to smaller, so we just
* take the first entry as the maximum.
*/
mMaxScreenWidth = modes[0]->w;
mMaxScreenHeight = modes[0]->h;
}
else
{
/* no restriction */
mMaxScreenWidth = ~(uint32_t)0;
mMaxScreenHeight = ~(uint32_t)0;
}
uint32_t newWidth;
uint32_t newHeight;
/* reset the centering offsets */
mCenterXOffset = 0;
mCenterYOffset = 0;
/* we either have a fixed SDL resolution or we take the guest's */
if (mFixedSDLWidth != ~(uint32_t)0)
{
newWidth = mFixedSDLWidth;
newHeight = mFixedSDLHeight;
}
else
{
newWidth = RT_MIN(mGuestXRes, mMaxScreenWidth);
#ifdef VBOX_SECURELABEL
newHeight = RT_MIN(mGuestYRes + mLabelHeight, mMaxScreenHeight);
#else
newHeight = RT_MIN(mGuestYRes, mMaxScreenHeight);
#endif
}
/* we don't have any extra space by default */
mTopOffset = 0;
#if defined(VBOX_WITH_SDL13)
int sdlWindowFlags = SDL_WINDOW_SHOWN;
if (mfResizable)
sdlWindowFlags |= SDL_WINDOW_RESIZABLE;
if (!mWindow)
{
SDL_DisplayMode desktop_mode;
int x = 40 + mScreenId * 20;
int y = 40 + mScreenId * 15;
SDL_GetDesktopDisplayMode(&desktop_mode);
/* create new window */
char szTitle[64];
RTStrPrintf(szTitle, sizeof(szTitle), "SDL window %d", mScreenId);
mWindow = SDL_CreateWindow(szTitle, x, y,
newWidth, newHeight, sdlWindowFlags);
if (SDL_CreateRenderer(mWindow, -1,
SDL_RENDERER_SINGLEBUFFER | SDL_RENDERER_PRESENTDISCARD) < 0)
AssertReleaseFailed();
SDL_GetRendererInfo(&mRenderInfo);
mTexture = SDL_CreateTexture(desktop_mode.format,
SDL_TEXTUREACCESS_STREAMING, newWidth, newHeight);
if (!mTexture)
AssertReleaseFailed();
}
else
{
int w, h;
uint32_t format;
int access;
/* resize current window */
SDL_GetWindowSize(mWindow, &w, &h);
if (w != (int)newWidth || h != (int)newHeight)
SDL_SetWindowSize(mWindow, newWidth, newHeight);
SDL_QueryTexture(mTexture, &format, &access, &w, &h);
SDL_SelectRenderer(mWindow);
SDL_DestroyTexture(mTexture);
mTexture = SDL_CreateTexture(format, access, newWidth, newHeight);
if (!mTexture)
AssertReleaseFailed();
}
void *pixels;
int pitch;
int w, h, bpp;
uint32_t Rmask, Gmask, Bmask, Amask;
uint32_t format;
if (SDL_QueryTexture(mTexture, &format, NULL, &w, &h) < 0)
AssertReleaseFailed();
if (!SDL_PixelFormatEnumToMasks(format, &bpp, &Rmask, &Gmask, &Bmask, &Amask))
AssertReleaseFailed();
if (SDL_QueryTexturePixels(mTexture, &pixels, &pitch) == 0)
{
mScreen = SDL_CreateRGBSurfaceFrom(pixels, w, h, bpp, pitch,
Rmask, Gmask, Bmask, Amask);
}
else
{
mScreen = SDL_CreateRGBSurface(0, w, h, bpp, Rmask, Gmask, Bmask, Amask);
AssertReleaseFailed();
}
SDL_SetClipRect(mScreen, NULL);
#else
/*
* Now set the screen resolution and get the surface pointer
* @todo BPP is not supported!
*/
mScreen = SDL_SetVideoMode(newWidth, newHeight, 0, sdlFlags);
/*
* Set the Window ID. Currently used for OpenGL accelerated guests.
*/
# if defined (RT_OS_WINDOWS)
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWMInfo(&info))
mWinId = (LONG64) info.window;
# elif defined (RT_OS_LINUX)
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWMInfo(&info))
mWinId = (LONG64) info.info.x11.wmwindow;
# elif defined(RT_OS_DARWIN)
mWinId = (intptr_t)VBoxSDLGetDarwinWindowId();
# else
/* XXX ignore this for other architectures */
# endif
#endif
#ifdef VBOX_SECURELABEL
/*
* For non fixed SDL resolution, the above call tried to add the label height
* to the guest height. If it worked, we have an offset. If it didn't the below
* code will try again with the original guest resolution.
*/
if (mFixedSDLWidth == ~(uint32_t)0)
{
/* if it didn't work, then we have to go for the original resolution and paint over the guest */
if (!mScreen)
{
mScreen = SDL_SetVideoMode(newWidth, newHeight - mLabelHeight, 0, sdlFlags);
}
else
{
/* we now have some extra space */
mTopOffset = mLabelHeight;
}
}
else
{
/* in case the guest resolution is small enough, we do have a top offset */
if (mFixedSDLHeight - mGuestYRes >= mLabelHeight)
mTopOffset = mLabelHeight;
/* we also might have to center the guest picture */
if (mFixedSDLWidth > mGuestXRes)
mCenterXOffset = (mFixedSDLWidth - mGuestXRes) / 2;
if (mFixedSDLHeight > mGuestYRes + mLabelHeight)
mCenterYOffset = (mFixedSDLHeight - (mGuestYRes + mLabelHeight)) / 2;
}
#endif
AssertMsg(mScreen, ("Error: SDL_SetVideoMode failed!\n"));
if (mScreen)
{
#ifdef VBOX_WIN32_UI
/* inform the UI code */
resizeUI(mScreen->w, mScreen->h);
#endif
if (mfShowSDLConfig)
RTPrintf("Resized to %dx%d, screen surface type: %s\n", mScreen->w, mScreen->h,
((mScreen->flags & SDL_HWSURFACE) == 0) ? "software" : "hardware");
}
}
/**
* Update specified framebuffer area. The coordinates can either be
* relative to the guest framebuffer or relative to the screen.
*
* @remarks Must be called from the SDL thread on Linux!
* @param x left column
* @param y top row
* @param w width in pixels
* @param h height in pixels
* @param fGuestRelative flag whether the above values are guest relative or screen relative;
*/
void VBoxSDLFB::update(int x, int y, int w, int h, bool fGuestRelative)
{
#ifdef VBOXSDL_WITH_X11
AssertMsg(gSdlNativeThread == RTThreadNativeSelf(), ("Wrong thread! SDL is not threadsafe!\n"));
#endif
RTCritSectEnter(&mUpdateLock);
Log(("Updates %d, %d,%d %dx%d\n", mfUpdates, x, y, w, h));
if (!mfUpdates)
{
RTCritSectLeave(&mUpdateLock);
return;
}
Assert(mScreen);
Assert(mSurfVRAM);
if (!mScreen || !mSurfVRAM)
{
RTCritSectLeave(&mUpdateLock);
return;
}
/* the source and destination rectangles */
SDL_Rect srcRect;
SDL_Rect dstRect;
/* this is how many pixels we have to cut off from the height for this specific blit */
int yCutoffGuest = 0;
#ifdef VBOX_SECURELABEL
bool fPaintLabel = false;
/* if we have a label and no space for it, we have to cut off a bit */
if (mLabelHeight && !mTopOffset)
{
if (y < (int)mLabelHeight)
yCutoffGuest = mLabelHeight - y;
}
#endif
/**
* If we get a SDL window relative update, we
* just perform a full screen update to keep things simple.
*
* @todo improve
*/
if (!fGuestRelative)
{
#ifdef VBOX_SECURELABEL
/* repaint the label if necessary */
if (y < (int)mLabelHeight)
fPaintLabel = true;
#endif
x = 0;
w = mGuestXRes;
y = 0;
h = mGuestYRes;
}
srcRect.x = x;
srcRect.y = y + yCutoffGuest;
srcRect.w = w;
srcRect.h = RT_MAX(0, h - yCutoffGuest);
/*
* Destination rectangle is just offset by the label height.
* There are two cases though: label height is added to the
* guest resolution (mTopOffset == mLabelHeight; yCutoffGuest == 0)
* or the label cuts off a portion of the guest screen (mTopOffset == 0;
* yCutoffGuest >= 0)
*/
dstRect.x = x + mCenterXOffset;
#ifdef VBOX_SECURELABEL
dstRect.y = RT_MAX(mLabelHeight, y + yCutoffGuest + mTopOffset) + mCenterYOffset;
#else
dstRect.y = y + yCutoffGuest + mTopOffset + mCenterYOffset;
#endif
dstRect.w = w;
dstRect.h = RT_MAX(0, h - yCutoffGuest);
/*
* Now we just blit
*/
SDL_BlitSurface(mSurfVRAM, &srcRect, mScreen, &dstRect);
/* hardware surfaces don't need update notifications */
#if defined(VBOX_WITH_SDL13)
AssertRelease(mScreen->flags & SDL_PREALLOC);
SDL_SelectRenderer(mWindow);
SDL_DirtyTexture(mTexture, 1, &dstRect);
AssertRelease(mRenderInfo.flags & SDL_RENDERER_PRESENTCOPY);
SDL_RenderCopy(mTexture, &dstRect, &dstRect);
SDL_RenderPresent();
#else
if ((mScreen->flags & SDL_HWSURFACE) == 0)
SDL_UpdateRect(mScreen, dstRect.x, dstRect.y, dstRect.w, dstRect.h);
#endif
#ifdef VBOX_SECURELABEL
if (fPaintLabel)
paintSecureLabel(0, 0, 0, 0, false);
#endif
RTCritSectLeave(&mUpdateLock);
}
/**
* Repaint the whole framebuffer
*
* @remarks Must be called from the SDL thread!
*/
void VBoxSDLFB::repaint()
{
AssertMsg(gSdlNativeThread == RTThreadNativeSelf(), ("Wrong thread! SDL is not threadsafe!\n"));
LogFlow(("VBoxSDLFB::repaint\n"));
update(0, 0, mScreen->w, mScreen->h, false /* fGuestRelative */);
}
/**
* Toggle fullscreen mode
*
* @remarks Must be called from the SDL thread!
*/
void VBoxSDLFB::setFullscreen(bool fFullscreen)
{
AssertMsg(gSdlNativeThread == RTThreadNativeSelf(), ("Wrong thread! SDL is not threadsafe!\n"));
LogFlow(("VBoxSDLFB::SetFullscreen: fullscreen: %d\n", fFullscreen));
mfFullscreen = fFullscreen;
/* only change the SDL resolution, do not touch the guest framebuffer */
resizeSDL();
repaint();
}
/**
* Return the geometry of the host. This isn't very well tested but it seems
* to work at least on Linux hosts.
*/
void VBoxSDLFB::getFullscreenGeometry(uint32_t *width, uint32_t *height)
{
SDL_Rect **modes;
/* Get available fullscreen/hardware modes */
modes = SDL_ListModes(NULL, SDL_FULLSCREEN);
Assert(modes != NULL);
/* -1 means that any mode is possible (usually non fullscreen) */
if (modes != (SDL_Rect **)-1)
{
/*
* According to the SDL documentation, the API guarantees that the modes
* are sorted from larger to smaller, so we just take the first entry as
* the maximum.
*
* XXX Crude Xinerama hack :-/
*/
if ( modes[0]->w > (16*modes[0]->h/9)
&& modes[1]
&& modes[1]->h == modes[0]->h)
{
*width = modes[1]->w;
*height = modes[1]->h;
}
else
{
*width = modes[0]->w;
*height = modes[0]->w;
}
}
}
#ifdef VBOX_SECURELABEL
/**
* Setup the secure labeling parameters
*
* @returns VBox status code
* @param height height of the secure label area in pixels
* @param font file path fo the TrueType font file
* @param pointsize font size in points
*/
int VBoxSDLFB::initSecureLabel(uint32_t height, char *font, uint32_t pointsize, uint32_t labeloffs)
{
LogFlow(("VBoxSDLFB:initSecureLabel: new offset: %d pixels, new font: %s, new pointsize: %d\n",
height, font, pointsize));
mLabelHeight = height;
mLabelOffs = labeloffs;
Assert(font);
pTTF_Init();
mLabelFont = pTTF_OpenFont(font, pointsize);
if (!mLabelFont)
{
AssertMsgFailed(("Failed to open TTF font file %s\n", font));
return VERR_OPEN_FAILED;
}
mSecureLabelColorFG = 0x0000FF00;
mSecureLabelColorBG = 0x00FFFF00;
repaint();
return VINF_SUCCESS;
}
/**
* Set the secure label text and repaint the label
*
* @param text UTF-8 string of new label
* @remarks must be called from the SDL thread!
*/
void VBoxSDLFB::setSecureLabelText(const char *text)
{
mSecureLabelText = text;
paintSecureLabel(0, 0, 0, 0, true);
}
/**
* Sets the secure label background color.
*
* @param colorFG encoded RGB value for text
* @param colorBG encored RGB value for background
* @remarks must be called from the SDL thread!
*/
void VBoxSDLFB::setSecureLabelColor(uint32_t colorFG, uint32_t colorBG)
{
mSecureLabelColorFG = colorFG;
mSecureLabelColorBG = colorBG;
paintSecureLabel(0, 0, 0, 0, true);
}
/**
* Paint the secure label if required
*
* @param fForce Force the repaint
* @remarks must be called from the SDL thread!
*/
void VBoxSDLFB::paintSecureLabel(int x, int y, int w, int h, bool fForce)
{
#ifdef VBOXSDL_WITH_X11
AssertMsg(gSdlNativeThread == RTThreadNativeSelf(), ("Wrong thread! SDL is not threadsafe!\n"));
#endif
/* only when the function is present */
if (!pTTF_RenderUTF8_Solid)
return;
/* check if we can skip the paint */
if (!fForce && ((uint32_t)y > mLabelHeight))
{
return;
}
/* first fill the background */
SDL_Rect rect = {0, 0, (Uint16)mScreen->w, (Uint16)mLabelHeight};
SDL_FillRect(mScreen, &rect, SDL_MapRGB(mScreen->format,
(mSecureLabelColorBG & 0x00FF0000) >> 16, /* red */
(mSecureLabelColorBG & 0x0000FF00) >> 8, /* green */
mSecureLabelColorBG & 0x000000FF)); /* blue */
/* now the text */
if ( mLabelFont != NULL
&& !mSecureLabelText.isEmpty()
)
{
SDL_Color clrFg = {(uint8_t)((mSecureLabelColorFG & 0x00FF0000) >> 16),
(uint8_t)((mSecureLabelColorFG & 0x0000FF00) >> 8),
(uint8_t)( mSecureLabelColorFG & 0x000000FF ), 0};
SDL_Surface *sText = (pTTF_RenderUTF8_Blended != NULL)
? pTTF_RenderUTF8_Blended(mLabelFont, mSecureLabelText.c_str(), clrFg)
: pTTF_RenderUTF8_Solid(mLabelFont, mSecureLabelText.c_str(), clrFg);
rect.x = 10;
rect.y = mLabelOffs;
SDL_BlitSurface(sText, NULL, mScreen, &rect);
SDL_FreeSurface(sText);
}
/* make sure to update the screen */
SDL_UpdateRect(mScreen, 0, 0, mScreen->w, mLabelHeight);
}
#endif /* VBOX_SECURELABEL */
// IFramebufferOverlay
///////////////////////////////////////////////////////////////////////////////////
/**
* Constructor for the VBoxSDLFBOverlay class (IFramebufferOverlay implementation)
*
* @param x Initial X offset for the overlay
* @param y Initial Y offset for the overlay
* @param width Initial width for the overlay
* @param height Initial height for the overlay
* @param visible Whether the overlay is initially visible
* @param alpha Initial alpha channel value for the overlay
*/
VBoxSDLFBOverlay::VBoxSDLFBOverlay(ULONG x, ULONG y, ULONG width, ULONG height,
BOOL visible, VBoxSDLFB *aParent) :
mOverlayX(x), mOverlayY(y), mOverlayWidth(width),
mOverlayHeight(height), mOverlayVisible(visible),
mParent(aParent)
{}
/**
* Destructor for the VBoxSDLFBOverlay class.
*/
VBoxSDLFBOverlay::~VBoxSDLFBOverlay()
{
SDL_FreeSurface(mBlendedBits);
SDL_FreeSurface(mOverlayBits);
}
/**
* Perform any initialisation of the overlay that can potentially fail
*
* @returns S_OK on success or the reason for the failure
*/
HRESULT VBoxSDLFBOverlay::init()
{
mBlendedBits = SDL_CreateRGBSurface(SDL_ANYFORMAT, mOverlayWidth, mOverlayHeight, 32,
0x00ff0000, 0x0000ff00, 0x000000ff, 0);
AssertMsgReturn(mBlendedBits != NULL, ("Failed to create an SDL surface\n"),
E_OUTOFMEMORY);
mOverlayBits = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, mOverlayWidth,
mOverlayHeight, 32, 0x00ff0000, 0x0000ff00,
0x000000ff, 0xff000000);
AssertMsgReturn(mOverlayBits != NULL, ("Failed to create an SDL surface\n"),
E_OUTOFMEMORY);
return S_OK;
}
/**
* Returns the current overlay X offset in pixels.
*
* @returns COM status code
* @param x Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(X)(ULONG *x)
{
LogFlow(("VBoxSDLFBOverlay::GetX\n"));
if (!x)
return E_INVALIDARG;
*x = mOverlayX;
return S_OK;
}
/**
* Returns the current overlay height in pixels.
*
* @returns COM status code
* @param height Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(Y)(ULONG *y)
{
LogFlow(("VBoxSDLFBOverlay::GetY\n"));
if (!y)
return E_INVALIDARG;
*y = mOverlayY;
return S_OK;
}
/**
* Returns the current overlay width in pixels. In fact, this returns the line size.
*
* @returns COM status code
* @param width Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(Width)(ULONG *width)
{
LogFlow(("VBoxSDLFBOverlay::GetWidth\n"));
if (!width)
return E_INVALIDARG;
*width = mOverlayBits->pitch;
return S_OK;
}
/**
* Returns the current overlay line size in pixels.
*
* @returns COM status code
* @param lineSize Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(BytesPerLine)(ULONG *bytesPerLine)
{
LogFlow(("VBoxSDLFBOverlay::GetBytesPerLine\n"));
if (!bytesPerLine)
return E_INVALIDARG;
*bytesPerLine = mOverlayBits->pitch;
return S_OK;
}
/**
* Returns the current overlay height in pixels.
*
* @returns COM status code
* @param height Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(Height)(ULONG *height)
{
LogFlow(("VBoxSDLFBOverlay::GetHeight\n"));
if (!height)
return E_INVALIDARG;
*height = mOverlayHeight;
return S_OK;
}
/**
* Returns whether the overlay is currently visible.
*
* @returns COM status code
* @param visible Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(Visible)(BOOL *visible)
{
LogFlow(("VBoxSDLFBOverlay::GetVisible\n"));
if (!visible)
return E_INVALIDARG;
*visible = mOverlayVisible;
return S_OK;
}
/**
* Sets whether the overlay is currently visible.
*
* @returns COM status code
* @param visible New value.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMSETTER(Visible)(BOOL visible)
{
LogFlow(("VBoxSDLFBOverlay::SetVisible\n"));
mOverlayVisible = visible;
return S_OK;
}
/**
* Returns the value of the global alpha channel.
*
* @returns COM status code
* @param alpha Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(Alpha)(ULONG *alpha)
{
LogFlow(("VBoxSDLFBOverlay::GetAlpha\n"));
return E_NOTIMPL;
}
/**
* Sets whether the overlay is currently visible.
*
* @returns COM status code
* @param alpha new value.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMSETTER(Alpha)(ULONG alpha)
{
LogFlow(("VBoxSDLFBOverlay::SetAlpha\n"));
return E_NOTIMPL;
}
/**
* Returns the address of the framebuffer bits for writing to.
*
* @returns COM status code
* @param alpha Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(Address)(ULONG *address)
{
LogFlow(("VBoxSDLFBOverlay::GetAddress\n"));
if (!address)
return E_INVALIDARG;
*address = (uintptr_t) mOverlayBits->pixels;
return S_OK;
}
/**
* Returns the current colour depth. In fact, this is always 32bpp.
*
* @returns COM status code
* @param bitsPerPixel Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(BitsPerPixel)(ULONG *bitsPerPixel)
{
LogFlow(("VBoxSDLFBOverlay::GetBitsPerPixel\n"));
if (!bitsPerPixel)
return E_INVALIDARG;
*bitsPerPixel = 32;
return S_OK;
}
/**
* Returns the current pixel format. In fact, this is always RGB.
*
* @returns COM status code
* @param pixelFormat Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(PixelFormat)(ULONG *pixelFormat)
{
LogFlow(("VBoxSDLFBOverlay::GetPixelFormat\n"));
if (!pixelFormat)
return E_INVALIDARG;
*pixelFormat = BitmapFormat_BGR;
return S_OK;
}
/**
* Returns whether the guest VRAM is used directly. In fact, this is always FALSE.
*
* @returns COM status code
* @param usesGuestVRAM Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(UsesGuestVRAM)(BOOL *usesGuestVRAM)
{
LogFlow(("VBoxSDLFBOverlay::GetUsesGuestVRAM\n"));
if (!usesGuestVRAM)
return E_INVALIDARG;
*usesGuestVRAM = FALSE;
return S_OK;
}
/**
* Returns the height reduction. In fact, this is always 0.
*
* @returns COM status code
* @param heightReduction Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(HeightReduction)(ULONG *heightReduction)
{
LogFlow(("VBoxSDLFBOverlay::GetHeightReduction\n"));
if (!heightReduction)
return E_INVALIDARG;
*heightReduction = 0;
return S_OK;
}
/**
* Returns the overlay for this framebuffer. Obviously, we return NULL here.
*
* @returns COM status code
* @param overlay Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(Overlay)(IFramebufferOverlay **aOverlay)
{
LogFlow(("VBoxSDLFBOverlay::GetOverlay\n"));
if (!aOverlay)
return E_INVALIDARG;
*aOverlay = 0;
return S_OK;
}
/**
* Returns associated window handle. We return NULL here.
*
* @returns COM status code
* @param winId Address of result buffer.
*/
STDMETHODIMP VBoxSDLFBOverlay::COMGETTER(WinId)(LONG64 *winId)
{
LogFlow(("VBoxSDLFBOverlay::GetWinId\n"));
if (!winId)
return E_INVALIDARG;
*winId = 0;
return S_OK;
}
/**
* Lock the overlay. This should not be used - lock the parent IFramebuffer instead.
*
* @returns COM status code
*/
STDMETHODIMP VBoxSDLFBOverlay::Lock()
{
LogFlow(("VBoxSDLFBOverlay::Lock\n"));
AssertMsgFailed(("You should not attempt to lock an IFramebufferOverlay object -\n"
"lock the parent IFramebuffer object instead.\n"));
return E_NOTIMPL;
}
/**
* Unlock the overlay.
*
* @returns COM status code
*/
STDMETHODIMP VBoxSDLFBOverlay::Unlock()
{
LogFlow(("VBoxSDLFBOverlay::Unlock\n"));
AssertMsgFailed(("You should not attempt to lock an IFramebufferOverlay object -\n"
"lock the parent IFramebuffer object instead.\n"));
return E_NOTIMPL;
}
/**
* Change the X and Y co-ordinates of the overlay area.
*
* @returns COM status code
* @param x New X co-ordinate.
* @param y New Y co-ordinate.
*/
STDMETHODIMP VBoxSDLFBOverlay::Move(ULONG x, ULONG y)
{
mOverlayX = x;
mOverlayY = y;
return S_OK;
}
/**
* Notify the overlay that a section of the framebuffer has been redrawn.
*
* @returns COM status code
* @param x X co-ordinate of upper left corner of modified area.
* @param y Y co-ordinate of upper left corner of modified area.
* @param w Width of modified area.
* @param h Height of modified area.
* @retval finished Set if the operation has completed.
*
* All we do here is to send a request to the parent to update the affected area,
* translating between our co-ordinate system and the parent's. It would be have
* been better to call the parent directly, but such is life. We leave bounds
* checking to the parent.
*/
STDMETHODIMP VBoxSDLFBOverlay::NotifyUpdate(ULONG x, ULONG y,
ULONG w, ULONG h)
{
return mParent->NotifyUpdate(x + mOverlayX, y + mOverlayY, w, h);
}
/**
* Change the dimensions of the overlay.
*
* @returns COM status code
* @param pixelFormat Must be BitmapFormat_BGR.
* @param vram Must be NULL.
* @param lineSize Ignored.
* @param w New overlay width.
* @param h New overlay height.
* @retval finished Set if the operation has completed.
*/
STDMETHODIMP VBoxSDLFBOverlay::RequestResize(ULONG aScreenId, ULONG pixelFormat, ULONG vram,
ULONG bitsPerPixel, ULONG bytesPerLine,
ULONG w, ULONG h, BOOL *finished)
{
AssertReturn(pixelFormat == BitmapFormat_BGR, E_INVALIDARG);
AssertReturn(vram == 0, E_INVALIDARG);
AssertReturn(bitsPerPixel == 32, E_INVALIDARG);
mOverlayWidth = w;
mOverlayHeight = h;
SDL_FreeSurface(mOverlayBits);
mBlendedBits = SDL_CreateRGBSurface(SDL_ANYFORMAT, mOverlayWidth, mOverlayHeight, 32,
0x00ff0000, 0x0000ff00, 0x000000ff, 0);
AssertMsgReturn(mBlendedBits != NULL, ("Failed to create an SDL surface\n"),
E_OUTOFMEMORY);
mOverlayBits = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, mOverlayWidth,
mOverlayHeight, 32, 0x00ff0000, 0x0000ff00,
0x000000ff, 0xff000000);
AssertMsgReturn(mOverlayBits != NULL, ("Failed to create an SDL surface\n"),
E_OUTOFMEMORY);
return S_OK;
}
/**
* Returns whether we like the given video mode.
*
* @returns COM status code
* @param width video mode width in pixels
* @param height video mode height in pixels
* @param bpp video mode bit depth in bits per pixel
* @retval supported pointer to result variable
*
* Basically, we support anything with 32bpp.
*/
STDMETHODIMP VBoxSDLFBOverlay::VideoModeSupported(ULONG width, ULONG height, ULONG bpp,
BOOL *supported)
{
if (!supported)
return E_POINTER;
if (bpp == 32)
*supported = true;
else
*supported = false;
return S_OK;
}
| 29.581114 | 106 | 0.622759 | egraba |
d0a7bec7424353250c0310a2f6ab72ef9d35ddb8 | 1,148 | cpp | C++ | PAT_A/PAT_A1070.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | 3 | 2019-07-08T05:20:28.000Z | 2021-09-22T10:53:26.000Z | PAT_A/PAT_A1070.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | null | null | null | PAT_A/PAT_A1070.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int n, d;
double tempF, profit = 0;
double amounts[1010], prices[1010], pricePerTon[1010];
struct item
{
double amount, prices, pricePerTon;
item(double _amount, double _prices, double _pricePerTon)
{
amount = _amount;
prices = _prices;
pricePerTon = _pricePerTon;
}
};
vector<item> items;
bool cmp(struct item &a, struct item &b) {return a.pricePerTon > b.pricePerTon;}
int main()
{
scanf("%d%d", &n, &d);
for(int i = 0; i < n; i++)
{
scanf("%lf", &tempF);
items.push_back(item(tempF, 0, 0));
}
for (int i = 0; i < n; i++)
{
scanf("%lf", &tempF);
items[i].prices = tempF;
items[i].pricePerTon = tempF / items[i].amount;
}
sort(items.begin(), items.end(), cmp);
for (int i = 0; i < items.size(); i++)
{
if(d <= items[i].amount)
{
profit += items[i].pricePerTon * d;
break;
}
else
{
profit += items[i].prices;
d -= items[i].amount;
}
}
printf("%.2lf\n", profit);
return 0;
} | 23.428571 | 80 | 0.515679 | EnhydraGod |
d0a96743b8e5ec7f9a0fc7cd18b9ece814290561 | 3,283 | cpp | C++ | src/Camera.cpp | hmkum/HMK-OpenGL-Demo | 254f5814ed1c552dd0ab348cd3ab9332c9d1ef70 | [
"MIT"
] | null | null | null | src/Camera.cpp | hmkum/HMK-OpenGL-Demo | 254f5814ed1c552dd0ab348cd3ab9332c9d1ef70 | [
"MIT"
] | null | null | null | src/Camera.cpp | hmkum/HMK-OpenGL-Demo | 254f5814ed1c552dd0ab348cd3ab9332c9d1ef70 | [
"MIT"
] | null | null | null | #include <cmath>
#include "Camera.h"
#include <thirdparty/glm/gtc/matrix_transform.hpp>
using namespace hmk;
static const float MaxVerticalAngle = 85.0f; //must be less than 90 to avoid gimbal lock
Camera::Camera() :
m_position(0.0f, 0.0f, 1.0f),
m_horizontalAngle(0.0f),
m_verticalAngle(0.0f),
m_fov(50.0f),
m_nearPlane(0.01f),
m_farPlane(100.0f),
m_viewportAspectRatio(4.0f/3.0f)
{
}
const glm::vec3& Camera::getPosition() const
{
return m_position;
}
void Camera::setPosition(const glm::vec3 &_position)
{
m_position = _position;
}
void Camera::offsetPosition(const glm::vec3 &offset)
{
m_position += offset;
}
float Camera::getFov() const
{
return m_fov;
}
void Camera::setFov(float _fov)
{
assert(_fov > 0.0f && _fov < 180.0f);
m_fov = _fov;
}
float Camera::getNearPlane() const
{
return m_nearPlane;
}
float Camera::getFarPlane() const
{
return m_farPlane;
}
void Camera::setNearAndFarPlanes(float _nearPlane, float _farPlane)
{
assert(_nearPlane > 0.0f);
assert(_farPlane > _nearPlane);
m_nearPlane = _nearPlane;
m_farPlane = _farPlane;
}
glm::mat4 Camera::getOrientation() const
{
glm::mat4 orientation = glm::mat4(1.0f);
orientation = glm::rotate(orientation, glm::radians(m_verticalAngle), glm::vec3(1,0,0));
orientation = glm::rotate(orientation, glm::radians(m_horizontalAngle), glm::vec3(0,1,0));
return orientation;
}
void Camera::offsetOrientation(float upAngle, float rightAngle)
{
m_horizontalAngle += rightAngle;
m_verticalAngle += upAngle;
NormalizeAngles();
}
void Camera::lookAt(glm::vec3 _position)
{
assert(_position != m_position);
auto direction = glm::normalize(m_position - _position);
m_verticalAngle = asinf(direction.y);
m_horizontalAngle = -atan2f(-direction.x, -direction.z);
NormalizeAngles();
}
float Camera::getViewportAspectRatio() const
{
return m_viewportAspectRatio;
}
void Camera::setViewportAspectRatio(float _viewportAspectRatio)
{
assert(_viewportAspectRatio > 0.0);
m_viewportAspectRatio = _viewportAspectRatio;
}
glm::vec3 Camera::getForward() const
{
auto forward = glm::inverse(getOrientation()) * glm::vec4(0,0,-1,1);
return glm::vec3(forward);
}
glm::vec3 Camera::getRight() const
{
auto right = glm::inverse(getOrientation()) * glm::vec4(1,0,0,1);
return glm::vec3(right);
}
glm::vec3 Camera::getUp() const
{
auto up = glm::inverse(getOrientation()) * glm::vec4(0,1,0,1);
return glm::vec3(up);
}
glm::mat4 Camera::getMatrix() const
{
return getProjection() * getView();
}
glm::mat4 Camera::getProjection() const
{
return glm::perspective(glm::radians(m_fov), m_viewportAspectRatio, m_nearPlane, m_farPlane);
}
glm::mat4 Camera::getView() const
{
return getOrientation() * glm::translate(glm::mat4(), -m_position);
}
void Camera::NormalizeAngles()
{
m_horizontalAngle = fmodf(m_horizontalAngle, 360.0f);
//fmodf can return negative values, but this will make them all positive
if(m_horizontalAngle < 0.0f)
m_horizontalAngle += 360.0f;
if(m_verticalAngle > MaxVerticalAngle)
m_verticalAngle = MaxVerticalAngle;
else if(m_verticalAngle < -MaxVerticalAngle)
m_verticalAngle = -MaxVerticalAngle;
}
| 22.798611 | 97 | 0.69601 | hmkum |
d0a987a31bf7d3d4181a725d0812bfb4c00305a2 | 8,851 | cpp | C++ | abclient/abclient/ClientPrediction.cpp | pablokawan/ABx | 064d6df265c48c667ce81b0a83f84e5e22a7ff53 | [
"MIT"
] | null | null | null | abclient/abclient/ClientPrediction.cpp | pablokawan/ABx | 064d6df265c48c667ce81b0a83f84e5e22a7ff53 | [
"MIT"
] | null | null | null | abclient/abclient/ClientPrediction.cpp | pablokawan/ABx | 064d6df265c48c667ce81b0a83f84e5e22a7ff53 | [
"MIT"
] | null | null | null | /**
* Copyright 2017-2020 Stefan Ascher
*
* 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 "ClientPrediction.h"
#include "Player.h"
#include "MathUtils.h"
#include <Urho3D/Physics/PhysicsWorld.h>
#include <Urho3D/Physics/CollisionShape.h>
#include <Urho3D/Physics/RigidBody.h>
#include "LevelManager.h"
void ClientPrediction::RegisterObject(Context* context)
{
context->RegisterFactory<ClientPrediction>();
}
ClientPrediction::ClientPrediction(Context* context) :
LogicComponent(context),
serverTime_(0)
{
serverPos_.y_ = std::numeric_limits<float>::max();
SetUpdateEventMask(USE_FIXEDUPDATE);
}
ClientPrediction::~ClientPrediction() = default;
void ClientPrediction::UpdateMove(float timeStep, uint8_t direction, float speedFactor)
{
if (direction == 0)
return;
const float speed = GetSpeed(timeStep, Game::BASE_MOVE_SPEED, speedFactor);
if ((direction & AB::GameProtocol::MoveDirectionNorth) == AB::GameProtocol::MoveDirectionNorth)
Move(speed, Vector3::FORWARD);
if ((direction & AB::GameProtocol::MoveDirectionSouth) == AB::GameProtocol::MoveDirectionSouth)
// Move slower backward
Move(speed, Vector3::BACK / 2.0f);
if ((direction & AB::GameProtocol::MoveDirectionWest) == AB::GameProtocol::MoveDirectionWest)
Move(speed, Vector3::LEFT / 2.0f);
if ((direction & AB::GameProtocol::MoveDirectionEast) == AB::GameProtocol::MoveDirectionEast)
Move(speed, Vector3::RIGHT / 2.0f);
}
bool ClientPrediction::CheckCollision(const Vector3& pos)
{
PhysicsWorld* physWorld = GetScene()->GetComponent<PhysicsWorld>();
if (!physWorld)
return true;
CollisionShape* collShape = node_->GetComponent<CollisionShape>(true);
if (!collShape)
return true;
RigidBody* rigidbody = node_->GetComponent<RigidBody>(true);
if (!rigidbody)
return true;
LevelManager* lMan = GetSubsystem<LevelManager>();
const bool isCollidingWithPlayers = !AB::Entities::IsOutpost(lMan->GetMapType());
// Actors always have AABB
const BoundingBox bb = collShape->GetWorldBoundingBox();
const Vector3 half = bb.HalfSize();
const BoundingBox newBB(pos - half, pos + half);
PODVector<RigidBody*> result;
physWorld->GetRigidBodies(result, newBB);
if (result.Size() < 2)
return true;
for (auto i = result.Begin(); i != result.End(); ++i)
{
if (!(*i)->GetNode())
continue;
Node* node = (*i)->GetNode()->GetParent();
if (!node)
continue;
if (node->GetComponent<Player>() != nullptr)
// Thats we
continue;
auto actor = node->GetComponent<Actor>();
if (!actor)
{
// Always collide with static objects on the same collision layer
auto* otherRb = (*i)->GetNode()->GetComponent<RigidBody>(true);
if (!otherRb)
return true;
if (rigidbody->GetCollisionLayer() & otherRb->GetCollisionLayer())
return false;
return true;
}
const ObjectType type = actor->objectType_;
if (type == ObjectType::Self)
// Don't collide with self
continue;
else if (type == ObjectType::Player && !isCollidingWithPlayers)
// Don't collide with other players in outposts
continue;
else if (type == ObjectType::AreaOfEffect || type == ObjectType::ItemDrop)
// Never collide with these
continue;
else if ((type == ObjectType::Player || type == ObjectType::Npc) && actor->IsDead())
// Dont collide with dead actors
continue;
// When we are here we do collide with some object and can't go to pos
return false;
}
return true;
}
void ClientPrediction::Move(float speed, const Vector3& amount)
{
Player* player = node_->GetComponent<Player>();
const Quaternion& oriention = player->rotateTo_;
Vector3 pos = player->moveToPos_;
const Matrix3 m = oriention.RotationMatrix();
const Vector3 a = amount * speed;
const Vector3 v = m * a;
pos += v;
Terrain* terrain = GetScene()->GetComponent<Terrain>(true);
if (terrain)
pos.y_ = terrain->GetHeight(pos);
else
{
if (!Equals(serverPos_.y_, std::numeric_limits<float>::max()))
pos.y_ = serverPos_.y_;
}
if (CheckCollision(pos))
player->moveToPos_ = pos;
}
void ClientPrediction::UpdateTurn(float timeStep, uint8_t direction, float speedFactor)
{
if (direction == 0)
return;
const float speed = GetSpeed(timeStep, Game::BASE_TURN_SPEED, speedFactor);
if ((direction & AB::GameProtocol::TurnDirectionLeft) == AB::GameProtocol::TurnDirectionLeft)
Turn(speed);
if ((direction & AB::GameProtocol::TurnDirectionRight) == AB::GameProtocol::TurnDirectionRight)
Turn(-speed);
}
void ClientPrediction::Turn(float yAngle)
{
float deg = RadToDeg(yAngle);
NormalizeAngle(deg);
Player* player = node_->GetComponent<Player>();
const float newangle = player->rotateTo_.EulerAngles().y_ + deg;
TurnAbsolute(newangle);
}
void ClientPrediction::TurnAbsolute(float yAngle)
{
Player* player = node_->GetComponent<Player>();
player->rotateTo_.FromEulerAngles(0.0f, yAngle, 0.0f);
}
void ClientPrediction::FixedUpdate(float timeStep)
{
LogicComponent::FixedUpdate(timeStep);
extern bool gNoClientPrediction;
if (gNoClientPrediction)
return;
Player* player = node_->GetComponent<Player>();
const AB::GameProtocol::CreatureState state = player->GetCreatureState();
if (state != AB::GameProtocol::CreatureState::Idle && state != AB::GameProtocol::CreatureState::Moving)
return;
const uint8_t moveDir = player->GetMoveDir();
if (moveDir != 0)
{
if (state == AB::GameProtocol::CreatureState::Idle)
{
TurnAbsolute(player->controls_.yaw_);
player->SetCreatureState(serverTime_, AB::GameProtocol::CreatureState::Moving);
}
UpdateMove(timeStep, moveDir, player->GetSpeedFactor());
}
const uint8_t turnDir = player->GetTurnDir();
// Kawan> Disabled
/*if (turnDir != 0)
{
if (state == AB::GameProtocol::CreatureState::Idle)
player->SetCreatureState(serverTime_, AB::GameProtocol::CreatureState::Moving);
UpdateTurn(timeStep, turnDir, player->GetSpeedFactor());
}*/
if (state == AB::GameProtocol::CreatureState::Moving)
{
if ((moveDir == 0 && lastMoveDir_ != 0) ||
(turnDir == 0 && lastTurnDir_ != 0))
player->SetCreatureState(serverTime_, AB::GameProtocol::CreatureState::Idle);
}
lastMoveDir_ = moveDir;
lastTurnDir_ = turnDir;
}
void ClientPrediction::CheckServerPosition(int64_t time, const Vector3& serverPos)
{
serverTime_ = time;
this->serverPos_ = serverPos;
Player* player = node_->GetComponent<Player>();
const Vector3& currPos = player->moveToPos_;
const float dist = (fabs(currPos.x_ - serverPos.x_) + fabs(currPos.z_ - serverPos.z_)) * 0.5f;
// FIXME: This sucks a bit, and needs some work.
if (dist > 5.0f || (dist > 1.0f && player->GetCreatureState() == AB::GameProtocol::CreatureState::Idle))
{
// If too far away or player is idle, Lerp to server position
player->moveToPos_ = serverPos;
}
}
void ClientPrediction::CheckServerRotation(int64_t time, float rad)
{
serverTime_ = time;
Player* player = node_->GetComponent<Player>();
const Quaternion& currRot = player->rotateTo_;
float deg = RadToDeg(rad);
NormalizeAngle(deg);
if (fabs(currRot.EulerAngles().y_ - deg) > 1.0f)
{
player->rotateTo_.FromEulerAngles(0.0f, deg, 0.0f);
}
}
| 35.123016 | 108 | 0.661055 | pablokawan |
d0a998f8d368a9dd4e71e0677cb0f552d3df8b2d | 358 | hpp | C++ | libs/gfxtk_vulkan/src/gfxtk/backend/vulkan/TriangleFillMode.hpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | libs/gfxtk_vulkan/src/gfxtk/backend/vulkan/TriangleFillMode.hpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | libs/gfxtk_vulkan/src/gfxtk/backend/vulkan/TriangleFillMode.hpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | #ifndef GFXTK_BACKEND_VULKAN_TRIANGLEFILLMODE_HPP
#define GFXTK_BACKEND_VULKAN_TRIANGLEFILLMODE_HPP
#include <vulkan/vulkan.h>
#include <gfxtk/TriangleFillMode.hpp>
namespace gfxtk::backend {
struct TriangleFillMode {
static VkPolygonMode convert(gfxtk::TriangleFillMode fillMode);
};
}
#endif //GFXTK_BACKEND_VULKAN_TRIANGLEFILLMODE_HPP
| 23.866667 | 71 | 0.807263 | NostalgicGhoul |
d0adf93377aa91b3c8b573a9192c780af827352c | 271 | cpp | C++ | driver/src/exception/DriverException.cpp | pranavsubramani/Birch | 0a4bb698ed44353c8e8b93d234f2941d7511683c | [
"Apache-2.0"
] | 86 | 2017-10-29T15:46:41.000Z | 2022-01-17T07:18:16.000Z | driver/src/exception/DriverException.cpp | pranavsubramani/Birch | 0a4bb698ed44353c8e8b93d234f2941d7511683c | [
"Apache-2.0"
] | 13 | 2020-09-27T03:31:57.000Z | 2021-05-27T00:39:14.000Z | driver/src/exception/DriverException.cpp | pranavsubramani/Birch | 0a4bb698ed44353c8e8b93d234f2941d7511683c | [
"Apache-2.0"
] | 12 | 2018-08-21T12:57:18.000Z | 2021-05-26T18:41:50.000Z | /**
* @file
*/
#include "src/exception/DriverException.hpp"
birch::DriverException::DriverException() {
//
}
birch::DriverException::DriverException(const std::string& msg) {
std::stringstream base;
base << "error: " << msg << '\n';
this->msg = base.str();
}
| 18.066667 | 65 | 0.642066 | pranavsubramani |
d0ae248d3cdab786948de9075956e0818d9fdf8d | 5,734 | cpp | C++ | dlls/weapons/CShockBeam.cpp | Admer456/halflife-dnf01 | a3cacddb5ff3dedfea2d157c72711ba1df429dac | [
"Unlicense"
] | null | null | null | dlls/weapons/CShockBeam.cpp | Admer456/halflife-dnf01 | a3cacddb5ff3dedfea2d157c72711ba1df429dac | [
"Unlicense"
] | null | null | null | dlls/weapons/CShockBeam.cpp | Admer456/halflife-dnf01 | a3cacddb5ff3dedfea2d157c72711ba1df429dac | [
"Unlicense"
] | null | null | null | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "weapons.h"
#include "customentity.h"
#include "skill.h"
#include "decals.h"
#include "gamerules.h"
#include "CShockBeam.h"
LINK_ENTITY_TO_CLASS( shock_beam, CShockBeam );
void CShockBeam::Precache()
{
PRECACHE_MODEL( "sprites/flare3.spr" );
PRECACHE_MODEL( "sprites/lgtning.spr" );
PRECACHE_MODEL( "sprites/glow01.spr" );
PRECACHE_MODEL( "models/shock_effect.mdl" );
PRECACHE_SOUND( "weapons/shock_impact.wav" );
}
void CShockBeam::Spawn()
{
Precache();
pev->movetype = MOVETYPE_FLY;
pev->solid = SOLID_BBOX;
SET_MODEL( edict(), "models/shock_effect.mdl" );
UTIL_SetOrigin( pev, pev->origin );
UTIL_SetSize( pev, Vector( -4, -4, -4 ), Vector( 4, 4, 4 ) );
SetTouch( &CShockBeam::BallTouch );
SetThink( &CShockBeam::FlyThink );
m_pSprite = CSprite::SpriteCreate( "sprites/flare3.spr", pev->origin, false );
m_pSprite->SetTransparency( kRenderTransAdd, 255, 255, 255, 255, kRenderFxDistort );
m_pSprite->SetScale( 0.35 );
m_pSprite->SetAttachment( edict(), 0 );
m_pBeam1 = CBeam::BeamCreate( "sprites/lgtning.spr", 60 );
if( m_pBeam1 )
{
UTIL_SetOrigin( m_pBeam1->pev, pev->origin );
m_pBeam1->EntsInit( entindex(), entindex() );
m_pBeam1->SetStartAttachment( 1 );
m_pBeam1->SetEndAttachment( 2 );
m_pBeam1->SetColor( 0, 253, 253 );
m_pBeam1->SetFlags( BEAM_FSHADEOUT );
m_pBeam1->SetBrightness( 180 );
m_pBeam1->SetNoise( 0 );
m_pBeam1->SetScrollRate( 10 );
if( g_pGameRules->IsMultiplayer() )
{
pev->nextthink = gpGlobals->time + 0.01;
return;
}
m_pBeam2 = CBeam::BeamCreate( "sprites/lgtning.spr", 20 );
if( m_pBeam2 )
{
UTIL_SetOrigin( m_pBeam2->pev, pev->origin );
m_pBeam2->EntsInit( entindex(), entindex() );
m_pBeam2->SetStartAttachment( 1 );
m_pBeam2->SetEndAttachment( 2 );
m_pBeam2->SetColor( 255, 255, 157 );
m_pBeam2->SetFlags( BEAM_FSHADEOUT );
m_pBeam2->SetBrightness( 180 );
m_pBeam2->SetNoise( 30 );
m_pBeam2->SetScrollRate( 30 );
pev->nextthink = gpGlobals->time + 0.01;
}
}
}
void CShockBeam::FlyThink()
{
if( pev->waterlevel == WATERLEVEL_HEAD )
{
SetThink( &CShockBeam::WaterExplodeThink );
}
pev->nextthink = gpGlobals->time + 0.01;
}
void CShockBeam::ExplodeThink()
{
Explode();
UTIL_Remove( this );
}
void CShockBeam::WaterExplodeThink()
{
auto pOwner = VARS( pev->owner );
Explode();
::RadiusDamage( pev->origin, pev, pOwner, 100.0, 150.0, CLASS_NONE, DMG_ALWAYSGIB | DMG_BLAST );
UTIL_Remove( this );
}
void CShockBeam::BallTouch( CBaseEntity* pOther )
{
SetTouch( nullptr );
SetThink( nullptr );
if( pOther->pev->takedamage != DAMAGE_NO )
{
TraceResult tr = UTIL_GetGlobalTrace();
ClearMultiDamage();
const auto damage = g_pGameRules->IsMultiplayer() ? gSkillData.plrDmgShockRoachM : gSkillData.plrDmgShockRoachS;
auto bitsDamageTypes = DMG_ALWAYSGIB | DMG_SHOCK;
auto pMonster = pOther->MyMonsterPointer();
if( pMonster )
{
bitsDamageTypes = DMG_BLAST;
if( pMonster->m_flShockDuration > 1 )
{
bitsDamageTypes = DMG_ALWAYSGIB;
}
}
pOther->TraceAttack( VARS( pev->owner ), damage, pev->velocity.Normalize(), &tr, bitsDamageTypes );
if( pMonster )
{
pMonster->AddShockEffect( 63.0, 152.0, 208.0, 16.0, 0.5 );
}
ApplyMultiDamage( pev, VARS( pev->owner ) );
pev->velocity = g_vecZero;
}
SetThink( &CShockBeam::ExplodeThink );
pev->nextthink = gpGlobals->time + 0.01;
if( pOther->pev->takedamage == DAMAGE_NO )
{
TraceResult tr;
UTIL_TraceLine( pev->origin, pev->origin + pev->velocity * 10, dont_ignore_monsters, edict(), &tr );
UTIL_DecalTrace( &tr, DECAL_OFSCORCH1 + RANDOM_LONG( 0, 2 ) );
MESSAGE_BEGIN( MSG_PAS, SVC_TEMPENTITY, pev->origin );
g_engfuncs.pfnWriteByte( TE_SPARKS );
g_engfuncs.pfnWriteCoord( pev->origin.x );
g_engfuncs.pfnWriteCoord( pev->origin.y );
g_engfuncs.pfnWriteCoord( pev->origin.z );
MESSAGE_END();
}
}
void CShockBeam::Explode()
{
if( m_pSprite )
{
UTIL_Remove( m_pSprite );
m_pSprite = nullptr;
}
if( m_pBeam1 )
{
UTIL_Remove( m_pBeam1 );
m_pBeam1 = nullptr;
}
if( m_pBeam2 )
{
UTIL_Remove( m_pBeam2 );
m_pBeam2 = nullptr;
}
pev->dmg = 40;
MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, pev->origin );
WRITE_BYTE( TE_DLIGHT );
WRITE_COORD( pev->origin.x );
WRITE_COORD( pev->origin.y );
WRITE_COORD( pev->origin.z );
WRITE_BYTE( 8 );
WRITE_BYTE( 0 );
WRITE_BYTE( 253 );
WRITE_BYTE( 253 );
WRITE_BYTE( 5 );
WRITE_BYTE( 10 );
MESSAGE_END();
pev->owner = nullptr;
EMIT_SOUND( edict(), CHAN_WEAPON, "weapons/shock_impact.wav", RANDOM_FLOAT( 0.8, 0.9 ), ATTN_NORM );
}
CShockBeam* CShockBeam::CreateShockBeam( const Vector& vecOrigin, const Vector& vecAngles, CBaseEntity* pOwner )
{
auto pBeam = GetClassPtr<CShockBeam>( nullptr );
pBeam->pev->angles = vecAngles;
pBeam->pev->angles.x = -pBeam->pev->angles.x;
UTIL_SetOrigin( pBeam->pev, vecOrigin );
UTIL_MakeVectors( pBeam->pev->angles );
pBeam->pev->velocity = gpGlobals->v_forward * 2000.0;
pBeam->pev->velocity.z = -pBeam->pev->velocity.z;
pBeam->pev->classname = MAKE_STRING( "shock_beam" );
pBeam->Spawn();
pBeam->pev->owner = pOwner->edict();
return pBeam;
}
| 22.311284 | 114 | 0.687129 | Admer456 |
d0b6485309e26c3d7ebb0b31f6618b1e94507eae | 8,190 | hpp | C++ | ql/math/statistics/histogram.hpp | markxio/Quantuccia | ebe71a1b9c2a9ee7fc4ea918a9602f100316869d | [
"BSD-3-Clause"
] | 29 | 2017-03-20T14:17:39.000Z | 2021-12-22T08:00:52.000Z | ql/math/statistics/histogram.hpp | markxio/Quantuccia | ebe71a1b9c2a9ee7fc4ea918a9602f100316869d | [
"BSD-3-Clause"
] | 10 | 2017-04-02T14:34:07.000Z | 2021-01-13T05:31:12.000Z | ql/math/statistics/histogram.hpp | markxio/Quantuccia | ebe71a1b9c2a9ee7fc4ea918a9602f100316869d | [
"BSD-3-Clause"
] | 22 | 2017-03-19T05:56:19.000Z | 2022-03-16T13:30:20.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2007 Gang Liang
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file histogram.hpp
\brief statistics tool for generating histogram of given data
*/
#ifndef quantlib_histogram_hpp
#define quantlib_histogram_hpp
#include <ql/utilities/null.hpp>
#include <vector>
namespace QuantLib {
//! Histogram class
/*! This class computes the histogram of a given data set. The
caller can specify the number of bins, the breaks, or the
algorithm for determining these quantities in computing the
histogram.
*/
class Histogram {
public:
enum Algorithm { None, Sturges, FD, Scott };
//! \name constructors
//@{
Histogram()
: bins_(0), algorithm_(Algorithm(-1)) {}
template <class T>
Histogram(T data_begin, T data_end, Size breaks)
: data_(data_begin,data_end), bins_(breaks+1),
algorithm_(None) {
calculate();
}
template <class T>
Histogram(T data_begin, T data_end, Algorithm algorithm)
: data_(data_begin,data_end), bins_(Null<Size>()),
algorithm_(algorithm) {
calculate();
}
template <class T, class U>
Histogram(T data_begin, T data_end,
U breaks_begin, U breaks_end)
: data_(data_begin,data_end), bins_(Null<Size>()),
algorithm_(None), breaks_(breaks_begin,breaks_end) {
bins_ = breaks_.size()+1;
calculate();
}
//@}
//! \name inspectors
//@{
Size bins() const;
const std::vector<Real>& breaks() const;
Algorithm algorithm() const;
bool empty() const;
//@}
//! \name results
//@{
Size counts(Size i) const;
Real frequency(Size i) const;
//@}
private:
std::vector<Real> data_;
Size bins_;
Algorithm algorithm_;
std::vector<Real> breaks_;
std::vector<Size> counts_;
std::vector<Real> frequency_;
// update counts and frequencies
void calculate();
};
}
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2007 Gang Liang
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <ql/math/statistics/incrementalstatistics.hpp>
#include <ql/math/comparison.hpp>
#include <algorithm>
namespace QuantLib
{
namespace
{
/* The discontinuous quantiles use the method (type 8) as
recommended by Hyndman and Fan (1996). The resulting
quantile estimates are approximately median-unbiased
regardless of the distribution of 'samples'.
If quantile function is called multiple times for the same
dataset, it is recommended to pre-sort the sample vector.
*/
Real quantile(const std::vector<Real>& samples, Real prob)
{
Size nsample = samples.size();
QL_REQUIRE(prob >= 0.0 && prob <= 1.0,
"Probability has to be in [0,1].");
QL_REQUIRE(nsample > 0, "The sample size has to be positive.");
if (nsample == 1)
return samples[0];
// two special cases: close to boundaries
const Real a = 1. / 3, b = 2 * a / (nsample + a);
if (prob < b)
return *std::min_element(samples.begin(), samples.end());
else if (prob > 1 - b)
return *std::max_element(samples.begin(), samples.end());
// general situation: middle region and nsample >= 2
Size index = static_cast<Size>(std::floor((nsample + a)*prob + a));
std::vector<Real> sorted(index + 1);
std::partial_sort_copy(samples.begin(), samples.end(),
sorted.begin(), sorted.end());
// use "index & index+1"th elements to interpolate the quantile
Real weight = nsample*prob + a - index;
return (1 - weight) * sorted[index - 1] + weight * sorted[index];
}
}
inline Size Histogram::bins() const
{
return bins_;
}
inline const std::vector<Real>& Histogram::breaks() const
{
return breaks_;
}
inline Histogram::Algorithm Histogram::algorithm() const
{
return algorithm_;
}
inline bool Histogram::empty() const
{
return bins_ == 0;
}
inline Size Histogram::counts(Size i) const
{
#if defined(QL_EXTRA_SAFETY_CHECKS)
return counts_.at(i);
#else
return counts_[i];
#endif
}
inline Real Histogram::frequency(Size i) const
{
#if defined(QL_EXTRA_SAFETY_CHECKS)
return frequency_.at(i);
#else
return frequency_[i];
#endif
}
inline void Histogram::calculate()
{
QL_REQUIRE(!data_.empty(), "no data given");
Real min = *std::min_element(data_.begin(), data_.end());
Real max = *std::max_element(data_.begin(), data_.end());
// calculate number of bins if necessary
if (bins_ == Null<Size>())
{
switch (algorithm_)
{
case Sturges:
{
bins_ = static_cast<Size>(
std::ceil(std::log(static_cast<Real>(data_.size()))
/ std::log(2.0) + 1));
break;
}
case FD:
{
Real r1 = quantile(data_, 0.25);
Real r2 = quantile(data_, 0.75);
Real h = 2.0 * (r2 - r1) * std::pow(static_cast<Real>(data_.size()), -1.0 / 3.0);
bins_ = static_cast<Size>(std::ceil((max - min) / h));
break;
}
case Scott:
{
IncrementalStatistics summary;
summary.addSequence(data_.begin(), data_.end());
Real variance = summary.variance();
Real h = 3.5 * std::sqrt(variance)
* std::pow(static_cast<Real>(data_.size()), -1.0 / 3.0);
bins_ = static_cast<Size>(std::ceil((max - min) / h));
break;
}
case None:
QL_FAIL("a bin-partition algorithm is required");
default:
QL_FAIL("unknown bin-partition algorithm");
};
bins_ = std::max<Size>(bins_, 1);
}
if (breaks_.empty())
{
// set breaks if not provided
breaks_.resize(bins_ - 1);
// ensure breaks_ evenly span over the range of data_
// TODO: borrow the idea of pretty in R.
Real h = (max - min) / bins_;
for (Size i = 0; i<breaks_.size(); ++i)
{
breaks_[i] = min + (i + 1)*h;
}
}
else
{
// or ensure they're sorted if given
std::sort(breaks_.begin(), breaks_.end());
std::vector<Real>::iterator end =
std::unique(breaks_.begin(), breaks_.end(),
std::ptr_fun(close_enough));
breaks_.resize(end - breaks_.begin());
}
// finally, calculate counts and frequencies
counts_.resize(bins_);
std::fill(counts_.begin(), counts_.end(), 0);
for (std::vector<Real>::const_iterator p = data_.begin();
p != data_.end(); ++p)
{
bool processed = false;
for (Size i = 0; i<breaks_.size(); ++i)
{
if (*p < breaks_[i])
{
++counts_[i];
processed = true;
break;
}
}
if (!processed)
++counts_[bins_ - 1];
}
frequency_.resize(bins_);
Size totalCounts = data_.size();
for (Size i = 0; i<bins_; ++i)
frequency_[i] = static_cast<Real>(counts_[i]) / totalCounts;
}
}
#endif
| 27.029703 | 86 | 0.634554 | markxio |
d0b692c546d9197e18f0d44f1121b0946f313b90 | 829 | hpp | C++ | rj_param_utils/include/rj_param_utils/ros2_local_param_provider.hpp | xiaoqingyu0113/robocup-software | 6127d25fc455051ef47610d0e421b2ca7330b4fa | [
"Apache-2.0"
] | 200 | 2015-01-26T01:45:34.000Z | 2022-03-19T13:05:31.000Z | rj_param_utils/include/rj_param_utils/ros2_local_param_provider.hpp | xiaoqingyu0113/robocup-software | 6127d25fc455051ef47610d0e421b2ca7330b4fa | [
"Apache-2.0"
] | 1,254 | 2015-01-03T01:57:35.000Z | 2022-03-16T06:32:21.000Z | rj_param_utils/include/rj_param_utils/ros2_local_param_provider.hpp | xiaoqingyu0113/robocup-software | 6127d25fc455051ef47610d0e421b2ca7330b4fa | [
"Apache-2.0"
] | 206 | 2015-01-21T02:03:18.000Z | 2022-02-01T17:57:46.000Z | #pragma once
#include <rclcpp/rclcpp.hpp>
#include "rj_param_utils/ros2_param_provider.hpp"
namespace params {
/**
*
*/
class LocalROS2ParamProvider : public BaseROS2ParamProvider {
public:
explicit LocalROS2ParamProvider(rclcpp::Node* node, const std::string& module);
protected:
/**
* @brief Calls node->declare_parameters on all the registered parameters.
* @param node
*/
void DeclareParameters(rclcpp::Node* node);
/**
* @brief Initializes the callback called by the ROS2 node ROS2 paramter
* updates. The callback will update the registered parameters in
* ParamRegistry.
* @param node
*/
void InitUpdateParamCallbacks(rclcpp::Node* node);
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr callback_handle_;
};
} // namespace params | 24.382353 | 87 | 0.714113 | xiaoqingyu0113 |
d0bc88174c2d966482ab38237640f5e9872d8b6a | 2,420 | cpp | C++ | Assigment 12/a12_p3/Tournamentmember.cpp | UrfanAlvany/Programming-in-C-and-Cpp | e23a485d5ce302cbbc14bd67a0f656797c3f6af1 | [
"MIT"
] | 1 | 2022-01-02T16:02:09.000Z | 2022-01-02T16:02:09.000Z | Assigment 12/a12_p3/Tournamentmember.cpp | UrfanAlvany/Programming-in-C-and-Cpp | e23a485d5ce302cbbc14bd67a0f656797c3f6af1 | [
"MIT"
] | null | null | null | Assigment 12/a12_p3/Tournamentmember.cpp | UrfanAlvany/Programming-in-C-and-Cpp | e23a485d5ce302cbbc14bd67a0f656797c3f6af1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
#include "TournamentMember.h"
using namespace std;
string TournamentMember::location;
TournamentMember::TournamentMember()
{
strcpy(this->name,"Tournament");
strcpy(this->LastName,"Member");
strcpy(this->Bday,"2000-12-19");
cout << "Created with TournamentMember empty constructor" << endl;
}
TournamentMember::TournamentMember(char * n, char * l, char * b)
{
for(int i=0; i<35; i++)
{
this->name[i]=n[i];
this->LastName[i]=l[i];
if(i<11)
{
this->Bday[i]=b[i];
}
}
cout << "Created with TournamentMember parametric constructor" << endl;
}
TournamentMember::~TournamentMember()
{
cout << "Destroying TournamentMember object" << endl;
}
TournamentMember::TournamentMember(const TournamentMember & t)
{
for(int i=0; i<35; i++)
{
this->name[i]=t.name[i];
this->LastName[i]=t.LastName[i];
if(i<11)
{
this->Bday[i]=t.Bday[i];
}
}
cout << "Created with TournamentMember copy constructor" << endl;
}
Player::Player() : TournamentMember()
{
this->number=0;
this->position="center";
this->goals=0;
this->foot="right-footed";
cout << "Created with Player empty constructor" << endl;
}
Player::Player(char * n, char * l, char * b, int nu, string p, int g, string f) : TournamentMember(n, l, b)
{
this->number=nu;
this->position=p;
this->goals=g;
this->foot=f;
cout << "Created with Player parametric constructor" << endl;
}
Player::~Player()
{
cout << "Destroying Player object" << endl;
}
Player::Player(const Player & t)
{
for(int i=0; i<35; i++)
{
this->name[i]=t.name[i];
this->LastName[i]=t.LastName[i];
if(i<11)
{
this->Bday[i]=t.Bday[i];
}
}
this->number=t.number;
this->position=t.position;
this->goals=t.goals;
this->foot=t.foot;
cout << "created with Player copy constructor" << endl;
}
void Player::print()
{
cout << "Player's name is " << this->name << " " << this->LastName << "." << endl;
cout << "Birthday: " << this->Bday << endl;
cout << "Location: " << this->location << endl;
cout << "Number: " << this->number << endl;
cout << "Position: " << this->position << endl;
cout << "Goals: " << this->goals << endl;
cout << "Footed: " << this->foot << endl;
}
| 25.744681 | 107 | 0.573554 | UrfanAlvany |
d0bd40ee95dab3b2589742b8a0c3a5de7918b5b9 | 1,804 | cc | C++ | paddle/operators/conv_op.cu.cc | boru-roylu/Paddle | b15c675530db541440ddb5b7e774d522ecaf1533 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-14T05:20:07.000Z | 2019-03-14T05:20:07.000Z | paddle/operators/conv_op.cu.cc | boru-roylu/Paddle | b15c675530db541440ddb5b7e774d522ecaf1533 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | paddle/operators/conv_op.cu.cc | boru-roylu/Paddle | b15c675530db541440ddb5b7e774d522ecaf1533 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/operators/conv_op.h"
namespace ops = paddle::operators;
REGISTER_OP_CUDA_KERNEL(
depthwise_conv2d,
ops::DepthwiseConvKernel<paddle::platform::CUDADeviceContext, float>,
ops::DepthwiseConvKernel<paddle::platform::CUDADeviceContext, double>);
REGISTER_OP_CUDA_KERNEL(
depthwise_conv2d_grad,
ops::DepthwiseConvGradKernel<paddle::platform::CUDADeviceContext, float>,
ops::DepthwiseConvGradKernel<paddle::platform::CUDADeviceContext, double>);
REGISTER_OP_CUDA_KERNEL(
conv2d, ops::GemmConvKernel<paddle::platform::CUDADeviceContext, float>,
ops::GemmConvKernel<paddle::platform::CUDADeviceContext, double>);
REGISTER_OP_CUDA_KERNEL(
conv2d_grad,
ops::GemmConvGradKernel<paddle::platform::CUDADeviceContext, float>,
ops::GemmConvGradKernel<paddle::platform::CUDADeviceContext, double>);
REGISTER_OP_CUDA_KERNEL(
conv3d, ops::GemmConvKernel<paddle::platform::CUDADeviceContext, float>,
ops::GemmConvKernel<paddle::platform::CUDADeviceContext, double>);
REGISTER_OP_CUDA_KERNEL(
conv3d_grad,
ops::GemmConvGradKernel<paddle::platform::CUDADeviceContext, float>,
ops::GemmConvGradKernel<paddle::platform::CUDADeviceContext, double>);
| 41 | 79 | 0.785477 | boru-roylu |
d0c02d240862c6c2988355a17767d2d13f3800e9 | 3,039 | hpp | C++ | src/e2/src/ASN1/lib/asn_x2ap.hpp | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 5 | 2020-08-31T08:27:42.000Z | 2022-03-27T10:39:37.000Z | src/e2/src/ASN1/lib/asn_x2ap.hpp | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 1 | 2020-08-28T23:32:17.000Z | 2020-08-28T23:32:17.000Z | src/e2/src/ASN1/lib/asn_x2ap.hpp | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 5 | 2020-08-27T23:04:34.000Z | 2021-11-17T01:49:52.000Z | /*****************************************************************************
# *
# Copyright 2019 AT&T Intellectual Property *
# Copyright 2019 Nokia *
# *
# 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 ASN_X2AP_HPP
#define ASN_X2AP_HPP
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "e2ap_config.hpp"
typedef struct c__dummy00 x2ap_pdu_t;
/*-----------------------------------------------------------------------
COMMON ROUTINES
-------------------------------------------------------------------------
*/
x2ap_pdu_t* new_x2ap_pdu(void);
void x2ap_asn_print(x2ap_pdu_t* pdu, char* buf, size_t buf_size);
int x2ap_asn_per_encode(x2ap_pdu_t* pdu, unsigned char* buf, size_t buf_size,
char* err_buf, size_t err_buf_size);
int x2ap_asn_per_decode(x2ap_pdu_t* pdu, unsigned char const* buf, size_t buf_size,
char* err_buf, size_t err_buf_size);
int x2ap_get_index(x2ap_pdu_t* pdu);
int x2ap_get_procedureCode(x2ap_pdu_t* pdu);
/*-----------------------------------------------------------------------
MESSAGE GENERATORS
-------------------------------------------------------------------------
*/
//X2Setup
bool x2ap_init_X2SetupRequest(x2ap_pdu_t* pdu);
bool x2ap_create_X2SetupRequest(x2ap_pdu_t* pdu, eNB_config &cfg);
bool x2ap_create_X2SetupResponse(x2ap_pdu_t* pdu, eNB_config &cfg);
bool x2ap_create_X2SetupFailure(x2ap_pdu_t* pdu);
//ENDCX2Setup
bool x2ap_create_ENDCX2SetupRequest(x2ap_pdu_t* pdu, eNB_config &cfg);
/*-----------------------------------------------------------------------
TESTS
-------------------------------------------------------------------------
*/
void test_X2Setup_codec(void);
#endif
| 41.630137 | 83 | 0.421849 | shadansari |
d0c0a73862578660ce0414f2437415954263af52 | 1,458 | hpp | C++ | cpp/shared/tflite_micro_model/tflite_micro_model/tflite_micro_utils.hpp | SiliconLabs/mltk | 56b19518187e9d1c8a0d275de137fc9058984a1f | [
"Zlib"
] | null | null | null | cpp/shared/tflite_micro_model/tflite_micro_model/tflite_micro_utils.hpp | SiliconLabs/mltk | 56b19518187e9d1c8a0d275de137fc9058984a1f | [
"Zlib"
] | 1 | 2021-11-19T20:10:09.000Z | 2021-11-19T20:10:09.000Z | cpp/shared/tflite_micro_model/tflite_micro_model/tflite_micro_utils.hpp | sldriedler/mltk | d82a60359cf875f542a2257f1bc7d8eb4bdaa204 | [
"Zlib"
] | null | null | null | #pragma once
#include <cstdint>
#include <cmath>
namespace mltk
{
/**
* @brief Scale the source buffer by the given scaler
*
* dst_float32 = src * scaler
*/
template<typename SrcType>
void scale_tensor(float scaler, const SrcType* src, float* dst, uint32_t length)
{
for(; length > 0; --length)
{
const float src_flt = static_cast<SrcType>(*src++);
*dst++ = src_flt * scaler;
}
}
/**
* @brief Normalize the source buffer by mean and STD
*
* dst_float32 = (src - mean(src)) / std(src)
*/
template<typename SrcType>
void samplewise_mean_std_tensor(const SrcType* src, float* dst, uint32_t length)
{
float mean = 0.0f;
float count = 0.0f;
float m2 = 0.0f;
const SrcType *ptr;
// Calculate the STD and mean
ptr = src;
for(int i = length; i > 0; --i)
{
const float value = (float)(*ptr++);
count += 1;
const float delta = value - mean;
mean += delta / count;
const float delta2 = value - mean;
m2 += delta * delta2;
}
const float variance = m2 / count;
const float std = sqrtf(variance);
const float std_recip = 1.0f / std; // multiplication is faster than division
// Subtract the mean and divide by the STD
ptr = src;
for(int i = length; i > 0; --i)
{
const float value = (float)(*ptr++);
const float x = value - mean;
*dst++ = x * std_recip;
}
}
} // namespace mltk | 20.25 | 81 | 0.587791 | SiliconLabs |
d0c4474cbb478c62a17f5eb45c64593af819be2e | 882 | cpp | C++ | CH17/COMPARE1/compare.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | CH17/COMPARE1/compare.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | CH17/COMPARE1/compare.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | #include <iostream>
bool comparesGreater(int a, int b) {
if (a > b)
return true;
return false;
}
bool comparesGreater(double a, double b) {
if (a > b)
return true;
return false;
}
int main(int argc, char *argv[]) {
using namespace std;
cout << "1 (int) compares greater than 2 (int)? " << comparesGreater(1, 2) << endl; // false
cout << "1.5 (float) compares greater than 1.22 (float)? " << comparesGreater(1.5, 1.22) << endl; // true
cout << "3.402E-38 (double) compares greater than 2.7E-35 (double)? " << comparesGreater(3.402E-38, 2.7E-35) << endl; // false
// cout << "'a' (char) compares greater than 2.48 (float)? " << comparesGreater('a', 2.48) << endl; // --> it gives 'ambiguos' error!!
// cout << "'a' (char) compares greater than 'c' (char)? " << comparesGreater('a', 2.48) << endl; // TODO: vedi come sono covertiti char->int
return 0;
}
| 27.5625 | 142 | 0.61678 | acastellanos95 |
d0c52e5448eb548e5699e99843f2f3b93659fb98 | 5,376 | cpp | C++ | tests/bin/test_two_sqz.cpp | YJieZhang/Tengine | f5cf2b4cecde412d9c9ae72c3278d9c65110e206 | [
"Apache-2.0"
] | null | null | null | tests/bin/test_two_sqz.cpp | YJieZhang/Tengine | f5cf2b4cecde412d9c9ae72c3278d9c65110e206 | [
"Apache-2.0"
] | null | null | null | tests/bin/test_two_sqz.cpp | YJieZhang/Tengine | f5cf2b4cecde412d9c9ae72c3278d9c65110e206 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2017, Open AI Lab
* Author: haitao@openailab.com
*/
#include <unistd.h>
#include <iostream>
#include <functional>
#include <algorithm>
#include <thread>
#include <fstream>
#include <iomanip>
#include "tengine_c_api.h"
#include "image_process.hpp"
#include "common_util.hpp"
#include "tengine_config.hpp"
const char * text_file="./tests/data/sqz.prototxt";
const char * model_file="./tests/data/squeezenet_v1.1.caffemodel";
const char * image_file="./tests/data/cat.jpg";
const char * mean_file="./tests/data/imagenet_mean.binaryproto";
const char * label_file="./tests/data/synset_words.txt";
const char * model_name="squeezenet";
int img_h=227;
int img_w=227;
using namespace TEngine;
void LoadLabelFile(std::vector<std::string>& result, const char * fname)
{
std::ifstream labels(fname);
std::string line;
while (std::getline(labels, line))
result.push_back(line);
}
int common_init(void)
{
init_tengine_library();
if(request_tengine_version("0.1")<0)
return 1;
if(load_model(model_name,"caffe",text_file,model_file)<0)
return 1;
std::cout<<"Load model successfully\n";
dump_model(model_name);
return 0;
}
int thread_func(void)
{
graph_t graph=create_runtime_graph("graph0",model_name,NULL);
if(!check_graph_valid(graph))
{
std::cout<<"create graph0 failed\n";
return 1;
}
/* set input and output node*/
const char * input_node_name="input";
const char * output_node_name="prob";
if(set_graph_input_node(graph,&input_node_name,1)<0)
{
std::printf("set input node: %s failed\n",input_node_name);
return 1;
}
if(set_graph_output_node(graph,&output_node_name,1)<0)
{
std::printf("set output node: %s failed\n",output_node_name);
return 1;
}
const char * input_tensor_name="data";
tensor_t input_tensor=get_graph_tensor(graph,input_tensor_name);
if(!check_tensor_valid(input_tensor))
{
std::printf("cannot find tensor: %s\n",input_tensor_name);
return -1;
}
int dims[]={1,3,img_h,img_w};
set_tensor_shape(input_tensor,dims,4);
/* setup input buffer */
float * input_data=(float *)malloc(3*img_h*img_w*4);
if(set_tensor_buffer(input_tensor,input_data,3*img_h*img_w*4)<0)
{
std::printf("set buffer for tensor: %s failed\n",input_tensor_name);
return -1;
}
const char * output_tensor_name="prob";
tensor_t output_tensor=get_graph_tensor(graph,output_tensor_name);
float * output_data=(float *)malloc(1000*4);
memset(output_data,0x0,4000);
if(set_tensor_buffer(output_tensor,output_data,1000*4)<0)
{
std::printf("set buffer for tensor: %s failed\n",output_tensor_name);
return -1;
}
/* run the graph */
prerun_graph(graph);
int dim_size=get_tensor_shape(output_tensor,dims,4);
if(dim_size<0)
{
printf("get output tensor shape failed\n");
return -1;
}
printf("output tensor shape: [");
for(int i=0;i<dim_size;i++)
printf("%d ",dims[i]);
printf("]\n");
int count=10;
while (count-->0)
{
float * input_image=caffe_process_image(image_file,mean_file,img_h,img_w);
int input_size=img_h*img_w*3*sizeof(float);
memcpy(input_data,input_image,input_size);
run_graph(graph,1);
int count=get_tensor_buffer_size(output_tensor)/4;
float * data=(float *)(output_data);
float * end=data+count;
std::vector<float> result(data, end);
std::vector<int> top_N=Argmax(result,5);
std::vector<std::string> labels;
LoadLabelFile(labels,label_file);
std::cout<<"RESULT:\n";
for(unsigned int i=0;i<top_N.size();i++)
{
int idx=top_N[i];
std::cout<<std::fixed << std::setprecision(4)<<result[idx]<<" - \"";
std::cout<< labels[idx]<<"\"\n";
}
sleep(1);
}
postrun_graph(graph);
put_graph_tensor(input_tensor);
put_graph_tensor(output_tensor);
destroy_runtime_graph(graph);
remove_model(model_name);
std::cout<<"ALL TESTS DONE\n";
return 0;
}
int main(int argc, char * argv[])
{
int res;
while((res=getopt(argc,argv,"e"))!=-1)
{
switch(res)
{
case 'e':
TEngineConfig::Set("exec.engine","event");
break;
default:
break;
}
}
common_init();
std::thread * tr1=new std::thread(thread_func);
std::thread * tr2=new std::thread(thread_func);
tr1->join();
tr2->join();
return 0;
}
| 22.4 | 81 | 0.65718 | YJieZhang |
d0c816c7b64d46de21dbb5dc8c67cc9c9d0c6211 | 34,263 | cc | C++ | open/DellEMC/code/ssd-mobilenet/xilinx/include/object_detection/protos/graph_rewriter.pb.cc | fenz-org/mlperf_inference_results_v0.7 | 2e38bec7f8df806283802a69db3d0038a37d026e | [
"Apache-2.0"
] | 19 | 2020-10-26T17:37:22.000Z | 2022-01-20T09:32:38.000Z | open/DellEMC/code/ssd-mobilenet/xilinx/include/object_detection/protos/graph_rewriter.pb.cc | fenz-org/mlperf_inference_results_v0.7 | 2e38bec7f8df806283802a69db3d0038a37d026e | [
"Apache-2.0"
] | 11 | 2020-10-21T19:18:48.000Z | 2021-03-11T18:50:36.000Z | open/DellEMC/code/ssd-mobilenet/xilinx/include/object_detection/protos/graph_rewriter.pb.cc | fenz-org/mlperf_inference_results_v0.7 | 2e38bec7f8df806283802a69db3d0038a37d026e | [
"Apache-2.0"
] | 19 | 2020-10-21T19:15:17.000Z | 2022-01-04T08:32:08.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: object_detection/protos/graph_rewriter.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "object_detection/protos/graph_rewriter.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace object_detection {
namespace protos {
class GraphRewriterDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<GraphRewriter>
_instance;
} _GraphRewriter_default_instance_;
class QuantizationDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Quantization>
_instance;
} _Quantization_default_instance_;
namespace protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto {
namespace {
::google::protobuf::Metadata file_level_metadata[2];
} // namespace
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField
const TableStruct::entries[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField
const TableStruct::aux[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
::google::protobuf::internal::AuxillaryParseTableField(),
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const
TableStruct::schema[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
};
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GraphRewriter, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GraphRewriter, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GraphRewriter, _extensions_),
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GraphRewriter, quantization_),
0,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantization, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantization, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantization, delay_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantization, weight_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantization, activation_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantization, symmetric_),
2,
3,
1,
0,
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 6, sizeof(GraphRewriter)},
{ 7, 16, sizeof(Quantization)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_GraphRewriter_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_Quantization_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"object_detection/protos/graph_rewriter.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 2);
}
} // namespace
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
_GraphRewriter_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_GraphRewriter_default_instance_);_Quantization_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_Quantization_default_instance_);_GraphRewriter_default_instance_._instance.get_mutable()->quantization_ = const_cast< ::object_detection::protos::Quantization*>(
::object_detection::protos::Quantization::internal_default_instance());
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
namespace {
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n,object_detection/protos/graph_rewriter"
".proto\022\027object_detection.protos\"W\n\rGraph"
"Rewriter\022;\n\014quantization\030\001 \001(\0132%.object_"
"detection.protos.Quantization*\t\010\350\007\020\200\200\200\200\002"
"\"s\n\014Quantization\022\025\n\005delay\030\001 \001(\005:\006500000\022"
"\026\n\013weight_bits\030\002 \001(\005:\0018\022\032\n\017activation_bi"
"ts\030\003 \001(\005:\0018\022\030\n\tsymmetric\030\004 \001(\010:\005false"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 277);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"object_detection/protos/graph_rewriter.proto", &protobuf_RegisterTypes);
}
} // anonymous namespace
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GraphRewriter::kQuantizationFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
GraphRewriter::GraphRewriter()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:object_detection.protos.GraphRewriter)
}
GraphRewriter::GraphRewriter(const GraphRewriter& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
if (from.has_quantization()) {
quantization_ = new ::object_detection::protos::Quantization(*from.quantization_);
} else {
quantization_ = NULL;
}
// @@protoc_insertion_point(copy_constructor:object_detection.protos.GraphRewriter)
}
void GraphRewriter::SharedCtor() {
_cached_size_ = 0;
quantization_ = NULL;
}
GraphRewriter::~GraphRewriter() {
// @@protoc_insertion_point(destructor:object_detection.protos.GraphRewriter)
SharedDtor();
}
void GraphRewriter::SharedDtor() {
if (this != internal_default_instance()) delete quantization_;
}
void GraphRewriter::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* GraphRewriter::descriptor() {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const GraphRewriter& GraphRewriter::default_instance() {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::InitDefaults();
return *internal_default_instance();
}
GraphRewriter* GraphRewriter::New(::google::protobuf::Arena* arena) const {
GraphRewriter* n = new GraphRewriter;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void GraphRewriter::Clear() {
// @@protoc_insertion_point(message_clear_start:object_detection.protos.GraphRewriter)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_extensions_.Clear();
if (has_quantization()) {
GOOGLE_DCHECK(quantization_ != NULL);
quantization_->::object_detection::protos::Quantization::Clear();
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool GraphRewriter::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:object_detection.protos.GraphRewriter)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .object_detection.protos.Quantization quantization = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_quantization()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
if ((8000u <= tag)) {
DO_(_extensions_.ParseField(tag, input,
internal_default_instance(),
_internal_metadata_.mutable_unknown_fields()));
continue;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:object_detection.protos.GraphRewriter)
return true;
failure:
// @@protoc_insertion_point(parse_failure:object_detection.protos.GraphRewriter)
return false;
#undef DO_
}
void GraphRewriter::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:object_detection.protos.GraphRewriter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .object_detection.protos.Quantization quantization = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->quantization_, output);
}
// Extension range [1000, 536870912)
_extensions_.SerializeWithCachedSizes(
1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:object_detection.protos.GraphRewriter)
}
::google::protobuf::uint8* GraphRewriter::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:object_detection.protos.GraphRewriter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .object_detection.protos.Quantization quantization = 1;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->quantization_, deterministic, target);
}
// Extension range [1000, 536870912)
target = _extensions_.InternalSerializeWithCachedSizesToArray(
1000, 536870912, deterministic, target);
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:object_detection.protos.GraphRewriter)
return target;
}
size_t GraphRewriter::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:object_detection.protos.GraphRewriter)
size_t total_size = 0;
total_size += _extensions_.ByteSize();
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
// optional .object_detection.protos.Quantization quantization = 1;
if (has_quantization()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->quantization_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void GraphRewriter::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:object_detection.protos.GraphRewriter)
GOOGLE_DCHECK_NE(&from, this);
const GraphRewriter* source =
::google::protobuf::internal::DynamicCastToGenerated<const GraphRewriter>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:object_detection.protos.GraphRewriter)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:object_detection.protos.GraphRewriter)
MergeFrom(*source);
}
}
void GraphRewriter::MergeFrom(const GraphRewriter& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:object_detection.protos.GraphRewriter)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_quantization()) {
mutable_quantization()->::object_detection::protos::Quantization::MergeFrom(from.quantization());
}
}
void GraphRewriter::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:object_detection.protos.GraphRewriter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void GraphRewriter::CopyFrom(const GraphRewriter& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:object_detection.protos.GraphRewriter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool GraphRewriter::IsInitialized() const {
if (!_extensions_.IsInitialized()) {
return false;
}
return true;
}
void GraphRewriter::Swap(GraphRewriter* other) {
if (other == this) return;
InternalSwap(other);
}
void GraphRewriter::InternalSwap(GraphRewriter* other) {
using std::swap;
swap(quantization_, other->quantization_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
_extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata GraphRewriter::GetMetadata() const {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// GraphRewriter
// optional .object_detection.protos.Quantization quantization = 1;
bool GraphRewriter::has_quantization() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void GraphRewriter::set_has_quantization() {
_has_bits_[0] |= 0x00000001u;
}
void GraphRewriter::clear_has_quantization() {
_has_bits_[0] &= ~0x00000001u;
}
void GraphRewriter::clear_quantization() {
if (quantization_ != NULL) quantization_->::object_detection::protos::Quantization::Clear();
clear_has_quantization();
}
const ::object_detection::protos::Quantization& GraphRewriter::quantization() const {
const ::object_detection::protos::Quantization* p = quantization_;
// @@protoc_insertion_point(field_get:object_detection.protos.GraphRewriter.quantization)
return p != NULL ? *p : *reinterpret_cast<const ::object_detection::protos::Quantization*>(
&::object_detection::protos::_Quantization_default_instance_);
}
::object_detection::protos::Quantization* GraphRewriter::mutable_quantization() {
set_has_quantization();
if (quantization_ == NULL) {
quantization_ = new ::object_detection::protos::Quantization;
}
// @@protoc_insertion_point(field_mutable:object_detection.protos.GraphRewriter.quantization)
return quantization_;
}
::object_detection::protos::Quantization* GraphRewriter::release_quantization() {
// @@protoc_insertion_point(field_release:object_detection.protos.GraphRewriter.quantization)
clear_has_quantization();
::object_detection::protos::Quantization* temp = quantization_;
quantization_ = NULL;
return temp;
}
void GraphRewriter::set_allocated_quantization(::object_detection::protos::Quantization* quantization) {
delete quantization_;
quantization_ = quantization;
if (quantization) {
set_has_quantization();
} else {
clear_has_quantization();
}
// @@protoc_insertion_point(field_set_allocated:object_detection.protos.GraphRewriter.quantization)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Quantization::kDelayFieldNumber;
const int Quantization::kWeightBitsFieldNumber;
const int Quantization::kActivationBitsFieldNumber;
const int Quantization::kSymmetricFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Quantization::Quantization()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:object_detection.protos.Quantization)
}
Quantization::Quantization(const Quantization& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&symmetric_, &from.symmetric_,
static_cast<size_t>(reinterpret_cast<char*>(&weight_bits_) -
reinterpret_cast<char*>(&symmetric_)) + sizeof(weight_bits_));
// @@protoc_insertion_point(copy_constructor:object_detection.protos.Quantization)
}
void Quantization::SharedCtor() {
_cached_size_ = 0;
symmetric_ = false;
activation_bits_ = 8;
delay_ = 500000;
weight_bits_ = 8;
}
Quantization::~Quantization() {
// @@protoc_insertion_point(destructor:object_detection.protos.Quantization)
SharedDtor();
}
void Quantization::SharedDtor() {
}
void Quantization::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Quantization::descriptor() {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Quantization& Quantization::default_instance() {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::InitDefaults();
return *internal_default_instance();
}
Quantization* Quantization::New(::google::protobuf::Arena* arena) const {
Quantization* n = new Quantization;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Quantization::Clear() {
// @@protoc_insertion_point(message_clear_start:object_detection.protos.Quantization)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 15u) {
symmetric_ = false;
activation_bits_ = 8;
delay_ = 500000;
weight_bits_ = 8;
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool Quantization::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:object_detection.protos.Quantization)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 delay = 1 [default = 500000];
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_delay();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &delay_)));
} else {
goto handle_unusual;
}
break;
}
// optional int32 weight_bits = 2 [default = 8];
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_weight_bits();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &weight_bits_)));
} else {
goto handle_unusual;
}
break;
}
// optional int32 activation_bits = 3 [default = 8];
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_activation_bits();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &activation_bits_)));
} else {
goto handle_unusual;
}
break;
}
// optional bool symmetric = 4 [default = false];
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
set_has_symmetric();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &symmetric_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:object_detection.protos.Quantization)
return true;
failure:
// @@protoc_insertion_point(parse_failure:object_detection.protos.Quantization)
return false;
#undef DO_
}
void Quantization::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:object_detection.protos.Quantization)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional int32 delay = 1 [default = 500000];
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->delay(), output);
}
// optional int32 weight_bits = 2 [default = 8];
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->weight_bits(), output);
}
// optional int32 activation_bits = 3 [default = 8];
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->activation_bits(), output);
}
// optional bool symmetric = 4 [default = false];
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteBool(4, this->symmetric(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:object_detection.protos.Quantization)
}
::google::protobuf::uint8* Quantization::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:object_detection.protos.Quantization)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional int32 delay = 1 [default = 500000];
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->delay(), target);
}
// optional int32 weight_bits = 2 [default = 8];
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->weight_bits(), target);
}
// optional int32 activation_bits = 3 [default = 8];
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->activation_bits(), target);
}
// optional bool symmetric = 4 [default = false];
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->symmetric(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:object_detection.protos.Quantization)
return target;
}
size_t Quantization::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:object_detection.protos.Quantization)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 15u) {
// optional bool symmetric = 4 [default = false];
if (has_symmetric()) {
total_size += 1 + 1;
}
// optional int32 activation_bits = 3 [default = 8];
if (has_activation_bits()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->activation_bits());
}
// optional int32 delay = 1 [default = 500000];
if (has_delay()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->delay());
}
// optional int32 weight_bits = 2 [default = 8];
if (has_weight_bits()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->weight_bits());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Quantization::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:object_detection.protos.Quantization)
GOOGLE_DCHECK_NE(&from, this);
const Quantization* source =
::google::protobuf::internal::DynamicCastToGenerated<const Quantization>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:object_detection.protos.Quantization)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:object_detection.protos.Quantization)
MergeFrom(*source);
}
}
void Quantization::MergeFrom(const Quantization& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:object_detection.protos.Quantization)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 15u) {
if (cached_has_bits & 0x00000001u) {
symmetric_ = from.symmetric_;
}
if (cached_has_bits & 0x00000002u) {
activation_bits_ = from.activation_bits_;
}
if (cached_has_bits & 0x00000004u) {
delay_ = from.delay_;
}
if (cached_has_bits & 0x00000008u) {
weight_bits_ = from.weight_bits_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void Quantization::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:object_detection.protos.Quantization)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Quantization::CopyFrom(const Quantization& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:object_detection.protos.Quantization)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Quantization::IsInitialized() const {
return true;
}
void Quantization::Swap(Quantization* other) {
if (other == this) return;
InternalSwap(other);
}
void Quantization::InternalSwap(Quantization* other) {
using std::swap;
swap(symmetric_, other->symmetric_);
swap(activation_bits_, other->activation_bits_);
swap(delay_, other->delay_);
swap(weight_bits_, other->weight_bits_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Quantization::GetMetadata() const {
protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_object_5fdetection_2fprotos_2fgraph_5frewriter_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Quantization
// optional int32 delay = 1 [default = 500000];
bool Quantization::has_delay() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
void Quantization::set_has_delay() {
_has_bits_[0] |= 0x00000004u;
}
void Quantization::clear_has_delay() {
_has_bits_[0] &= ~0x00000004u;
}
void Quantization::clear_delay() {
delay_ = 500000;
clear_has_delay();
}
::google::protobuf::int32 Quantization::delay() const {
// @@protoc_insertion_point(field_get:object_detection.protos.Quantization.delay)
return delay_;
}
void Quantization::set_delay(::google::protobuf::int32 value) {
set_has_delay();
delay_ = value;
// @@protoc_insertion_point(field_set:object_detection.protos.Quantization.delay)
}
// optional int32 weight_bits = 2 [default = 8];
bool Quantization::has_weight_bits() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
void Quantization::set_has_weight_bits() {
_has_bits_[0] |= 0x00000008u;
}
void Quantization::clear_has_weight_bits() {
_has_bits_[0] &= ~0x00000008u;
}
void Quantization::clear_weight_bits() {
weight_bits_ = 8;
clear_has_weight_bits();
}
::google::protobuf::int32 Quantization::weight_bits() const {
// @@protoc_insertion_point(field_get:object_detection.protos.Quantization.weight_bits)
return weight_bits_;
}
void Quantization::set_weight_bits(::google::protobuf::int32 value) {
set_has_weight_bits();
weight_bits_ = value;
// @@protoc_insertion_point(field_set:object_detection.protos.Quantization.weight_bits)
}
// optional int32 activation_bits = 3 [default = 8];
bool Quantization::has_activation_bits() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
void Quantization::set_has_activation_bits() {
_has_bits_[0] |= 0x00000002u;
}
void Quantization::clear_has_activation_bits() {
_has_bits_[0] &= ~0x00000002u;
}
void Quantization::clear_activation_bits() {
activation_bits_ = 8;
clear_has_activation_bits();
}
::google::protobuf::int32 Quantization::activation_bits() const {
// @@protoc_insertion_point(field_get:object_detection.protos.Quantization.activation_bits)
return activation_bits_;
}
void Quantization::set_activation_bits(::google::protobuf::int32 value) {
set_has_activation_bits();
activation_bits_ = value;
// @@protoc_insertion_point(field_set:object_detection.protos.Quantization.activation_bits)
}
// optional bool symmetric = 4 [default = false];
bool Quantization::has_symmetric() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void Quantization::set_has_symmetric() {
_has_bits_[0] |= 0x00000001u;
}
void Quantization::clear_has_symmetric() {
_has_bits_[0] &= ~0x00000001u;
}
void Quantization::clear_symmetric() {
symmetric_ = false;
clear_has_symmetric();
}
bool Quantization::symmetric() const {
// @@protoc_insertion_point(field_get:object_detection.protos.Quantization.symmetric)
return symmetric_;
}
void Quantization::set_symmetric(bool value) {
set_has_symmetric();
symmetric_ = value;
// @@protoc_insertion_point(field_set:object_detection.protos.Quantization.symmetric)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace protos
} // namespace object_detection
// @@protoc_insertion_point(global_scope)
| 35.915094 | 169 | 0.734378 | fenz-org |
d0cbd4e80f26e7e85fcf16d32e8d80f7a872bb82 | 245 | cpp | C++ | source/automated-tests/boost-test/main.test.cpp | alf-p-steinbach/cppx-core-language | 930351fe0df65e231e8e91998f1c94d345938107 | [
"MIT"
] | 3 | 2020-05-24T16:29:42.000Z | 2021-09-10T13:33:15.000Z | source/automated-tests/boost-test/main.test.cpp | alf-p-steinbach/cppx-core-language | 930351fe0df65e231e8e91998f1c94d345938107 | [
"MIT"
] | null | null | null | source/automated-tests/boost-test/main.test.cpp | alf-p-steinbach/cppx-core-language | 930351fe0df65e231e8e91998f1c94d345938107 | [
"MIT"
] | null | null | null | #define BOOST_TEST_MODULE cppx-core unit tests
#include <_/test-framework.hpp>
#ifdef _WIN32
# include <c/stdlib.hpp> // system
const bool dummy = []()
{
return EXIT_SUCCESS == system( "chcp 65001 >nul" );
}();
#endif
| 22.272727 | 59 | 0.62449 | alf-p-steinbach |
d0cc1e55b47760d4df738d02ab8603975614ff1f | 219 | cpp | C++ | test/scratch/test.scratch.temp_file/implicit_link.cpp | stlsoft/xTests | fa0a0315283f85f2b8c07a5ce9e5dce19127541a | [
"BSD-3-Clause"
] | 1 | 2016-04-02T16:56:29.000Z | 2016-04-02T16:56:29.000Z | test/scratch/test.scratch.temp_file/implicit_link.cpp | stlsoft/xTests | fa0a0315283f85f2b8c07a5ce9e5dce19127541a | [
"BSD-3-Clause"
] | 1 | 2019-10-09T18:16:48.000Z | 2019-10-09T18:16:48.000Z | test/scratch/test.scratch.temp_file/implicit_link.cpp | stlsoft/xTests | fa0a0315283f85f2b8c07a5ce9e5dce19127541a | [
"BSD-3-Clause"
] | 2 | 2016-02-08T20:20:09.000Z | 2021-03-31T10:37:23.000Z |
#include <platformstl/platformstl.h>
#if defined(PLATFORMSTL_OS_IS_UNIX) && \
defined(_WIN32)
# include <unixem/implicit_link.h>
#endif
/* ///////////////////////////// end of file //////////////////////////// */
| 24.333333 | 76 | 0.525114 | stlsoft |
d0cc96f2d42506c592cd5a70db196590b758bcc8 | 2,559 | cpp | C++ | tcpserver.cpp | GSIO01/gsnet | 3f073c82c41f3a5832d34ab5edfdbb935e844c05 | [
"MIT"
] | null | null | null | tcpserver.cpp | GSIO01/gsnet | 3f073c82c41f3a5832d34ab5edfdbb935e844c05 | [
"MIT"
] | null | null | null | tcpserver.cpp | GSIO01/gsnet | 3f073c82c41f3a5832d34ab5edfdbb935e844c05 | [
"MIT"
] | null | null | null | /*
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Walter Julius Hennecke
*
* 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 "tcpserver.h"
#if !defined(WIN32) & !defined(_MSC_VER)
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <cstring>
static int32_t(*closesocket)(int32_t s) = close;
static int32_t(*ioctlsocket)(int32_t s, unsigned long cmd, ...) = ioctl;
#endif
namespace GSNet {
CTcpServer::CTcpServer(int32_t port, int32_t connections, ESocketType type /* = ST_BLOCKING */) {
sockaddr_in sa;
_lastError = SE_SUCCESS;
memset(&sa, 0, sizeof(sockaddr_in));
sa.sin_family = PF_INET;
sa.sin_port = htons(port);
_s = socket(AF_INET, SOCK_STREAM, 0);
if (_s == INVALID_SOCKET) {
_lastError = SE_ERROR_CREATE;
return;
}
if (type == ST_NON_BLOCKING) {
u_long arg = 1;
if (ioctlsocket(_s, FIONBIO, &arg) == SOCKET_ERROR) {
_lastError = SE_ERROR_IOCTL;
return;
}
}
if (bind(_s, (sockaddr*)& sa, sizeof(sockaddr_in)) == SOCKET_ERROR) {
_lastError = SE_ERROR_BIND;
closesocket(_s);
return;
}
if (listen(_s, connections) == SOCKET_ERROR) {
_lastError = SE_ERROR_LISTEN;
}
}
ISocket* CTcpServer::Accept() {
SOCKET new_sock = ::accept(_s, 0, 0);
if (new_sock == INVALID_SOCKET) {
_lastError = SE_ERROR_CREATE;
return nullptr;
}
CTcpSocket* r = new CTcpSocket(new_sock);
_lastError = SE_SUCCESS;
return r;
}
} | 28.433333 | 99 | 0.684642 | GSIO01 |
d0cd0bd45b34b913f96ff501a606f32db873c560 | 1,329 | hpp | C++ | sprout/weed/expr/make_terminal.hpp | jwakely/Sprout | a64938fad0a64608f22d39485bc55a1e0dc07246 | [
"BSL-1.0"
] | 1 | 2018-09-21T23:50:44.000Z | 2018-09-21T23:50:44.000Z | sprout/weed/expr/make_terminal.hpp | jwakely/Sprout | a64938fad0a64608f22d39485bc55a1e0dc07246 | [
"BSL-1.0"
] | null | null | null | sprout/weed/expr/make_terminal.hpp | jwakely/Sprout | a64938fad0a64608f22d39485bc55a1e0dc07246 | [
"BSL-1.0"
] | null | null | null | #ifndef SPROUT_WEED_EXPR_MAKE_TERMINAL_HPP
#define SPROUT_WEED_EXPR_MAKE_TERMINAL_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/string.hpp>
#include <sprout/utility/forward.hpp>
#include <sprout/weed/traits/type/is_c_str.hpp>
#include <sprout/weed/traits/expr/terminal_of.hpp>
#include <sprout/weed/detail/uncvref.hpp>
namespace sprout {
namespace weed {
//
// make_terminal
//
template<typename Arg>
inline SPROUT_CONSTEXPR typename std::enable_if<
!sprout::weed::traits::is_c_str<
typename sprout::weed::detail::uncvref<Arg>::type
>::value,
typename sprout::weed::traits::terminal_of<Arg>::type
>::type make_terminal(Arg&& arg) {
return typename sprout::weed::traits::terminal_of<Arg>::type(
sprout::forward<Arg>(arg)
);
}
template<typename Arg>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::weed::traits::is_c_str<
typename sprout::weed::detail::uncvref<Arg>::type
>::value,
typename sprout::weed::traits::terminal_of<Arg>::type
>::type make_terminal(Arg&& arg) {
return typename sprout::weed::traits::terminal_of<Arg>::type(
sprout::to_string(sprout::forward<Arg>(arg))
);
}
} // namespace weed
} // namespace sprout
#endif // #ifndef SPROUT_WEED_EXPR_MAKE_TERMINAL_HPP
| 30.906977 | 65 | 0.702032 | jwakely |
d0d0058950a4176a24de8d223669ec2d476de9d2 | 1,091 | hpp | C++ | include/Nyengine/geometry/Point.hpp | NyantasticUwU/nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | 2 | 2021-12-26T05:10:41.000Z | 2022-01-30T19:51:23.000Z | include/Nyengine/geometry/Point.hpp | NyantasticUwU/Nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | null | null | null | include/Nyengine/geometry/Point.hpp | NyantasticUwU/Nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | null | null | null | #ifndef NYENGINE_GEOMETRY_POINT_HPP_INCLUDED
#define NYENGINE_GEOMETRY_POINT_HPP_INCLUDED
#include "../type/types.hpp"
/// Contains Nyengine geometry helpers.
namespace nyengine::geometry
{
/// Represents a 2D point.
template <typename T>
struct Point2D
{
T x;
T y;
};
/// Point2D represented by signed integral type.
using Point2DI = Point2D<type::int32_dynamic_t>;
/// Point2D represented by unsigned integral type.
using Point2DU = Point2D<type::uint32_dynamic_t>;
/// Point2D represented by floating point type.
using Point2DF = Point2D<type::float32_dynamic_t>;
/// Represents a 3D point.
template <typename T>
struct Point3D
{
T x;
T y;
T z;
};
/// Point3D represented by signed integral type.
using Point3DI = Point3D<type::int32_dynamic_t>;
/// Point3D represented by unsigned integral type.
using Point3DU = Point3D<type::uint32_dynamic_t>;
/// Point3D represented by floating point type.
using Point3DF = Point3D<type::float32_dynamic_t>;
}
#endif
| 26.609756 | 54 | 0.678277 | NyantasticUwU |
d0d0670d1518e15449a7afd9df986fd1e2aa883c | 17,088 | cc | C++ | modules/rtp_rtcp/source/rtp_depacketizer_av1_unittest.cc | gaoxiaoyang/webrtc | 21021f022be36f5d04f8a3a309e345f65c8603a9 | [
"BSD-3-Clause"
] | 1 | 2020-07-31T06:11:36.000Z | 2020-07-31T06:11:36.000Z | modules/rtp_rtcp/source/rtp_depacketizer_av1_unittest.cc | gaoxiaoyang/webrtc | 21021f022be36f5d04f8a3a309e345f65c8603a9 | [
"BSD-3-Clause"
] | null | null | null | modules/rtp_rtcp/source/rtp_depacketizer_av1_unittest.cc | gaoxiaoyang/webrtc | 21021f022be36f5d04f8a3a309e345f65c8603a9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/rtp_rtcp/source/rtp_depacketizer_av1.h"
#include "test/gmock.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
using ::testing::ElementsAre;
// Signals number of the OBU (fragments) in the packet.
constexpr uint8_t kObuCountOne = 0b00'01'0000;
constexpr uint8_t kObuHeaderSequenceHeader = 0b0'0001'000;
constexpr uint8_t kObuHeaderFrame = 0b0'0110'000;
constexpr uint8_t kObuHeaderHasSize = 0b0'0000'010;
TEST(RtpDepacketizerAv1Test, ParsePassFullRtpPayloadAsCodecPayload) {
const uint8_t packet[] = {(uint8_t{1} << 7) | kObuCountOne, 1, 2, 3, 4};
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
ASSERT_TRUE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
EXPECT_EQ(parsed.payload_length, sizeof(packet));
EXPECT_TRUE(parsed.payload == packet);
}
TEST(RtpDepacketizerAv1Test, ParseTreatsContinuationFlagAsNotBeginningOfFrame) {
const uint8_t packet[] = {
(uint8_t{1} << 7) | kObuCountOne,
kObuHeaderFrame}; // Value doesn't matter since it is a
// continuation of the OBU from previous packet.
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
ASSERT_TRUE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
EXPECT_FALSE(parsed.video.is_first_packet_in_frame);
}
TEST(RtpDepacketizerAv1Test, ParseTreatsNoContinuationFlagAsBeginningOfFrame) {
const uint8_t packet[] = {(uint8_t{0} << 7) | kObuCountOne, kObuHeaderFrame};
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
ASSERT_TRUE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
EXPECT_TRUE(parsed.video.is_first_packet_in_frame);
}
TEST(RtpDepacketizerAv1Test, ParseTreatsWillContinueFlagAsNotEndOfFrame) {
const uint8_t packet[] = {(uint8_t{1} << 6) | kObuCountOne, kObuHeaderFrame};
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
ASSERT_TRUE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
EXPECT_FALSE(parsed.video.is_last_packet_in_frame);
}
TEST(RtpDepacketizerAv1Test, ParseTreatsNoWillContinueFlagAsEndOfFrame) {
const uint8_t packet[] = {(uint8_t{0} << 6) | kObuCountOne, kObuHeaderFrame};
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
ASSERT_TRUE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
EXPECT_TRUE(parsed.video.is_last_packet_in_frame);
}
TEST(RtpDepacketizerAv1Test,
ParseUsesNewCodedVideoSequenceBitAsKeyFrameIndidcator) {
const uint8_t packet[] = {(uint8_t{1} << 3) | kObuCountOne,
kObuHeaderSequenceHeader};
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
ASSERT_TRUE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
EXPECT_TRUE(parsed.video.is_first_packet_in_frame);
EXPECT_TRUE(parsed.video.frame_type == VideoFrameType::kVideoFrameKey);
}
TEST(RtpDepacketizerAv1Test,
ParseUsesUnsetNewCodedVideoSequenceBitAsDeltaFrameIndidcator) {
const uint8_t packet[] = {(uint8_t{0} << 3) | kObuCountOne,
kObuHeaderSequenceHeader};
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
ASSERT_TRUE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
EXPECT_TRUE(parsed.video.is_first_packet_in_frame);
EXPECT_TRUE(parsed.video.frame_type == VideoFrameType::kVideoFrameDelta);
}
TEST(RtpDepacketizerAv1Test,
ParseRejectsPacketWithNewCVSAndContinuationFlagsBothSet) {
const uint8_t packet[] = {0b10'00'1000 | kObuCountOne,
kObuHeaderSequenceHeader};
RtpDepacketizerAv1 depacketizer;
RtpDepacketizer::ParsedPayload parsed;
EXPECT_FALSE(depacketizer.Parse(&parsed, packet, sizeof(packet)));
}
TEST(RtpDepacketizerAv1Test, AssembleFrameSetsOBUPayloadSizeWhenAbsent) {
const uint8_t payload1[] = {0b00'01'0000, // aggregation header
0b0'0110'000, // / Frame
20, 30, 40}; // \ OBU
rtc::ArrayView<const uint8_t> payloads[] = {payload1};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
rtc::ArrayView<const uint8_t> frame_view(*frame);
EXPECT_TRUE(frame_view[0] & kObuHeaderHasSize);
EXPECT_EQ(frame_view[1], 3);
}
TEST(RtpDepacketizerAv1Test, AssembleFrameSetsOBUPayloadSizeWhenPresent) {
const uint8_t payload1[] = {0b00'01'0000, // aggregation header
0b0'0110'010, // / Frame OBU header
3, // obu_size
20,
30,
40}; // \ obu_payload
rtc::ArrayView<const uint8_t> payloads[] = {payload1};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
rtc::ArrayView<const uint8_t> frame_view(*frame);
EXPECT_TRUE(frame_view[0] & kObuHeaderHasSize);
EXPECT_EQ(frame_view[1], 3);
}
TEST(RtpDepacketizerAv1Test,
AssembleFrameSetsOBUPayloadSizeAfterExtensionWhenAbsent) {
const uint8_t payload1[] = {0b00'01'0000, // aggregation header
0b0'0110'100, // / Frame
0b010'01'000, // | extension_header
20, 30, 40}; // \ OBU
rtc::ArrayView<const uint8_t> payloads[] = {payload1};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
rtc::ArrayView<const uint8_t> frame_view(*frame);
EXPECT_TRUE(frame_view[0] & kObuHeaderHasSize);
EXPECT_EQ(frame_view[2], 3);
}
TEST(RtpDepacketizerAv1Test,
AssembleFrameSetsOBUPayloadSizeAfterExtensionWhenPresent) {
const uint8_t payload1[] = {0b00'01'0000, // aggregation header
0b0'0110'110, // / Frame OBU header
0b010'01'000, // | extension_header
3, // | obu_size
20,
30,
40}; // \ obu_payload
rtc::ArrayView<const uint8_t> payloads[] = {payload1};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
rtc::ArrayView<const uint8_t> frame_view(*frame);
EXPECT_TRUE(frame_view[0] & kObuHeaderHasSize);
EXPECT_EQ(frame_view[2], 3);
}
TEST(RtpDepacketizerAv1Test, AssembleFrameFromOnePacketWithOneObu) {
const uint8_t payload1[] = {0b00'01'0000, // aggregation header
0b0'0110'000, // / Frame
20}; // \ OBU
rtc::ArrayView<const uint8_t> payloads[] = {payload1};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0110'010, 1, 20));
}
TEST(RtpDepacketizerAv1Test, AssembleFrameFromOnePacketWithTwoObus) {
const uint8_t payload1[] = {0b00'10'0000, // aggregation header
2, // / Sequence
0b0'0001'000, // | Header
10, // \ OBU
0b0'0110'000, // / Frame
20}; // \ OBU
rtc::ArrayView<const uint8_t> payloads[] = {payload1};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0001'010, 1, 10, // Sequence Header OBU
0b0'0110'010, 1, 20)); // Frame OBU
}
TEST(RtpDepacketizerAv1Test, AssembleFrameFromTwoPacketsWithOneObu) {
const uint8_t payload1[] = {0b01'01'0000, // aggregation header
0b0'0110'000, 20, 30};
const uint8_t payload2[] = {0b10'01'0000, // aggregation header
40};
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0110'010, 3, 20, 30, 40));
}
TEST(RtpDepacketizerAv1Test, AssembleFrameFromTwoPacketsWithTwoObu) {
const uint8_t payload1[] = {0b01'10'0000, // aggregation header
2, // / Sequence
0b0'0001'000, // | Header
10, // \ OBU
0b0'0110'000, //
20,
30}; //
const uint8_t payload2[] = {0b10'01'0000, // aggregation header
40}; //
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0001'010, 1, 10, // SH
0b0'0110'010, 3, 20, 30, 40)); // Frame
}
TEST(RtpDepacketizerAv1Test,
AssembleFrameFromTwoPacketsWithManyObusSomeWithExtensions) {
const uint8_t payload1[] = {0b01'00'0000, // aggregation header
2, // /
0b0'0001'000, // | Sequence Header
10, // \ OBU
2, // /
0b0'0101'000, // | Metadata OBU
20, // \ without extension
4, // /
0b0'0101'100, // | Metadata OBU
0b001'10'000, // | with extension
20, // |
30, // \ metadata payload
5, // /
0b0'0110'100, // | Frame OBU
0b001'10'000, // | with extension
40, // |
50, // |
60}; // |
const uint8_t payload2[] = {0b10'01'0000, // aggregation header
70, 80, 90}; // \ tail of the frame OBU
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre( // Sequence header OBU
0b0'0001'010, 1, 10,
// Metadata OBU without extension
0b0'0101'010, 1, 20,
// Metadata OBU with extenion
0b0'0101'110, 0b001'10'000, 2, 20, 30,
// Frame OBU with extension
0b0'0110'110, 0b001'10'000, 6, 40, 50, 60, 70, 80, 90));
}
TEST(RtpDepacketizerAv1Test, AssembleFrameWithOneObuFromManyPackets) {
const uint8_t payload1[] = {0b01'01'0000, // aggregation header
0b0'0110'000, 11, 12};
const uint8_t payload2[] = {0b11'01'0000, // aggregation header
13, 14};
const uint8_t payload3[] = {0b11'01'0000, // aggregation header
15, 16, 17};
const uint8_t payload4[] = {0b10'01'0000, // aggregation header
18};
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2, payload3,
payload4};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0110'010, 8, 11, 12, 13, 14, 15, 16, 17, 18));
}
TEST(RtpDepacketizerAv1Test,
AssembleFrameFromManyPacketsWithSomeObuBorderAligned) {
const uint8_t payload1[] = {0b01'10'0000, // aggregation header
3, // size of the 1st fragment
0b0'0011'000, // Frame header OBU
11,
12,
0b0'0100'000, // Tile group OBU
21,
22,
23};
const uint8_t payload2[] = {0b10'01'0000, // aggregation header
24, 25, 26, 27};
// payload2 ends an OBU, payload3 starts a new one.
const uint8_t payload3[] = {0b01'10'0000, // aggregation header
3, // size of the 1st fragment
0b0'0111'000, // Redundant frame header OBU
11,
12,
0b0'0100'000, // Tile group OBU
31,
32};
const uint8_t payload4[] = {0b10'01'0000, // aggregation header
33, 34, 35, 36};
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2, payload3,
payload4};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0011'010, 2, 11, 12, // Frame header
0b0'0100'010, 7, 21, 22, 23, 24, 25, 26, 27, //
0b0'0111'010, 2, 11, 12, //
0b0'0100'010, 6, 31, 32, 33, 34, 35, 36));
}
TEST(RtpDepacketizerAv1Test,
AssembleFrameFromOnePacketsOneObuPayloadSize127Bytes) {
uint8_t payload1[4 + 127];
memset(payload1, 0, sizeof(payload1));
payload1[0] = 0b00'00'0000; // aggregation header
payload1[1] = 0x80; // leb128 encoded size of 128 bytes
payload1[2] = 0x01; // in two bytes
payload1[3] = 0b0'0110'000; // obu_header with size and extension bits unset.
payload1[4 + 42] = 0x42;
rtc::ArrayView<const uint8_t> payloads[] = {payload1};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_EQ(frame->size(), 2 + 127u);
rtc::ArrayView<const uint8_t> frame_view(*frame);
EXPECT_EQ(frame_view[0], 0b0'0110'010); // obu_header with size bit set.
EXPECT_EQ(frame_view[1], 127); // obu payload size, 1 byte enough to encode.
// Check 'random' byte from the payload is at the same 'random' offset.
EXPECT_EQ(frame_view[2 + 42], 0x42);
}
TEST(RtpDepacketizerAv1Test,
AssembleFrameFromTwoPacketsOneObuPayloadSize128Bytes) {
uint8_t payload1[3 + 32];
memset(payload1, 0, sizeof(payload1));
payload1[0] = 0b01'00'0000; // aggregation header
payload1[1] = 33; // leb128 encoded size of 33 bytes in one byte
payload1[2] = 0b0'0110'000; // obu_header with size and extension bits unset.
payload1[3 + 10] = 0x10;
uint8_t payload2[2 + 96];
memset(payload2, 0, sizeof(payload2));
payload2[0] = 0b10'00'0000; // aggregation header
payload2[1] = 96; // leb128 encoded size of 96 bytes in one byte
payload2[2 + 20] = 0x20;
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_EQ(frame->size(), 3 + 128u);
rtc::ArrayView<const uint8_t> frame_view(*frame);
EXPECT_EQ(frame_view[0], 0b0'0110'010); // obu_header with size bit set.
EXPECT_EQ(frame_view[1], 0x80); // obu payload size of 128 bytes.
EXPECT_EQ(frame_view[2], 0x01); // encoded in two byes
// Check two 'random' byte from the payload is at the same 'random' offset.
EXPECT_EQ(frame_view[3 + 10], 0x10);
EXPECT_EQ(frame_view[3 + 32 + 20], 0x20);
}
TEST(RtpDepacketizerAv1Test, AssembleFrameFromAlmostEmptyPacketStartingAnOBU) {
const uint8_t payload1[] = {0b01'01'0000};
const uint8_t payload2[] = {0b10'01'0000, 0b0'0110'000, 10, 20, 30};
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0110'010, 3, 10, 20, 30));
}
TEST(RtpDepacketizerAv1Test, AssembleFrameFromAlmostEmptyPacketFinishingAnOBU) {
const uint8_t payload1[] = {0b01'01'0000, 0b0'0110'000, 10, 20, 30};
const uint8_t payload2[] = {0b10'01'0000};
rtc::ArrayView<const uint8_t> payloads[] = {payload1, payload2};
auto frame = RtpDepacketizerAv1::AssembleFrame(payloads);
ASSERT_TRUE(frame);
EXPECT_THAT(rtc::ArrayView<const uint8_t>(*frame),
ElementsAre(0b0'0110'010, 3, 10, 20, 30));
}
} // namespace
} // namespace webrtc
| 45.087071 | 80 | 0.59691 | gaoxiaoyang |
d0d458081e465741613614c4084425fa51ef7a5b | 491 | hpp | C++ | src/Engine/Scene/GeometrySystem.hpp | Yasoo31/Radium-Engine | e22754d0abe192207fd946509cbd63c4f9e52dd4 | [
"Apache-2.0"
] | 78 | 2017-12-01T12:23:22.000Z | 2022-03-31T05:08:09.000Z | src/Engine/Scene/GeometrySystem.hpp | neurodiverseEsoteric/Radium-Engine | ebebc29d889a9d32e0637e425e589e403d8edef8 | [
"Apache-2.0"
] | 527 | 2017-09-25T13:05:32.000Z | 2022-03-31T18:47:44.000Z | src/Engine/Scene/GeometrySystem.hpp | neurodiverseEsoteric/Radium-Engine | ebebc29d889a9d32e0637e425e589e403d8edef8 | [
"Apache-2.0"
] | 48 | 2018-01-04T22:08:08.000Z | 2022-03-03T08:13:41.000Z | #pragma once
#include <Engine/Scene/System.hpp>
namespace Ra {
namespace Engine {
namespace Scene {
class RA_ENGINE_API GeometrySystem : public System
{
public:
GeometrySystem();
~GeometrySystem() override = default;
void handleAssetLoading( Entity* entity, const Ra::Core::Asset::FileData* fileData ) override;
void generateTasks( Ra::Core::TaskQueue* taskQueue, const FrameInfo& frameInfo ) override;
};
} // namespace Scene
} // namespace Engine
} // namespace Ra
| 21.347826 | 98 | 0.725051 | Yasoo31 |
d0d750ac8d8d08fd75030c52baa1dadb284b7aef | 31,939 | cc | C++ | io/reader_test.cc | chronos-tachyon/mojo | 8d268932dd927a24a2b5de167d63869484e1433a | [
"MIT"
] | 3 | 2017-04-24T07:00:59.000Z | 2020-04-13T04:53:06.000Z | io/reader_test.cc | chronos-tachyon/mojo | 8d268932dd927a24a2b5de167d63869484e1433a | [
"MIT"
] | 1 | 2017-01-10T04:23:55.000Z | 2017-01-10T04:23:55.000Z | io/reader_test.cc | chronos-tachyon/mojo | 8d268932dd927a24a2b5de167d63869484e1433a | [
"MIT"
] | 1 | 2020-04-13T04:53:07.000Z | 2020-04-13T04:53:07.000Z | // Copyright © 2016 by Donald King <chronos@chronos-tachyon.net>
// Available under the MIT License. See LICENSE for details.
#include "gtest/gtest.h"
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <condition_variable>
#include <mutex>
#include <thread>
#include "base/cleanup.h"
#include "base/fd.h"
#include "base/logging.h"
#include "base/result_testing.h"
#include "event/task.h"
#include "io/reader.h"
#include "io/util.h"
#include "io/writer.h"
namespace {
class TempFile {
public:
TempFile() {
CHECK_OK(base::make_tempfile(&path_, &fd_, "mojo-io-reader-test.XXXXXX"));
}
~TempFile() noexcept {
::unlink(path_.c_str());
}
const std::string& path() const noexcept { return path_; }
const base::FD fd() const noexcept { return fd_; }
void rewind() {
CHECK_OK(base::seek(nullptr, fd_, 0, SEEK_SET));
}
void truncate() {
CHECK_OK(base::truncate(fd_));
}
void write(const char* ptr, std::size_t len) {
CHECK_OK(base::write_exactly(fd_, ptr, len, path_.c_str()));
}
void write(base::StringPiece sp) {
write(sp.data(), sp.size());
}
void set(const char* ptr, std::size_t len) {
rewind();
truncate();
write(ptr, len);
rewind();
}
void set(base::StringPiece sp) {
set(sp.data(), sp.size());
}
TempFile(const TempFile&) = delete;
TempFile(TempFile&&) = delete;
TempFile& operator=(const TempFile&) = delete;
TempFile& operator=(TempFile&&) = delete;
private:
std::string path_;
base::FD fd_;
};
} // anonymous namespace
// StringReader {{{
TEST(StringReader, ZeroThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, OneThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, ZeroFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, OneFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, ThreeFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 3, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, WriteTo) {
io::Reader r;
io::Writer w;
event::Task task;
char buf[16];
std::size_t len = 0;
std::size_t copied = 42;
r = io::stringreader("abcdefg");
w = io::bufferwriter(buf, sizeof(buf), &len);
r.write_to(&task, &copied, ~std::size_t(0), w);
EXPECT_OK(task.result());
EXPECT_EQ(7U, copied);
EXPECT_EQ(7U, len);
EXPECT_EQ("abcdefg", std::string(buf, len));
}
TEST(StringReader, Close) {
event::Task task;
io::Reader r = io::stringreader("");
r.close(&task);
EXPECT_OK(task.result());
task.reset();
r.close(&task);
EXPECT_FAILED_PRECONDITION(task.result());
}
// }}}
// BufferReader {{{
TEST(BufferReader, ZeroThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, OneThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, ZeroFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, OneFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, ThreeFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 3, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, WriteTo) {
io::Reader r;
io::Writer w;
event::Task task;
char buf[16];
std::size_t len = 0;
std::size_t copied = 42;
r = io::bufferreader("abcdefg", 7);
w = io::bufferwriter(buf, sizeof(buf), &len);
r.write_to(&task, &copied, ~std::size_t(0), w);
EXPECT_OK(task.result());
EXPECT_EQ(7U, copied);
EXPECT_EQ(7U, len);
EXPECT_EQ("abcdefg", std::string(buf, len));
}
TEST(BufferReader, Close) {
event::Task task;
io::Reader r = io::bufferreader("", 0);
r.close(&task);
EXPECT_OK(task.result());
task.reset();
r.close(&task);
EXPECT_FAILED_PRECONDITION(task.result());
}
// }}}
// IgnoreCloseReader {{{
TEST(IgnoreCloseReader, Close) {
int n = 0;
auto rfn = [](event::Task* task, char* ptr, std::size_t* len, std::size_t min,
std::size_t max, const base::Options& o) {
*len = 0;
if (task->start()) task->finish(base::Result::not_implemented());
};
auto cfn = [&n](event::Task* task, const base::Options& o) {
++n;
if (task->start()) task->finish_ok();
};
io::Reader r;
event::Task task;
r = io::reader(rfn, cfn);
r.close(&task);
EXPECT_OK(task.result());
EXPECT_EQ(1, n);
task.reset();
r.close(&task);
EXPECT_OK(task.result());
EXPECT_EQ(2, n);
r = io::ignore_close(std::move(r));
task.reset();
r.close(&task);
EXPECT_OK(task.result());
EXPECT_EQ(2, n);
}
// }}}
// LimitedReader {{{
TEST(LimitedReader, BigRead) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::limited_reader(io::stringreader("abcdef"), 4);
r.read(&task, buf, &len, 1, 16);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 16);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(LimitedReader, SmallReadAligned) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::limited_reader(io::stringreader("abcdef"), 4);
r.read(&task, buf, &len, 1, 2);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ab", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 2);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("cd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 2);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(LimitedReader, SmallReadUnaligned) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::limited_reader(io::stringreader("abcdef"), 4);
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(1U, len);
EXPECT_EQ("d", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(LimitedReader, WriteTo) {
io::Reader r;
io::Writer w;
event::Task task;
std::string in(8192, 'a');
std::string out;
std::size_t n = 0;
r = io::limited_reader(io::stringreader(in), 4096);
w = io::stringwriter(&out);
r.write_to(&task, &n, 4096, w);
EXPECT_OK(task.result());
EXPECT_EQ(4096U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
task.reset();
r.write_to(&task, &n, 4096, w);
EXPECT_OK(task.result());
EXPECT_EQ(0U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
out.clear();
r = io::limited_reader(io::stringreader(in), 4096);
w = io::stringwriter(&out);
task.reset();
r.write_to(&task, &n, 3072, w);
EXPECT_OK(task.result());
EXPECT_EQ(3072U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
task.reset();
r.write_to(&task, &n, 3072, w);
EXPECT_OK(task.result());
EXPECT_EQ(1024U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
task.reset();
r.write_to(&task, &n, 3072, w);
EXPECT_OK(task.result());
EXPECT_EQ(0U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
}
// }}}
// NullReader {{{
TEST(NullReader, Read) {
io::Reader r = io::nullreader();
base::Options o;
char buf[16];
std::size_t n = 42;
EXPECT_OK(r.read(buf, &n, 0, sizeof(buf), o));
EXPECT_EQ(0U, n);
n = 42;
EXPECT_EOF(r.read(buf, &n, 1, sizeof(buf), o));
EXPECT_EQ(0U, n);
}
// }}}
// ZeroReader {{{
TEST(ZeroReader, Read) {
io::Reader r = io::zeroreader();
base::Options o;
char buf[16];
std::size_t n = 42;
std::string expected;
expected.assign(sizeof(buf), '\0');
EXPECT_OK(r.read(buf, &n, 0, sizeof(buf), o));
EXPECT_EQ(sizeof(buf), n);
EXPECT_EQ(expected, std::string(buf, n));
n = 42;
EXPECT_OK(r.read(buf, &n, 1, sizeof(buf), o));
EXPECT_EQ(sizeof(buf), n);
EXPECT_EQ(expected, std::string(buf, n));
n = 42;
EXPECT_OK(r.read(buf, &n, sizeof(buf), sizeof(buf), o));
EXPECT_EQ(sizeof(buf), n);
EXPECT_EQ(expected, std::string(buf, n));
}
// }}}
// FDReader {{{
static void TestFDReader_Read(const base::Options& o) {
base::Pipe pipe;
ASSERT_OK(base::make_pipe(&pipe));
LOG(INFO) << "made pipes";
std::mutex mu;
std::condition_variable cv;
std::size_t x = 0, y = 0;
std::thread t1([&pipe, &mu, &cv, &x, &y] {
auto lock = base::acquire_lock(mu);
while (x < 1) cv.wait(lock);
LOG(INFO) << "T1 awoken: x = " << x;
EXPECT_OK(base::write_exactly(pipe.write, "abcd", 4, "pipe"));
LOG(INFO) << "wrote: abcd";
while (x < 2) cv.wait(lock);
LOG(INFO) << "T1 awoken: x = " << x;
EXPECT_OK(base::write_exactly(pipe.write, "efgh", 4, "pipe"));
LOG(INFO) << "wrote: efgh";
++y;
cv.notify_all();
LOG(INFO) << "woke T0: y = " << y;
while (x < 3) cv.wait(lock);
LOG(INFO) << "T1 awoken: x = " << x;
EXPECT_OK(base::write_exactly(pipe.write, "ijkl", 4, "pipe"));
LOG(INFO) << "wrote: ijkl";
});
LOG(INFO) << "spawned thread";
io::Reader r = io::fdreader(pipe.read);
LOG(INFO) << "made fdreader";
char buf[8];
std::size_t n;
EXPECT_OK(r.read(buf, &n, 0, 8, o));
EXPECT_EQ(0U, n);
LOG(INFO) << "read zero bytes";
auto lock = base::acquire_lock(mu);
++x;
cv.notify_all();
LOG(INFO) << "woke T1: x = " << x;
lock.unlock();
LOG(INFO) << "initiating read #1";
EXPECT_OK(r.read(buf, &n, 1, 8, o));
LOG(INFO) << "read #1 complete";
EXPECT_EQ(4U, n);
EXPECT_EQ("abcd", std::string(buf, n));
lock.lock();
++x;
cv.notify_all();
LOG(INFO) << "woke T1: x = " << x;
while (y < 1) cv.wait(lock);
LOG(INFO) << "T0 awoken: y = " << y;
lock.unlock();
event::Task task;
LOG(INFO) << "initiating read #2";
r.read(&task, buf, &n, 8, 8, o);
lock.lock();
++x;
cv.notify_all();
LOG(INFO) << "woke T1: x = " << x;
lock.unlock();
event::wait(io::get_manager(o), &task);
LOG(INFO) << "read #2 complete";
EXPECT_OK(task.result());
EXPECT_EQ(8U, n);
EXPECT_EQ("efghijkl", std::string(buf, n));
t1.join();
base::log_flush();
}
static void TestFDReader_WriteTo(const base::Options& o) {
TempFile tempfile;
for (std::size_t i = 0; i < 16; ++i) {
std::string tmp;
tmp.assign(4096, 'A' + i);
tempfile.write(tmp);
}
tempfile.rewind();
LOG(INFO) << "temp file is ready";
base::SocketPair s;
ASSERT_OK(base::make_socketpair(&s, AF_UNIX, SOCK_STREAM, 0));
ASSERT_OK(base::set_blocking(s.right, true));
LOG(INFO) << "socketpair is ready";
std::mutex mu;
std::condition_variable cv;
bool ready = false;
std::size_t sunk = 0;
std::thread t([&s, &mu, &cv, &ready, &sunk] {
base::Result r;
std::vector<char> buf;
std::string expected;
std::size_t i = 0;
buf.resize(4096);
expected.resize(4096);
auto lock = base::acquire_lock(mu);
while (!ready) cv.wait(lock);
LOG(INFO) << "sink thread running";
while (true) {
expected.assign(4096, 'A' + i);
r = base::read_exactly(s.right, buf.data(), buf.size(), "socket");
if (!r) break;
EXPECT_EQ(expected, std::string(buf.data(), buf.size()));
sunk += buf.size();
++i;
}
EXPECT_EOF(r);
});
LOG(INFO) << "thread launched";
io::Reader r = io::fdreader(tempfile.fd());
io::Writer w = io::fdwriter(s.left);
event::Task task;
std::size_t n;
io::copy(&task, &n, w, r, o);
auto lock = base::acquire_lock(mu);
ready = true;
cv.notify_all();
lock.unlock();
event::wait(io::get_manager(o), &task);
LOG(INFO) << "task done";
EXPECT_OK(task.result());
EXPECT_EQ(16U * 4096U, n);
ASSERT_OK(base::shutdown(s.left, SHUT_WR));
t.join();
LOG(INFO) << "thread done";
EXPECT_EQ(sunk, n);
base::log_flush();
}
TEST(FDReader, AsyncRead) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestFDReader_Read(o);
m.shutdown();
}
TEST(FDReader, ThreadedRead) {
event::ManagerOptions mo;
mo.set_minimal_threaded_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestFDReader_Read(o);
m.shutdown();
}
TEST(FDReader, WriteToFallback) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
o.get<io::Options>().transfer_mode = io::TransferMode::read_write;
TestFDReader_WriteTo(o);
m.shutdown();
}
TEST(FDReader, WriteToSendfile) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
o.get<io::Options>().transfer_mode = io::TransferMode::sendfile;
TestFDReader_WriteTo(o);
m.shutdown();
}
TEST(FDReader, WriteToSplice) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
o.get<io::Options>().transfer_mode = io::TransferMode::splice;
TestFDReader_WriteTo(o);
m.shutdown();
}
// }}}
// MultiReader {{{
void TestMultiReader_LineUp(const base::Options& o) {
std::string a = "01234567";
std::string b = "abcdefgh";
std::string c = "ABCDEFGH";
std::string d = "!@#$%^&*";
std::string expected;
expected.reserve(8 * 4);
expected.append(a);
expected.append(b);
expected.append(c);
expected.append(d);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b), io::stringreader(c),
io::stringreader(d),
});
base::Result result;
char buf[8];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 8, 8, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader_Half(const base::Options& o) {
std::string a = "01234567";
std::string b = "abcdefgh";
std::string expected;
expected.reserve(8 * 2);
expected.append(a);
expected.append(b);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b),
});
base::Result result;
char buf[4];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 4, 4, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader_Double(const base::Options& o) {
std::string a = "01234567";
std::string b = "abcdefgh";
std::string c = "ABCDEFGH";
std::string d = "!@#$%^&*";
std::string expected;
expected.reserve(8 * 4);
expected.append(a);
expected.append(b);
expected.append(c);
expected.append(d);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b), io::stringreader(c),
io::stringreader(d),
});
base::Result result;
char buf[16];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 16, 16, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader_OffAxis(const base::Options& o) {
std::string a = "01234";
std::string b = "abcde";
std::string c = "ABCDE";
std::string d = "!@#$%";
std::string expected;
expected.reserve(5 * 4);
expected.append(a);
expected.append(b);
expected.append(c);
expected.append(d);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b), io::stringreader(c),
io::stringreader(d),
});
base::Result result;
char buf[8];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 8, 8, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader(const base::Options& o, const char* what) {
LOG(INFO) << "[TestMultiReader_LineUp:" << what << "]";
TestMultiReader_LineUp(o);
LOG(INFO) << "[TestMultiReader_Half:" << what << "]";
TestMultiReader_Half(o);
LOG(INFO) << "[TestMultiReader_Double:" << what << "]";
TestMultiReader_Double(o);
LOG(INFO) << "[TestMultiReader_OffAxis:" << what << "]";
TestMultiReader_OffAxis(o);
LOG(INFO) << "[Done:" << what << "]";
base::log_flush();
}
TEST(MultiReader, Async) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestMultiReader(o, "async");
m.shutdown();
}
TEST(MultiReader, Threaded) {
event::ManagerOptions mo;
mo.set_threaded_mode();
mo.set_num_pollers(2);
mo.dispatcher().set_num_workers(2);
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestMultiReader(o, "threaded");
m.shutdown();
}
// }}}
// BufferedReader {{{
static io::Reader wrap(bool do_buffer, io::Reader r) {
if (do_buffer) r = io::bufferedreader(std::move(r));
return r;
};
static void TestBufferedReader_Fixed(const base::Options& o, bool do_buffer, const char* what) {
constexpr unsigned char kBytes[] = {
0x00, // 8-bit datum #0
0x7f, // 8-bit datum #1
0x81, // 8-bit datum #2
0xff, // 8-bit datum #3
0x00, 0x00, // 16-bit datum #0
0x7f, 0xff, // 16-bit datum #1
0x80, 0x01, // 16-bit datum #2
0xff, 0xff, // 16-bit datum #3
0x00, 0x00, 0x00, 0x00, // 32-bit datum #0
0x7f, 0xff, 0xff, 0xff, // 32-bit datum #1
0x80, 0x00, 0x00, 0x01, // 32-bit datum #2
0xff, 0xff, 0xff, 0xff, // 32-bit datum #3
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 64-bit datum #0
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // 64-bit datum #1
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // 64-bit datum #2
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // 64-bit datum #3
};
LOG(INFO) << "[TestBufferedReader_Fixed:" << what << ":unsigned]";
TempFile tempfile;
tempfile.set(reinterpret_cast<const char*>(kBytes), sizeof(kBytes));
io::Reader r = wrap(do_buffer, io::fdreader(tempfile.fd()));
uint8_t u8 = 0;
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0x00U, u8);
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0x7fU, u8);
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0x81U, u8);
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0xffU, u8);
uint16_t u16 = 0;
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0x0000U, u16);
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0x7fffU, u16);
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0x8001U, u16);
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0xffffU, u16);
uint32_t u32 = 0;
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0x00000000U, u32);
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0x7fffffffU, u32);
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0x80000001U, u32);
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0xffffffffU, u32);
uint64_t u64 = 0;
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0x0000000000000000ULL, u64);
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0x7fffffffffffffffULL, u64);
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0x8000000000000001ULL, u64);
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0xffffffffffffffffULL, u64);
EXPECT_EOF(r.read_u8(&u8, o));
LOG(INFO) << "[TestBufferedReader_Fixed:" << what << ":signed]";
tempfile.rewind();
r = wrap(do_buffer, io::fdreader(tempfile.fd()));
int8_t s8 = 0;
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(0x00, s8);
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(0x7f, s8);
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(-0x7f, s8);
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(-0x01, s8);
int16_t s16 = 0;
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(0x0000, s16);
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(0x7fff, s16);
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(-0x7fff, s16);
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(-0x0001, s16);
int32_t s32 = 0;
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(0x00000000, s32);
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(0x7fffffff, s32);
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(-0x7fffffff, s32);
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(-0x00000001, s32);
int64_t s64 = 0;
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(0x0000000000000000LL, s64);
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(0x7fffffffffffffffLL, s64);
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(-0x7fffffffffffffffLL, s64);
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(-0x0000000000000001LL, s64);
EXPECT_EOF(r.read_u8(&u8, o));
}
static void TestBufferedReader_Varint(const base::Options& o, bool do_buffer, const char* what) {
constexpr unsigned char kBytes[] = {
0x00, // 0, 0, 0
0x01, // 1, 1, -1
0x02, // 2, 2, 1
0x03, // 3, 3, -2
0x04, // 4, 4, 2
0x7f, // 127, 127, -64
0xac, 0x02, // 300, 300, 150
0xff, 0x7f, // 16383, 16383, -8192
0xff, 0xff, 0x03, // 65535, 65535, -32768
0xfe, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x01, // UINT64MAX - 1, -2, INT64MAX
};
LOG(INFO) << "[TestBufferedReader_Varint:" << what << ":unsigned]";
TempFile tempfile;
tempfile.set(reinterpret_cast<const char*>(kBytes), sizeof(kBytes));
io::Reader r = wrap(do_buffer, io::fdreader(tempfile.fd()));
uint64_t u64;
int64_t s64;
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(0U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(1U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(2U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(3U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(4U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(127U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(300U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(16383U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(65535U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(0xfffffffffffffffeULL, u64);
EXPECT_EOF(r.read_uvarint(&u64, o));
LOG(INFO) << "[TestBufferedReader_Varint:" << what << ":signed]";
tempfile.rewind();
r = wrap(do_buffer, io::fdreader(tempfile.fd()));
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(0, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(1, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(2, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(3, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(4, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(127, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(300, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(16383, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(65535, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(-2, s64);
EXPECT_EOF(r.read_svarint(&s64, o));
LOG(INFO) << "[TestBufferedReader_Varint:" << what << ":zigzag]";
tempfile.rewind();
r = wrap(do_buffer, io::fdreader(tempfile.fd()));
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(0, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-1, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(1, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-2, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(2, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-64, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(150, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-8192, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-32768, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(0x7fffffffffffffffLL, s64);
EXPECT_EOF(r.read_svarint_zigzag(&s64, o));
}
static void TestBufferedReader_ReadLine(const base::Options& o, bool do_buffer, const char* what) {
constexpr char kBytes[] =
"Line 1\n"
"Line 2\r\n"
"Line 3 is a very long line\r\n"
"Line 4";
LOG(INFO) << "[TestBufferedReader_ReadLine:" << what << "]";
TempFile tempfile;
tempfile.set(kBytes, sizeof(kBytes) - 1);
io::Reader r = wrap(do_buffer, io::fdreader(tempfile.fd()));
std::string str;
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("Line 1\n", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("Line 2\r\n", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("Line 3 is ", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("a very lon", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("g line\r\n", str);
EXPECT_EOF(r.readline(&str, 10, o));
EXPECT_EQ("Line 4", str);
}
static void TestBufferedReader(const base::Options& o, bool do_buffer, const char* what) {
TestBufferedReader_Fixed(o, do_buffer, what);
TestBufferedReader_Varint(o, do_buffer, what);
TestBufferedReader_ReadLine(o, do_buffer, what);
base::log_flush();
}
TEST(BufferedReader, Inline) {
event::ManagerOptions mo;
mo.set_inline_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, true, "buffered/inline");
m.shutdown();
}
TEST(BufferedReader, Async) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, true, "buffered/async");
m.shutdown();
}
TEST(BufferedReader, Threaded) {
event::ManagerOptions mo;
mo.set_threaded_mode();
mo.set_num_pollers(2);
mo.dispatcher().set_num_workers(2);
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, true, "buffered/threaded");
m.shutdown();
}
TEST(UnbufferedReader, Inline) {
event::ManagerOptions mo;
mo.set_inline_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, false, "unbuffered/inline");
m.shutdown();
}
TEST(UnbufferedReader, Async) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, false, "unbuffered/async");
m.shutdown();
}
TEST(UnbufferedReader, Threaded) {
event::ManagerOptions mo;
mo.set_threaded_mode();
mo.set_num_pollers(2);
mo.dispatcher().set_num_workers(2);
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, false, "unbuffered/threaded");
m.shutdown();
}
// }}}
static void init() __attribute__((constructor));
static void init() { base::log_stderr_set_level(VLOG_LEVEL(6)); }
| 23.96024 | 99 | 0.616832 | chronos-tachyon |
d0d849b10ed26b212ddc9b843f578b538bed3146 | 5,099 | cpp | C++ | launcher/src/launcher/ExecutableLoader.cpp | norelock/Project-MP-1 | 31dbb5c74b29a47df4cf41280887a66794fdc5ff | [
"MIT"
] | 1 | 2022-02-19T15:52:29.000Z | 2022-02-19T15:52:29.000Z | launcher/src/launcher/ExecutableLoader.cpp | cleoppa/norasa | 6f8d697922dca2fcc42a5830a384e790c687833a | [
"MIT"
] | 2 | 2020-11-08T08:12:41.000Z | 2022-01-08T07:20:45.000Z | launcher/src/launcher/ExecutableLoader.cpp | cleoppa/norasa | 6f8d697922dca2fcc42a5830a384e790c687833a | [
"MIT"
] | 3 | 2020-03-23T06:56:35.000Z | 2021-06-06T02:30:06.000Z | #include "stdafx.h"
/*
#pragma bss_seg(".cdummy")
char dummy_seg[0x2500000];
#pragma data_seg(".zdata")
char zdata[0x50000] = { 1 };
*/
ExecutableLoader::ExecutableLoader(const BYTE* origBinary)
{
m_origBinary = origBinary;
m_loadLimit = UINT_MAX;
SetLibraryLoader([](const char* name)
{
return LoadLibraryA(name);
});
SetFunctionResolver([](HMODULE module, const char* name)
{
return reinterpret_cast<LPVOID>(GetProcAddress(module, name));
});
}
std::wstring s2ws(const std::string& str)
{
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
bool ExecutableLoader::LoadDependentLibraries(IMAGE_NT_HEADERS* ntHeader)
{
IMAGE_DATA_DIRECTORY* importDirectory = &ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
IMAGE_IMPORT_DESCRIPTOR* descriptor = GetTargetRVA<IMAGE_IMPORT_DESCRIPTOR>(importDirectory->VirtualAddress);
while (descriptor->Name)
{
const char* name = GetTargetRVA<char>(descriptor->Name);
HMODULE module = ResolveLibrary(name);
if (!module)
{
std::ostringstream os;
os << GetLastError();
std::string str = "Could not load dependent module " + std::string(name) + ". Error code: " + os.str();
MessageBox(NULL, s2ws(str).c_str(), L"Launch error", MB_OK);
//FatalError(va("Could not load dependent module %s. Error code was %i.", name, GetLastError()));
return false;
}
if (reinterpret_cast<unsigned>(module) == 0xFFFFFFFF)
{
descriptor++;
continue;
}
auto nameTableEntry = GetTargetRVA<unsigned>(descriptor->OriginalFirstThunk);
auto addressTableEntry = GetTargetRVA<unsigned>(descriptor->FirstThunk);
while (*nameTableEntry)
{
FARPROC function;
const char* functionName;
if (IMAGE_SNAP_BY_ORDINAL(*nameTableEntry))
{
function = reinterpret_cast<FARPROC>(
ResolveLibraryFunction(module, MAKEINTRESOURCEA(IMAGE_ORDINAL(*nameTableEntry))));
char buff[256];
snprintf(buff, sizeof(buff), "#%d", IMAGE_ORDINAL(*nameTableEntry));
std::string buffAsStdStr = buff;
functionName = buffAsStdStr.c_str();
}
else
{
auto import = GetTargetRVA<IMAGE_IMPORT_BY_NAME>(*nameTableEntry);
function = reinterpret_cast<FARPROC>(ResolveLibraryFunction(module, (const char*)import->Name));
functionName = static_cast<const char*>(import->Name);
}
if (!function)
{
char pathName[MAX_PATH];
GetModuleFileNameA(module, pathName, sizeof(pathName));
MessageBox(NULL, L"Could not load function in dependent module", L"Launch error", MB_OK);
//FatalError(va("Could not load function %s in dependent module %s (%s).", functionName, name, pathName));
return false;
}
*addressTableEntry = reinterpret_cast<unsigned>(function);
nameTableEntry++;
addressTableEntry++;
}
descriptor++;
}
return true;
}
void ExecutableLoader::LoadSection(IMAGE_SECTION_HEADER* section)
{
void* targetAddress = GetTargetRVA<uint8_t>(section->VirtualAddress);
const void* sourceAddress = m_origBinary + section->PointerToRawData;
if ((uintptr_t)targetAddress >= m_loadLimit)
{
MessageBox(NULL, L"Exceeded load limit.", L"Launch error", MB_OK);
//FatalError("Exceeded load limit.");
return;
}
if (section->SizeOfRawData > 0)
{
uint32_t sizeOfData = section->SizeOfRawData < section->Misc.VirtualSize ? section->SizeOfRawData : section->Misc.VirtualSize;
DWORD oldProtect;
VirtualProtect(targetAddress, sizeOfData, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy(targetAddress, sourceAddress, sizeOfData);
}
}
void ExecutableLoader::LoadSections(IMAGE_NT_HEADERS* ntHeader)
{
IMAGE_SECTION_HEADER* section = IMAGE_FIRST_SECTION(ntHeader);
for (int i = 0; i < ntHeader->FileHeader.NumberOfSections; i++)
{
// Load the given section into memory
LoadSection(section);
section++;
}
}
void ExecutableLoader::LoadIntoModule(HMODULE module)
{
m_executableHandle = module;
IMAGE_DOS_HEADER* header = (IMAGE_DOS_HEADER*)m_origBinary;
if (header->e_magic != IMAGE_DOS_SIGNATURE)
{
MessageBox(NULL, L"Cannot find dos signature.", L"Launch error", MB_OK);
return;
}
IMAGE_DOS_HEADER* sourceHeader = (IMAGE_DOS_HEADER*)module;
IMAGE_NT_HEADERS* sourceNtHeader = GetTargetRVA<IMAGE_NT_HEADERS>(sourceHeader->e_lfanew);
IMAGE_NT_HEADERS* ntHeader = (IMAGE_NT_HEADERS*)(m_origBinary + header->e_lfanew);
LoadSections(ntHeader);
LoadDependentLibraries(ntHeader);
m_entryPoint = GetTargetRVA<void>(ntHeader->OptionalHeader.AddressOfEntryPoint);
DWORD oldProtect;
VirtualProtect(sourceNtHeader, 0x1000, PAGE_EXECUTE_READWRITE, &oldProtect);
sourceNtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
}
HMODULE ExecutableLoader::ResolveLibrary(const char* name)
{
return m_libraryLoader(name);
}
LPVOID ExecutableLoader::ResolveLibraryFunction(HMODULE module, const char* name)
{
return m_functionResolver(module, name);
} | 28.171271 | 147 | 0.741322 | norelock |
d0d92265f0023344ded77fb2b55cfca4787bf23e | 1,427 | cpp | C++ | compiler-rt/test/asan/TestCases/invalid-pointer-pairs-compare-success.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | compiler-rt/test/asan/TestCases/invalid-pointer-pairs-compare-success.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | compiler-rt/test/asan/TestCases/invalid-pointer-pairs-compare-success.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // RUN: %clangxx_asan -O0 %s -o %t -mllvm -asan-detect-invalid-pointer-pair
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=2 %run %t
#include <assert.h>
#include <stdlib.h>
int foo(char *p) {
char *p2 = p + 20;
return p > p2;
}
int bar(char *p, char *q) {
return p <= q;
}
int baz(char *p, char *q) {
return p != 0 && p < q;
}
char global[8192] = {};
char small_global[7] = {};
int main() {
// Heap allocated memory.
char *p = (char *)malloc(42);
int r = foo(p);
free(p);
p = (char *)malloc(1024);
bar(p, p + 1024);
bar(p + 1024, p + 1023);
bar(p + 1, p + 1023);
free(p);
p = (char *)malloc(4096);
bar(p, p + 4096);
bar(p + 10, p + 100);
bar(p + 1024, p + 4096);
bar(p + 4095, p + 4096);
bar(p + 4095, p + 4094);
bar(p + 100, p + 4096);
bar(p + 100, p + 4094);
free(p);
// Global variable.
bar(&global[0], &global[1]);
bar(&global[1], &global[2]);
bar(&global[2], &global[1]);
bar(&global[0], &global[100]);
bar(&global[1000], &global[7000]);
bar(&global[500], &global[10]);
p = &global[0];
bar(p, p + 8192);
p = &global[8000];
bar(p, p + 192);
p = &small_global[0];
bar(p, p + 1);
bar(p, p + 7);
bar(p + 7, p + 1);
bar(p + 6, p + 7);
bar(p + 7, p + 7);
// Stack variable.
char stack[10000];
bar(&stack[0], &stack[100]);
bar(&stack[1000], &stack[9000]);
bar(&stack[500], &stack[10]);
baz(0, &stack[10]);
return 0;
}
| 19.026667 | 75 | 0.533287 | medismailben |
d0d9f3b56c01c8c2e111ce19b00c4d2f25bea615 | 9,503 | cxx | C++ | modules/ITK/cli/statismo-build-shape-model.cxx | skn123/statismo | 5998a32e1b1fd496f2703eea27dc143a6b3f8e1f | [
"BSD-3-Clause"
] | 223 | 2015-02-02T18:50:07.000Z | 2022-01-24T08:14:17.000Z | modules/ITK/cli/statismo-build-shape-model.cxx | skn123/statismo | 5998a32e1b1fd496f2703eea27dc143a6b3f8e1f | [
"BSD-3-Clause"
] | 84 | 2015-01-07T09:54:37.000Z | 2020-03-05T17:17:05.000Z | modules/ITK/cli/statismo-build-shape-model.cxx | skn123/statismo | 5998a32e1b1fd496f2703eea27dc143a6b3f8e1f | [
"BSD-3-Clause"
] | 94 | 2015-01-14T20:02:17.000Z | 2021-12-15T08:45:18.000Z | /*
* Copyright (c) 2015 University of Basel
* 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 project's author 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 <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <itkDataManager.h>
#include <itkDirectory.h>
#include <itkImage.h>
#include <itkLandmarkBasedTransformInitializer.h>
#include <itkMesh.h>
#include <itkMeshFileReader.h>
#include <itkMeshFileWriter.h>
#include <itkPCAModelBuilder.h>
#include <itkRigid3DTransform.h>
#include <itkStandardMeshRepresenter.h>
#include <itkStatismoIO.h>
#include <itkStatisticalModel.h>
#include <itkTransformMeshFilter.h>
#include "utils/statismo-build-models-utils.h"
namespace po = boost::program_options;
using namespace std;
struct programOptions {
bool bDisplayHelp;
string strDataListFile;
string strProcrustesMode;
string strProcrustesReferenceFile;
string strOutputFileName;
float fNoiseVariance;
};
po::options_description initializeProgramOptions(programOptions& poParameters);
bool isOptionsConflictPresent(programOptions& opt);
void buildAndSaveShapeModel(programOptions opt);
int main(int argc, char** argv) {
programOptions poParameters;
po::positional_options_description optPositional;
optPositional.add("output-file", 1);
po::options_description optAllOptions = initializeProgramOptions(poParameters);
po::variables_map vm;
try {
po::parsed_options parsedOptions = po::command_line_parser(argc, argv).options(optAllOptions).positional(optPositional).run();
po::store(parsedOptions, vm);
po::notify(vm);
} catch (po::error& e) {
cerr << "An exception occurred while parsing the Command line:"<<endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
}
if (poParameters.bDisplayHelp == true) {
cout << optAllOptions << endl;
return EXIT_SUCCESS;
}
if (isOptionsConflictPresent(poParameters) == true) {
cerr << "A conflict in the options exists or insufficient options were set." << endl;
cout << optAllOptions << endl;
return EXIT_FAILURE;
}
try {
buildAndSaveShapeModel(poParameters);
} catch (ifstream::failure & e) {
cerr << "Could not read the data-list:" << endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
} catch (itk::ExceptionObject & e) {
cerr << "Could not build the model:" << endl;
cerr << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool isOptionsConflictPresent(programOptions& opt) {
boost::algorithm::to_lower(opt.strProcrustesMode);
if (opt.strProcrustesMode != "reference" && opt.strProcrustesMode != "gpa") {
return true;
}
if(opt.strProcrustesMode == "reference" && opt.strProcrustesReferenceFile == "") {
return true;
}
if (opt.strProcrustesMode == "gpa" && opt.strProcrustesReferenceFile != "") {
return true;
}
if (opt.strDataListFile == "" || opt.strOutputFileName == "") {
return true;
}
if (opt.strDataListFile == opt.strOutputFileName) {
return true;
}
if (opt.strProcrustesMode == "reference") {
if (opt.strDataListFile == opt.strProcrustesReferenceFile || opt.strOutputFileName == opt.strProcrustesReferenceFile) {
return true;
}
}
if (opt.fNoiseVariance < 0) {
return true;
}
return false;
}
void buildAndSaveShapeModel(programOptions opt) {
const unsigned Dimensions = 3;
typedef itk::StandardMeshRepresenter<float, Dimensions> RepresenterType;
RepresenterType::Pointer representer = RepresenterType::New();
typedef itk::Mesh<float, Dimensions> MeshType;
typedef itk::DataManager<MeshType> DataManagerType;
DataManagerType::Pointer dataManager = DataManagerType::New();
StringList fileNames = getFileList(opt.strDataListFile);
typedef itk::MeshFileReader<MeshType> MeshReaderType;
typedef vector<MeshReaderType::Pointer> MeshReaderList;
MeshReaderList meshes;
meshes.reserve(fileNames.size());
for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) {
MeshReaderType::Pointer reader = MeshReaderType::New();
reader->SetFileName(it->c_str());
reader->Update();
//itk::PCAModelBuilder is not a Filter in the ITK world, so the pipeline would not get executed if its main method is called. So the pipeline before calling itk::PCAModelBuilder must be executed by the means of calls to Update() (at least for last elements needed by itk::PCAModelBuilder).
meshes.push_back(reader);
}
if (meshes.size() == 0) {
itkGenericExceptionMacro( << "The specified data-list is empty.");
}
if (opt.strProcrustesMode == "reference") {
MeshReaderType::Pointer refReader = MeshReaderType::New();
refReader->SetFileName(opt.strProcrustesReferenceFile);
refReader->Update();
representer->SetReference(refReader->GetOutput());
} else {
vector<MeshType::Pointer> originalMeshes;
for (MeshReaderList::iterator it = meshes.begin(); it != meshes.end(); ++it) {
MeshReaderType::Pointer reader = *it;
originalMeshes.push_back(reader->GetOutput());
}
const unsigned uMaxGPAIterations = 20;
const unsigned uNumberOfPoints = 100;
const float fBreakIfChangeBelow = 0.001f;
typedef itk::VersorRigid3DTransform< float > Rigid3DTransformType;
typedef itk::Image<float, Dimensions> ImageType;
typedef itk::LandmarkBasedTransformInitializer<Rigid3DTransformType, ImageType, ImageType> LandmarkBasedTransformInitializerType;
typedef itk::TransformMeshFilter< MeshType, MeshType, Rigid3DTransformType > FilterType;
MeshType::Pointer referenceMesh = calculateProcrustesMeanMesh<MeshType, LandmarkBasedTransformInitializerType, Rigid3DTransformType, FilterType>(originalMeshes, uMaxGPAIterations, uNumberOfPoints, fBreakIfChangeBelow);
representer->SetReference(referenceMesh);
}
dataManager->SetRepresenter(representer);
for (MeshReaderList::const_iterator it = meshes.begin(); it != meshes.end(); ++it) {
MeshReaderType::Pointer reader = *it;
dataManager->AddDataset(reader->GetOutput(), reader->GetFileName());
}
typedef itk::StatisticalModel<MeshType> StatisticalModelType;
StatisticalModelType::Pointer model;
typedef itk::PCAModelBuilder<MeshType> PCAModelBuilder;
PCAModelBuilder::Pointer pcaModelBuilder = PCAModelBuilder::New();
model = pcaModelBuilder->BuildNewModel(dataManager->GetData(), opt.fNoiseVariance);
itk::StatismoIO<MeshType>::SaveStatisticalModel(model, opt.strOutputFileName.c_str());
}
po::options_description initializeProgramOptions(programOptions& poParameters) {
po::options_description optMandatory("Mandatory options");
optMandatory.add_options()
("data-list,l", po::value<string>(&poParameters.strDataListFile), "File containing a list of meshes to build shape model from")
("output-file,o", po::value<string>(&poParameters.strOutputFileName), "Name of the output file")
;
po::options_description optAdditional("Optional options");
optAdditional.add_options()
("procrustes,p", po::value<string>(&poParameters.strProcrustesMode)->default_value("GPA"), "Specify how the data is aligned: REFERENCE aligns all datasets rigidly to the reference and GPA alignes all datasets to the population mean.")
("reference,r", po::value<string>(&poParameters.strProcrustesReferenceFile), "Specify the reference used for model building. This is needed if --procrustes is REFERENCE")
("noise,n", po::value<float>(&poParameters.fNoiseVariance)->default_value(0), "Noise variance of the PPCA model")
("help,h", po::bool_switch(&poParameters.bDisplayHelp), "Display this help message")
;
po::options_description optAllOptions;
optAllOptions.add(optMandatory).add(optAdditional);
return optAllOptions;
}
| 40.097046 | 297 | 0.716826 | skn123 |
d0dd4f6265b888ac8b8da9558df840ec2de1453f | 2,709 | cpp | C++ | Source/Arnoldi/Select_Shifts.cpp | evstigneevnm/NS3DPeriodic | 094c168f153e36f00ac9103675416ddb9ee6b586 | [
"BSD-3-Clause"
] | null | null | null | Source/Arnoldi/Select_Shifts.cpp | evstigneevnm/NS3DPeriodic | 094c168f153e36f00ac9103675416ddb9ee6b586 | [
"BSD-3-Clause"
] | null | null | null | Source/Arnoldi/Select_Shifts.cpp | evstigneevnm/NS3DPeriodic | 094c168f153e36f00ac9103675416ddb9ee6b586 | [
"BSD-3-Clause"
] | null | null | null | #include "Select_Shifts.h"
#include "Products.h"
#include "LAPACK_routines.h"
void check_nans_H(int N, real *H){
for(int i=0;i<N;i++)
if(H[i]!=H[i]){
printf("\nNANs in H-matrix detected!!!\n");
}
}
int struct_cmp_by_value(const void *a, const void *b)
{
struct sort_struct *ia = (struct sort_struct *)a;
struct sort_struct *ib = (struct sort_struct *)b;
real val_a=ia->value;
real val_b=ib->value;
if(val_a>val_b)
return 1;
else if (val_a<val_b)
return -1;
else
return 0;
}
void get_sorted_index(int m, char which[2], real complex *eigenvaluesH, int *sorted_list){
sort_struct *eigs_struct=new sort_struct[m];
real complex *eigs_local=new real complex[m];
for(int i=0;i<m;i++){
real value=0.0;
if((which[0]=='L')&&(which[1]=='R'))
value=-creal(eigenvaluesH[i]);
else if((which[0]=='L')&&(which[1]=='M'))
value=-cabs(eigenvaluesH[i]);
eigs_struct[i].index=i;
eigs_struct[i].value=value;
eigs_local[i]=eigenvaluesH[i];
}
size_t structs_len = m;
qsort(eigs_struct, structs_len, sizeof(struct sort_struct), struct_cmp_by_value);
for(int i=0;i<m;i++){
int j=eigs_struct[i].index;
sorted_list[i]=j;
eigenvaluesH[i]=eigs_local[j];
}
delete [] eigs_struct;
delete [] eigs_local;
}
void filter_small_imags(int N, real complex *eigenvaluesH){
for(int i=0;i<N;i++){
real eig_imag=cimag(eigenvaluesH[i]);
real eig_real=creal(eigenvaluesH[i]);
if(fabsf(eig_imag)<Im_eig_tol)
eig_imag=0.0;
real complex Ctemp=eig_real+eig_imag*I;
eigenvaluesH[i]=Ctemp;
}
}
void select_shifts(int m, real *H, char which[2], real complex *eigenvectorsH, real complex *eigenvaluesH, real *ritz_vector){
real complex *HC=new real complex[m*m];
real complex *eigs_local=new real complex[m];
//real complex *eigvs_local=new real complex[m*m];
check_nans_H(m*m, H);
real_to_complex_matrix(m, m, H, HC);
MatrixComplexEigensystem(eigenvectorsH, eigs_local, HC, m);
//filter_small_imags(m, eigs_local);
sort_struct *eigs_struct=new sort_struct[m];
for(int i=0;i<m;i++){
real value=0.0;
if((which[0]=='L')&&(which[1]=='R'))
value=-creal(eigs_local[i]);
else if((which[0]=='L')&&(which[1]=='M'))
value=-cabs(eigs_local[i]);
eigs_struct[i].index=i;
eigs_struct[i].value=value;
}
size_t structs_len = m;
qsort(eigs_struct, structs_len, sizeof(struct sort_struct), struct_cmp_by_value);
for(int i=0;i<m;i++){
int j=eigs_struct[i].index;
eigenvaluesH[i]=eigs_local[j];
//for(int k=0;k<m;k++){
// eigenvectorsH[I2(k,i,m)]=eigvs_local[I2(k,j,m)];
//}
ritz_vector[i]=cabs(eigenvectorsH[I2(m-1,j,m)]);
}
delete [] eigs_struct;
delete [] HC;
delete [] eigs_local;
//delete [] eigvs_local;
} | 20.216418 | 127 | 0.670727 | evstigneevnm |
d0e3f1cfbabbe3e3f5baa0e292ede09e18cea908 | 838 | cpp | C++ | Problems/0096. Unique Binary Search Trees.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | Problems/0096. Unique Binary Search Trees.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | Problems/0096. Unique Binary Search Trees.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | class Solution {
vector<int> dp;
public:
int uniqueBST(int n) {
// BASE CASE
if (n == 0 or n == 1)
return 1;
// MEMOIZATION
if (dp[n] != -1)
return dp[n];
//RECURSIVE
int res{0};
for (int i = 1; i <= n; i++) { // selecting each node one by one
res += uniqueBST(i - 1) * uniqueBST(n - i); // will have (i-1)LEFT NODES and (n-i)RIGHT NODES
}
return dp[n] = res;
}
int numTrees(int n) {
// MEMOIZATION ================
dp.resize(n + 1, -1);
return uniqueBST(n);
// TABULAR ====================
//CATALAN NUMBERS
if (n < 2)
return n;
vector<int> dp(n + 1);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) // finding unique BSTs for i nodes
for (int j = 0; j < i; j++)
dp[i] += dp[j] * dp[i - j - 1]; //select each node one by oneas root..solving subproblems
return dp[n];
}
};
| 22.648649 | 96 | 0.52148 | KrKush23 |
d0e448ee9b1522ce62fe22ecd63f81b7c5e0bb82 | 14,803 | cpp | C++ | aspects/fluid/potential/GunnsFluidImpeller.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | aspects/fluid/potential/GunnsFluidImpeller.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | aspects/fluid/potential/GunnsFluidImpeller.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | /************************** TRICK HEADER **********************************************************
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
PURPOSE:
(Classes for the GUNNS Fluid Impeller Model.)
REQUIREMENTS:
()
REFERENCE:
()
ASSUMPTIONS AND LIMITATIONS:
()
LIBRARY DEPENDENCY:
((core/GunnsFluidPotential.o))
PROGRAMMERS:
((Kenneth McMurtrie) (Tietronix Software) (Initial) (2011-09))
**************************************************************************************************/
#include "core/GunnsFluidUtils.hh"
#include "simulation/hs/TsHsMsg.hh"
#include "software/exceptions/TsInitializationException.hh"
#include "GunnsFluidImpeller.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] name (--) Name of object.
/// @param[in,out] nodes (--) Pointer to nodes.
/// @param[in] maxConductivity (m2) Max conductivity.
/// @param[in] expansionScaleFactor (--) Scale factor for isentropic gas cooling.
/// @param[in] referenceDensity (kg/m3) Reference fluid density for power curve.
/// @param[in] referenceSpeed (revolution/min) Reference impeller speed for power curve.
/// @param[in] thermalLength (m) Impeller length for thermal convection.
/// @param[in] thermalDiameter (m) Impeller inner diameter for thermal convection.
/// @param[in] surfaceRoughness (m) Impeller wall surface roughness for convection.
///
/// @details Default constructs this GUNNS Fluid Impeller link model configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpellerConfigData::GunnsFluidImpellerConfigData(const std::string& name,
GunnsNodeList* nodes,
const double maxConductivity,
const double expansionScaleFactor,
const double referenceDensity,
const double referenceSpeed,
const double thermalLength,
const double thermalDiameter,
const double surfaceRoughness)
:
GunnsFluidPotentialConfigData(name, nodes, maxConductivity, expansionScaleFactor),
mReferenceDensity(referenceDensity),
mReferenceSpeed(referenceSpeed),
mThermalLength(thermalLength),
mThermalDiameter(thermalDiameter),
mSurfaceRoughness(surfaceRoughness)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Source object to copy.
///
/// @details Copy constructs this GUNNS Fluid Impeller link model configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpellerConfigData::GunnsFluidImpellerConfigData(const GunnsFluidImpellerConfigData& that)
:
GunnsFluidPotentialConfigData(that),
mReferenceDensity(that.mReferenceDensity),
mReferenceSpeed(that.mReferenceSpeed),
mThermalLength(that.mThermalLength),
mThermalDiameter(that.mThermalDiameter),
mSurfaceRoughness(that.mSurfaceRoughness)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this GUNNS Fluid Impeller link model configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpellerConfigData::~GunnsFluidImpellerConfigData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] malfBlockageFlag (--) Blockage malfunction flag.
/// @param[in] malfBlockageValue (--) Blockage malfunction fractional value (0-1).
/// @param[in] sourcePressure (kPa) Initial pressure rise of the link.
/// @param[in] motorSpeed (revolution/min) Initial speed of the motor.
/// @param[in] wallTemperature (K) Initial impeller wall temperature.
///
/// @details Default constructs this GUNNS Fluid Impeller link model input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpellerInputData::GunnsFluidImpellerInputData(const bool malfBlockageFlag,
const double malfBlockageValue,
const double sourcePressure,
const double motorSpeed,
const double wallTemperature)
:
GunnsFluidPotentialInputData(malfBlockageFlag, malfBlockageValue, sourcePressure),
mMotorSpeed (motorSpeed),
mWallTemperature(wallTemperature)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Source object to copy.
///
/// @details Copy constructs this GUNNS Fluid Impeller link model input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpellerInputData::GunnsFluidImpellerInputData(const GunnsFluidImpellerInputData& that)
:
GunnsFluidPotentialInputData(that),
mMotorSpeed (that.mMotorSpeed),
mWallTemperature(that.mWallTemperature)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this GUNNS Fluid Impeller link model input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpellerInputData::~GunnsFluidImpellerInputData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @note This should be followed by a call to the initialize method before calling an update
/// method.
///
/// @details Default constructs this GUNNS Fluid Impeller link model.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpeller::GunnsFluidImpeller()
:
GunnsFluidPotential(),
mPowerCurveCoefficient(0.0),
mThermalDiameter(0.0),
mThermalSurfaceArea(0.0),
mThermalROverD(0.0),
mMotorSpeed(0.0),
mWallTemperature(0.0),
mWallHeatFlux(0.0)
{
// nothing to do
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this GUNNS Fluid Impeller link model.
///////////////////////////////////////////////////////////////////////////////////////////////////
GunnsFluidImpeller::~GunnsFluidImpeller()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] configData (--) Configuration data.
/// @param[in] inputData (--) Input data.
/// @param[in,out] links (--) Link vector.
/// @param[in] port0 (--) Nominal inlet port map index.
/// @param[in] port1 (--) Nominal outlet port map index.
///
/// @return void
///
/// @throws TsInitializationException
///
/// @details Initializes this GUNNS Fluid Impeller link model with configuration and input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsFluidImpeller::initialize(const GunnsFluidImpellerConfigData& configData,
const GunnsFluidImpellerInputData& inputData,
std::vector<GunnsBasicLink*>& links,
const int port0,
const int port1)
{
/// - First initialize & validate parent.
GunnsFluidPotential::initialize(configData, inputData, links, port0, port1);
/// - Reset initialization status flag.
mInitFlag = false;
/// - Validate configuration and input data.
validate(configData, inputData);
/// - Initialize from input data.
mMotorSpeed = inputData.mMotorSpeed;
mWallTemperature = inputData.mWallTemperature;
mWallHeatFlux = 0.0;
/// - Initialize from configuration data.
mPowerCurveCoefficient = inputData.mSourcePressure / (configData.mReferenceDensity * configData.mReferenceSpeed * configData.mReferenceSpeed);
mThermalDiameter = configData.mThermalDiameter;
mThermalSurfaceArea = UnitConversion::PI_UTIL * configData.mThermalLength * configData.mThermalDiameter;
if (mThermalSurfaceArea > DBL_EPSILON) {
mThermalROverD = configData.mSurfaceRoughness / configData.mThermalDiameter;
} else {
mThermalROverD = 0.0;
}
/// - Create the internal fluid.
createInternalFluid();
/// - Warn of deprecation due to obsolescence by GunnsGasFan.
GUNNS_WARNING("this link is deprecated! It is obsoleted by GunnsGasFan.");
/// - Set initialization status flag to indicate successful initialization.
mInitFlag = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] configData (--) Configuration data.
/// @param[in] inputData (--) Input data.
///
/// @return void
///
/// @throws TsInitializationException
///
/// @details Validates this GUNNS Fluid Impeller Model link model initial state.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsFluidImpeller::validate(const GunnsFluidImpellerConfigData& configData,
const GunnsFluidImpellerInputData& inputData) const
{
/// - Throw an exception if reference density is non-positive,
if (configData.mReferenceDensity < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data", "Reference density < DBL_EPSILON.");
}
/// - Throw an exception if reference speed is non-positive,
if (configData.mReferenceSpeed < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data", "Reference speed < DBL_EPSILON.");
}
/// - Throw an exception if source (reference) pressure is non-positive,
if (inputData.mSourcePressure < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Input Data", "Source (reference) pressure value < DBL_EPSILON.");
}
/// - Throw an exception if impeller speed is negative,
if (inputData.mMotorSpeed < 0.0) {
GUNNS_ERROR(TsInitializationException, "Invalid Input Data", "Impeller speed < 0.");
}
/// - Throw an exception if impeller temperature is negative,
if (inputData.mWallTemperature < 0.0) {
GUNNS_ERROR(TsInitializationException, "Invalid Input Data", "Impeller temperature < 0.");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Derived classes should call their base class implementation too.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsFluidImpeller::restartModel()
{
/// - Reset the base class.
GunnsFluidPotential::restartModel();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Time step (not used).
///
/// @return void
///
/// @details Updates this GUNNS Fluid Impeller link model source pressure.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void GunnsFluidImpeller::updateState(const double dt __attribute__((unused)))
{
/// - Compute delta pressure proportional to fluid density and square of impeller speed.
mSourcePressure = mPowerCurveCoefficient * mMotorSpeed * mMotorSpeed * mInternalFluid->getDensity();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Time step.
/// @param[in] flowRate (kg/s) Mass flow rate.
///
/// @return void
///
/// @details Updates this GUNNS Fluid Impeller link model internal fluid.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsFluidImpeller::updateFluid(const double dt __attribute__((unused)), const double flowRate)
{
/// - Perform heat convection between the internal fluid and pipe wall.
mWallHeatFlux = GunnsFluidUtils::computeConvectiveHeatFlux(mInternalFluid,
flowRate,
mThermalROverD,
mThermalDiameter,
mThermalSurfaceArea,
mWallTemperature);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] value (m2) New Thermal Surface Area.
///
/// @returns void
///
/// @details Sets the thermal surface area of this this GUNNS Fluid Impeller link model.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsFluidImpeller::setThermalSurfaceArea(const double value)
{
mThermalSurfaceArea = std::max(0.0, value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] value (K) New Wall Temperature.
///
/// @returns void
///
/// @details Sets the wall temperature of this this GUNNS Fluid Impeller link model.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsFluidImpeller::setWallTemperature(const double value)
{
mWallTemperature = std::max(0.0, value);
}
| 47.445513 | 146 | 0.49159 | nasa |
d0e4c044d23ff96422fd660b3405d7d58ee08fa7 | 4,733 | cc | C++ | src/limits/MemoryLimitListener.cc | NieDzejkob/sio2jail | 8589541cfe11c68ce5ef13eb30a488b09ad3a139 | [
"MIT"
] | 14 | 2018-06-19T19:54:22.000Z | 2021-09-16T18:03:40.000Z | src/limits/MemoryLimitListener.cc | NieDzejkob/sio2jail | 8589541cfe11c68ce5ef13eb30a488b09ad3a139 | [
"MIT"
] | 16 | 2018-09-16T17:08:43.000Z | 2022-01-19T15:43:41.000Z | src/limits/MemoryLimitListener.cc | NieDzejkob/sio2jail | 8589541cfe11c68ce5ef13eb30a488b09ad3a139 | [
"MIT"
] | 6 | 2018-09-15T20:56:06.000Z | 2022-03-05T09:27:22.000Z | #include "MemoryLimitListener.h"
#include "common/ProcFS.h"
#include "common/WithErrnoCheck.h"
#include "logger/Logger.h"
#include "seccomp/SeccompRule.h"
#include "seccomp/action/ActionAllow.h"
#include "seccomp/action/ActionTrace.h"
#include "seccomp/filter/LibSeccompFilter.h"
#include <sys/resource.h>
#include <sys/time.h>
#include <csignal>
#include <fstream>
#include <iostream>
namespace s2j {
namespace limits {
const uint64_t MemoryLimitListener::MEMORY_LIMIT_MARGIN = 8 * 1024 * 1024;
MemoryLimitListener::MemoryLimitListener(uint64_t memoryLimitKb)
: memoryPeakKb_(0)
, memoryLimitKb_(memoryLimitKb)
, vmPeakValid_(false)
, childPid_(-1) {
TRACE(memoryLimitKb);
// Possible memory problem here, we will return this references to *this.
// User is responsible for ensuring that MemoryLimitListener last at least
// as long as any reference to it's rules.
using Arg = seccomp::filter::SyscallArg;
for (const auto& syscall: {"mmap2", "mmap"}) {
syscallRules_.emplace_back(seccomp::SeccompRule(
syscall,
seccomp::action::ActionTrace([this](tracer::Tracee& tracee) {
TRACE();
if (!vmPeakValid_) {
return tracer::TraceAction::CONTINUE;
}
uint64_t memoryUsage = getMemoryUsageKb() +
tracee.getSyscallArgument(1) / 1024;
memoryPeakKb_ = std::max(memoryPeakKb_, memoryUsage);
outputBuilder_->setMemoryPeak(memoryPeakKb_);
logger::debug(
"Memory usage after mmap ",
VAR(memoryUsage),
", ",
VAR(memoryPeakKb_));
if (memoryUsage > memoryLimitKb_) {
outputBuilder_->setKillReason(
printer::OutputBuilder::KillReason::MLE,
"memory limit exceeded");
logger::debug(
"Limit ",
VAR(memoryLimitKb_),
" exceeded, killing tracee");
return tracer::TraceAction::KILL;
}
return tracer::TraceAction::CONTINUE;
}),
Arg(0) == 0 && Arg(1) > MEMORY_LIMIT_MARGIN / 2));
}
}
void MemoryLimitListener::onPostForkChild() {
TRACE();
// If there is any memory limit, set it.
if (memoryLimitKb_ > 0) {
struct rlimit memoryLimit {};
memoryLimit.rlim_cur = memoryLimit.rlim_max =
memoryLimitKb_ * 1024 + MEMORY_LIMIT_MARGIN;
logger::debug("Seting address space limit ", VAR(memoryLimit.rlim_max));
withErrnoCheck(
"setrlimit address space", setrlimit, RLIMIT_AS, &memoryLimit);
memoryLimit.rlim_cur = memoryLimit.rlim_max = RLIM_INFINITY;
logger::debug("Seting stack limit to infinity");
withErrnoCheck(
"setrlimit stack", setrlimit, RLIMIT_STACK, &memoryLimit);
}
}
void MemoryLimitListener::onPostForkParent(pid_t childPid) {
TRACE(childPid);
childPid_ = childPid;
}
tracer::TraceAction MemoryLimitListener::onPostExec(
const tracer::TraceEvent& /* traceEvent */,
tracer::Tracee& /* tracee */) {
vmPeakValid_ = true;
return tracer::TraceAction::CONTINUE;
}
executor::ExecuteAction MemoryLimitListener::onExecuteEvent(
const executor::ExecuteEvent& /*executeEvent*/) {
TRACE();
if (!vmPeakValid_) {
return executor::ExecuteAction::CONTINUE;
}
memoryPeakKb_ = std::max(memoryPeakKb_, getMemoryPeakKb());
logger::debug("Read new memory peak ", VAR(memoryPeakKb_));
outputBuilder_->setMemoryPeak(memoryPeakKb_);
if (memoryLimitKb_ > 0 && memoryPeakKb_ > memoryLimitKb_) {
outputBuilder_->setKillReason(
printer::OutputBuilder::KillReason::MLE,
"memory limit exceeded");
logger::debug(
"Limit ", VAR(memoryLimitKb_), " exceeded, killing tracee");
return executor::ExecuteAction::KILL;
}
return executor::ExecuteAction::CONTINUE;
}
uint64_t MemoryLimitListener::getMemoryPeakKb() {
return procfs::readProcFS(childPid_, procfs::Field::VM_PEAK);
}
uint64_t MemoryLimitListener::getMemoryUsageKb() {
return procfs::readProcFS(childPid_, procfs::Field::VM_SIZE);
}
const std::vector<seccomp::SeccompRule>& MemoryLimitListener::getRules() const {
return syscallRules_;
}
} // namespace limits
} // namespace s2j
| 33.807143 | 80 | 0.597929 | NieDzejkob |
d0e8c437cc7f6fc0049650f97977094f121ea048 | 1,040 | cpp | C++ | CS Academy/Overlapping Matrices/28.57 points.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | CS Academy/Overlapping Matrices/28.57 points.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | CS Academy/Overlapping Matrices/28.57 points.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created:
* solution_verdict: 28.57 points language: C++
* run_time: 94 ms memory_used: 5492 KB
* problem:
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
int h,w,x,y,mat[1010][1010],ans[1010][1010],tmp[1010][1010];
int main()
{
cin>>h>>w>>x>>y;
for(int i=1;i<=h+x;i++)
{
for(int j=1;j<=w+y;j++)
{
cin>>mat[i][j];
}
}
for(int i=1;i<=h;i++)
{
if(i<=x)
{
for(int j=1;j<=w;j++)ans[i][j]=mat[i][j];
for(int j=1;j<=w;j++)tmp[i+x][j+y]=mat[i][j];
}
else
{
for(int j=1;j<=w;j++)ans[i][j]=mat[i][j]-tmp[i][j];
}
}
for(int i=1;i<=h;i++)
{
for(int j=1;j<=w;j++)cout<<ans[i][j]<<" ";
cout<<endl;
}
return 0;
} | 26.666667 | 111 | 0.35 | kzvd4729 |
d0eb0778f46b42091d041d80c65db5dbed3348ba | 545 | cpp | C++ | src/enclave/ServiceProvider/KeyGen.cpp | brucechin/opaque | 29e1755078412c46706608b17b4932ebd92d34b2 | [
"Apache-2.0"
] | null | null | null | src/enclave/ServiceProvider/KeyGen.cpp | brucechin/opaque | 29e1755078412c46706608b17b4932ebd92d34b2 | [
"Apache-2.0"
] | null | null | null | src/enclave/ServiceProvider/KeyGen.cpp | brucechin/opaque | 29e1755078412c46706608b17b4932ebd92d34b2 | [
"Apache-2.0"
] | 1 | 2021-09-23T03:06:08.000Z | 2021-09-23T03:06:08.000Z | #include "ServiceProvider.h"
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: ./keygen <public_key_cpp_file>\n");
return 1;
}
const char *private_key_path = "/home/lqp0562/opaque/private_key.pem";
if (!private_key_path) {
printf("Set $PRIVATE_KEY_PATH to the file generated by openssl ecparam -genkey, probably "
"called ${OPAQUE_HOME}/private_key.pem.");
return 1;
}
service_provider.load_private_key(private_key_path);
service_provider.export_public_key_code(argv[1]);
return 0;
}
| 27.25 | 94 | 0.695413 | brucechin |
d0ecd90e65a39df4df042ee391c3afe1a91f6e45 | 3,546 | hpp | C++ | Rx/v2/src/rxcpp/rx-test.hpp | guhwanbae/RxCpp | 7f97aa901701343593869acad1ee5a02292f39cf | [
"Apache-2.0"
] | 1 | 2022-02-20T18:08:22.000Z | 2022-02-20T18:08:22.000Z | Rx/v2/src/rxcpp/rx-test.hpp | ivan-cukic/wip-fork-rxcpp | 483963939e4a2adf674450dcb829005d84be1d59 | [
"Apache-2.0"
] | null | null | null | Rx/v2/src/rxcpp/rx-test.hpp | ivan-cukic/wip-fork-rxcpp | 483963939e4a2adf674450dcb829005d84be1d59 | [
"Apache-2.0"
] | null | null | null | #pragma once
#if !defined(RXCPP_RX_TEST_HPP)
#define RXCPP_RX_TEST_HPP
#include "rx-includes.hpp"
namespace rxcpp {
namespace test {
namespace detail {
template<class T>
struct test_subject_base
: public std::enable_shared_from_this<test_subject_base<T>>
{
using recorded_type = rxn::recorded<typename rxn::notification<T>::type>;
using type = std::shared_ptr<test_subject_base<T>>;
virtual ~test_subject_base() {}
virtual void on_subscribe(subscriber<T>) const =0;
virtual std::vector<recorded_type> messages() const =0;
virtual std::vector<rxn::subscription> subscriptions() const =0;
};
template<class T>
struct test_source
: public rxs::source_base<T>
{
explicit test_source(typename test_subject_base<T>::type ts)
: ts(std::move(ts))
{
if (!this->ts) std::terminate();
}
typename test_subject_base<T>::type ts;
void on_subscribe(subscriber<T> o) const {
ts->on_subscribe(std::move(o));
}
template<class Subscriber>
typename std::enable_if<!std::is_same_v<Subscriber, subscriber<T>>, void>::type
on_subscribe(Subscriber o) const {
static_assert(is_subscriber<Subscriber>::value, "on_subscribe must be passed a subscriber.");
ts->on_subscribe(o.as_dynamic());
}
};
}
template<class T>
class testable_observer
: public observer<T>
{
using observer_base = observer<T>;
using test_subject = typename detail::test_subject_base<T>::type;
test_subject ts;
public:
using recorded_type = typename detail::test_subject_base<T>::recorded_type;
testable_observer(test_subject ts, observer_base ob)
: observer_base(std::move(ob))
, ts(std::move(ts))
{
}
std::vector<recorded_type> messages() const {
return ts->messages();
}
};
//struct tag_test_observable : public tag_observable {};
/*!
\brief a source of values that records the time of each subscription/unsubscription and all the values and the time they were emitted.
\ingroup group-observable
*/
template<class T>
class testable_observable
: public observable<T, typename detail::test_source<T>>
{
using observable_base = observable<T, typename detail::test_source<T>>;
using test_subject = typename detail::test_subject_base<T>::type;
test_subject ts;
//typedef tag_test_observable observable_tag;
public:
using recorded_type = typename detail::test_subject_base<T>::recorded_type;
explicit testable_observable(test_subject ts)
: observable_base(detail::test_source<T>(ts))
, ts(ts)
{
}
std::vector<rxn::subscription> subscriptions() const {
return ts->subscriptions();
}
std::vector<recorded_type> messages() const {
return ts->messages();
}
};
}
namespace rxt=test;
}
//
// support range() >> filter() >> subscribe() syntax
// '>>' is spelled 'stream'
//
template<class T, class OperatorFactory>
auto operator >> (const rxcpp::test::testable_observable<T>& source, OperatorFactory&& of)
-> decltype(source.op(std::forward<OperatorFactory>(of))) {
return source.op(std::forward<OperatorFactory>(of));
}
//
// support range() | filter() | subscribe() syntax
// '|' is spelled 'pipe'
//
template<class T, class OperatorFactory>
auto operator | (const rxcpp::test::testable_observable<T>& source, OperatorFactory&& of)
-> decltype(source.op(std::forward<OperatorFactory>(of))) {
return source.op(std::forward<OperatorFactory>(of));
}
#include "schedulers/rx-test.hpp"
#endif
| 25.695652 | 138 | 0.688099 | guhwanbae |
d0ede1d40781c2931400b92d1159f53961e4f744 | 36,164 | cc | C++ | tests/core/test_core_focus_manager.cc | nugulinux/nugu-linux | c166d61b2037247d4574b7f791c31ba79ceb575e | [
"Apache-2.0"
] | null | null | null | tests/core/test_core_focus_manager.cc | nugulinux/nugu-linux | c166d61b2037247d4574b7f791c31ba79ceb575e | [
"Apache-2.0"
] | null | null | null | tests/core/test_core_focus_manager.cc | nugulinux/nugu-linux | c166d61b2037247d4574b7f791c31ba79ceb575e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 SK Telecom Co., Ltd. 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include "focus_manager.hh"
using namespace NuguCore;
#define ASR_USER_FOCUS_TYPE "ASRUser"
#define ASR_USER_FOCUS_PRIORITY 100
#define INFO_FOCUS_TYPE "Info"
#define INFO_FOCUS_PRIORITY 200
#define ALERTS_FOCUS_TYPE "Alerts"
#define ALERTS_FOCUS_PRIORITY 300
#define MEDIA_FOCUS_TYPE "Media"
#define MEDIA_FOCUS_PRIORITY 400
#define INVALID_FOCUS_NAME "Invalid"
#define ASR_USER_NAME "asr_user"
#define ANOTHER_ASR_USER_NAME "another_asr_user"
#define INFO_NAME "information"
#define ALERTS_NAME "alerts"
#define MEDIA_NAME "media"
#define REQUEST_FOCUS(resource, type, name) \
resource->requestFocus(type, name)
#define RELEASE_FOCUS(resource, type) \
resource->releaseFocus(type)
#define HOLD_FOCUS(resource, type) \
resource->holdFocus(type)
#define UNHOLD_FOCUS(resource, type) \
resource->unholdFocus(type)
#define ASSERT_EXPECTED_STATE(resource, state) \
g_assert(resource->getState() == state);
class FocusManagerObserver : public IFocusManagerObserver {
public:
explicit FocusManagerObserver(IFocusManager* focus_manager)
: focus_manager_interface(focus_manager)
{
}
virtual ~FocusManagerObserver() = default;
void onFocusChanged(const FocusConfiguration& configuration, FocusState state, const std::string& name) override
{
std::string msg;
msg.append("==================================================\n[")
.append(configuration.type)
.append(" - ")
.append(name)
.append("] ")
.append(focus_manager_interface->getStateString(state))
.append(" (priority: ")
.append(std::to_string(configuration.priority))
.append(")\n==================================================");
std::cout << msg << std::endl;
}
private:
IFocusManager* focus_manager_interface;
};
class TestFocusResorce : public IFocusResourceListener {
public:
explicit TestFocusResorce(IFocusManager* focus_manager)
: focus_manager_interface(focus_manager)
, cur_state(FocusState::NONE)
{
}
virtual ~TestFocusResorce() = default;
bool requestFocus(const std::string& type, const std::string& name)
{
this->name = name;
return focus_manager_interface->requestFocus(type, name, this);
}
bool releaseFocus(const std::string& type)
{
return focus_manager_interface->releaseFocus(type, name);
}
bool holdFocus(const std::string& type)
{
return focus_manager_interface->holdFocus(type);
}
bool unholdFocus(const std::string& type)
{
return focus_manager_interface->unholdFocus(type);
}
void stopAllFocus()
{
focus_manager_interface->stopAllFocus();
}
void stopForegroundFocus()
{
focus_manager_interface->stopForegroundFocus();
}
void onFocusChanged(FocusState state) override
{
cur_state = state;
}
FocusState getState()
{
return cur_state;
}
private:
IFocusManager* focus_manager_interface;
FocusState cur_state;
std::string name;
};
typedef struct {
FocusManager* focus_manager;
FocusManagerObserver* focus_observer;
TestFocusResorce* asr_resource;
TestFocusResorce* info_resource;
TestFocusResorce* alert_resource;
TestFocusResorce* media_resource;
TestFocusResorce* another_asr_resource;
} ntimerFixture;
static void setup(ntimerFixture* fixture, gconstpointer user_data)
{
fixture->focus_manager = new FocusManager();
fixture->focus_observer = new FocusManagerObserver(fixture->focus_manager);
fixture->focus_manager->addObserver(fixture->focus_observer);
fixture->asr_resource = new TestFocusResorce(fixture->focus_manager);
fixture->info_resource = new TestFocusResorce(fixture->focus_manager);
fixture->alert_resource = new TestFocusResorce(fixture->focus_manager);
fixture->media_resource = new TestFocusResorce(fixture->focus_manager);
fixture->another_asr_resource = new TestFocusResorce(fixture->focus_manager);
std::vector<FocusConfiguration> focus_configuration;
focus_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
fixture->focus_manager->setConfigurations(focus_configuration, focus_configuration);
}
static void teardown(ntimerFixture* fixture, gconstpointer user_data)
{
delete fixture->focus_manager;
delete fixture->focus_observer;
delete fixture->asr_resource;
delete fixture->info_resource;
delete fixture->alert_resource;
delete fixture->media_resource;
delete fixture->another_asr_resource;
}
#define G_TEST_ADD_FUNC(name, func) \
g_test_add(name, ntimerFixture, NULL, setup, func, teardown);
static void test_focusmanager_configurations(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_configuration;
// Add asr user Resource to FocusManager
focus_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_configuration, focus_configuration);
g_assert(focus_manager->getFocusResourcePriority(ASR_USER_FOCUS_TYPE) == ASR_USER_FOCUS_PRIORITY);
g_assert(focus_manager->getFocusResourcePriority(INFO_FOCUS_TYPE) == -1);
// Add asr user Resource with higher priority and Information Resource to FocusManager
focus_configuration.clear();
focus_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY + 100 });
focus_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_configuration, focus_configuration);
g_assert(focus_manager->getFocusResourcePriority(ASR_USER_FOCUS_TYPE) == (ASR_USER_FOCUS_PRIORITY + 100));
g_assert(focus_manager->getFocusResourcePriority(INFO_FOCUS_TYPE) == INFO_FOCUS_PRIORITY);
}
static void test_focusmanager_request_resource_with_invalid_name(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(!REQUEST_FOCUS(fixture->asr_resource, INVALID_FOCUS_NAME, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_request_resource_with_no_activate_resource(ntimerFixture* fixture, gconstpointer igresource)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_resource_with_higher_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_resource_with_lower_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_two_resources_with_highest_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_two_resources_with_medium_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_two_resources_with_lowest_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_same_resource_on_foreground(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_same_resource_on_background(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_same_resource_with_other_name(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->another_asr_resource, ASR_USER_FOCUS_TYPE, ANOTHER_ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->another_asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_no_activity_resource(ntimerFixture* fixture, gconstpointer ignored)
{
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
}
static void test_focusmanager_release_resource_with_other_name(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->another_asr_resource, ASR_USER_FOCUS_TYPE, ANOTHER_ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->another_asr_resource, FocusState::FOREGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->another_asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_foreground_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_release_foreground_resource_with_background_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_background_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::NONE);
}
static void test_focusmanager_stop_foreground_focus_with_one_activity(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
fixture->asr_resource->stopForegroundFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_stop_foreground_focus_with_one_activity_one_pending(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
fixture->asr_resource->stopForegroundFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_stop_all_focus_with_no_resource(ntimerFixture* fixture, gconstpointer ignored)
{
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
fixture->asr_resource->stopAllFocus();
}
static void test_focusmanager_stop_all_focus_with_one_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
fixture->asr_resource->stopAllFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_stop_all_focus_with_two_resources(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
fixture->asr_resource->stopAllFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::NONE);
}
static void test_focusmanager_request_resource_hold_and_unhold(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(HOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(UNHOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_resource_with_hold_higher_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(HOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(UNHOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_resource_with_hold_higher_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// hold info priority: asr user > info > media
g_assert(HOLD_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
// media focus is still background because info is holded with higher priority.
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_same_holded_resource_and_auto_unhold(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(HOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
// unhold focus because of request with same priority
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_higher_resource_with_hold(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(HOLD_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE));
// maintain hold focus because of request with higher priority than hold priority
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(UNHOLD_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_and_release_configurations(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Add asr user Resource to FocusManager
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
// Focus resource's priority is followed by focus release configuration.
g_assert(focus_manager->getFocusResourcePriority(ASR_USER_FOCUS_TYPE) == ASR_USER_FOCUS_PRIORITY);
g_assert(focus_manager->getFocusResourcePriority(INFO_FOCUS_TYPE) == -1);
}
static void test_focusmanager_release_resource_with_different_request_and_same_release_priority_resources(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Add asr user Resource to FocusManager
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_request_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ALERTS_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// stacked resource: asr user > info
g_assert(REQUEST_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE, INFO_NAME));
ASSERT_EXPECTED_STATE(fixture->info_resource, FocusState::BACKGROUND);
// stacked resource: asr user > info = alerts
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
// stacked resource: info = alerts
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
// pop fifo resource
ASSERT_EXPECTED_STATE(fixture->info_resource, FocusState::FOREGROUND);
g_assert(RELEASE_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->info_resource, FocusState::NONE);
// pop fifo resource
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_steal_resource_with_higher_resource_by_request_priority(ntimerFixture* fixture, gconstpointer igresource)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user = media
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
// Release Priority: asr user > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// asr user focus is stealed by media focus caused by equal to request priority
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_no_steal_resource_with_higher_resource_request_priority(ntimerFixture* fixture, gconstpointer igresource)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user > media
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
// Release Priority: asr user > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// asr user focus can't be stolen because media focus has a low request priority
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_release_resources_by_release_priority(ntimerFixture* fixture, gconstpointer igresource)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user = media > alerts
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
// Release Priority: asr user > alerts > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_resource_hold_and_unhold_with_different_request_release_priority(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user = media > info > alerts
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_request_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
// Release Priority: asr user > info > alerts > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(HOLD_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
// request priority: info > alerts
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
// request priority: info < media
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
// request priority: asr user = media
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
// release priority: info > alert > media
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
// release priority: alert > media
g_assert(UNHOLD_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
}
int main(int argc, char* argv[])
{
#if !GLIB_CHECK_VERSION(2, 36, 0)
g_type_init();
#endif
g_test_init(&argc, &argv, (void*)NULL);
g_log_set_always_fatal((GLogLevelFlags)G_LOG_FATAL_MASK);
G_TEST_ADD_FUNC("/core/FocusManager/FocusConfigurations", test_focusmanager_configurations);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceInvalidName", test_focusmanager_request_resource_with_invalid_name);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithNoActivateResource", test_focusmanager_request_resource_with_no_activate_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithHigherPriorityResource", test_focusmanager_request_resource_with_higher_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithLowerPriorityResource", test_focusmanager_request_resource_with_lower_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestTowResourcesWithHighestPriorityResource", test_focusmanager_request_two_resources_with_highest_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestTowResourcesWithMediumPriorityResource", test_focusmanager_request_two_resources_with_medium_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestTowResourcesWithLowestPriorityResource", test_focusmanager_request_two_resources_with_lowest_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameResourceOnForeground", test_focusmanager_request_same_resource_on_foreground);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameResourceOnBackground", test_focusmanager_request_same_resource_on_background);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameResourceWithOtherInterfaceName", test_focusmanager_request_same_resource_with_other_name);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseNoActivityResource", test_focusmanager_release_no_activity_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseResourceWithOtherInterfaceName", test_focusmanager_release_resource_with_other_name);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseForegroundResource", test_focusmanager_release_foreground_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseForegroundResourceWithBackgroundResource", test_focusmanager_release_foreground_resource_with_background_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseBackgroundResource", test_focusmanager_release_background_resource);
G_TEST_ADD_FUNC("/core/FocusManager/StopForegroundFocusWithOneActivity", test_focusmanager_stop_foreground_focus_with_one_activity);
G_TEST_ADD_FUNC("/core/FocusManager/StopForegroundFocusWithOneActivityOnePending", test_focusmanager_stop_foreground_focus_with_one_activity_one_pending);
G_TEST_ADD_FUNC("/core/FocusManager/StopAllFocusWithNoResource", test_focusmanager_stop_all_focus_with_no_resource);
G_TEST_ADD_FUNC("/core/FocusManager/StopAllFocusWithOneResource", test_focusmanager_stop_all_focus_with_one_resource);
G_TEST_ADD_FUNC("/core/FocusManager/StopAllFocusWithTwoResources", test_focusmanager_stop_all_focus_with_two_resources);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceHoldAndUnHold", test_focusmanager_request_resource_hold_and_unhold);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithHoldHigherResource", test_focusmanager_request_resource_with_hold_higher_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseResourceWithHoldHigherResource", test_focusmanager_release_resource_with_hold_higher_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameHoldedResourceAndAutoUnhold", test_focusmanager_request_same_holded_resource_and_auto_unhold);
G_TEST_ADD_FUNC("/core/FocusManager/RequestHigherResourceWithHold", test_focusmanager_request_higher_resource_with_hold);
G_TEST_ADD_FUNC("/core/FocusManager/FocusRequestAndReleaseConfigurations", test_focusmanager_request_and_release_configurations);
G_TEST_ADD_FUNC("/core/FocusManager/FocusReleaseResourceWithDifferentRequestAndSameReleasePriorityResources", test_focusmanager_release_resource_with_different_request_and_same_release_priority_resources);
G_TEST_ADD_FUNC("/core/FocusManager/StealResourceWithHigherResourceByRequestPriority", test_focusmanager_steal_resource_with_higher_resource_by_request_priority);
G_TEST_ADD_FUNC("/core/FocusManager/NoStealResourceWithHigherResourceByRequestPriority", test_focusmanager_no_steal_resource_with_higher_resource_request_priority);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseResourcesByReleasePriority", test_focusmanager_release_resources_by_release_priority);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceHoldAndUnHoldWithDifferentRequestReleasePriority", test_focusmanager_request_resource_hold_and_unhold_with_different_request_release_priority);
return g_test_run();
}
| 50.019364 | 209 | 0.808428 | nugulinux |
d0f48c9d8316176fa6633b420486642150f6f79e | 1,009 | hpp | C++ | plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/stencil/enabled_visitor.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/stencil/enabled_visitor.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/stencil/enabled_visitor.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_D3D9_STATE_CORE_DEPTH_STENCIL_STENCIL_ENABLED_VISITOR_HPP_INCLUDED
#define SGE_D3D9_STATE_CORE_DEPTH_STENCIL_STENCIL_ENABLED_VISITOR_HPP_INCLUDED
#include <sge/d3d9/state/render_vector.hpp>
#include <sge/renderer/state/core/depth_stencil/stencil/combined_fwd.hpp>
#include <sge/renderer/state/core/depth_stencil/stencil/separate_fwd.hpp>
namespace sge
{
namespace d3d9
{
namespace state
{
namespace core
{
namespace depth_stencil
{
namespace stencil
{
class enabled_visitor
{
public:
typedef sge::d3d9::state::render_vector result_type;
result_type
operator()(sge::renderer::state::core::depth_stencil::stencil::combined const &) const;
result_type
operator()(sge::renderer::state::core::depth_stencil::stencil::separate const &) const;
};
}
}
}
}
}
}
#endif
| 21.934783 | 89 | 0.77106 | cpreh |
d0f957374b6a73dd463c98489d59005bb92124e0 | 890 | cpp | C++ | COS1511/Part3/Lesson21/aii.cpp | GalliWare/UNISA-studies | 32bab94930b176c4dfe943439781ef102896fab5 | [
"Unlicense"
] | null | null | null | COS1511/Part3/Lesson21/aii.cpp | GalliWare/UNISA-studies | 32bab94930b176c4dfe943439781ef102896fab5 | [
"Unlicense"
] | null | null | null | COS1511/Part3/Lesson21/aii.cpp | GalliWare/UNISA-studies | 32bab94930b176c4dfe943439781ef102896fab5 | [
"Unlicense"
] | null | null | null | // compute the average of 3 marks for 2 students and display the better average
// my code with the addition of the reference so input can be turned into a function.
#include <iostream>
using namespace std;
float averageMark(float mark1, float mark2, float mark3)
{
float average = 0, divider = 3;
average = (mark1 + mark2 + mark3) / divider;
return average;
}
void inputMark(float &m1P, float &m2P, float &m3P)
{
cout << "Enter the 3 marks: ";
cin >> m1P >> m2P >> m3P;
}
int main()
{
float student1Average, student2Average, m1, m2, m3;
inputMark(m1, m2, m3);
student1Average = averageMark(m1, m2, m3);
inputMark(m1, m2, m3);
student2Average = averageMark(m1, m2, m3);
if (student1Average > student2Average)
cout << "The first student has the higher average" << endl;
else
cout << "The second student has the higher average" << endl;
return 0;
}
| 23.421053 | 85 | 0.682022 | GalliWare |
d0fafcfdb8f8a6871c6e2180216b295eb5740119 | 630 | cc | C++ | sdk/src/http/HttpClient.cc | OpenInspur/inspur-oss-cpp-sdk | a0932232aaf46aab7c5a2079f72d80cc5d634ba2 | [
"Apache-2.0"
] | null | null | null | sdk/src/http/HttpClient.cc | OpenInspur/inspur-oss-cpp-sdk | a0932232aaf46aab7c5a2079f72d80cc5d634ba2 | [
"Apache-2.0"
] | null | null | null | sdk/src/http/HttpClient.cc | OpenInspur/inspur-oss-cpp-sdk | a0932232aaf46aab7c5a2079f72d80cc5d634ba2 | [
"Apache-2.0"
] | null | null | null | #include "HttpClient.h"
using namespace InspurCloud::OSS;
HttpClient::HttpClient():
disable_(false)
{
}
HttpClient::~HttpClient()
{
}
bool HttpClient::isEnable()
{
return disable_.load() == false;
}
void HttpClient::disable()
{
disable_ = true;
requestSignal_.notify_all();
}
void HttpClient::enable()
{
disable_ = false;
}
void HttpClient::waitForRetry(long milliseconds)
{
if (milliseconds == 0)
return;
std::unique_lock<std::mutex> lck(requestLock_);
requestSignal_.wait_for(lck, std::chrono::milliseconds(milliseconds), [this] ()-> bool { return disable_.load() == true; });
}
| 16.153846 | 128 | 0.669841 | OpenInspur |
d0fbfe48bb505e758e1f3c5f0a1b864a86a1a6f2 | 330 | cpp | C++ | src/Common/DrvCppLib/cppstub_i386.cpp | apriorit/windows-process-monitor | 97197b898555daebe7a2a4a68e373dc5bea6da6b | [
"MIT"
] | 100 | 2017-04-14T01:02:10.000Z | 2022-02-10T07:42:33.000Z | src/Common/DrvCppLib/cppstub_i386.cpp | apriorit/windows-process-monitor | 97197b898555daebe7a2a4a68e373dc5bea6da6b | [
"MIT"
] | 1 | 2021-05-30T20:19:07.000Z | 2021-05-30T20:19:07.000Z | src/Common/DrvCppLib/cppstub_i386.cpp | apriorit/windows-process-monitor | 97197b898555daebe7a2a4a68e373dc5bea6da6b | [
"MIT"
] | 44 | 2017-05-04T12:55:36.000Z | 2021-12-09T08:21:44.000Z | #ifndef _M_AMD64
void __stdcall _JumpToContinuation(void *,struct EHRegistrationNode *);
struct EHRegistrationNode;
extern "C" void CPPLIB_ThreadRelease();
_declspec(naked)
void __stdcall _JumpToCONTINUATION(void *,struct EHRegistrationNode *)
{
__asm call CPPLIB_ThreadRelease
__asm jmp _JumpToContinuation;
}
#endif | 20.625 | 71 | 0.8 | apriorit |
d0fe07728ee8b80ba65061e3b9026b2b10473da7 | 1,294 | hpp | C++ | PSME/agent/network/include/api/lldp/exceptions/err_code.hpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 5 | 2021-10-07T15:36:37.000Z | 2022-03-01T07:21:49.000Z | PSME/agent/network/include/api/lldp/exceptions/err_code.hpp | opencomputeproject/DM-Redfish-PSME | 912f7b6abf5b5c2aae33c75497de4753281c6a51 | [
"Apache-2.0"
] | null | null | null | PSME/agent/network/include/api/lldp/exceptions/err_code.hpp | opencomputeproject/DM-Redfish-PSME | 912f7b6abf5b5c2aae33c75497de4753281c6a51 | [
"Apache-2.0"
] | 1 | 2021-03-24T19:37:58.000Z | 2021-03-24T19:37:58.000Z | /*!
* @copyright
* Copyright (c) 2015-2017 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @file err_code.hpp
*
* @brief LLDP exception error codes
* */
#pragma once
namespace agent {
namespace network {
namespace api {
namespace lldp {
namespace exception {
/*!
* @enum ErrCode
* @brief LLDP exception error codes
*
* @var ErrCode::NOT_SPECIFIED
* Error code isn't specified
*
* @var ErrCode::EOM
* End Of Message
*
* @var ErrCode::NO_CONNECTION
* NO connection to LLDP agent
*
* @var ErrCode::NO_INFO
* Requested information isn't available
*
* */
enum class ErrCode {
/* internal errors */
NOT_SPECIFIED,
EOM,
/* user errors */
NO_CONNECTION,
NO_INFO
};
}
}
}
}
}
| 19.907692 | 75 | 0.690108 | opencomputeproject |
d0fefaa5331178f857d00a53133e62e18b343b44 | 3,202 | cpp | C++ | bootloader/drivers/pci.cpp | mstniy/cerius | ac8a0e3e68243f3e38b2a259e7a7b6f87e6787e3 | [
"MIT"
] | 2 | 2018-01-28T19:04:56.000Z | 2018-12-12T20:59:40.000Z | bootloader/drivers/pci.cpp | mstniy/cerius | ac8a0e3e68243f3e38b2a259e7a7b6f87e6787e3 | [
"MIT"
] | null | null | null | bootloader/drivers/pci.cpp | mstniy/cerius | ac8a0e3e68243f3e38b2a259e7a7b6f87e6787e3 | [
"MIT"
] | null | null | null | #include "pci.h"
DWORD PciDevice::ConfigReadDword(BYTE reg)
{
if (reg > 15)
{
pstring("Invalid register given to PciDevice::ConfigReadDword!");
return 0;
}
DWORD lbus = (DWORD)bus;
DWORD lslot = (DWORD)slot;
DWORD lfunc = (DWORD)function;
DWORD address = (DWORD)((lbus << 16) | (lslot << 11) | (lfunc << 8) | (reg << 2) | ((DWORD)0x80000000));
/* write out the address */
PortIO::OutD(0xCF8, address);
/* read in the data */
return PortIO::InD(0xCFC);
}
WORD PciDevice::GetVendorID()
{
return ConfigReadDword(0) & 0xFFFF;
}
BYTE PciDevice::GetBaseClass()
{
return (ConfigReadDword(2) >> 24) & 0xFF;
}
BYTE PciDevice::GetHeaderType()
{
return (ConfigReadDword(3) >> 16) & 0xFF;
}
BYTE PciDevice::GetSubClass()
{
return (ConfigReadDword(2) >> 16) & 0xFF;
}
BYTE PciDevice::GetSecondaryBus()
{
return (ConfigReadDword(6) >> 8) & 0xFF;
}
DWORD PciDevice::GetBar(int bar)
{
if (bar<0 || bar >5)
{
pstring("Invalid bar number given to pciGetBar.");
return 0;
}
return ConfigReadDword(bar+4);
}
int PciDevice::CheckFunction(PciDevice* array, int max_length)
{
BYTE baseClass = GetBaseClass();
BYTE subClass = GetSubClass();
if( (baseClass == 0x06) && (subClass == 0x04) )
return CheckBus(GetSecondaryBus(), array, max_length);
else
{
array[0]=(*this);
return 1;
}
}
int PciDevice::CheckDevice(BYTE bus, BYTE device, PciDevice* array, int max_length)
{
PciDevice tmpDev;
tmpDev.bus = bus;
tmpDev.slot = device;
tmpDev.function = 0;
if(tmpDev.GetVendorID() == 0xFFFF)
return 0; // Device doesn't exist
int res, added=0;
res = tmpDev.CheckFunction(array, max_length);
array += res;
max_length -= res;
added += res;
BYTE headerType = tmpDev.GetHeaderType();
if( (headerType & 0x80) != 0)
{
/* It is a multi-function device, so check remaining functions */
for(BYTE function = 1; (function < 8) && (max_length > 0); function++)
{
tmpDev.function = function;
if(tmpDev.GetVendorID() != 0xFFFF)
{
res = tmpDev.CheckFunction(array, max_length);
array += res;
max_length -= res;
added += res;
}
}
}
return added;
}
int PciDevice::CheckBus(BYTE bus, PciDevice* array, int max_length)
{
int added = 0;
for(BYTE device = 0; (device < 32) && (max_length > 0) ; device++)
{
const int res = CheckDevice(bus, device, array, max_length);
array += res;
max_length -= res;
added += res;
}
return added;
}
int PciDevice::EnumerateDevices(PciDevice* array, int max_length)
{
PciDevice tmpDev;
tmpDev.bus=0;
tmpDev.slot=0;
tmpDev.function=0;
BYTE headerType = tmpDev.GetHeaderType();
if( (headerType & 0x80) == 0)
{
/* Single PCI host controller */
return CheckBus(0, array, max_length);
}
else
{
int added = 0;
/* Multiple PCI host controllers */
for(BYTE function = 0; (function < 8) && (max_length > 0) ; function++)
{
tmpDev.function=function;
if(tmpDev.GetVendorID() == 0xFFFF)
break;
const int res = CheckBus(function, array, max_length);
array += res;
max_length -= res;
added += res;
}
return added;
}
}
| 22.236111 | 106 | 0.624297 | mstniy |
cb9a373ec41f42ee378088a2ae8ce3a076652bbd | 2,492 | cpp | C++ | NESting/APUNoise.cpp | Bindernews/NESting | dc1bf9c38dc814d554d85066cb75c5d68a5de74b | [
"MIT"
] | 7 | 2020-07-30T18:07:07.000Z | 2021-02-18T19:23:34.000Z | NESting/APUNoise.cpp | Bindernews/NESting | dc1bf9c38dc814d554d85066cb75c5d68a5de74b | [
"MIT"
] | null | null | null | NESting/APUNoise.cpp | Bindernews/NESting | dc1bf9c38dc814d554d85066cb75c5d68a5de74b | [
"MIT"
] | null | null | null |
#include "APUNoise.h"
#include "IPlugLogger.h"
#include "math_utils.h"
using iplug::sample;
#define TIMER_PERIOD_SIZE (16)
//static const int TIMER_PERIOD_TABLE[] = { 4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068 };
static const int TIMER_PERIOD_TABLE[] = { 4068, 2034, 1016, 762, 508, 380, 254, 202, 160, 128, 96, 64, 32, 16, 8, 4 };
APUNoise::APUNoise()
{
Reset();
}
APUNoise::~APUNoise()
{}
void APUNoise::SetParameter(int paramId, double value)
{
switch (paramId) {
// Sample rate
case 0:
sampleRate = int(value);
sampleCount = 0;
updateTimerPeriod();
break;
// Timer mode (0 - 1)
case 2:
timerMode = bool(std::roundf(float(value)));
break;
}
}
double APUNoise::GetParameter(int paramId)
{
switch (paramId) {
case 0: return double(sampleRate);
case 2: return double(timerMode);
default: return 0.f;
}
}
void APUNoise::Reset() {
sampleRate = 48000;
timerMode = 0;
sampleCount = 0;
updateTimerPeriod();
}
void APUNoise::OnRelease()
{
sampleCount = 0;
for (int i = 0; i < TIMER_PERIOD_SIZE; i++) {
shiftReg = 0x1;
}
}
void APUNoise::ProcessBlock(sample** inputs, sample** outputs, int nFrames) {
sample* gain = inputs[0];
sample* pitch = inputs[1];
sample* output0 = outputs[0];
for (int i = 0; i < nFrames; i += 1) {
// Determine the timer index to use
int timerIndex = int(HzToMidi(pitch[i])) % 16;
// Output the next bit of noise
output0[i] = sample(double( (shiftReg >> 0) & 0x1 ) * gain[i]);
// Update our sample count which acts as the timer
sampleCount += 1;
// If our timer ticked to 0, perform the register shift.
if (sampleCount >= timerPeriod[timerIndex]) {
doShiftRegister();
sampleCount = 0;
}
}
}
void APUNoise::updateTimerPeriod() {
for (int i = 0; i < TIMER_PERIOD_SIZE; i++) {
float nesApuSpeed = float(sampleRate) / 44750.f;
timerPeriod[i] = std::max(int(nesApuSpeed * float(TIMER_PERIOD_TABLE[i])), 1);
}
// Also reset shiftReg
shiftReg = 0x1;
}
void APUNoise::doShiftRegister() {
uint16_t feedback = shiftReg;
if (timerMode) {
feedback ^= (shiftReg >> 6);
}
else {
feedback ^= (shiftReg >> 1);
}
feedback = (feedback << 14) & 0x4000;
shiftReg = (shiftReg >> 1) & 0x3FFF;
shiftReg = shiftReg | feedback;
}
| 24.673267 | 120 | 0.591091 | Bindernews |
cb9c0d8189012fbe41d8ea09293342927a1b3d2e | 1,707 | cpp | C++ | Barometer/src/main.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 2 | 2017-06-03T01:07:16.000Z | 2017-07-14T17:49:16.000Z | Barometer/src/main.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | 5 | 2017-04-24T20:29:04.000Z | 2017-06-26T17:40:53.000Z | Barometer/src/main.cpp | michprev/drone | 51c659cdd4e1d50446a563bb11e800defda9a298 | [
"MIT"
] | null | null | null | /**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f4xx_hal.h"
#include "MS5611.h"
using namespace flyhero;
extern "C" void initialise_monitor_handles(void);
int main(void)
{
HAL_Init();
initialise_monitor_handles();
if (__GPIOB_IS_CLK_DISABLED())
__GPIOB_CLK_ENABLE();
if (__I2C1_IS_CLK_DISABLED())
__I2C1_CLK_ENABLE();
I2C_HandleTypeDef hi2c;
GPIO_InitTypeDef gpio;
gpio.Pin = GPIO_PIN_8 | GPIO_PIN_9;
gpio.Mode = GPIO_MODE_AF_OD;
gpio.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
gpio.Pull = GPIO_PULLUP;
gpio.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_8 | GPIO_PIN_9);
HAL_GPIO_Init(GPIOB, &gpio);
hi2c.Instance = I2C1;
hi2c.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c.Init.ClockSpeed = 400000;
hi2c.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
hi2c.Init.OwnAddress1 = 0;
hi2c.Init.OwnAddress2 = 0;
HAL_I2C_DeInit(&hi2c);
HAL_I2C_Init(&hi2c);
MS5611& ms5611 = MS5611::Instance();
ms5611.Init(&hi2c);
int32_t press, temp;
ms5611.ConvertD1();
while (true) {
if (ms5611.D1_Ready())
ms5611.ConvertD2();
else if (ms5611.D2_Ready()) {
ms5611.GetData(&temp, &press);
printf("Temp: %d, press: %d\n", temp, press);
HAL_Delay(100);
ms5611.ConvertD1();
}
}
}
| 23.383562 | 81 | 0.620972 | michprev |
cb9e0823aad36f6d2f7eef03549bbaa15a5f3002 | 514 | hpp | C++ | src/LovelaceConfig/FanCardConfig.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | 2 | 2020-10-23T19:53:56.000Z | 2020-11-06T08:59:48.000Z | src/LovelaceConfig/FanCardConfig.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | src/LovelaceConfig/FanCardConfig.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | #ifndef __FANCARDCONFIG_H__
#define __FANCARDCONFIG_H__
#include "BaseEntityCardConfig.hpp"
#include <string.h>
class FanCardConfig : public BaseEntityCardConfig {
public:
FanCardConfig(const char * entity, const char * title, const char * icon, const char * rowIcon, bool state_color);
FanCardConfig(const char * entity, const char * title, const char * icon, bool state_color);
FanCardConfig(const char * entity);
static constexpr const char * TYPE = "fan";
};
#endif // __FANCARDCONFIG_H__ | 32.125 | 118 | 0.745136 | RobinSinghNanda |
cba0569739e874dce90f679b8584d0275a0621ed | 1,482 | cxx | C++ | src/sdp_read/read_input/read_json/JSON_Parser/Key.cxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 45 | 2015-02-10T15:45:22.000Z | 2022-02-24T07:45:01.000Z | src/sdp_read/read_input/read_json/JSON_Parser/Key.cxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 58 | 2015-02-27T10:03:18.000Z | 2021-08-10T04:21:42.000Z | src/sdp_read/read_input/read_json/JSON_Parser/Key.cxx | ChrisPattison/sdpb | 4668f72c935e7feba705dd8247d9aacb23185f1c | [
"MIT"
] | 38 | 2015-02-10T11:11:27.000Z | 2022-02-11T20:59:42.000Z | #include "../JSON_Parser.hxx"
bool JSON_Parser::Key(const Ch *str, rapidjson::SizeType length, bool)
{
std::string key(str, length);
if(inside)
{
if(parsing_objective)
{
throw std::runtime_error("Invalid input file. Found the key '" + key
+ "' inside '" + objective_state.name
+ "'.");
}
else if(parsing_normalization)
{
throw std::runtime_error("Invalid input file. Found the key '" + key
+ "' inside '" + normalization_state.name
+ "'.");
}
else if(parsing_positive_matrices_with_prefactor)
{
positive_matrices_with_prefactor_state.json_key(key);
}
else if(key == objective_state.name)
{
parsing_objective = true;
}
else if(key == normalization_state.name)
{
parsing_normalization = true;
}
else if(key == positive_matrices_with_prefactor_state.name)
{
parsing_positive_matrices_with_prefactor = true;
}
else
{
throw std::runtime_error("Invalid input file. Found the key '" + key
+ "' inside the main object.");
}
}
else
{
throw std::runtime_error("Found a key outside of the main object: "
+ key);
}
return true;
}
| 30.244898 | 79 | 0.503374 | ChrisPattison |
cba0791f5eca806f6815df559074a9506c725ba3 | 1,681 | cc | C++ | src/codegen/query/header.cc | viyadb/viyadb | 56d9b9836a57a36483bee98e6bc79f79e2f5c772 | [
"Apache-2.0"
] | 109 | 2017-10-03T06:52:30.000Z | 2022-03-22T18:38:48.000Z | src/codegen/query/header.cc | b-xiang/viyadb | b72f9cabacb4b24bd2192ed824d930ccb73d3609 | [
"Apache-2.0"
] | 26 | 2017-10-15T19:45:18.000Z | 2019-10-18T09:55:54.000Z | src/codegen/query/header.cc | viyadb/viyadb | 56d9b9836a57a36483bee98e6bc79f79e2f5c772 | [
"Apache-2.0"
] | 7 | 2017-10-03T09:37:36.000Z | 2020-12-15T01:04:45.000Z | /*
* Copyright (c) 2017-present ViyaDB Group
*
* 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 "codegen/query/header.h"
#include "db/column.h"
namespace viya {
namespace codegen {
void HeaderGenerator::Visit(query::SelectQuery *query) {
if (query->header()) {
for (auto &dim_col : query->dimension_cols()) {
code_ << "row[" << std::to_string(dim_col.index())
<< "] = table.dimension(" << std::to_string(dim_col.dim()->index())
<< ")->name();\n";
}
for (auto &metric_col : query->metric_cols()) {
code_ << "row[" << std::to_string(metric_col.index())
<< "] = table.metric("
<< std::to_string(metric_col.metric()->index()) << ")->name();\n";
}
code_ << "output.Send(row);\n";
}
}
void HeaderGenerator::Visit(query::AggregateQuery *query) {
Visit(static_cast<query::SelectQuery *>(query));
}
void HeaderGenerator::Visit(query::SearchQuery *query) {
if (query->header()) {
code_ << "output.Send(std::vector<std::string> { table.dimension("
<< std::to_string(query->dimension()->index()) << ")->name() });\n";
}
}
} // namespace codegen
} // namespace viya
| 32.326923 | 79 | 0.64188 | viyadb |
cba22ffe23f9fd59bebeae414c33b8a77daec1dd | 199 | hpp | C++ | src/modules/osg/generated_code/Sequence.pypp.hpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osg/generated_code/Sequence.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osg/generated_code/Sequence.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#ifndef Sequence_hpp__pyplusplus_wrapper
#define Sequence_hpp__pyplusplus_wrapper
void register_Sequence_class();
#endif//Sequence_hpp__pyplusplus_wrapper
| 22.111111 | 40 | 0.844221 | JaneliaSciComp |
cba39c9fe3964e17c3fbaba4964ab89d280b3acb | 3,915 | cpp | C++ | EulerRender/src/graphics/Skybox.cpp | jjovanovski/eulerrender | 9ef87b4c0c3667414edc8104c84d3ac08aa2303d | [
"MIT"
] | null | null | null | EulerRender/src/graphics/Skybox.cpp | jjovanovski/eulerrender | 9ef87b4c0c3667414edc8104c84d3ac08aa2303d | [
"MIT"
] | null | null | null | EulerRender/src/graphics/Skybox.cpp | jjovanovski/eulerrender | 9ef87b4c0c3667414edc8104c84d3ac08aa2303d | [
"MIT"
] | null | null | null | #include "Skybox.h"
#include <stb_image.h>
#include <iostream>
using namespace Euler;
Skybox::Skybox(std::vector<std::string> textures) {
// create texture
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_CUBE_MAP, id);
int width, height, channels;
for (int i = 0; i < textures.size(); i++) {
unsigned char* data = stbi_load(textures[i].c_str(), &width, &height, &channels, 0);
if (data) {
if (channels == 4) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
} else {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
}
}
stbi_image_free(data);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
skyboxMesh = new Mesh();
int rings = 30;
int sectors = 30;
float d_theta = 180.0f / rings;
float d_phi = 360.0f / sectors;
float theta = -90.0f;
float phi = 0.0f;
float PI = 3.141592f;
float DEG = PI / 180.0f;
float x, y, z;
for (int i = 0; i <= rings; i++) {
phi = 0.0f;
for (int j = 0; j < sectors; j++) {
float x = cos(theta*DEG)*cos(phi*DEG);
float y = cos(theta*DEG)*sin(phi*DEG);
float z = sin(theta*DEG);
float u = atan2(x, z) / (2.0 * PI) + 0.5f;
float v = y * 0.5f + 0.5f;
float normalLen = x * x + y * y + z * z;
float dot = y;
float tx = 0 - x * (dot / normalLen);
float ty = 1 - y * (dot / normalLen);
float tz = 0 - z * (dot / normalLen);
skyboxMesh->vertices.push_back(Vertex(x, y, z, x, y, z, 3 * u, v, tx, ty, tz));
if (j < sectors) {
skyboxMesh->indices.push_back((i + 1)*(sectors)+(j + 1) % sectors);
skyboxMesh->indices.push_back(i*(sectors)+(j + 1) % sectors);
skyboxMesh->indices.push_back(i*(sectors)+j);
skyboxMesh->indices.push_back((i + 1)*(sectors)+j);
skyboxMesh->indices.push_back((i + 1)*(sectors)+(j + 1) % sectors);
skyboxMesh->indices.push_back(i*(sectors)+j);
}
phi += d_phi;
}
theta += d_theta;
}
skyboxMesh->Upload();
/*// create mesh
float skyboxVertices[] = {
// Front face
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0
};
skyboxMesh = new Mesh();
for (int i = 0; i < 3 * 4 * 6; i += 3) {
skyboxMesh->vertices.push_back(Vertex(skyboxVertices[i], skyboxVertices[i + 1], skyboxVertices[i + 2]));
}
int skyboxIndices[] = {
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // back
8, 9, 10, 8, 10, 11, // top
12, 13, 14, 12, 14, 15, // bottom
16, 17, 18, 16, 18, 19, // right
20, 21, 22, 20, 22, 23, // left
};
// add the indices in reversed winding order
for (int i = 35; i >= 0; i--) {
skyboxMesh->indices.push_back(skyboxIndices[i]);
}
skyboxMesh->Upload();*/
}
Skybox::~Skybox() {
Dispose();
}
void Skybox::Dispose() {
delete skyboxMesh;
glDeleteTextures(1, &id);
}
void Skybox::Draw() {
glDepthMask(GL_FALSE);
skyboxMesh->Bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, id);
glDrawElements(GL_TRIANGLES, skyboxMesh->indices.size(), GL_UNSIGNED_INT, 0);
glDepthMask(GL_TRUE);
} | 24.936306 | 115 | 0.592848 | jjovanovski |
cba42f85d77a37f23b5b06b555e43d2c6793f139 | 1,068 | hpp | C++ | include/stl2/detail/concepts/urng.hpp | melton1968/cmcstl2 | 15052dda39c93c460b8e0e16fff62d8eb4388627 | [
"MIT"
] | null | null | null | include/stl2/detail/concepts/urng.hpp | melton1968/cmcstl2 | 15052dda39c93c460b8e0e16fff62d8eb4388627 | [
"MIT"
] | null | null | null | include/stl2/detail/concepts/urng.hpp | melton1968/cmcstl2 | 15052dda39c93c460b8e0e16fff62d8eb4388627 | [
"MIT"
] | null | null | null | // cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
// Copyright Eric Niebler 2015
//
// Use, modification and distribution is subject to 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)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_CONCEPTS_URNG_HPP
#define STL2_DETAIL_CONCEPTS_URNG_HPP
#include <stl2/detail/concepts/callable.hpp>
STL2_OPEN_NAMESPACE {
template<auto> struct __require_constant; // not defined
template<class G>
META_CONCEPT UniformRandomBitGenerator =
Invocable<G&> && UnsignedIntegral<invoke_result_t<G&>> &&
requires {
G::min(); requires Same<decltype(G::min()), invoke_result_t<G&>>;
G::max(); requires Same<decltype(G::max()), invoke_result_t<G&>>;
#if 1 // This is the PR for https://wg21.link/lwg3150
typename __require_constant<G::min()>;
typename __require_constant<G::min()>;
requires G::min() < G::max();
#endif
};
} STL2_CLOSE_NAMESPACE
#endif
| 29.666667 | 68 | 0.725655 | melton1968 |
cba740176da8f44f6f7564be03e6518f8eb042e9 | 2,042 | cpp | C++ | libhpx/gas/affinity/CuckooHash.cpp | luglio/hpx5 | 6cbeebb8e730ee9faa4487dba31a38e3139e1ce7 | [
"BSD-3-Clause"
] | 1 | 2019-11-05T21:11:32.000Z | 2019-11-05T21:11:32.000Z | libhpx/gas/affinity/CuckooHash.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | null | null | null | libhpx/gas/affinity/CuckooHash.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | 3 | 2019-06-21T07:05:43.000Z | 2020-11-21T15:24:04.000Z | // =============================================================================
// High Performance ParalleX Library (libhpx)
//
// Copyright (c) 2013-2017, Trustees of Indiana University,
// All rights reserved.
//
// This software may be modified and distributed under the terms of the BSD
// license. See the COPYING file for details.
//
// This software was created at the Indiana University Center for Research in
// Extreme Scale Technologies (CREST).
// =============================================================================
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "libhpx/gas/Affinity.h"
#include "libhpx/debug.h"
#include "libhpx/locality.h"
#include "libhpx/Scheduler.h"
#include <cinttypes>
namespace {
using libhpx::Scheduler;
using libhpx::gas::Affinity;
using libhpx::gas::affinity::CuckooHash;
}
CuckooHash::CuckooHash() : Affinity(), map_()
{
}
CuckooHash::~CuckooHash()
{
}
void
CuckooHash::setAffinity(hpx_addr_t gva, int worker)
{
DEBUG_IF(here->gas->ownerOf(gva) != here->rank) {
dbg_error("Attempt to set affinity of %" PRIu64 " at %d (owned by %d)\n",
gva, here->rank, here->gas->ownerOf(gva));
}
DEBUG_IF(worker < 0 || here->sched->getNWorkers() <= worker) {
dbg_error("Attempt to set affinity of %" PRIu64
" to %d is outside range [0, %d)\n",
gva, worker, here->sched->getNWorkers());
}
// @todo: Should we be pinning gva? The interface doesn't require it, but it
// could prevent usage errors in AGAS? On the other hand, it could
// result in debugging issues with pin reference counting.
map_.insert(gva, worker);
}
void
CuckooHash::clearAffinity(hpx_addr_t gva)
{
DEBUG_IF(here->gas->ownerOf(gva) != here->rank) {
dbg_error("Attempt to clear affinity of %" PRIu64 " at %d (owned by %d)\n",
gva, here->rank, here->gas->ownerOf(gva));
}
map_.erase(gva);
}
int
CuckooHash::getAffinity(hpx_addr_t gva) const
{
int worker = -1;
map_.find(gva, worker);
return worker;
}
| 28.361111 | 80 | 0.618022 | luglio |
cba7aac455f42b3c965db0784984de83aab58298 | 5,002 | cpp | C++ | mcu/timer/LPTimer.cpp | sourcebox/mcu_stm32l4xx | 509433f5fbbd6f3238b1694b681d21241412a400 | [
"MIT"
] | null | null | null | mcu/timer/LPTimer.cpp | sourcebox/mcu_stm32l4xx | 509433f5fbbd6f3238b1694b681d21241412a400 | [
"MIT"
] | null | null | null | mcu/timer/LPTimer.cpp | sourcebox/mcu_stm32l4xx | 509433f5fbbd6f3238b1694b681d21241412a400 | [
"MIT"
] | null | null | null | /**
* @file LPTimer.cpp
*
* Driver for low power timer peripherals on STM32L4xx
*
* @author: Oliver Rockstedt <info@sourcebox.de>
* @license MIT
*/
// Corresponding header
#include "LPTimer.h"
// This component
#include "../core/NVIC.h"
#include "../rcc/RCC.h"
#include "../rcc/RCC_Registers.h"
#include "../utility/bit_manipulation.h"
#include "../utility/log2.h"
// System libraries
#include <cstdlib>
namespace mcu {
// ============================================================================
// Public members
// ============================================================================
LPTimer::LPTimer(Id id)
: id(id)
{
}
void LPTimer::init()
{
enableClock();
auto registers = getRegisters();
registers->CFGR |= (1 << LPTimer_Registers::CFGR::PRELOAD);
}
void LPTimer::init(uint16_t prescaler, uint32_t period)
{
init();
setPrescaler(prescaler);
setPeriod(period);
}
void LPTimer::init(int freq)
{
init();
setFrequency(freq);
}
void LPTimer::init(Config& config)
{
init();
setPrescaler(config.prescaler);
setPeriod(config.period);
}
void LPTimer::deinit()
{
disableClock();
}
uint32_t LPTimer::getPrescaler()
{
auto registers = getRegisters();
return (1 << bitsValue(registers->CFGR, 3, LPTimer_Registers::CFGR::PRESC_0));
}
void LPTimer::setPrescaler(uint16_t value)
{
disable();
auto registers = getRegisters();
registers->CFGR = bitsReplace(registers->CFGR, log2(value), 3,
LPTimer_Registers::CFGR::PRESC_0);
enable();
}
uint32_t LPTimer::getPeriod()
{
auto registers = getRegisters();
return registers->ARR;
}
void LPTimer::setPeriod(volatile uint32_t value)
{
enable();
auto registers = getRegisters();
registers->ARR = value;
}
void LPTimer::setFrequency(uint32_t freq)
{
uint32_t clockFreq = RCC::get().getPCLK1Freq();
auto periodCycles = clockFreq / freq;
uint16_t prescaler = (periodCycles / 0xFFFF) + 1;
// Force prescaler to a power of 2
prescaler = 1 << log2(prescaler);
auto period = (periodCycles + (prescaler / 2)) / prescaler;
if (period > 0xFFFF) {
prescaler <<= 1;
period = (periodCycles + (prescaler / 2)) / prescaler;
}
setPrescaler(prescaler);
setPeriod(period);
}
void LPTimer::enable()
{
auto registers = getRegisters();
registers->CR |= (1 << LPTimer_Registers::CR::ENABLE);
}
void LPTimer::disable()
{
auto registers = getRegisters();
registers->CR &= ~(1 << LPTimer_Registers::CR::ENABLE);
}
void LPTimer::start()
{
auto registers = getRegisters();
registers->CR |= 1 << LPTimer_Registers::CR::CNTSTRT;
}
void LPTimer::stop()
{
disable();
enable();
}
uint32_t LPTimer::getCounter()
{
auto registers = getRegisters();
return registers->CNT;
}
void LPTimer::setCounter(uint32_t value)
{
auto registers = getRegisters();
registers->CNT = value;
}
void LPTimer::setUpdateCallback(CallbackFunc func)
{
disable();
updateCallback = func;
auto registers = getRegisters();
if (func != nullptr) {
registers->IER |= (1 << LPTimer_Registers::IER::ARRMIE);
auto& nvic = NVIC::get();
nvic.enableIrq(getIRQNumber(id));
} else {
registers->IER &= ~(1 << LPTimer_Registers::IER::ARRMIE);
}
enable();
}
void LPTimer::irq()
{
auto registers = getRegisters();
if (registers->ISR & (1 << LPTimer_Registers::ISR::ARRM)) {
registers->ICR |= (1 << LPTimer_Registers::ICR::ARRMCF);
if (updateCallback != nullptr) {
updateCallback();
}
}
if (registers->ISR & (1 << LPTimer_Registers::ISR::CMPM)) {
registers->ICR |= (1 << LPTimer_Registers::ICR::CMPMCF);
auto callback = channels[0].ch1Callbacks[id];
if (callback != nullptr) {
callback();
}
}
}
// ============================================================================
// Protected members
// ============================================================================
void LPTimer::enableClock()
{
auto rccRegisters = RCC_Registers::get();
switch (id) {
case LPTIM1:
rccRegisters->APB1ENR1 |= (1 << RCC_Registers::APB1ENR1::LPTIM1EN);
break;
case LPTIM2:
rccRegisters->APB1ENR2 |= (1 << RCC_Registers::APB1ENR2::LPTIM2EN);
break;
default:
break;
}
}
void LPTimer::disableClock()
{
auto rccRegisters = RCC_Registers::get();
switch (id) {
case LPTIM1:
rccRegisters->APB1ENR1 &= ~(1 << RCC_Registers::APB1ENR1::LPTIM1EN);
break;
case LPTIM2:
rccRegisters->APB1ENR2 &= ~(1 << RCC_Registers::APB1ENR2::LPTIM2EN);
break;
default:
break;
}
}
LPTimer LPTimer::lptimer1 = LPTimer(LPTimer::LPTIM1);
LPTimer LPTimer::lptimer2 =LPTimer(LPTimer::LPTIM2);
} // namespace mcu
| 18.594796 | 82 | 0.570972 | sourcebox |
cba7e87ac1438fe9452d7660e49845d7e8ea457c | 1,253 | cpp | C++ | problems/triangle/src/Solution.cpp | bbackspace/leetcode | bc3f235fcd42c37800e6ef7eefab4c826d70f3d3 | [
"CC0-1.0"
] | null | null | null | problems/triangle/src/Solution.cpp | bbackspace/leetcode | bc3f235fcd42c37800e6ef7eefab4c826d70f3d3 | [
"CC0-1.0"
] | null | null | null | problems/triangle/src/Solution.cpp | bbackspace/leetcode | bc3f235fcd42c37800e6ef7eefab4c826d70f3d3 | [
"CC0-1.0"
] | null | null | null | class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<vector<int>> dp(triangle.size(), vector<int>(triangle.size(), 0));
dp[0][0] = triangle[0][0];
for (int i = 1; i < triangle.size(); i++) {
dp[i][0] = dp[i - 1][0] + triangle[i][0];
for (int j = 1; j < triangle[i].size(); j++) {
if (j == triangle[i].size() - 1) {
dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];
} else {
dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j];
}
}
}
int ans = dp[triangle.size() - 1][0];
for (int i = 1; i < triangle.size(); i++) {
ans = min(ans, dp[triangle.size() - 1][i]);
}
return ans;
}
void print(vector<vector<int>> v) {
cout << "[";
print(v[0]);
for (int i = 1; i < v.size(); i++) {
cout << ",\n";
print(v[i]);
}
cout << "]";
}
void print(vector<int> v) {
cout << "[";
cout << (v[0]);
for (int i = 1; i < v.size(); i++) {
cout << ",";
cout << (v[i]);
}
cout << "]";
}
};
| 29.139535 | 84 | 0.365523 | bbackspace |
cbab0365253e5ebe740a9bce439976463500b347 | 2,702 | cpp | C++ | easter/easter.cpp | mika314/simuleios | 0b05660c7df0cd6e31eb5e70864cbedaec29b55a | [
"MIT"
] | 197 | 2015-07-26T02:04:17.000Z | 2022-01-21T11:53:33.000Z | easter/easter.cpp | shiffman/simuleios | 57239350d2cbed10893483bda65fa323e5e3a06d | [
"MIT"
] | 18 | 2015-08-04T22:55:46.000Z | 2020-11-06T02:33:48.000Z | easter/easter.cpp | shiffman/simuleios | 57239350d2cbed10893483bda65fa323e5e3a06d | [
"MIT"
] | 55 | 2015-08-02T21:43:18.000Z | 2021-12-13T18:25:08.000Z | /*-------------easter.cpp-----------------------------------------------------//
*
* Purpose: To calculate the date of easter, based on Gauss's algotihm (~1816)
*
*-----------------------------------------------------------------------------*/
#include <iostream>
#include "../visualization/cairo/cairo_vis.h"
// Function to calculate the date of easter between start and finish
std::vector<int> easter_date_between(int start, int end);
// Function to calculate the date for a particular year
int easter_date(int year);
/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/
int main(){
// Creating scene and frames and stuff
int fps = 30;
double res_x = 400;
double res_y = 400;
vec res = {res_x, res_y};
color bg_clr = {0, 0, 0, 1};
color line_clr = {1, 1, 1, 1};
std::vector<frame> layers = init_layers(3, res, fps, bg_clr);
std::vector<int> dates = easter_date_between(1600, 2000);
// Concatenate them all into a single array
std::vector<int> dist(35);
for (size_t i = 0; i < dates.size(); i++){
dist[dates[i]]++;
bar_graph(layers[1], 0, layers[1].curr_frame, layers[1].curr_frame+1,
dist, res_x, res_y, line_clr);
layers[1].curr_frame++;
}
draw_layers(layers);
}
/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/
// Function to calculate the date for a particular year
int easter_date(int year){
int date;
int a = year % 19;
int b = year % 4;
int c = year % 7;
int k = year/100;
int p = (13 + 8*k)/25;
int q = k/4;
int M = (15 - p + k - q) % 30;
int N = (4 + k - q) % 7;
int d = (19 * a + M) % 30;
int e = (2*b + 4*c + 6*d + N) % 7;
// determining whether the date is in March or April
date = d+e;
/*
if (22 + d + e < 31){
date = 22 + d + e;
}
else{
date = d+e;
}
if (d == 29 && e == 6){
date = 19+9;
}
if (d == 28 && e == 6 && (11 * M + 11) % 30 < 10){
date = 18+9;
}
*/
return date;
}
// Function to calculate the date of easter between start and finish
std::vector<int> easter_date_between(int start, int end){
// Initialize the vector
std::vector<int> dates(end - start+1);
for (size_t i = 0; i < dates.size(); i++){
dates[i] = easter_date(start + i);
}
return dates;
}
| 26.752475 | 80 | 0.439304 | mika314 |
cbb1da2c040116cf0d8da2745d2ead7a5ff1b427 | 9,025 | cpp | C++ | src/client/SkinnedGUI/CGuiSkin.cpp | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 192 | 2015-02-13T14:53:59.000Z | 2022-03-29T11:18:58.000Z | src/client/SkinnedGUI/CGuiSkin.cpp | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 48 | 2015-01-06T22:00:53.000Z | 2022-01-15T18:22:46.000Z | src/client/SkinnedGUI/CGuiSkin.cpp | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 51 | 2015-01-16T00:55:16.000Z | 2022-02-05T03:09:30.000Z | /////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
#include "SkinnedGUI/CGuiSkin.h"
#include "FindFile.h"
#include "StringUtils.h"
#include "AuxLib.h"
#include "Cursor.h"
#include "SkinnedGUI/CWidget.h"
// Widgets
#include "SkinnedGUI/CAnimation.h"
#include "SkinnedGUI/CButton.h"
#include "SkinnedGUI/CCheckbox.h"
#include "SkinnedGUI/CCombobox.h"
#include "SkinnedGUI/CDialog.h"
#include "SkinnedGUI/CGuiSkinnedLayout.h"
#include "SkinnedGUI/CImageButton.h"
#include "SkinnedGUI/CInputBox.h"
#include "SkinnedGUI/CLabel.h"
#include "SkinnedGUI/CLine.h"
#include "SkinnedGUI/CListview.h"
#include "SkinnedGUI/CMapEditor.h"
#include "SkinnedGUI/CMarquee.h"
#include "SkinnedGUI/CMenu.h"
#include "SkinnedGUI/CMinimap.h"
#include "SkinnedGUI/CProgressbar.h"
#include "SkinnedGUI/CScrollbar.h"
#include "SkinnedGUI/CSlider.h"
#include "SkinnedGUI/CTabControl.h"
#include "SkinnedGUI/CTextbox.h"
#include "SkinnedGUI/CToggleButton.h"
namespace SkinnedGUI {
CGuiSkin *cMainSkin = NULL;
#define SKIN_DIRECTORY (std::string("gui_skins/"))
///////////////
// Initialize skinning
bool InitializeGuiSkinning()
{
if (!cMainSkin)
cMainSkin = new CGuiSkin();
if (tLXOptions)
return cMainSkin->Load(tLXOptions->sSkinPath);
return false;
}
//////////////////
// Shutdown skinning
void ShutdownGuiSkinning()
{
if (cMainSkin)
delete cMainSkin;
cMainSkin = NULL;
}
/////////////
// Constructor
CGuiSkin::CGuiSkin()
{
sPath = SKIN_DIRECTORY + "default";
sName = "Default";
sAuthor = "OpenLieroX Development Team";
cActiveLayout = NULL;
cPreviousLayout = NULL;
iBufferCount = 1;
// Listen to the events
sdlEvents[SDL_KEYDOWN].handler() += getEventHandler(this, &CGuiSkin::SDL_OnKeyDown);
sdlEvents[SDL_KEYUP].handler() += getEventHandler(this, &CGuiSkin::SDL_OnKeyUp);
sdlEvents[SDL_MOUSEMOTION].handler() += getEventHandler(this, &CGuiSkin::SDL_OnMouseMotion);
sdlEvents[SDL_MOUSEBUTTONDOWN].handler() += getEventHandler(this, &CGuiSkin::SDL_OnMouseButtonDown);
sdlEvents[SDL_MOUSEBUTTONUP].handler() += getEventHandler(this, &CGuiSkin::SDL_OnMouseButtonUp);
sdlEvents[SDL_MOUSEWHEEL].handler() += getEventHandler(this, &CGuiSkin::SDL_OnMouseWheel);
onAddWidget.handler() = getEventHandler(this, &CGuiSkin::SDL_OnAddWidget);;
onDestroyWidget.handler() = getEventHandler(this, &CGuiSkin::SDL_OnDestroyWidget);
}
//////////////
// Destructor
CGuiSkin::~CGuiSkin()
{
sdlEvents[SDL_KEYDOWN].handler() -= getEventHandler(this, &CGuiSkin::SDL_OnKeyDown);
sdlEvents[SDL_KEYUP].handler() -= getEventHandler(this, &CGuiSkin::SDL_OnKeyUp);
sdlEvents[SDL_MOUSEMOTION].handler() -= getEventHandler(this, &CGuiSkin::SDL_OnMouseMotion);
sdlEvents[SDL_MOUSEBUTTONDOWN].handler() -= getEventHandler(this, &CGuiSkin::SDL_OnMouseButtonDown);
sdlEvents[SDL_MOUSEBUTTONUP].handler() -= getEventHandler(this, &CGuiSkin::SDL_OnMouseButtonUp);
sdlEvents[SDL_MOUSEWHEEL].handler() -= getEventHandler(this, &CGuiSkin::SDL_OnMouseWheel);
// No effects, just destroy
if (cActiveLayout)
delete cActiveLayout;
if (cPreviousLayout)
delete cPreviousLayout;
}
////////////////
// Load the GUI skin
bool CGuiSkin::Load(const std::string& skin)
{
sPath = SKIN_DIRECTORY + skin;
// TODO: author + name
// TODO: verify that the important files exist
return true;
}
//////////////////
// Open a layout
bool CGuiSkin::OpenLayout(const std::string &layout)
{
// Because of the GUI effects we have to remember the old layout for a while
if (cActiveLayout) {
cActiveLayout->Destroy();
if (cPreviousLayout) // Another layout still effecting, just quit it
delete cPreviousLayout;
cPreviousLayout = cActiveLayout;
}
// Load the new layout
cActiveLayout = new CGuiSkinnedLayout();
if (cActiveLayout->Load(layout, *this)) {
cActiveLayout->DoCreate();
return true;
}
return false;
}
////////////////////
// Converts the path that is relative to the skin to path relative to OLX
std::string CGuiSkin::getSkinFilePath(const std::string& file)
{
// Check
if (!sPath.size())
return file;
return JoinPaths(sPath, file);
}
///////////////////////
// Opens a file from the current skin
FILE *CGuiSkin::OpenSkinFile(const std::string &filename, const char *mode)
{
if (!filename.size())
return NULL;
return OpenGameFile(getSkinFilePath(filename), mode);
}
/////////////////////
// Creates a new widget based on the tag name, returns NULL for unknown widgets
CWidget *CGuiSkin::CreateWidgetByTagName(const std::string& tagname, CContainerWidget *parent, const std::string& id)
{
if (stringcaseequal(tagname, CAnimation::tagName()))
return new CAnimation(id, parent);
else if (stringcaseequal(tagname, CButton::tagName()))
return new CButton(id, parent);
else if (stringcaseequal(tagname, CCheckbox::tagName()))
return new CCheckbox(id, parent);
else if (stringcaseequal(tagname, CCombobox::tagName()))
return new CCombobox(id, parent);
else if (stringcaseequal(tagname, CDialog::tagName()))
return new CDialog(id, parent);
else if (stringcaseequal(tagname, CGuiSkinnedLayout::tagName()))
return new CGuiSkinnedLayout(id, parent);
else if (stringcaseequal(tagname, CImageButton::tagName()))
return new CImageButton(id, parent);
else if (stringcaseequal(tagname, CInputbox::tagName()))
return new CInputbox(id, parent);
else if (stringcaseequal(tagname, CLabel::tagName()))
return new CLabel(id, parent);
else if (stringcaseequal(tagname, CLine::tagName()))
return new CLine(id, parent);
else if (stringcaseequal(tagname, CListview::tagName()))
return new CListview(id, parent);
else if (stringcaseequal(tagname, CMapEditor::tagName()))
return new CMapEditor(id, parent);
else if (stringcaseequal(tagname, CMarquee::tagName()))
return new CMarquee(id, parent);
else if (stringcaseequal(tagname, CMenu::tagName()))
return new CMenu(id, parent);
else if (stringcaseequal(tagname, CMinimap::tagName()))
return new CMinimap(id, parent);
else if (stringcaseequal(tagname, CProgressBar::tagName()))
return new CProgressBar(id, parent);
else if (stringcaseequal(tagname, CScrollbar::tagName()))
return new CScrollbar(id, parent);
else if (stringcaseequal(tagname, CSlider::tagName()))
return new CSlider(id, parent);
else if (stringcaseequal(tagname, CTabControl::tagName()))
return new CTabControl(id, parent);
else if (stringcaseequal(tagname, CTextbox::tagName()))
return new CTextbox(id, parent);
else if (stringcaseequal(tagname, CToggleButton::tagName()))
return new CToggleButton(id, parent);
else
return NULL; // Unknown widget
}
//////////////////
// Draws the content and processes things
void CGuiSkin::Frame()
{
// Reset the game cursor
SetGameCursor(CUR_ARROW);
if (cPreviousLayout) {
if (cPreviousLayout->needsRepaint())
cPreviousLayout->DoRepaint();
cPreviousLayout->Process();
cPreviousLayout->Draw(VideoPostProcessor::videoSurface().get(), 0, 0);
}
cActiveLayout->Process();
if (cActiveLayout->needsRepaint())
cActiveLayout->DoRepaint();
cActiveLayout->Draw(VideoPostProcessor::videoSurface().get(), 0, 0);
DrawCursor(VideoPostProcessor::videoSurface().get());
doVideoFrameInMainThread();
}
void CGuiSkin::SDL_OnKeyDown(SDL_Event *ev) {
if(!cActiveLayout) return;
cActiveLayout->DoKeyDown(0, ev->key.keysym.sym, ModifiersState()); // TODO ...
}
void CGuiSkin::SDL_OnKeyUp(SDL_Event *ev) {
if(!cActiveLayout) return;
cActiveLayout->DoKeyUp(0, ev->key.keysym.sym, ModifiersState()); // TODO ...
}
void CGuiSkin::SDL_OnMouseMotion(SDL_Event* ev) {
if(!cActiveLayout) return;
cActiveLayout->DoMouseMove(ev->motion.x, ev->motion.y, ev->motion.xrel, ev->motion.yrel,
ev->motion.state != 0, SDLButtonStateToMouseButton(ev->motion.state), *GetCurrentModstate());
}
void CGuiSkin::SDL_OnMouseButtonDown(SDL_Event* ev) {
if(!cActiveLayout) return;
cActiveLayout->DoMouseDown(ev->button.x, ev->button.y, GetMouse()->deltaX, GetMouse()->deltaY,
SDLButtonToMouseButton(ev->button.button), *GetCurrentModstate());
}
void CGuiSkin::SDL_OnMouseButtonUp(SDL_Event* ev) {
if(!cActiveLayout) return;
cActiveLayout->DoMouseUp(ev->button.x, ev->button.y, GetMouse()->deltaX, GetMouse()->deltaY,
SDLButtonToMouseButton(ev->button.button), *GetCurrentModstate());
}
void CGuiSkin::SDL_OnMouseWheel(SDL_Event* ev) {
if(!cActiveLayout) return;
if(ev->wheel.y < 0)
cActiveLayout->DoMouseWheelDown(GetMouse()->X, GetMouse()->Y, GetMouse()->deltaX, GetMouse()->deltaY, *GetCurrentModstate());
else if(ev->wheel.y > 0)
cActiveLayout->DoMouseWheelUp(GetMouse()->X, GetMouse()->Y, GetMouse()->deltaX, GetMouse()->deltaY, *GetCurrentModstate());
}
void CGuiSkin::SDL_OnAddWidget(WidgetData ev) {
if(!cActiveLayout) return;
cActiveLayout->DoChildAddEvent(ev.widget);
}
void CGuiSkin::SDL_OnDestroyWidget(WidgetData ev) {
if(!cActiveLayout) return;
cActiveLayout->DoChildDestroyEvent(ev.widget);
}
}; // namespace SkinnedGUI
| 30.697279 | 127 | 0.72277 | JiPRA |
cbb9c7d5b8a43f68400e32fa296212b8bcc0b56b | 1,620 | cpp | C++ | AtCoder/dwango6/B.cpp | takaaki82/Java-Lessons | c4f11462bf84c091527dde5f25068498bfb2cc49 | [
"MIT"
] | 1 | 2018-11-25T04:15:45.000Z | 2018-11-25T04:15:45.000Z | AtCoder/dwango6/B.cpp | takaaki82/Java-Lessons | c4f11462bf84c091527dde5f25068498bfb2cc49 | [
"MIT"
] | null | null | null | AtCoder/dwango6/B.cpp | takaaki82/Java-Lessons | c4f11462bf84c091527dde5f25068498bfb2cc49 | [
"MIT"
] | 2 | 2018-08-08T13:01:14.000Z | 2018-11-25T12:38:36.000Z | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
using Graph = vector<vector<ll>>;
#define rep(i, n) for(ll i=0;i<(ll)(n);i++)
#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)
#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll MOD = 1000000007;
const ll INF = 1000000000000000000L;
#ifdef __DEBUG
/**
* For DEBUG
* https://github.com/ta7uw/cpp-pyprint
*/
#include "cpp-pyprint/pyprint.h"
#endif
ll mod_inverse(ll a, ll mod) {
ll b = mod, u = 1, v = 0;
while (b) {
ll t = a / b;
a -= t * b;
swap(a, b);
u -= t * v;
swap(u, v);
}
u %= mod;
if (u < 0) u += mod;
return u;
}
/**
* B - Fusing Slimes
* https://atcoder.jp/contests/dwacon6th-prelims/submissions/9432346
*
* 各区間を通るスライムの個数の期待値を求め、各区間の大きさをかける。
* これの和に (N-1)! をかけたものが答え
* 各区間を通るスライムの個数は
* Cn = Cn-1 + 1/n
* で合わすことができる
*/
void Main() {
ll N;
cin >> N;
vector<ll> A(N);
rep(i, N) cin >> A[i];
vector<ll> C(N);
C[0] = 1;
rep(i, N - 1) {
C[i + 1] += C[i] + mod_inverse(i + 2, MOD);
}
ll ans = 0;
rep(i, N - 1) {
ll dis = A[i + 1] - A[i];
ans += dis * C[i];
ans %= MOD;
}
rep2(i, 1, N) {
ans *= i;
ans %= MOD;
}
cout << ans << '\n';
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << fixed << setprecision(15);
Main();
return 0;
}
| 19.756098 | 68 | 0.491975 | takaaki82 |
cbbb20203048656dfd071519280ec9992fd02140 | 1,678 | cpp | C++ | src/distance_functions.cpp | ChristianDueben/conleyreg | 73d71fa50b02adcd8dae3b8b407db50403d8017b | [
"MIT"
] | 3 | 2021-11-03T12:35:58.000Z | 2022-03-30T11:21:42.000Z | src/distance_functions.cpp | ChristianDueben/conleyreg | 73d71fa50b02adcd8dae3b8b407db50403d8017b | [
"MIT"
] | 2 | 2021-04-19T17:32:47.000Z | 2021-11-29T21:13:14.000Z | src/distance_functions.cpp | ChristianDueben/conleyreg | 73d71fa50b02adcd8dae3b8b407db50403d8017b | [
"MIT"
] | null | null | null | #include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_num_threads() 1
#define omp_get_thread_num() 0
#define omp_get_max_threads() 1
#define omp_get_thread_limit() 1
#define omp_get_num_procs() 1
#endif
// [[Rcpp::plugins(openmp)]]
#include <cmath>
#include "distance_functions.h"
// 1a Function computing haversine distance
double haversine_dist(double lat1, double lat2, double lon1, double lon2) {
double the_terms = (std::pow(std::sin((lat2 - lat1) / 2), 2)) + (std::cos(lat1) * std::cos(lat2) * std::pow(std::sin((lon2 - lon1) / 2), 2));
double delta_sigma = 2 * std::atan2(std::sqrt(the_terms), std::sqrt(1 - the_terms));
return (6371.01 * delta_sigma);
}
// 1b Function computing euclidean distance
double euclidean_dist(double lat1, double lat2, double lon1, double lon2) {
return (std::sqrt(std::pow(lon1 - lon2, 2) + std::pow(lat1 - lat2, 2)));
}
// 1c Function computing rounded haversine distance
unsigned int haversine_dist_r(double lat1, double lat2, double lon1, double lon2) {
double the_terms = (std::pow(std::sin((lat2 - lat1) / 2), 2)) + (std::cos(lat1) * std::cos(lat2) * std::pow(std::sin((lon2 - lon1) / 2), 2));
double delta_sigma = 2 * std::atan2(std::sqrt(the_terms), std::sqrt(1 - the_terms));
unsigned int dist_r = (int)(6371.01 * delta_sigma + 0.5);
return dist_r;
}
// 1d Function computing rounded euclidean distance
unsigned int euclidean_dist_r(double lat1, double lat2, double lon1, double lon2) {
unsigned int dist_r = (int)(std::sqrt(std::pow(lon1 - lon2, 2) + std::pow(lat1 - lat2, 2)));
return dist_r;
}
| 38.136364 | 143 | 0.68534 | ChristianDueben |
cbbb2c1c702f560230f2291b6406139381713261 | 3,327 | cc | C++ | lite/backends/nnadapter/nnadapter/driver/huawei_kirin_npu/converter/elementwise.cc | PaddleLite-EB/Paddle-Lite | 40cae8672712552de5eb0894d0b5316ae89d3c17 | [
"Apache-2.0"
] | 6 | 2020-07-01T02:52:16.000Z | 2021-06-22T12:15:59.000Z | lite/backends/nnadapter/nnadapter/driver/huawei_kirin_npu/converter/elementwise.cc | PaddleLite-EB/Paddle-Lite | 40cae8672712552de5eb0894d0b5316ae89d3c17 | [
"Apache-2.0"
] | null | null | null | lite/backends/nnadapter/nnadapter/driver/huawei_kirin_npu/converter/elementwise.cc | PaddleLite-EB/Paddle-Lite | 40cae8672712552de5eb0894d0b5316ae89d3c17 | [
"Apache-2.0"
] | 1 | 2021-07-24T15:30:46.000Z | 2021-07-24T15:30:46.000Z | // Copyright (c) 2019 PaddlePaddle Authors. 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 "driver/huawei_kirin_npu/converter.h"
#include "utility/debug.h"
namespace nnadapter {
namespace huawei_kirin_npu {
int Program::ConvertElementwise(hal::Operation* operation) {
auto& input_operands = operation->input_operands;
auto& output_operands = operation->output_operands;
auto input_count = input_operands.size();
auto output_count = output_operands.size();
NNADAPTER_CHECK_EQ(input_count, 3);
NNADAPTER_CHECK_EQ(output_count, 1);
// Input0
auto input0_operand = input_operands[0];
NNADAPTER_VLOG(5) << "input0: " << OperandToString(input0_operand);
// Input1
auto input1_operand = input_operands[1];
NNADAPTER_VLOG(5) << "input1: " << OperandToString(input1_operand);
// Fuse code
auto fuse_code = *reinterpret_cast<int32_t*>(input_operands[2]->buffer);
NNADAPTER_VLOG(5) << "fuse_code=" << fuse_code;
// Output
auto output_operand = output_operands[0];
NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand);
// Convert to HiAI operators
auto input0_operator = ConvertOperand(input0_operand);
auto input1_operator = ConvertOperand(input1_operand);
std::shared_ptr<ge::Operator> eltwise_operator = nullptr;
if (operation->type == NNADAPTER_ADD) {
auto add_operator = AddOperator<ge::op::Add>(output_operand);
add_operator->set_input_x1(*input0_operator);
add_operator->set_input_x2(*input1_operator);
eltwise_operator = add_operator;
} else if (operation->type == NNADAPTER_SUB) {
auto sub_operator = AddOperator<ge::op::Sub>(output_operand);
sub_operator->set_input_x1(*input0_operator);
sub_operator->set_input_x2(*input1_operator);
eltwise_operator = sub_operator;
} else if (operation->type == NNADAPTER_MUL) {
auto mul_operator = AddOperator<ge::op::Mul>(output_operand);
mul_operator->set_input_x(*input0_operator);
mul_operator->set_input_y(*input1_operator);
eltwise_operator = mul_operator;
} else if (operation->type == NNADAPTER_DIV) {
auto div_operator = AddOperator<ge::op::RealDiv>(output_operand);
div_operator->set_input_x1(*input0_operator);
div_operator->set_input_x2(*input1_operator);
eltwise_operator = div_operator;
} else {
NNADAPTER_LOG(FATAL) << "Unsupported element-wise operation type "
<< OperationTypeToString(operation->type)
<< " is found.";
}
if (fuse_code != NNADAPTER_FUSED_NONE) {
auto act_operator = AddOperator<ge::op::Activation>(output_operand);
act_operator->set_input_x(*eltwise_operator);
act_operator->set_attr_mode(ConvertFuseCode(fuse_code));
}
return NNADAPTER_NO_ERROR;
}
} // namespace huawei_kirin_npu
} // namespace nnadapter
| 41.5875 | 75 | 0.733093 | PaddleLite-EB |
cbbc838b43269f4e27c7ac866427322f0dd802df | 40,733 | hpp | C++ | SDK/ARKSurvivalEvolved_GiantTurtle_Character_BP_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_GiantTurtle_Character_BP_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_GiantTurtle_Character_BP_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_GiantTurtle_Character_BP_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass GiantTurtle_Character_BP.GiantTurtle_Character_BP_C
// 0x06D8 (0x2940 - 0x2268)
class AGiantTurtle_Character_BP_C : public ADino_Character_BP_C
{
public:
class UBoxComponent* PlatformSaddleBuildArea; // 0x2268(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UAudioComponent* BreathSound; // 0x2270(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* IdleWake; // 0x2278(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* Submerage; // 0x2280(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* ParticleSystem1; // 0x2288(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* Wake; // 0x2290(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* AirCone; // 0x2298(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* BubbleCone; // 0x22A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Right_Back_Leg; // 0x22A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Right_Middle_Leg; // 0x22B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Right_Front_Leg; // 0x22B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Left_Back_Leg; // 0x22C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Left_Middle_Leg; // 0x22C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Left_Front_Leg; // 0x22D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* FlockRoot; // 0x22D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USkeletalMeshComponent* InvisibleSaddle; // 0x22E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UDinoCharacterStatusComponent_BP_GiantTurtle_C* DinoCharacterStatus_BP_GiantTurtle_C1; // 0x22E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
double LastGiveOxygenTime; // 0x22F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UStaticMeshComponent* CropSMTest; // 0x22F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<struct FGiantTurtle_Crop_Struct> CropDataStructs; // 0x2300(0x0010) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame)
TArray<class ACropPlotLarge_SM_C*> CropPlots; // 0x2310(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance)
float TimeintervalToAddOxygen; // 0x2320(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float OxygenRadius; // 0x2324(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TotalGrowthTime; // 0x2328(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float GrowthTimeInterval; // 0x232C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float CurrentGrowthTime; // 0x2330(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlowerGrowthPercentage; // 0x2334(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData)
float MushroomGrowthPercentage; // 0x2338(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x233C(0x0004) MISSED OFFSET
class UClass* FlowerToGiveOnGrowth; // 0x2340(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UClass* MushroomToGiveOnGrowth; // 0x2348(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
int FlowersToGivePerGrowth; // 0x2350(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
int MushroomToGivePerGrowth; // 0x2354(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
TArray<class UStaticMeshComponent*> CropBaseMeshes; // 0x2358(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
bool bIsDebugging; // 0x2368(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData01[0x7]; // 0x2369(0x0007) MISSED OFFSET
double LastAddOxygenVFXTime; // 0x2370(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<int> TakenLocationIndex; // 0x2378(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
double LastCheckInventoryForSeedTime; // 0x2388(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int AmountOfBubblePerAttack; // 0x2390(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsBreathing; // 0x2394(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData02[0x3]; // 0x2395(0x0003) MISSED OFFSET
struct FVector TPVCamera; // 0x2398(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector KCamera; // 0x23A4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastBubbleTime; // 0x23B0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeMaxLength; // 0x23B8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector BreathDirection; // 0x23BC(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector BreathViewStartLocation; // 0x23C8(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeCurrentLength; // 0x23D4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeFilledTime; // 0x23D8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeAngleDegree; // 0x23DC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FHUDElement BubbleCooldownHudTemplate; // 0x23E0(0x0150) (Edit, BlueprintVisible, DisableEditOnInstance)
float BubbleCooldownTick; // 0x2530(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackCooldown; // 0x2534(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackMinRequireStamina; // 0x2538(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackMaxDuration; // 0x253C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackStaminaCostPerSecond; // 0x2540(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackDuration; // 0x2544(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsFullyInWater; // 0x2548(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData03[0x3]; // 0x2549(0x0003) MISSED OFFSET
struct FVector InWaterCheckOffset; // 0x254C(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeDestroyFlock; // 0x2558(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SpawnFlockCooldown; // 0x2560(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector SpawnFlockOffset; // 0x2564(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class APrimalCharacter* MicrobeSwarm; // 0x2570(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
int FlockSize; // 0x2578(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int NumLeaderBoids; // 0x257C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<struct FBoid> FlockData; // 0x2580(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
bool bHasFlock; // 0x2590(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData04[0x7]; // 0x2591(0x0007) MISSED OFFSET
class UStaticMesh* BoidStaticMesh; // 0x2598(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugFlock; // 0x25A0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData05[0x7]; // 0x25A1(0x0007) MISSED OFFSET
TArray<class UStaticMeshComponent*> FlockStaticMeshComps; // 0x25A8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
unsigned char UnknownData06[0x8]; // 0x25B8(0x0008) MISSED OFFSET
struct UObject_FTransform CurrentFlockTarget; // 0x25C0(0x0030) (Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData)
float CurAngle; // 0x25F0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData07[0xC]; // 0x25F4(0x000C) MISSED OFFSET
struct UObject_FTransform CurrentFlockTarget_Smoothed; // 0x2600(0x0030) (Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData)
struct FFlockPersistentData FlockPersistentData; // 0x2630(0x0038) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FBoidBehavior Behavior; // 0x2668(0x0040) (Edit, BlueprintVisible, DisableEditOnInstance)
float TamingProcess; // 0x26A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlockDuration; // 0x26AC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlockCooldown; // 0x26B0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData08[0x4]; // 0x26B4(0x0004) MISSED OFFSET
double LastTimeToggleFlock; // 0x26B8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TestFloat; // 0x26C0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector CurrentDisappearingLocationOffset; // 0x26C4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentDisapperaingMultiplier; // 0x26D0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector FlockFlyingOffset; // 0x26D4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<class UClass*> SeedToGiveClass; // 0x26E0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
double LastTamingProcessIncrease; // 0x26F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class APrimalDinoCharacter* TamingFish; // 0x26F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
double LastTimeTamingFishDie; // 0x2700(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeDamageMicrobe; // 0x2708(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class AShooterCharacter* Tamer; // 0x2710(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float MinTimeBetweenOxygenVFX; // 0x2718(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxTimeBetweenOxygenVFX; // 0x271C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MinBubblesToSpawnPerWave; // 0x2720(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxBubblesToSpawnPerWave; // 0x2724(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WakeThreshold; // 0x2728(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData09[0x4]; // 0x272C(0x0004) MISSED OFFSET
TArray<class APrimalDinoCharacter*> TamingFishes; // 0x2730(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance)
TArray<class UClass*> SpawnFishClasses; // 0x2740(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
float SubmergedRotationRate; // 0x2750(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float UnsubmergedRotationRate; // 0x2754(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float AffinityBasePerSec; // 0x2758(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TPVOffsetMultiplier; // 0x275C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TameRate; // 0x2760(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float UnsubmergeBuoyancy; // 0x2764(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SubmergeBuoyancy; // 0x2768(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsInRaftMode; // 0x276C(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData)
bool UseWidgetHUD; // 0x276D(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData10[0x2]; // 0x276E(0x0002) MISSED OFFSET
class UClass* HudWidgetClass; // 0x2770(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UUserWidget* HUDWidgetInstance; // 0x2778(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CloseHUDWidgetDelay; // 0x2780(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bAllowMating; // 0x2784(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData11[0x3]; // 0x2785(0x0003) MISSED OFFSET
class FString UnableToMateString; // 0x2788(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
float TotalGrowthTimeFastGrowth; // 0x2798(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float GrowthTimeIntervalFastGrowth; // 0x279C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTickTime; // 0x27A0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TamingFishRespawnTimer; // 0x27A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData12[0x4]; // 0x27AC(0x0004) MISSED OFFSET
class APrimalBuff* RaftModeDisplayBuff; // 0x27B0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
int MaxMushroomsToGiveOnUnstasis; // 0x27B8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxFlowersToGiveOnUnstasis; // 0x27BC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxSeedsToGiveOnUnstasis; // 0x27C0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData13[0x4]; // 0x27C4(0x0004) MISSED OFFSET
TArray<class APrimalCharacter*> BlowedAwayPawns; // 0x27C8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance)
class UTexture2D* BubbleHUDFillTexture; // 0x27D8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UTexture2D* BubbleHUDInUseTexture; // 0x27E0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float K2Node_Event_DeltaSeconds; // 0x27E8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData14[0x4]; // 0x27EC(0x0004) MISSED OFFSET
class FString CallFunc_Conv_FloatToString_ReturnValue; // 0x27F0(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
class FString CallFunc_Concat_StrStr_ReturnValue; // 0x2800(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
class FString CallFunc_Conv_FloatToString_ReturnValue2; // 0x2810(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
class FString CallFunc_Concat_StrStr_ReturnValue2; // 0x2820(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
bool K2Node_CustomEvent_bIsBreathing; // 0x2830(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_BoolBool_ReturnValue; // 0x2831(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData15[0x2]; // 0x2832(0x0002) MISSED OFFSET
struct FVector K2Node_CustomEvent_BreathViewStartLocation; // 0x2834(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_BreathDirection; // 0x2840(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData16[0x4]; // 0x284C(0x0004) MISSED OFFSET
class AShooterPlayerController* K2Node_CustomEvent_OwnerContoler; // 0x2850(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BPGetCurrentStatusValue_ReturnValue; // 0x2858(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_GreaterEqual_FloatFloat_ReturnValue; // 0x285C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_LessEqual_FloatFloat_ReturnValue; // 0x285D(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData17[0x2]; // 0x285E(0x0002) MISSED OFFSET
float CallFunc_PlayAnimEx_ReturnValue; // 0x2860(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ByteByte_ReturnValue; // 0x2864(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData18[0x3]; // 0x2865(0x0003) MISSED OFFSET
float CallFunc_PlayAnimEx_ReturnValue2; // 0x2868(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData19[0x4]; // 0x286C(0x0004) MISSED OFFSET
class UAnimMontage* CallFunc_GetCurrentMontage_ReturnValue; // 0x2870(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ObjectObject_ReturnValue; // 0x2878(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ByteByte_ReturnValue2; // 0x2879(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ObjectObject_ReturnValue2; // 0x287A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue; // 0x287B(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_PlayAnimEx_ReturnValue3; // 0x287C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_PlayAnimEx_ReturnValue4; // 0x2880(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData20[0x4]; // 0x2884(0x0004) MISSED OFFSET
class UAnimMontage* CallFunc_GetCurrentMontage_ReturnValue2; // 0x2888(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAnimInstance* CallFunc_GetAnimInstance_ReturnValue; // 0x2890(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UGiantTurtle_AnimBlueprintNew_C* K2Node_DynamicCast_AsGiantTurtle_AnimBlueprintNew_C; // 0x2898(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast_CastSuccess; // 0x28A0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetworkModeResult> CallFunc_CanRunCosmeticEvents_OutNetworkMode; // 0x28A1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum_CmpSuccess; // 0x28A2(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData21[0x1]; // 0x28A3(0x0001) MISSED OFFSET
float CallFunc_SelectFloat_ReturnValue; // 0x28A4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_MakeVector_ReturnValue; // 0x28A8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FInterpTo_ReturnValue; // 0x28B4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FClamp_ReturnValue; // 0x28B8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue; // 0x28BC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Subtract_FloatFloat_ReturnValue; // 0x28C8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_MakeVector_ReturnValue2; // 0x28CC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue2; // 0x28D8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData22[0x4]; // 0x28E4(0x0004) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue; // 0x28E8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class ABuff_Client_GiantTurtleRaftState_C* K2Node_DynamicCast_AsBuff_Client_GiantTurtleRaftState_C; // 0x28F0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast2_CastSuccess; // 0x28F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData23[0x7]; // 0x28F9(0x0007) MISSED OFFSET
TArray<class AActor*> CallFunc_BoxOverlapActors_NEW_ActorsToIgnore_RefProperty; // 0x2900(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<int> CallFunc_FlockTickFollowersAndFreeAgents_BoidIndexWhitelist_RefProperty;// 0x2910(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<int> CallFunc_FlockTickLeaders_BoidIndexWhitelist_RefProperty; // 0x2920(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore_RefProperty; // 0x2930(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass GiantTurtle_Character_BP.GiantTurtle_Character_BP_C");
return ptr;
}
bool BPCanBaseOnCharacter(class APrimalCharacter** BaseCharacter);
void BPBecomeAdult();
void BPBecomeBaby();
void BPUnstasis();
void BPOnDinoCheat(struct FName* CheatName, bool* bSetValue, float* Value);
void BPNotifyToggleHUD(bool* bHudHidden);
void OnRep_bAllowMating();
void ReceiveBeginPlay();
void GetAllowMating(bool* Allow);
void BlueprintDrawFloatingHUD(class AShooterHUD** HUD, float* CenterX, float* CenterY, float* DrawScale);
void UpdateAllowMating();
void BPTimerServer();
void ReceiveDestroyed();
void DestroyHUDWidget(bool DestroyNow);
void BPNotifyClearRider(class AShooterCharacter** RiderClearing);
void BPNotifySetRider(class AShooterCharacter** RiderSetting);
void BPNotifyLevelUp(int* ExtraCharacterLevel);
bool AllowPlayMontage(class UAnimMontage** AnimMontage);
bool BP_InterceptMoveForward(float* AxisValue);
void CheckRaftMode(float DeltaTime);
void BPPostLoadedFromSaveGame();
void ClearPreventHurtAnim();
void AnimBpSetBreathing(bool On);
void DestroySaddle();
void BPPlayDying(float* KillingDamage, class APawn** InstigatingPawn, class AActor** DamageCauser, struct FDamageEvent* DamageEvent);
void TickWake();
void UpdateMaterial();
void BubbleAttackToggle(bool On);
void BlueprintAnimNotifyCustomEvent(struct FName* CustomEventName, class USkeletalMeshComponent** MeshComp, class UAnimSequenceBase** Animation, class UAnimNotify** AnimNotifyObject);
class UAnimMontage* BPOverrideHurtAnim(float* DamageTaken, class APawn** PawnInstigator, class AActor** DamageCauser, bool* bIsLocalPath, bool* bIsPointDamage, struct FVector* PointDamageLocation, struct FVector* PointDamageHitNormal, struct FDamageEvent* DamageEvent);
void CheckCave();
void TurnOffFlock();
float BPAdjustDamage(float* IncomingDamage, struct FDamageEvent* TheDamageEvent, class AController** EventInstigator, class AActor** DamageCauser, bool* bIsPointDamage, struct FHitResult* PointHitInfo);
void Setup_Flock();
void CheckTurtleTargetForFollowers();
void TickTaming(float DeltaSeconds);
void CheckFullyInWater();
void STATIC_TickBirdsFlock(float DeltaSeconds);
void PushBackPawnNotInWater(class APrimalCharacter* Pawn);
void TickBubbleCooldown(float DeltaSeconds);
void BPGetHUDElements(class APlayerController** ForPC, TArray<struct FHUDElement>* OutElements);
void UpdateBreath_Rotation();
void Tick_Breathing(float DeltSeconds);
float BPGetCrosshairAlpha();
bool BPHandleControllerInitiatedAttack(int* AttackIndex);
bool BPHandleOnStopTargeting();
void STATIC_GetPlayersOnSeats();
void K2_OnMovementModeChanged(TEnumAsByte<EMovementMode>* PrevMovementMode, TEnumAsByte<EMovementMode>* NewMovementMode, unsigned char* PrevCustomMode, unsigned char* NewCustomMode);
bool BlueprintCanRiderAttack(int* AttackIndex);
void SpawnBubble();
float BP_GetCustomModifier_RotationRate();
void STATIC_Setup_New_Crop_DataStruct(int LocationIndex, class UPrimalItemConsumableSeed_C* SeedItem);
void Check_Inventory_for_Seed_Items();
void GetCropGrowLocation(int* LocationIndex);
void SpawnOxygenVFX();
void Update_CropsVisuals();
void UpdateFlowerAndMushroom(float DeltaSecond);
void STATIC_UpdateCropStructs(float DeltaSeconds);
void STATIC_AddOxygenBuff();
void BPNotifyInventoryItemChange(bool* bIsItemAdd, class UPrimalItem** theItem, bool* bEquipItem);
void GetMovementMontage(TEnumAsByte<ERootMotionMovementMode> Mode, class UAnimMontage** Montage);
struct FVector BPGetRiderUnboardLocation(class APrimalCharacter** RidingCharacter);
void UserConstructionScript();
void ReceiveTick(float* DeltaSeconds);
void SpawnBubbles();
void Server_SetIsBreathing(bool bIsBreathing);
void Server_SetBreathDirection(const struct FVector& BreathViewStartLocation, const struct FVector& BreathDirection);
void Server_TryBubbleAttack(class AShooterPlayerController* OwnerContoler);
void Server_StopBubbleAttack();
void Multi_StopCurrentMontage();
void ExecuteUbergraph_GiantTurtle_Character_BP(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 137.611486 | 270 | 0.558859 | 2bite |