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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
599f7a6db73425a6b163880e7a94cfff1b1d45f7 | 640 | cpp | C++ | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex02-romanharv1 | 7d40d08235a36a78539c9bd21d6512a1d58c1410 | [
"MIT"
] | null | null | null | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex02-romanharv1 | 7d40d08235a36a78539c9bd21d6512a1d58c1410 | [
"MIT"
] | null | null | null | prob03/main.cpp | CSUF-CPSC120-2019F23-24/labex02-romanharv1 | 7d40d08235a36a78539c9bd21d6512a1d58c1410 | [
"MIT"
] | null | null | null | // Name: Restaurant Bill Calculator
// This program calculates the tax and tip on a restaurant bill.
#include <iostream>
int main()
{
double price, tax, tip;
double total;
//Get value of price.
std::cout << "Welcome to the Restaurant Bill Calculator!\n";
std::cout << "What is the total meal cost? $";
std::cin >> price;
//Calculate values for tax, tip, and total.
tax = price * 0.0775;
tip = price * 0.2;
total = price + tax +tip;
//Display calculated values.
std::cout << "Tax:\t\t$" << tax << "\n";
std::cout << "Tip:\t\t$" << tip << "\n";
std::cout << "Total Bill: \t$" << total << "\n";
return 0;
}
| 22.857143 | 64 | 0.598438 | CSUF-CPSC120-2019F23-24 |
59a025de88daf215df7f57db160ed988f3a58fc9 | 281 | hpp | C++ | sfml/python/src/Input.hpp | fu7mu4/entonetics | d0b2643f039a890b25d5036cc94bfe3b4d840480 | [
"MIT"
] | null | null | null | sfml/python/src/Input.hpp | fu7mu4/entonetics | d0b2643f039a890b25d5036cc94bfe3b4d840480 | [
"MIT"
] | null | null | null | sfml/python/src/Input.hpp | fu7mu4/entonetics | d0b2643f039a890b25d5036cc94bfe3b4d840480 | [
"MIT"
] | null | null | null | #ifndef __PYINPUT_HPP
#define __PYINPUT_HPP
#include <SFML/Window/Input.hpp>
#include <SFML/Window/Event.hpp>
#include <iostream>
#include <Python.h>
#include <structmember.h>
typedef struct {
PyObject_HEAD
sf::Input *obj;
} PySfInput;
PySfInput *
GetNewPySfInput();
#endif
| 14.05 | 32 | 0.75089 | fu7mu4 |
59a0362851cf6e7818413ded809a3f639d96f054 | 4,064 | cpp | C++ | course/Course_8/Source.cpp | catalinboja/catalinboja-cpp_2020 | ff1d2dc8620ff722aef151c9c823ec20f766d5b2 | [
"MIT"
] | 4 | 2020-10-13T13:37:15.000Z | 2021-07-10T15:40:40.000Z | course/Course_8/Source.cpp | catalinboja/catalinboja-cpp_2020 | ff1d2dc8620ff722aef151c9c823ec20f766d5b2 | [
"MIT"
] | null | null | null | course/Course_8/Source.cpp | catalinboja/catalinboja-cpp_2020 | ff1d2dc8620ff722aef151c9c823ec20f766d5b2 | [
"MIT"
] | 7 | 2020-10-16T08:32:42.000Z | 2021-03-02T14:38:28.000Z | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class LenghtException {
};
class Student {
const int id;
char* name = nullptr;
float tuitionFee = 0;
const int groupNumber;
const static int MIN_LENGTH = 3;
static float feesTotal;
static int NO_OBJECTS;
public:
Student(int id, const char* name, float fee, int group):id(id),groupNumber(group) {
//this->id = id;
this->setName(name);
this->tuitionFee = fee;
Student::feesTotal += fee;
Student::NO_OBJECTS += 1;
}
Student(const char* name, float fee, int group):id(Student::NO_OBJECTS), groupNumber(group) {
//this->id = id;
this->setName(name);
this->tuitionFee = fee;
Student::feesTotal += fee;
Student::NO_OBJECTS += 1;
}
void setName(const char* newName) {
//validate input
if (strlen(newName) < MIN_LENGTH) {
throw LenghtException();
}
if (this->name != nullptr) {
delete[] this->name;
}
this->name = new char[strlen(newName) + 1];
strcpy(this->name, newName);
}
void setTuitionFee(int newValue) {
Student::feesTotal -= this->tuitionFee;
this->tuitionFee = newValue;
Student::feesTotal += newValue;
}
~Student() {
if (this->name) {
delete[] this->name;
}
//this->feesTotal -= this->tuitionFee;
Student::feesTotal -= this->tuitionFee;
}
//copy constructor
Student(Student& student):id(-1), groupNumber(student.groupNumber) {
cout << endl << "Calling copy ctor";
//this->id = student.id;
//this->tuitionFee = student.tuitionFee;
//Student::feesTotal += this->tuitionFee;
this->setTuitionFee(student.tuitionFee);
this->setName(student.name);
}
static float getTotalFees() {
cout << endl << "A static method";
return Student::feesTotal;
}
float getTuition() {
return this->tuitionFee;
}
Student operator+(int value) {
//+ does not change the operands
//this->tuitionFee += value; //DON't
Student result = *this;
result.tuitionFee += value;
return result;
}
//you can't
//Student operator+(int value, Student s) {
//}
};
int Student::NO_OBJECTS = 0;
float Student::feesTotal = 0;
//is calling the copy constructor
void doNothing(Student s) {
s.setName("Joker");
}
void doNothing2(const Student& s) {
//s.setName("Joker");
}
//calls copy constructor
Student createObject() {
Student s(0, "John Doe", 0, 0);
return s;
}
int sum(int a, int b) {
return a + b;
}
int sum(int a, char* aPointer) {
return a + 10;
}
int sum(int a, int b, int c) {
return a + b + c;
}
//overload ==
bool operator==(Student s1, Student s2) {
if (s1.getTuition() == s2.getTuition()) {
return true;
} else
return false;
}
bool operator>(Student s1, Student s2) {
if (s1.getTuition() > s2.getTuition()) {
return true;
}
else
return false;
}
Student operator+(int value, Student s) {
}
int main(int argc, char* argv[]) {
//Student s1;
//Student students[10];
Student s1(1, "Johny", 1000, 1064);
Student* pS = new Student(2, "Alice", 0, 1064);
//Student s3(3);
//Student s4(3,"Boby");
delete pS;
//copy constructor
Student s2 = s1;
cout << endl << "The sum of tuition fees is " << Student::getTotalFees();
doNothing(s1);
createObject();
//function overloading
int rez = sum(10, 20);
//operator overloading
cout << s1; //operator <<(cout, s1)
cout >> s1;
s1 = s2; //operator =(s1, s2)
s1 = s1 + 100; // s1.operator+(100)
s1 = s1 + 100; //increase tuition fee operator +(s1, 100)
s1 = 100 + s1; //operator+(100, s1)
s1 = s1 - 100;
s1 += 100;
s1++; //increase group number by 1 operator ++(s1, int)
++s1; // operator ++(s1)
if (!s1) { //operator!(s1)
cout << endl << "S1 has a scholarship";
}
float tuitionFee = s1; //cast operator // operator float(s1)
if (s1 > s2) { //operator > (s1, s2)
cout << endl << "S1 has a bigger tuition fee";
}
if (s1 == s2) { //operator == (s1, s2)
cout << endl << "They have the same tuition fee";
}
char initial = s1[0]; //get the name initial letter //operator [] (s1, 0)
int vb = 10;
//vb = vb + 10;
//vb = operator +(vb, 10);
} | 19.444976 | 94 | 0.629183 | catalinboja |
59a2bdcb7fa24d28a4eb324ad0cdd199a914270c | 1,988 | cpp | C++ | LudumGame/Source/LudumGame/Private/Flocking/OtherTeamGoalBehaviourComponent.cpp | inbetweengames/TheMammoth_Public | d12d644266076ff739d912def6bc127827c82dc9 | [
"MIT"
] | 21 | 2015-11-05T07:26:27.000Z | 2021-06-01T11:35:05.000Z | LudumGame/Source/LudumGame/Private/Flocking/OtherTeamGoalBehaviourComponent.cpp | inbetweengames/TheMammoth_Public | d12d644266076ff739d912def6bc127827c82dc9 | [
"MIT"
] | null | null | null | LudumGame/Source/LudumGame/Private/Flocking/OtherTeamGoalBehaviourComponent.cpp | inbetweengames/TheMammoth_Public | d12d644266076ff739d912def6bc127827c82dc9 | [
"MIT"
] | 6 | 2015-11-06T08:54:36.000Z | 2017-01-21T18:40:30.000Z | // copyright 2015 inbetweengames GBR
#include "LudumGame.h"
#include "OtherTeamGoalBehaviourComponent.h"
#include "FlockingGameMode.h"
#include "AI/Navigation/NavigationPath.h"
#include "DrawDebugHelpers.h"
#include "../FlockingDataCache.h"
#include "BasicAIAgent.h"
DECLARE_CYCLE_STAT(TEXT("Goal Behaviour"),STAT_AI_GoalBehaviour,STATGROUP_Flocking);
// Sets default values for this component's properties
UOtherTeamGoalBehaviourComponent::UOtherTeamGoalBehaviourComponent()
{
m_behaviourWeight = 1.0f;
m_maxDistance = 10000.0f;
}
FVector UOtherTeamGoalBehaviourComponent::CalcAccelerationVector(int32 thisAIIndex, const FYAgentTeamData &forTeam, class UFlockingDataCache * dataCache, uint8 *scratchData, float tickTime) const
{
SCOPE_CYCLE_COUNTER(STAT_AI_GoalBehaviour);
const FVector &thisLocation = forTeam.m_locations[thisAIIndex];
float closest = MAX_FLT;
FVector closestLocation = FVector::ZeroVector;
for (int32 otherTeam : m_targetTeams)
{
const FYAgentTeamData *targetTeamData = dataCache->GetTeamData(otherTeam);
if (targetTeamData == nullptr)
{
continue;
}
const TArray<FVector> &targetLocations = targetTeamData->m_locations;
if (targetLocations.Num() == 0)
{
continue;
}
for (const FVector & targetLocation : targetLocations)
{
float distSq = FVector::DistSquared(thisLocation, targetLocation);
if (distSq < closest)
{
closest = distSq;
closestLocation = targetLocation;
}
}
}
if (!closestLocation.IsNearlyZero())
{
FVector toLocation = closestLocation - thisLocation;
toLocation.Z = 0.0f;
if (toLocation.Size() <= m_maxDistance)
{
toLocation.Normalize();
return toLocation * m_behaviourWeight;
}
}
if (dataCache->GetLocationsPlayer().Num() > 0)
{
FVector player = dataCache->GetLocationsPlayer()[0];
FVector toLocation = player - thisLocation;
toLocation.Z = 0.0f;
toLocation.Normalize();
return toLocation * m_behaviourWeight;
}
return FVector::ZeroVector;
}
| 23.951807 | 195 | 0.748994 | inbetweengames |
59a984616754955c2911c5b8851b2a7dabb35d9d | 5,121 | cpp | C++ | src/omexmeta/Triples.cpp | sys-bio/tesemantic | f25f44a0a7e67d38f1e94fd69c08ae7f73be2079 | [
"Apache-2.0"
] | 6 | 2020-07-07T11:23:29.000Z | 2021-11-19T09:49:02.000Z | src/omexmeta/Triples.cpp | sys-bio/tesemantic | f25f44a0a7e67d38f1e94fd69c08ae7f73be2079 | [
"Apache-2.0"
] | 79 | 2020-06-23T15:32:44.000Z | 2022-02-23T06:46:43.000Z | src/omexmeta/Triples.cpp | sys-bio/tesemantic | f25f44a0a7e67d38f1e94fd69c08ae7f73be2079 | [
"Apache-2.0"
] | 5 | 2020-11-29T04:29:54.000Z | 2021-08-17T15:55:41.000Z | //
// Created by Ciaran on 4/29/2020.
//
#include "omexmeta/Triples.h"
namespace omexmeta {
Triples::Triples() = default;
Triples::Triples(Triple &triple) {
moveBack(triple);
}
Triples::Triples(std::vector<Triple> triples) {
for (auto &triple: triples) {
moveBack(triple);
}
}
/**
* @brief moves a Triple object to the back of Triples
* @param triple The Triple object to move.
* @details The vector storing the Triples is increased
* in size by 1 and the @param triple is moved into that
* slot. Therefore, ownership of the triple passes to
* the Triples object who is reposible for freeing the Triple.
*/
void Triples::moveBack(Triple &triple) {
// This move calls Triple destrubtor?
triples_.push_back(std::move(triple));
}
// void Triples::emplace_back(UriHandler& uriHandler, librdf_node *subject, librdf_node *predicate, librdf_node *resource) {
// Triple triple(uriHandler, subject, predicate, resource);
// moveBack(triple);
// }
void Triples::emplace_back(UriHandler& uriHandler, LibrdfNode subject, const PredicatePtr &predicatePtr, const LibrdfNode &resource) {
Triple triple(uriHandler, subject, predicatePtr->getNode(), resource);
moveBack(triple);
}
void Triples::emplace_back(UriHandler& uriHandler, const LibrdfNode& subject, const LibrdfNode& predicate, const LibrdfNode &resource) {
Triple triple(uriHandler, subject, predicate, resource);
// creating a triple, a wrapper around a shared poitner. So we increment the usage count
moveBack(triple);
}
void Triples::emplace_back(UriHandler& uriHandler, LibrdfNode subject, const Predicate &predicate, const LibrdfNode &resource) {
LibrdfNode p = LibrdfNode::fromUriString(predicate.getNamespace());
Triple triple(uriHandler, subject, p, resource);
moveBack(triple);
}
// void Triples::emplace_back(UriHandler& uriHandler, LibrdfNode subject, BiomodelsBiologyQualifier predicate, const LibrdfNode &resource) {
// Triple triple(uriHandler, subject, std::make_shared<BiomodelsBiologyQualifier>(std::move(predicate)).get(), resource);
// moveBack(triple);
// }
//
// void Triples::emplace_back(UriHandler& uriHandler, LibrdfNode subject, BiomodelsModelQualifier predicate, const LibrdfNode &resource) {
// Triple triple(uriHandler, subject, std::make_shared<BiomodelsModelQualifier>(std::move(predicate))->get(), resource);
// moveBack(triple);
// }
//
// void Triples::emplace_back(UriHandler& uriHandler, LibrdfNode subject, DCTerm predicate, const LibrdfNode &resource) {
// Triple triple(uriHandler, subject, std::make_shared<DCTerm>(std::move(predicate))->get(), resource);
// moveBack(triple);
// }
//
// void Triples::emplace_back(UriHandler& uriHandler, LibrdfNode subject, SemSim predicate, const LibrdfNode &resource) {
// Triple triple(uriHandler, subject, std::make_shared<SemSim>(std::move(predicate))->get(), resource);
// moveBack(triple);
// }
std::vector<std::string> Triples::getSubjectsStr() {
std::vector<std::string> vec;
for (auto &triple : triples_) {
vec.push_back(triple.getSubjectNode().str());
}
return vec;
}
std::vector<std::string> Triples::getPredicates() {
std::vector<std::string> vec;
for (auto &triple: triples_) {
vec.push_back(triple.getPredicateNode().str());
}
return vec;
}
std::vector<std::string> Triples::getResources() {
std::vector<std::string> vec;
for (auto &triple: triples_) {
vec.push_back(triple.getResourceNode().str());
}
return vec;
}
int Triples::size() const {
return triples_.size();
}
TripleVector::iterator Triples::begin() {
return triples_.begin();
}
TripleVector::iterator Triples::end() {
return triples_.end();
}
Triple Triples::pop() {
// get reference to back of triples_ vector
Triple triple = triples_.back();
// then remove it from the triples_ vector
triples_.pop_back();
// return by move so no copies are made.
return std::move(triple);
}
void Triples::freeTriples() {
for (auto& triple: triples_){
triple.freeTriple();
}
triples_ = std::vector<Triple>();
}
bool Triples::isEmpty() {
return triples_.empty();
}
Triple &Triples::operator[](int index) {
return triples_[index];
}
const Triple &Triples::operator[](int index) const {
return triples_[index];
}
bool Triples::operator==(const Triples &rhs) const {
return triples_ == rhs.triples_;
}
bool Triples::operator!=(const Triples &rhs) const {
return !(rhs == *this);
}
Triples::Triples(int size) {
triples_.reserve(size);
}
int Triples::capacity() {
return triples_.capacity();
}
} | 32.411392 | 143 | 0.635618 | sys-bio |
59ac0db41ad97556f7b974340dacb1dac206a672 | 329 | cc | C++ | sdk/src/model/object/MultipartUpload.cc | volcengine/ve-tos-cpp-sdk | 3f18be2d924f69bf6271b4cc3bdd1b7a023e795f | [
"Apache-2.0"
] | null | null | null | sdk/src/model/object/MultipartUpload.cc | volcengine/ve-tos-cpp-sdk | 3f18be2d924f69bf6271b4cc3bdd1b7a023e795f | [
"Apache-2.0"
] | null | null | null | sdk/src/model/object/MultipartUpload.cc | volcengine/ve-tos-cpp-sdk | 3f18be2d924f69bf6271b4cc3bdd1b7a023e795f | [
"Apache-2.0"
] | null | null | null | #include "model/object/MultipartUpload.h"
#include "../src/external/json/json.hpp"
using namespace nlohmann;
void VolcengineTos::inner::MultipartUpload::fromJsonString(const std::string &input) {
auto j = json::parse(input);
j.at("Bucket").get_to(bucket_);
j.at("Key").get_to(key_);
j.at("UploadId").get_to(uploadID_);
} | 32.9 | 86 | 0.723404 | volcengine |
59ac6920998e09b663601f50562e2488a7452f28 | 1,171 | hpp | C++ | src/common/fix.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 10 | 2020-01-23T20:41:19.000Z | 2021-12-28T20:24:44.000Z | src/common/fix.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 22 | 2021-03-25T16:22:08.000Z | 2022-03-17T12:50:38.000Z | src/common/fix.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | null | null | null | #ifndef TIRO_COMMON_FIX_HPP
#define TIRO_COMMON_FIX_HPP
#include <utility>
namespace tiro {
/// Makes it possible to write recursive lambda functions.
///
/// In C++, lambda functions cannot refer to themselves by name, i.e.
/// they cannot be used to implement recursive functions.
/// The class `Fix` takes a lambda (or any other function object)
/// as an argument and creates a new function object that always
/// passes itself as the first argument.
/// This additional argument enables the function to refer to itself.
///
/// Example:
///
/// Fix fib = [](auto& self, int i) -> int {
/// if (i == 0)
/// return 0;
/// if (i == 1)
/// return 1;
/// return self(i - 2) + self(i - 1);
/// });
/// fib(42); // Works.
///
template<typename Function>
class Fix {
private:
Function fn_;
public:
Fix(const Function& fn)
: fn_(fn) {}
Fix(Function&& fn)
: fn_(std::move(fn)) {}
template<typename... Args>
decltype(auto) operator()(Args&&... args) const {
return fn_(*this, std::forward<Args>(args)...);
}
};
} // namespace tiro
#endif // TIRO_COMMON_FIX_HPP
| 23.897959 | 69 | 0.599488 | mbeckem |
59b3892ac77bbc7b1b37b94f2a04681a32bb4b2c | 7,228 | cpp | C++ | game/code/common/engine/math/matrix.cpp | justinctlam/MarbleStrike | 64fe36a5a4db2b299983b0e2556ab1cd8126259b | [
"MIT"
] | null | null | null | game/code/common/engine/math/matrix.cpp | justinctlam/MarbleStrike | 64fe36a5a4db2b299983b0e2556ab1cd8126259b | [
"MIT"
] | null | null | null | game/code/common/engine/math/matrix.cpp | justinctlam/MarbleStrike | 64fe36a5a4db2b299983b0e2556ab1cd8126259b | [
"MIT"
] | 2 | 2019-03-08T03:02:45.000Z | 2019-05-14T08:41:26.000Z | ////////////////////////////////////////////////////////
//// INCLUDES
////////////////////////////////////////////////////////
//
//#include "common/engine/math/matrix.hpp"
//#include "common/engine/system/assert.hpp"
//#include "common/engine/system/memory.hpp"
//#include "common/engine/system/utilities.hpp"
//#include "common/engine/math/gaussjordan.hpp"
//
////////////////////////////////////////////////////////
//// CLASS METHODS
////////////////////////////////////////////////////////
//
//namespace Math
//{
// void TransposeMatrix( int row, int col, float** matrix, float** transpose )
// {
// int transposeRow = col;
// int transposeCol = row;
// for ( int i = 0; i < transposeRow; i++ )
// {
// for ( int j = 0; j < transposeCol; j++ )
// {
// transpose[i][j] = matrix[j][i];
// }
// }
// }
//
// //===========================================================================
//
// void MultiplyMatrix( int row1, int col1, float** matrix1, int row2, int col2, float** matrix2, float** result )
// {
// if ( col1 == row2 )
// {
// for ( int r1 = 0; r1 < row1; r1++ )
// {
// for ( int c2 = 0; c2 < col2; c2++ )
// {
// result[r1][c2] = 0;
// float temp = result[r1][c2];
// for ( int n = 0; n < col1; n++ )
// {
// result[r1][c2] += matrix1[r1][n] * matrix2[n][c2];
// temp += matrix1[r1][n] * matrix2[n][c2];
// }
// }
// }
// }
// }
//
// //===========================================================================
//
// void SubtractMatrix( int row1, int col1, float** matrix1, int row2, int col2, float** matrix2, float** result )
// {
// if ( col1 == col2 && row1 == row2 )
// {
// for ( int r = 0; r < row1; r++ )
// {
// for ( int c = 0; c < col1; c++ )
// {
// result[r][c] = matrix1[r][c] - matrix2[r][c];
// }
// }
// }
// }
//
// //===========================================================================
//
// void VectorMultiply( const Math::Matrix& matrix, int vectorSize, float* vector, int resultSize, float* result )
// {
// if ( matrix.GetNumCols() == vectorSize && matrix.GetNumRows() == resultSize )
// {
// for ( int r = 0; r < matrix.GetNumRows(); r++ )
// {
// result[r] = 0;
// for ( int c = 0; c < matrix.GetNumCols(); c++ )
// {
// result[r] += matrix[r][c] * vector[c];
// }
// }
// }
// else
// {
// Assert( false, "" );
// }
// }
//
// //////////////////////////////////////////////////////
// // Matrix Row x Column Class Implementation
// //////////////////////////////////////////////////////
//
// Matrix::Matrix()
// : mNumRows( 0 ),
// mNumCols( 0 ),
// mData( NULL )
// {
// }
//
// //===========================================================================
//
// Matrix::Matrix( int rows, int cols )
// : mNumRows( 0 ),
// mNumCols( 0 ),
// mData( NULL )
// {
// Set( rows, cols );
// }
//
// //===========================================================================
//
// Matrix::Matrix( const Matrix &otherMatrix )
// : mNumRows( 0 ),
// mNumCols( 0 ),
// mData( NULL )
// {
// Copy( otherMatrix );
// }
//
// //===========================================================================
//
// Matrix::~Matrix()
// {
// Clean();
// }
//
// //===========================================================================
//
// void Matrix::Set( int rows, int cols )
// {
// Clean();
//
// mNumRows = rows;
// mNumCols = cols;
//
// mData = NEW_PTR( "Matrix Data 1" ) float*[mNumRows];
// for ( int r = 0; r < mNumRows; r++ )
// {
// mData[r] = NEW_PTR( "Matrix Data 2" ) float[mNumCols];
//
// for ( int c = 0; c < mNumCols; c++ )
// {
// mData[r][c] = 0.0f;
// }
// }
// }
//
// //===========================================================================
//
// void Matrix::SetIdentity()
// {
// if ( mNumRows == mNumCols )
// {
// for ( int r = 0; r < mNumRows; r++ )
// {
// for ( int c = 0; c < mNumCols; c++ )
// {
// if ( r == c )
// {
// mData[r][c] = 1.0f;
// }
// else
// {
// mData[r][c] = 0.0f;
// }
// }
// }
// }
// else
// {
// Assert( false, "Cannot set identity for non-square matrix.\n" );
// }
// }
//
// //===========================================================================
//
// Matrix& Matrix::operator=( const Matrix& otherMatrix )
// {
// //
// // Check for self assignment
// //
// if ( this != &otherMatrix )
// {
// Copy( otherMatrix );
// }
//
// return *this;
// }
//
// //===========================================================================
//
// Matrix Matrix::operator* ( const Matrix& m ) const
// {
// Matrix result( mNumRows, m.GetNumCols() );
// if ( mNumCols == m.GetNumRows() )
// {
// for ( int r1 = 0; r1 < mNumRows; r1++ )
// {
// for ( int c2 = 0; c2 < m.GetNumCols(); c2++ )
// {
// result[r1][c2] = 0;
// for ( int n = 0; n < mNumCols; n++ )
// {
// result[r1][c2] += mData[r1][n] * m[n][c2];
// }
// }
// }
// }
// else
// {
// Assert( false, "Cannot mutiply matrices\n" );
// }
//
// return result;
// }
//
// //===========================================================================
//
// void Matrix::PrintMatrix() const
// {
// System::PrintToConsole( "\n" );
//
// for ( int r = 0; r < mNumRows; r++ )
// {
// for ( int c = 0; c < mNumCols; c++ )
// {
// System::PrintToConsole( "%f ", mData[r][c] );
// }
// System::PrintToConsole( "\n" );
// }
// System::PrintToConsole( "\n" );
// }
//
// //===========================================================================
//
// Matrix Matrix::Transpose()
// {
// Matrix transpose( mNumCols, mNumRows );
// for ( int r = 0; r < transpose.GetNumRows(); r++ )
// {
// for ( int c = 0; c < transpose.GetNumCols(); c++ )
// {
// transpose[r][c] = mData[c][r];
// }
// }
//
// return transpose;
// }
//
// //===========================================================================
//
// Matrix Matrix::Inverse()
// {
// Matrix inverse( *this );
// if ( mNumRows == mNumCols )
// {
// Matrix identity( mNumCols, mNumRows );
// identity.SetIdentity();
//
// GaussJordan( inverse, mNumRows, identity, mNumRows );
// }
// else
// {
// Assert( false, "Cannot invert a non-square matrix.\n" );
// }
// return inverse;
// }
//
// //===========================================================================
//
// void Matrix::Copy( const Matrix &otherMatrix )
// {
// Clean();
//
// mNumRows = otherMatrix.GetNumRows();
// mNumCols = otherMatrix.GetNumCols();
//
// mData = NEW_PTR( "Matrix Data 1" ) float*[mNumRows];
// for ( int r = 0; r < mNumRows; r++ )
// {
// mData[r] = NEW_PTR( "Matrix Data 2" ) float[mNumCols];
// }
//
// for ( int r = 0; r < mNumRows; r++ )
// {
// for ( int c = 0; c < mNumCols; c++ )
// {
// mData[r][c] = otherMatrix[r][c];
// }
// }
// }
//
// //===========================================================================
//
// void Matrix::Clean()
// {
// for ( int r = 0; r < mNumRows; r++ )
// {
// DELETE_PTR_ARRAY( mData[r] );
// }
// DELETE_PTR_ARRAY( mData );
//
// mNumRows = 0;
// mNumCols = 0;
// }
//
//} | 23.543974 | 114 | 0.375484 | justinctlam |
59bb1f985a4264e2a094a4db98c4c4685b2409b3 | 5,059 | hpp | C++ | RX600/src.hpp | duybang140494/RX | 7fed06a9d8295f4504e8a08fa589d4a52792095f | [
"BSD-3-Clause"
] | 1 | 2020-01-16T03:38:30.000Z | 2020-01-16T03:38:30.000Z | RX600/src.hpp | duybang140494/RX | 7fed06a9d8295f4504e8a08fa589d4a52792095f | [
"BSD-3-Clause"
] | null | null | null | RX600/src.hpp | duybang140494/RX | 7fed06a9d8295f4504e8a08fa589d4a52792095f | [
"BSD-3-Clause"
] | null | null | null | #pragma once
//=====================================================================//
/*! @file
@brief RX600 グループ・SRC 定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
#include "common/device.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief サンプリングレートコンバータ(SRC)
@param[in] t ペリフェラル型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <peripheral t>
struct src_t {
//-----------------------------------------------------------------//
/*!
@brief 入力データレジスタ( SRCID )
*/
//-----------------------------------------------------------------//
static rw32_t<0x0009DFF0> SRCID;
//-----------------------------------------------------------------//
/*!
@brief 出力データレジスタ( SRCOD )
*/
//-----------------------------------------------------------------//
static rw32_t<0x0009DFF4> SRCOD;
//-----------------------------------------------------------------//
/*!
@brief 入力データ制御レジスタ( SRCIDCTRL )
@param[in] ofs オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct srcidctrl_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> IFTRG;
bit_rw_t< io_, bitpos::B8> IEN;
bit_rw_t< io_, bitpos::B9> IED;
};
static srcidctrl_t<0x0009DFF8> SRCIDCTRL;
//-----------------------------------------------------------------//
/*!
@brief 出力データ制御レジスタ( SRCODCTRL )
@param[in] ofs オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct srcodctrl_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> OFTRG;
bit_rw_t< io_, bitpos::B8> OEN;
bit_rw_t< io_, bitpos::B9> OED;
bit_rw_t< io_, bitpos::B10> OCH;
};
static srcodctrl_t<0x0009DFFA> SRCODCTRL;
//-----------------------------------------------------------------//
/*!
@brief 制御レジスタ( SRCCTRL )
@param[in] ofs オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct srcctrl_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bits_rw_t<io_, bitpos::B0, 2> OFS;
bits_rw_t<io_, bitpos::B4, 4> IFS;
bit_rw_t< io_, bitpos::B8> CL;
bit_rw_t< io_, bitpos::B9> FL;
bit_rw_t< io_, bitpos::B10> OVEN;
bit_rw_t< io_, bitpos::B11> UDEN;
bit_rw_t< io_, bitpos::B12> SRCEN;
bit_rw_t< io_, bitpos::B13> CEEN;
bit_rw_t< io_, bitpos::B15> FICRAE;
};
static srcctrl_t<0x0009DFFC> SRCCTRL;
//-----------------------------------------------------------------//
/*!
@brief ステータスレジスタ( SRCSTAT )
@param[in] ofs オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct srcstat_t : public rw16_t<ofs> {
typedef rw16_t<ofs> io_;
typedef ro16_t<ofs> ro_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t< io_, bitpos::B0> OINT;
bit_rw_t< io_, bitpos::B1> IINT;
bit_rw_t< io_, bitpos::B2> OVF;
bit_rw_t< io_, bitpos::B3> UDF;
bit_rw_t< ro_, bitpos::B4> ELF;
bit_rw_t< io_, bitpos::B5> CEF;
bits_rw_t<ro_, bitpos::B7, 4> OIFDN;
bits_rw_t<ro_, bitpos::B11, 5> OFDN;
};
static srcstat_t<0x0009DFFE> SRCSTAT;
//-----------------------------------------------------------------//
/*!
@brief フィルタ係数テーブル n ( SRCFCTRn )( n = 0 ~ 5551 )
@param[in] ofs オフセット
*/
//-----------------------------------------------------------------//
template <uint32_t ofs>
struct srcfctr_t {
uint32_t get(uint16_t idx) const { return rd32_(ofs + idx); }
void put(uint16_t idx, uint32_t val) { wr32_(ofs + idx, val); }
uint32_t operator() (uint16_t idx) const { return get(idx); }
// void operator[] (uint16_t idx) { put(idx, val); }
};
static srcfctr_t<0x00098000> SRCFCTR;
//-----------------------------------------------------------------//
/*!
@brief ペリフェラル型を返す
@return ペリフェラル型
*/
//-----------------------------------------------------------------//
static peripheral get_peripheral() { return t; }
};
typedef src_t<peripheral::SRC> SRC;
}
| 29.584795 | 75 | 0.426369 | duybang140494 |
59bbcc558f0645f6af83f3f8b5515150be75f2bc | 18,251 | cpp | C++ | engine/gui/Widgets.cpp | taida957789/ouzel | a8c1cc74e6151a0f7d7d2c534f8747cba46a36af | [
"Unlicense"
] | 1 | 2021-03-01T13:17:49.000Z | 2021-03-01T13:17:49.000Z | engine/gui/Widgets.cpp | taida957789/ouzel | a8c1cc74e6151a0f7d7d2c534f8747cba46a36af | [
"Unlicense"
] | null | null | null | engine/gui/Widgets.cpp | taida957789/ouzel | a8c1cc74e6151a0f7d7d2c534f8747cba46a36af | [
"Unlicense"
] | null | null | null | // Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#if defined(__APPLE__)
# include <TargetConditionals.h>
#endif
#include <algorithm>
#include <functional>
#include "Widgets.hpp"
#include "BMFont.hpp"
#include "../core/Engine.hpp"
#include "../events/EventHandler.hpp"
#include "../events/EventDispatcher.hpp"
#include "../math/Color.hpp"
#include "../scene/Layer.hpp"
#include "../scene/Camera.hpp"
namespace ouzel::gui
{
Button::Button():
eventHandler(EventHandler::priorityMax + 1)
{
eventHandler.uiHandler = std::bind(&Button::handleUI, this, std::placeholders::_1);
engine->getEventDispatcher().addEventHandler(eventHandler);
pickable = true;
}
Button::Button(const std::string& normalImage,
const std::string& selectedImage,
const std::string& pressedImage,
const std::string& disabledImage,
const std::string& label,
const std::string& font,
float fontSize,
Color initLabelColor,
Color initLabelSelectedColor,
Color initLabelPressedColor,
Color initLabelDisabledColor):
eventHandler(EventHandler::priorityMax + 1),
labelColor(initLabelColor),
labelSelectedColor(initLabelSelectedColor),
labelPressedColor(initLabelPressedColor),
labelDisabledColor(initLabelDisabledColor)
{
eventHandler.uiHandler = std::bind(&Button::handleUI, this, std::placeholders::_1);
engine->getEventDispatcher().addEventHandler(eventHandler);
if (!normalImage.empty())
{
normalSprite = std::make_unique<scene::SpriteRenderer>();
normalSprite->init(normalImage);
addComponent(*normalSprite);
}
if (!selectedImage.empty())
{
selectedSprite = std::make_unique<scene::SpriteRenderer>();
selectedSprite->init(selectedImage);
addComponent(*selectedSprite);
}
if (!pressedImage.empty())
{
pressedSprite = std::make_unique<scene::SpriteRenderer>();
pressedSprite->init(pressedImage);
addComponent(*pressedSprite);
}
if (!disabledImage.empty())
{
disabledSprite = std::make_unique<scene::SpriteRenderer>();
disabledSprite->init(disabledImage);
addComponent(*disabledSprite);
}
if (!label.empty())
{
labelDrawable = std::make_unique<scene::TextRenderer>(font, fontSize, label);
labelDrawable->setColor(labelColor);
addComponent(*labelDrawable);
}
pickable = true;
updateSprite();
}
void Button::setEnabled(bool newEnabled)
{
Widget::setEnabled(newEnabled);
selected = false;
pointerOver = false;
pressed = false;
updateSprite();
}
void Button::setSelected(bool newSelected)
{
Widget::setSelected(newSelected);
updateSprite();
}
bool Button::handleUI(const UIEvent& event)
{
if (!enabled) return false;
if (event.actor == this)
{
switch (event.type)
{
case Event::Type::actorEnter:
{
pointerOver = true;
updateSprite();
break;
}
case Event::Type::actorLeave:
{
pointerOver = false;
updateSprite();
break;
}
case Event::Type::actorPress:
{
pressed = true;
updateSprite();
break;
}
case Event::Type::actorRelease:
case Event::Type::actorClick:
{
if (pressed)
{
pressed = false;
updateSprite();
}
break;
}
default:
return false;
}
}
return false;
}
void Button::updateSprite()
{
if (normalSprite) normalSprite->setHidden(true);
if (selectedSprite) selectedSprite->setHidden(true);
if (pressedSprite) pressedSprite->setHidden(true);
if (disabledSprite) disabledSprite->setHidden(true);
if (enabled)
{
if (pressed && pointerOver && pressedSprite)
pressedSprite->setHidden(false);
else if (selected && selectedSprite)
selectedSprite->setHidden(false);
else if (normalSprite)
normalSprite->setHidden(false);
if (labelDrawable)
{
if (pressed && pointerOver)
labelDrawable->setColor(labelPressedColor);
else if (selected)
labelDrawable->setColor(labelSelectedColor);
else
labelDrawable->setColor(labelColor);
}
}
else // disabled
{
if (disabledSprite)
disabledSprite->setHidden(false);
else if (normalSprite)
normalSprite->setHidden(false);
if (labelDrawable)
labelDrawable->setColor(labelDisabledColor);
}
}
CheckBox::CheckBox(const std::string& normalImage,
const std::string& selectedImage,
const std::string& pressedImage,
const std::string& disabledImage,
const std::string& tickImage):
eventHandler(EventHandler::priorityMax + 1)
{
eventHandler.uiHandler = std::bind(&CheckBox::handleUI, this, std::placeholders::_1);
engine->getEventDispatcher().addEventHandler(eventHandler);
if (!normalImage.empty())
{
normalSprite = std::make_unique<scene::SpriteRenderer>();
normalSprite->init(normalImage);
addComponent(*normalSprite);
}
if (!selectedImage.empty())
{
selectedSprite = std::make_unique<scene::SpriteRenderer>();
selectedSprite->init(selectedImage);
addComponent(*selectedSprite);
}
if (!pressedImage.empty())
{
pressedSprite = std::make_unique<scene::SpriteRenderer>();
pressedSprite->init(pressedImage);
addComponent(*pressedSprite);
}
if (!disabledImage.empty())
{
disabledSprite = std::make_unique<scene::SpriteRenderer>();
disabledSprite->init(disabledImage);
addComponent(*disabledSprite);
}
if (!tickImage.empty())
{
tickSprite = std::make_unique<scene::SpriteRenderer>();
tickSprite->init(tickImage);
addComponent(*tickSprite);
}
pickable = true;
updateSprite();
}
void CheckBox::setEnabled(bool newEnabled)
{
Widget::setEnabled(newEnabled);
selected = false;
pointerOver = false;
pressed = false;
updateSprite();
}
void CheckBox::setChecked(bool newChecked)
{
checked = newChecked;
updateSprite();
}
bool CheckBox::handleUI(const UIEvent& event)
{
if (!enabled) return false;
if (event.actor == this)
{
switch (event.type)
{
case Event::Type::actorEnter:
{
pointerOver = true;
updateSprite();
break;
}
case Event::Type::actorLeave:
{
pointerOver = false;
updateSprite();
break;
}
case Event::Type::actorPress:
{
pressed = true;
updateSprite();
break;
}
case Event::Type::actorRelease:
{
if (pressed)
{
pressed = false;
updateSprite();
}
break;
}
case Event::Type::actorClick:
{
pressed = false;
checked = !checked;
updateSprite();
auto changeEvent = std::make_unique<UIEvent>();
changeEvent->type = Event::Type::widgetChange;
changeEvent->actor = event.actor;
engine->getEventDispatcher().dispatchEvent(std::move(changeEvent));
break;
}
default:
return false;
}
}
return false;
}
void CheckBox::updateSprite()
{
if (enabled)
{
if (pressed && pointerOver && pressedSprite)
pressedSprite->setHidden(false);
else if (selected && selectedSprite)
selectedSprite->setHidden(false);
else if (normalSprite)
normalSprite->setHidden(false);
}
else
{
if (disabledSprite)
disabledSprite->setHidden(false);
else if (normalSprite)
normalSprite->setHidden(false);
}
if (tickSprite)
tickSprite->setHidden(!checked);
}
ComboBox::ComboBox()
{
pickable = true;
}
EditBox::EditBox()
{
pickable = true;
}
void EditBox::setValue(const std::string& newValue)
{
value = newValue;
}
Label::Label(const std::string& initText,
const std::string& fontFile,
float fontSize,
Color color,
const Vector2F& textAnchor):
text(initText),
labelDrawable(std::make_shared<scene::TextRenderer>(fontFile, fontSize, text, color, textAnchor))
{
addComponent(*labelDrawable);
labelDrawable->setText(text);
pickable = true;
}
void Label::setText(const std::string& newText)
{
text = newText;
labelDrawable->setText(text);
}
Menu::Menu():
eventHandler(EventHandler::priorityMax + 1)
{
eventHandler.keyboardHandler = std::bind(&Menu::handleKeyboard, this, std::placeholders::_1);
eventHandler.gamepadHandler = std::bind(&Menu::handleGamepad, this, std::placeholders::_1);
eventHandler.uiHandler = std::bind(&Menu::handleUI, this, std::placeholders::_1);
}
void Menu::enter()
{
engine->getEventDispatcher().addEventHandler(eventHandler);
}
void Menu::leave()
{
eventHandler.remove();
}
void Menu::setEnabled(bool newEnabled)
{
Widget::setEnabled(newEnabled);
if (enabled)
{
if (!selectedWidget && !widgets.empty())
selectWidget(widgets.front());
}
else
{
selectedWidget = nullptr;
for (Widget* childWidget : widgets)
childWidget->setSelected(false);
}
}
void Menu::addWidget(Widget& widget)
{
addChild(widget);
if (widget.menu)
widget.menu->removeChild(widget);
widget.menu = this;
widgets.push_back(&widget);
if (!selectedWidget)
selectWidget(&widget);
}
bool Menu::removeChild(const Actor& actor)
{
const auto i = std::find(widgets.begin(), widgets.end(), &actor);
if (i != widgets.end())
{
Widget* widget = *i;
widget->menu = nullptr;
widgets.erase(i);
}
if (selectedWidget == &actor)
selectWidget(nullptr);
if (!Actor::removeChild(actor))
return false;
return true;
}
void Menu::selectWidget(Widget* widget)
{
if (!enabled) return;
selectedWidget = nullptr;
for (Widget* childWidget : widgets)
{
if (childWidget == widget)
{
selectedWidget = widget;
childWidget->setSelected(true);
}
else
childWidget->setSelected(false);
}
}
void Menu::selectNextWidget()
{
if (!enabled) return;
auto firstWidgetIterator = selectedWidget ?
std::find(widgets.begin(), widgets.end(), selectedWidget) :
widgets.end();
auto widgetIterator = firstWidgetIterator;
do
{
if (widgetIterator == widgets.end())
widgetIterator = widgets.begin();
else
++widgetIterator;
if (widgetIterator != widgets.end() && (*widgetIterator)->isEnabled())
{
selectWidget(*widgetIterator);
break;
}
}
while (widgetIterator != firstWidgetIterator);
}
void Menu::selectPreviousWidget()
{
if (!enabled) return;
const auto firstWidgetIterator = selectedWidget ?
std::find(widgets.begin(), widgets.end(), selectedWidget) :
widgets.end();
auto widgetIterator = firstWidgetIterator;
do
{
if (widgetIterator == widgets.begin()) widgetIterator = widgets.end();
if (widgetIterator != widgets.begin()) --widgetIterator;
if (widgetIterator != widgets.end() && (*widgetIterator)->isEnabled())
{
selectWidget(*widgetIterator);
break;
}
}
while (widgetIterator != firstWidgetIterator);
}
bool Menu::handleKeyboard(const KeyboardEvent& event)
{
if (!enabled) return false;
if (event.type == Event::Type::keyboardKeyPress && !widgets.empty())
{
switch (event.key)
{
case input::Keyboard::Key::left:
case input::Keyboard::Key::up:
selectPreviousWidget();
break;
case input::Keyboard::Key::right:
case input::Keyboard::Key::down:
selectNextWidget();
break;
case input::Keyboard::Key::enter:
case input::Keyboard::Key::space:
case input::Keyboard::Key::select:
{
if (selectedWidget)
{
auto clickEvent = std::make_unique<UIEvent>();
clickEvent->type = Event::Type::actorClick;
clickEvent->actor = selectedWidget;
clickEvent->position = Vector2F(selectedWidget->getPosition());
engine->getEventDispatcher().dispatchEvent(std::move(clickEvent));
}
break;
}
default:
break;
}
}
return false;
}
bool Menu::handleGamepad(const GamepadEvent& event)
{
if (!enabled) return false;
if (event.type == Event::Type::gamepadButtonChange)
{
if (event.button == input::Gamepad::Button::dPadLeft ||
event.button == input::Gamepad::Button::dPadUp)
{
if (!event.previousPressed && event.pressed) selectPreviousWidget();
}
else if (event.button == input::Gamepad::Button::dPadRight ||
event.button == input::Gamepad::Button::dPadDown)
{
if (!event.previousPressed && event.pressed) selectNextWidget();
}
else if (event.button == input::Gamepad::Button::leftThumbLeft ||
event.button == input::Gamepad::Button::leftThumbUp)
{
if (event.previousValue < 0.6F && event.value > 0.6F) selectPreviousWidget();
}
else if (event.button == input::Gamepad::Button::leftThumbRight ||
event.button == input::Gamepad::Button::leftThumbDown)
{
if (event.previousValue < 0.6F && event.value > 0.6F) selectNextWidget();
}
#if !defined(__APPLE__) || (!TARGET_OS_IOS && !TARGET_OS_TV) // on iOS and tvOS menu items ar selected with a SELECT button
else if (event.button == input::Gamepad::Button::faceBottom)
{
if (!event.previousPressed && event.pressed && selectedWidget)
{
auto clickEvent = std::make_unique<UIEvent>();
clickEvent->type = Event::Type::actorClick;
clickEvent->actor = selectedWidget;
clickEvent->position = Vector2F(selectedWidget->getPosition());
engine->getEventDispatcher().dispatchEvent(std::move(clickEvent));
}
}
#endif
}
return false;
}
bool Menu::handleUI(const UIEvent& event)
{
if (!enabled) return false;
if (event.type == Event::Type::actorEnter)
if (std::find(widgets.begin(), widgets.end(), event.actor) != widgets.end())
selectWidget(static_cast<Widget*>(event.actor));
return false;
}
RadioButton::RadioButton()
{
pickable = true;
}
void RadioButton::setEnabled(bool newEnabled)
{
Widget::setEnabled(newEnabled);
selected = false;
pointerOver = false;
pressed = false;
}
void RadioButton::setChecked(bool newChecked)
{
checked = newChecked;
}
RadioButtonGroup::RadioButtonGroup()
{
}
ScrollArea::ScrollArea()
{
}
ScrollBar::ScrollBar()
{
pickable = true;
}
SlideBar::SlideBar()
{
pickable = true;
}
}
| 28.606583 | 123 | 0.508958 | taida957789 |
59bc0a74db0ec01862fd96606385adfbb287e688 | 606 | cpp | C++ | PML/Renderer/Mesh.cpp | NickAOndo/PML | bcb228d012ffc99a4701afed5a05692df85c1ffa | [
"MIT"
] | null | null | null | PML/Renderer/Mesh.cpp | NickAOndo/PML | bcb228d012ffc99a4701afed5a05692df85c1ffa | [
"MIT"
] | null | null | null | PML/Renderer/Mesh.cpp | NickAOndo/PML | bcb228d012ffc99a4701afed5a05692df85c1ffa | [
"MIT"
] | null | null | null | /*******************************************************************
** Author: Nicholas Ondo
** License: MIT
** Description: DEPRECATED. Template-class, src in header only.
*******************************************************************/
#include "PML/Renderer/Mesh.h"
#include <iostream> // STL
#include <vector>
#include <glm/glm.hpp> // Middleware
#include <GL/glew.h>
#include "PML/Renderer/XBObuffer.h"
#include "PML/Renderer/MeshXBO.h"
namespace pm {
MeshAdapter::MeshAdapter()
{}
MeshAdapter::~MeshAdapter()
{}
MeshAdapter::MeshAdapter(const MeshAdapter& other)
{}
} // namespace pm
| 24.24 | 68 | 0.551155 | NickAOndo |
59bdf98b722003e92ff6cb50555881c6d0d68b0c | 5,675 | hpp | C++ | oddgravitysdk/controls/TreePropSheetEx/TreePropSheetUtil.hpp | mschulze46/PlaylistCreator | d1fb60c096eecb816f469754cada3e5c8901157b | [
"MIT"
] | 1 | 2020-05-18T13:47:35.000Z | 2020-05-18T13:47:35.000Z | oddgravitysdk/controls/TreePropSheetEx/TreePropSheetUtil.hpp | mschulze46/PlaylistCreator | d1fb60c096eecb816f469754cada3e5c8901157b | [
"MIT"
] | null | null | null | oddgravitysdk/controls/TreePropSheetEx/TreePropSheetUtil.hpp | mschulze46/PlaylistCreator | d1fb60c096eecb816f469754cada3e5c8901157b | [
"MIT"
] | null | null | null | // TreePropSheetUtil.hpp
//
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2004 by Yves Tkaczyk
// (http://www.tkaczyk.net - yves@tkaczyk.net)
//
// The contents of this file are subject to the Artistic License (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.opensource.org/licenses/artistic-license.html
//
// Documentation: http://www.codeproject.com/property/treepropsheetex.asp
// CVS tree: http://sourceforge.net/projects/treepropsheetex
//
/////////////////////////////////////////////////////////////////////////////
#ifndef _TREEPROPSHEET_TREEPROPSHEETUTIL_HPP__INCLUDED_
#define _TREEPROPSHEET_TREEPROPSHEETUTIL_HPP__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
namespace TreePropSheet
{
//////////////////////////////////////////////////////////////////////
/*! \brief Scope class that prevent control redraw.
This class prevents update of a window by sending WM_SETREDRAW.
@author Yves Tkaczyk (yves@tkaczyk.net)
@date 04/2004 */
class CWindowRedrawScope
{
// Construction/Destruction
public:
//@{
/*!
@param hWnd Handle of window for which update should be disabled.
@param bInvalidateOnUnlock Flag indicating if window should be
invalidating after update is re-enabled. */
CWindowRedrawScope(HWND hWnd, const bool bInvalidateOnUnlock)
: m_hWnd(hWnd),
m_bInvalidateOnUnlock(bInvalidateOnUnlock)
{
::SendMessage(m_hWnd, WM_SETREDRAW, (WPARAM)FALSE, 0L);
}
/*!
@param pWnd Window for which update should be disabled.
@param bInvalidateOnUnlock Flag indicating if window should be
invalidating after update is re-enabled. */
CWindowRedrawScope(CWnd* pWnd, const bool bInvalidateOnUnlock)
: m_hWnd(pWnd->GetSafeHwnd()),
m_bInvalidateOnUnlock(bInvalidateOnUnlock)
{
::SendMessage(m_hWnd, WM_SETREDRAW, (WPARAM)FALSE, 0L);
}
//@}
~CWindowRedrawScope()
{
::SendMessage(m_hWnd, WM_SETREDRAW, (WPARAM)TRUE, 0L);
if( m_bInvalidateOnUnlock )
{
::InvalidateRect(m_hWnd, NULL, TRUE);
}
}
// Members
private:
/*! Handle of the window for which update should be disabled and enabled. */
HWND m_hWnd;
/*! Flag indicating if window should be invalidating after update is re-enabled. */
const bool m_bInvalidateOnUnlock;
};
//////////////////////////////////////////////////////////////////////
/*! \brief Scope class incrementing the provided value.
This class increments the provided value in its contructor and
decrement in destructor.
@author Yves Tkaczyk (yves@tkaczyk.net)
@date 04/2004 */
class CIncrementScope
{
// Construction/Destruction
public:
/*!
@param rValue Reference to value to be manipulated.
*/
CIncrementScope(int& rValue)
: m_value(rValue)
{
++m_value;
}
~CIncrementScope()
{
--m_value;
}
// Members
private:
/*! Value to be manipulated. */
int& m_value;
};
//////////////////////////////////////////////////////////////////////
/*! \brief Helper class for managing background in property page.
This class simply manage a state that can be used by each property
page to determine how the background should be drawn.
@author Yves Tkaczyk (yves@tkaczyk.net)
@date 09/2004 */
class CWhiteBackgroundProvider
{
// Construction/Destruction
public:
CWhiteBackgroundProvider()
: m_bHasWhiteBackground(false)
{
}
protected:
~CWhiteBackgroundProvider()
{
}
// Methods
public:
void SetHasWhiteBackground(const bool bHasWhiteBackground)
{
m_bHasWhiteBackground = bHasWhiteBackground;
}
bool HasWhiteBackground() const
{
return m_bHasWhiteBackground;
}
//Members
private:
/*! Flag indicating background drawing state. */
bool m_bHasWhiteBackground;
};
//////////////////////////////////////////////////////////////////////
/* \brief Expand/Collapse items in tree.
ExpandTreeItem expand or collapse all the tree items under the provided
tree item.
@param pTree THe tree control.
@param htiThe tree item from which the operation is applied.
@param nCode Operation code:
- <pre>TVE_COLLAPSE</pre> Collapses the list.
- <pre>TVE_COLLAPSERESET</pre> Collapses the list and removes the child items.
- <pre>TVE_EXPAND</pre> Expands the list.
- <pre>TVE_TOGGLE</pre> Collapses the list if it is currently expanded or expands it if it is currently collapsed.
@author Yves Tkaczyk (yves@tkaczyk.net)
@date 09/2004
*/
template<typename Tree>
void ExpandTreeItem(Tree* pTree, HTREEITEM hti, UINT nCode)
{
bool bOk= true;
bOk= pTree->Expand(hti, nCode) != 0;
if (bOk)
{
HTREEITEM htiChild= pTree->GetChildItem(hti);
while (htiChild != NULL)
{
ExpandTreeItem(pTree, htiChild, nCode);
htiChild= pTree->GetNextSiblingItem(htiChild);
}
}
HTREEITEM htiSibling = pTree->GetNextSiblingItem(hti);
if( htiSibling )
{
ExpandTreeItem(pTree, htiSibling, nCode);
}
}
};
#endif // _TREEPROPSHEET_TREEPROPSHEETUTIL_HPP__INCLUDED_ | 28.375 | 133 | 0.589427 | mschulze46 |
59be498c6a255456a19ff2dc7270c16f97f49060 | 2,096 | cpp | C++ | Competitive Programming/USACO/2014GuardMark.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 3 | 2018-12-18T13:39:42.000Z | 2021-06-23T18:05:18.000Z | Competitive Programming/USACO/2014GuardMark.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 1 | 2018-11-02T21:32:40.000Z | 2018-11-02T22:47:12.000Z | Competitive Programming/USACO/2014GuardMark.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 6 | 2018-10-27T14:07:52.000Z | 2019-11-14T13:49:29.000Z | #include <bits/stdc++.h>
#define lli long long int
using namespace std;
/* Tutorial:
The first thing to notice is that there's an optimal order for the cows
This order will allow us to use a greedy strategy
c[i].w + c[i].s > c[i+1].w + c[i+1].s, for all i
It's proven that following this order, you will be able to put
the maximum amount of cows on top of each order. Of course which cow
will be discarted isn't known, but they sure will follow this order
Now, we can try every possible set of cows using bitmask
The bitmask will be an integer, where the i-th bit represents wheter
or not the i-th cow is present in that set
memo[bitmask] will store the minimum strenght available, set all to inf
for every bitmask in [1, (1 << n) - 1]:
height = 0
for j in [0, n - 1]: (remember this is the optimal order)
if (j-th cow is present in bitmask and c[j].w <= memo[bitmask]):
memo[bitmask] = min(memo[bitmask] - c[j].w, c[j].s)
height += c[j].h
if (height >= H): ans = max(ans, memo[bitmask])
*/
const int maxN = 20; int n; lli H;
const lli inf = 1e18;
struct Cow
{
lli height, weight, strength;
bool operator<(const Cow &c) const { return(weight + strength < c.weight + c.strength); }
};
Cow cows[maxN];
lli memo[1 << maxN];
int main()
{
FILE *input = fopen("guard.in", "rb");
FILE *output = fopen("guard.out", "wb");
fscanf(input, "%d %lld", &n, &H);
for (int i = 0; i < n; i ++)
fscanf(input, "%lld %lld %lld", &cows[i].height, &cows[i].weight, &cows[i].strength);
sort(cows, cows+n); reverse(cows, cows+n);
lli ans = -1;
for (int bitmask = 1, end = 1 << n; bitmask < end; bitmask ++)
{
memo[bitmask] = inf; lli height = 0;
for (int j = 0; j < n; j ++)
if ((bitmask & (1 << j)) && cows[j].weight <= memo[bitmask])
memo[bitmask] = min(memo[bitmask] - cows[j].weight, cows[j].strength), height += cows[j].height;
if (height >= H) ans = max(ans, memo[bitmask]);
}
if (ans == -1) fprintf(output, "Mark is too tall\n");
else fprintf(output, "%lld\n", ans);
return(0);
} | 34.933333 | 104 | 0.617844 | NelsonGomesNeto |
59bfd68b1a341f6732aee395051546d10a3af2ea | 6,929 | cpp | C++ | Source/SpaceHorror/Private/MasterWeapons.cpp | littlefalcon/ISS_Columbus | f4192d19a0350553de317041ec1c17aa280dc1d0 | [
"MIT"
] | null | null | null | Source/SpaceHorror/Private/MasterWeapons.cpp | littlefalcon/ISS_Columbus | f4192d19a0350553de317041ec1c17aa280dc1d0 | [
"MIT"
] | null | null | null | Source/SpaceHorror/Private/MasterWeapons.cpp | littlefalcon/ISS_Columbus | f4192d19a0350553de317041ec1c17aa280dc1d0 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 LittleFalcon.
#include "MasterWeapons.h"
#include "FireMechanicAuto.h" // Handle Automatic Mechanic for Weapon
#include "FireMechanicBeam.h" // Handle Beam Mechanic for Weapon
#include "FireMechanicCharge.h" // Handle Charge Mechanic for Weapon
#include "Animation/AnimInstance.h" // Handle SkeletalMesh
#include "Kismet/GameplayStatics.h" //Handle Particle / Sound
#include "SpaceHorrorProjectile.h" //Handle Projectile Bullet /TODO make this class itself
#include "Runtime/Engine/Classes/Particles/Emitter.h" // beam weapon
// Sets default values
AMasterWeapons::AMasterWeapons(){
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
//Create Inherit Class TODO Create Inherit Class to same with Weapontype
FireMechanicAuto = CreateDefaultSubobject<UFireMechanicAuto>(FName("FireMechanicAuto"));
FireMechanicBeam = CreateDefaultSubobject<UFireMechanicBeam>(FName("FireMechanicBeam"));
//TODO Set only player see
Weapon = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Weapon"));
Weapon->SetOnlyOwnerSee(true); // only the owning player will see this mesh
Weapon->bCastDynamicShadow = false;
Weapon->CastShadow = false;
}
// Called when the game starts or when spawned
void AMasterWeapons::BeginPlay()
{
Super::BeginPlay();
if (BP_Beam != nullptr) {
UE_LOG(LogTemp, Log, TEXT("Beam Found"));
}
else
{
UE_LOG(LogTemp, Log, TEXT("Beam Not Found"));
}
//Attach to BP_FirstPersonCharacter
//attach
//Check what weapon mechanic in this instance
updateWeaponMechanic(WeaponMechanic);
currentAmmo = magazineCapacity; //TODO sync to upgrade class
uCurrentAmmo = currentAmmo;
uMaxAmmo = currentBattery;
}
// Called every frame
void AMasterWeapons::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
//Check Weapon Mechanic of this Weapon Blueprint
void AMasterWeapons::updateWeaponMechanic(EWeaponMechanic WeaponMechanic) {
switch (WeaponMechanic)
{
case EWeaponMechanic::BEAM:
UE_LOG(LogTemp, Log, TEXT("(%s)WP - Beam"), *GetName());
FireMechanicAuto->IsHoldingThisWeapon = false;
break;
case EWeaponMechanic::SEMI:
if (FireMechanicAuto != nullptr) {
UE_LOG(LogTemp, Log, TEXT("(%s)WP - SemiAutomatic"), *GetName());
FireMechanicAuto->IsHoldingThisWeapon = true;
FireMechanicAuto->bSemiMechanic = true;
}
else {
UE_LOG(LogTemp, Error, TEXT("(%s)WP - SemiAutomatic NOT FOUND"), *GetName());
}
break;
case EWeaponMechanic::AUTO:
if (FireMechanicAuto != nullptr) {
UE_LOG(LogTemp, Log, TEXT("(%s)WP - Automatic"));
FireMechanicAuto->IsHoldingThisWeapon = true;
FireMechanicAuto->bSemiMechanic = false;
}else{
UE_LOG(LogTemp, Error, TEXT("(%s)WP - Automatic NOT FOUND"),*GetName());
}
break;
case EWeaponMechanic::CHRG:
UE_LOG(LogTemp, Warning, TEXT("(%s)WP - Charge"), *GetName());
break;
}
}
///FUNCTION
void AMasterWeapons::soundFire() {
if (muzzleParticle == nullptr) {
UE_LOG(LogTemp, Error, TEXT("muzzleParticle Not Assign!"));
}
if (Weapon == nullptr) {
UE_LOG(LogTemp, Error, TEXT("Weapon Not Assign!"));
}
if (weaponSound == nullptr) {
UE_LOG(LogTemp, Error, TEXT("weaponSound Not Assign!"));
}
if (muzzleParticle != nullptr && Weapon != nullptr && weaponSound != nullptr) {
UGameplayStatics::PlaySoundAtLocation(this, weaponSound, Weapon->GetSocketLocation(TEXT("Muzzle")), 1, 1, 0, nullptr, nullptr);
}
else {
UE_LOG(LogTemp, Error, TEXT("Some Actor Not Assign!"));
}
}
void AMasterWeapons::spawnParticleMuzzle()
{
if (muzzleParticle != nullptr && Weapon != nullptr && weaponSound != nullptr) {
UGameplayStatics::SpawnEmitterAtLocation(this, muzzleParticle, Weapon->GetSocketLocation(TEXT("Muzzle")), FRotator::ZeroRotator, FVector::OneVector, true);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Some Actor Not Assign!"));
}
}
void AMasterWeapons::EsetCurrentAmmo(int NewAmmo) {
setCurrentAmmo(NewAmmo);
}
void AMasterWeapons::spawnProjectileBullet() {
if (Weapon == nullptr) { return; }
if (ProjectileClass != NULL)
{
UWorld* const World = GetWorld();
if (World != NULL)
{
FRotator SpawnRotation = Weapon->GetSocketRotation(TEXT("Muzzle"));
//SpawnRotation. += 90;
// MuzzleOffset is in camera space, so transform it to world space before offsetting from the character location to find the final muzzle position
//const FVector SpawnLocation = (this->GetActorForwardVector() * 2000) + Weapon->GetSocketLocation(TEXT("Muzzle"));;
const FVector SpawnLocation = Weapon->GetSocketLocation(TEXT("Muzzle"));
//const FVector SpawnLocation = ((FP_MuzzleLocation != nullptr) ? FP_MuzzleLocation->GetComponentLocation() : GetActorLocation()) + SpawnRotation.RotateVector(GunOffset);
//Set Spawn Collision Handling Override
FActorSpawnParameters ActorSpawnParams;
ActorSpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButDontSpawnIfColliding;
// spawn the projectile at the muzzle
World->SpawnActor<ASpaceHorrorProjectile>(ProjectileClass, SpawnLocation, SpawnRotation, ActorSpawnParams);
}
}
}
void AMasterWeapons::decreaseAmmo(int amount) { //TODO Clamp amount
if (currentAmmo == 0) {
return;
}
else
{
currentAmmo -= amount;
uCurrentAmmo = currentAmmo;
}
}
void AMasterWeapons::inceaseAmmo(int amount) {
currentAmmo += amount;
uCurrentAmmo = currentAmmo;
}
bool AMasterWeapons::IsAmmoDepleted() {
if (currentAmmo == 0) {
return true;
}
else
{
return false;
}
}
///Set Method
void AMasterWeapons::setCurrentBattery(int newcurrentbattery)
{
uMaxAmmo = newcurrentbattery;
currentBattery = newcurrentbattery;
}
void AMasterWeapons::setCurrentAmmo(int newcurrentammo)
{
currentAmmo = newcurrentammo;
}
///Get Method
int AMasterWeapons::getWeaponSlot(){
return weaponSlot;
}
int AMasterWeapons::getCurrentAmmo()
{
return currentAmmo;
}
float AMasterWeapons::getFireRate()
{
return fireRate;
}
int AMasterWeapons::getBaseDamage() {
return fireDamage;
}
int AMasterWeapons::getMagazineCapacity()
{
return magazineCapacity;
}
int AMasterWeapons::getBatteryConsume()
{
return batteryConsume;
}
int AMasterWeapons::getBatteryCapacity()
{
return batteryCapacity;
}
float AMasterWeapons::getReloadTime()
{
return reloadTime;
}
float AMasterWeapons::getRecoil()
{
return recoil;
}
float AMasterWeapons::getControl()
{
return control;
}
int AMasterWeapons::getAccuracy()
{
return accuracy;
}
int AMasterWeapons::getFireRange()
{
return fireRange;
}
int AMasterWeapons::getCurrentBattery()
{
return currentBattery;
}
EWeaponMechanic AMasterWeapons::getWeaponMechanic() {
return WeaponMechanic;
}
FVector AMasterWeapons::getWeaponMuzzlePosition() {
if (Weapon == nullptr) { return FVector(0); }
return Weapon->GetSocketLocation(TEXT("Muzzle"));
}
FVector AMasterWeapons::getWeaponForward() {
return Weapon->GetForwardVector();
}
| 25.662963 | 173 | 0.7408 | littlefalcon |
59c2cf047b4d98a9b75b73a7b01f44f8e7dca9d2 | 835 | cpp | C++ | problems/add_strings/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/add_strings/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/add_strings/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.size() - 1;
int n2 = num2.size() - 1;
int sum, carry = 0;
auto add = [&](int a, int b) {
sum = a + b + carry;
carry = sum / 10;
sum -= 10 * carry;
};
string ans;
while (n1 >= 0 && n2 >= 0) {
add(num1[n1] - '0', num2[n2] - '0');
ans += sum + '0';
n1--, n2--;
}
while (n1 >= 0) {
add(num1[n1] - '0', 0);
ans += sum + '0';
n1--;
}
while (n2 >= 0) {
add(num2[n2] - '0', 0);
ans += sum + '0';
n2--;
}
if (carry) ans += carry + '0';
reverse(ans.begin(), ans.end());
return ans;
}
}; | 26.09375 | 49 | 0.347305 | sauravchandra1 |
59c4ac56f7c757e9e516594bc026bdd4ba25ffe6 | 305 | cpp | C++ | RVTuto1/main.cpp | josnelihurt/qt-3d-cube | 1abc8b36ee23f9137a8ddaae115e0067367f18bf | [
"Unlicense"
] | null | null | null | RVTuto1/main.cpp | josnelihurt/qt-3d-cube | 1abc8b36ee23f9137a8ddaae115e0067367f18bf | [
"Unlicense"
] | null | null | null | RVTuto1/main.cpp | josnelihurt/qt-3d-cube | 1abc8b36ee23f9137a8ddaae115e0067367f18bf | [
"Unlicense"
] | null | null | null | // Cours de Réalité Virtuelle
// leo.donati@univ-cotedazur.fr
//
// EPU 2019-20
//
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("Réalité Virtuelle: Tuto1");
w.show();
return a.exec();
}
| 16.944444 | 49 | 0.652459 | josnelihurt |
59c4ad9b4b49e643275f5a8aa0b405e17fe9fd04 | 2,350 | hpp | C++ | Util/std_hash.hpp | cypox/devacus-backend | ba3d2ca8d72843560c4ff754780482dfe8a67c6b | [
"BSD-2-Clause"
] | 1 | 2015-03-16T12:49:12.000Z | 2015-03-16T12:49:12.000Z | Util/std_hash.hpp | antoinegiret/osrm-backend | ebe34da5428c2bfdb2b227392248011c757822e5 | [
"BSD-2-Clause"
] | 1 | 2015-02-25T18:27:19.000Z | 2015-02-25T18:27:19.000Z | Util/std_hash.hpp | antoinegiret/osrm-backend | ebe34da5428c2bfdb2b227392248011c757822e5 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
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.
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.
*/
#ifndef STD_HASH_HPP
#define STD_HASH_HPP
#include <functional>
// this is largely inspired by boost's hash combine as can be found in
// "The C++ Standard Library" 2nd Edition. Nicolai M. Josuttis. 2012.
namespace {
template<typename T>
void hash_combine(std::size_t &seed, const T& val)
{
seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template<typename T>
void hash_val(std::size_t &seed, const T& val)
{
hash_combine(seed, val);
}
template<typename T, typename ... Types>
void hash_val(std::size_t &seed, const T& val, const Types& ... args)
{
hash_combine(seed, val);
hash_val(seed, args ...);
}
template<typename ... Types>
std::size_t hash_val(const Types&... args)
{
std::size_t seed = 0;
hash_val(seed, args...);
return seed;
}
}
namespace std
{
template <typename T1, typename T2> struct hash<std::pair<T1, T2>>
{
size_t operator()(const std::pair<T1, T2> &pair) const
{
return hash_val(pair.first, pair.second);
}
};
}
#endif // STD_HASH_HPP
| 30.128205 | 80 | 0.744255 | cypox |
59c8782a58e05e74090f6cf7e32d2d945da69e95 | 4,250 | cpp | C++ | src/core/LunaIpc.cpp | webosose/libpmscore | 04fb394972209f7adf81585845745edc3f2d5e3f | [
"Apache-2.0"
] | null | null | null | src/core/LunaIpc.cpp | webosose/libpmscore | 04fb394972209f7adf81585845745edc3f2d5e3f | [
"Apache-2.0"
] | null | null | null | src/core/LunaIpc.cpp | webosose/libpmscore | 04fb394972209f7adf81585845745edc3f2d5e3f | [
"Apache-2.0"
] | 1 | 2021-06-19T14:52:56.000Z | 2021-06-19T14:52:56.000Z | // @@@LICENSE
//
// Copyright (c) 2017-2020 LG Electronics, Inc.
//
// Confidential computer software. Valid license from LG required for
// possession, use or copying. Consistent with FAR 12.211 and 12.212,
// Commercial Computer Software, Computer Software Documentation, and
// Technical Data for Commercial Items are licensed to the U.S. Government
// under vendor's standard commercial license.
//
// LICENSE@@@
#include "LunaInterfaceBase.h"
#include "LunaIpc.h"
#include "LunaInterfaceFactory.h"
/** @brief Definition of all static class members
*/
const char* const LunaIpc::kPmsIpcName = "Luna";
const char* const LunaIpc::kPmsLunaPMS = "LunaPMS";
const char* const LunaIpc::kPmsLunaServiceName = "ServiceName";
const char* const LunaIpc::kPmsLunaInterface = "Interface";
bool LunaIpc::mIsObjRegistered = LunaIpc::RegisterObject();
PmsErrorCode_t LunaIpc::InitIpc()
{
PmsErrorCode_t err = kPmsSuccess;
err = mpConfig->GetString(mType, LunaIpc::kPmsLunaServiceName, &mServiceName);
if (err == kPmsSuccess)
{
LSError lserror;
LSErrorInit(&lserror);
if (!LSRegister(mServiceName.c_str(), &mpLsHandle, &lserror))
return kPmsErrClientNotRegistered;
if (LSErrorIsSet(&lserror))
{
err = kPmsErrResponseTooLate;
MSG_ERROR(err, "Could not register pms service name %s", mServiceName.c_str());
MSG_DEBUG("LUNASERVICE ERROR %d: %s (%s @ %s:%d)\n", lserror.error_code, lserror.message, lserror.func, lserror.file, lserror.line);
}
else
{
MSG_NOTICE("Service %s registered, mpLsHandle %p", mServiceName.c_str(), (void *)mpLsHandle);
}
}
return err;
}
PmsErrorCode_t LunaIpc::DeinitIpc()
{
LSError lserror;
LSErrorInit(&lserror);
PmsErrorCode_t err = kPmsSuccess;
LSUnregister(mpLsHandle, &lserror);
if (LSErrorIsSet(&lserror))
{
MSG_DEBUG("LUNASERVICE ERROR %d: %s (%s @ %s:%d)\n", lserror.error_code, lserror.message, lserror.func, lserror.file, lserror.line);
return kPmsErrResponseTooLate;
}
return kPmsSuccess;
}
LunaIpc::~LunaIpc()
{
if (mIsStarted)
Stop();
if (mIsInitialized)
Deinitialize();
mpLsHandle = 0;
}
PmsErrorCode_t LunaIpc::CreateHandlers()
{
PmsErrorCode_t err = kPmsSuccess;
std::vector<std::string> lunaInterfaces;
err = mpConfig->GetStringList(mType, LunaIpc::kPmsLunaInterface, &lunaInterfaces);
if (err == kPmsSuccess)
{
for(uint8_t i = 0; i < lunaInterfaces.size(); i++)
{
IpcInterfaceBase* pIpcInterface =
sLunaInterfaceFactory::GetInstance().CreateObject(lunaInterfaces[i], mpConfig, mpLsHandle);
if (pIpcInterface)
{
mIpcInterfaces.push_back(pIpcInterface);
MSG_DEBUG("%s created", lunaInterfaces.at(i).c_str());
}
else
{
MSG_ERROR(kPmsErrUnknown, "%s could not be created", lunaInterfaces.at(i).c_str());
}
}
}
return err;
}
PmsErrorCode_t LunaIpc::Start(GMainLoop* loopData)
{
LSError lserror;
LSErrorInit(&lserror);
PmsErrorCode_t err = kPmsSuccess;
IpcBase::Start(loopData);
LSGmainAttach( mpLsHandle, loopData, &lserror);
if (!mIpcInterfaces.empty())
{
LSSubscriptionSetCancelFunction(mpLsHandle, CancelSubscriptionCb, (void*)mIpcInterfaces[0], NULL);
}
for (uint8_t i=0; i<mIpcInterfaces.size(); i++)
{
err = ((IpcInterfaceBase *)mIpcInterfaces[i])->Start(); // this to attach observers
}
return err;
}
PmsErrorCode_t LunaIpc::Stop()
{
PmsErrorCode_t err = kPmsSuccess;
LSError lserror;
LSErrorInit(&lserror);
for (uint8_t i=0; i<mIpcInterfaces.size(); i++)
{
err = ((IpcInterfaceBase *)mIpcInterfaces[i])->Stop();
}
IpcBase::Stop();
return err;
}
bool
LunaIpc::CancelSubscriptionCb(LSHandle* pLsH, LSMessage* pLsMsg, void* pData)
{
LunaInterfaceBase *pThis = static_cast<LunaInterfaceBase*>(pData);
if (pThis != NULL)
{
return pThis->CancelSubscription(pLsH, pLsMsg, pData);
}
else
{
return false;
}
}
| 25.60241 | 144 | 0.642824 | webosose |
59c8835b1263d6bd3797b429097aa06d69199e59 | 4,530 | cpp | C++ | src/plugins/lmp/mpris/fdopropsadaptor.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/lmp/mpris/fdopropsadaptor.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/plugins/lmp/mpris/fdopropsadaptor.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "fdopropsadaptor.h"
#include <QVariantMap>
#include <QStringList>
#include <QMetaMethod>
#include <QDBusConnection>
#include <QDBusContext>
#include <QDBusVariant>
#include <QtDebug>
namespace LeechCraft
{
namespace LMP
{
namespace MPRIS
{
FDOPropsAdaptor::FDOPropsAdaptor (QObject *parent)
: QDBusAbstractAdaptor (parent)
{
}
void FDOPropsAdaptor::Notify (const QString& iface, const QString& prop, const QVariant& val)
{
QVariantMap changes;
changes [prop] = val;
emit PropertiesChanged (iface, changes, QStringList ());
}
QDBusVariant FDOPropsAdaptor::Get (const QString& iface, const QString& propName)
{
QObject *child = 0;
QMetaProperty prop;
if (!GetProperty (iface, propName, &prop, &child))
return QDBusVariant (QVariant ());
return QDBusVariant (prop.read (child));
}
QVariantMap FDOPropsAdaptor::GetAll (const QString& iface)
{
QVariantMap result;
const auto& adaptors = parent ()->findChildren<QDBusAbstractAdaptor*> ();
for (const auto child : adaptors)
{
const auto mo = child->metaObject ();
if (!iface.isEmpty ())
{
const auto idx = mo->indexOfClassInfo ("D-Bus Interface");
if (idx == -1)
continue;
const auto& info = mo->classInfo (idx);
if (iface != info.value ())
continue;
}
for (int i = 0, cnt = mo->propertyCount (); i < cnt; ++i)
{
const auto& property = mo->property (i);
result [property.name ()] = property.read (child);
}
}
return result;
}
void FDOPropsAdaptor::Set (const QString& iface, const QString& propName, const QDBusVariant& value)
{
QObject *child = 0;
QMetaProperty prop;
if (!GetProperty (iface, propName, &prop, &child))
return;
if (!prop.isWritable ())
{
auto context = dynamic_cast<QDBusContext*> (parent ());
if (context->calledFromDBus ())
context->sendErrorReply (QDBusError::AccessDenied, propName + " isn't writable");
return;
}
prop.write (child, value.variant ());
}
bool FDOPropsAdaptor::GetProperty (const QString& iface, const QString& prop, QMetaProperty *propObj, QObject **childObject) const
{
auto adaptors = parent ()->findChildren<QDBusAbstractAdaptor*> ();
for (const auto& child : adaptors)
{
const auto mo = child->metaObject ();
if (!iface.isEmpty ())
{
const auto idx = mo->indexOfClassInfo ("D-Bus Interface");
if (idx == -1)
continue;
const auto& info = mo->classInfo (idx);
if (iface != info.value ())
continue;
}
const auto idx = mo->indexOfProperty (prop.toUtf8 ().constData ());
if (idx != -1)
{
*propObj = mo->property (idx);
*childObject = child;
return true;
}
}
auto context = dynamic_cast<QDBusContext*> (parent ());
if (context->calledFromDBus ())
context->sendErrorReply (QDBusError::InvalidMember, "no such property " + prop);
return false;
}
}
}
}
| 30 | 131 | 0.675717 | MellonQ |
59cb0df0bc7759b79c2c078dbbb5396876505e60 | 19 | cpp | C++ | AYK/src/aykpch.cpp | AreYouReal/AYK | c6859047cfed674291692cc31095d8bb61b27a35 | [
"Apache-2.0"
] | null | null | null | AYK/src/aykpch.cpp | AreYouReal/AYK | c6859047cfed674291692cc31095d8bb61b27a35 | [
"Apache-2.0"
] | null | null | null | AYK/src/aykpch.cpp | AreYouReal/AYK | c6859047cfed674291692cc31095d8bb61b27a35 | [
"Apache-2.0"
] | null | null | null | #include "aykpch.h" | 19 | 19 | 0.736842 | AreYouReal |
59cc6a70c25214cdcd315edd118ba47ea601427d | 18,839 | cpp | C++ | library/cpp/langs/generated/uniscripts.cpp | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | library/cpp/langs/generated/uniscripts.cpp | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | library/cpp/langs/generated/uniscripts.cpp | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | // Generated from http://www.unicode.org/Public/UNIDATA/Scripts.txt
// The best way to alter this file is to modify uniscripts.py
#include <library/cpp/langs/langs.h>
#include <util/system/yassert.h>
#include <cstring>
namespace NCharsetInternal {
struct TScriptRange {
EScript Script;
wchar32 Start;
wchar32 End;
};
const TScriptRange ScriptRanges[] = {
{ SCRIPT_ETHIOPIC, 0x1200, 0x1248 },
{ SCRIPT_ETHIOPIC, 0x124A, 0x124D },
{ SCRIPT_ETHIOPIC, 0x1250, 0x1256 },
{ SCRIPT_ETHIOPIC, 0x1258, 0x1258 },
{ SCRIPT_ETHIOPIC, 0x125A, 0x125D },
{ SCRIPT_ETHIOPIC, 0x1260, 0x1288 },
{ SCRIPT_ETHIOPIC, 0x128A, 0x128D },
{ SCRIPT_ETHIOPIC, 0x1290, 0x12B0 },
{ SCRIPT_ETHIOPIC, 0x12B2, 0x12B5 },
{ SCRIPT_ETHIOPIC, 0x12B8, 0x12BE },
{ SCRIPT_ETHIOPIC, 0x12C0, 0x12C0 },
{ SCRIPT_ETHIOPIC, 0x12C2, 0x12C5 },
{ SCRIPT_ETHIOPIC, 0x12C8, 0x12D6 },
{ SCRIPT_ETHIOPIC, 0x12D8, 0x1310 },
{ SCRIPT_ETHIOPIC, 0x1312, 0x1315 },
{ SCRIPT_ETHIOPIC, 0x1318, 0x135A },
{ SCRIPT_ETHIOPIC, 0x135D, 0x137C },
{ SCRIPT_ETHIOPIC, 0x1380, 0x1399 },
{ SCRIPT_ETHIOPIC, 0x2D80, 0x2D96 },
{ SCRIPT_ETHIOPIC, 0x2DA0, 0x2DA6 },
{ SCRIPT_ETHIOPIC, 0x2DA8, 0x2DAE },
{ SCRIPT_ETHIOPIC, 0x2DB0, 0x2DB6 },
{ SCRIPT_ETHIOPIC, 0x2DB8, 0x2DBE },
{ SCRIPT_ETHIOPIC, 0x2DC0, 0x2DC6 },
{ SCRIPT_ETHIOPIC, 0x2DC8, 0x2DCE },
{ SCRIPT_ETHIOPIC, 0x2DD0, 0x2DD6 },
{ SCRIPT_ETHIOPIC, 0x2DD8, 0x2DDE },
{ SCRIPT_ETHIOPIC, 0xAB01, 0xAB06 },
{ SCRIPT_ETHIOPIC, 0xAB09, 0xAB0E },
{ SCRIPT_ETHIOPIC, 0xAB11, 0xAB16 },
{ SCRIPT_ETHIOPIC, 0xAB20, 0xAB26 },
{ SCRIPT_ETHIOPIC, 0xAB28, 0xAB2E },
{ SCRIPT_ARABIC, 0x600, 0x604 },
{ SCRIPT_ARABIC, 0x606, 0x60B },
{ SCRIPT_ARABIC, 0x60D, 0x61A },
{ SCRIPT_ARABIC, 0x61E, 0x61E },
{ SCRIPT_ARABIC, 0x620, 0x63F },
{ SCRIPT_ARABIC, 0x641, 0x64A },
{ SCRIPT_ARABIC, 0x656, 0x66F },
{ SCRIPT_ARABIC, 0x671, 0x6DC },
{ SCRIPT_ARABIC, 0x6DE, 0x6FF },
{ SCRIPT_ARABIC, 0x750, 0x77F },
{ SCRIPT_ARABIC, 0x8A0, 0x8B4 },
{ SCRIPT_ARABIC, 0x8B6, 0x8BD },
{ SCRIPT_ARABIC, 0x8D4, 0x8E1 },
{ SCRIPT_ARABIC, 0x8E3, 0x8FF },
{ SCRIPT_ARABIC, 0xFB50, 0xFBC1 },
{ SCRIPT_ARABIC, 0xFBD3, 0xFD3D },
{ SCRIPT_ARABIC, 0xFD50, 0xFD8F },
{ SCRIPT_ARABIC, 0xFD92, 0xFDC7 },
{ SCRIPT_ARABIC, 0xFDF0, 0xFDFD },
{ SCRIPT_ARABIC, 0xFE70, 0xFE74 },
{ SCRIPT_ARABIC, 0xFE76, 0xFEFC },
{ SCRIPT_MONGOLIAN, 0x1800, 0x1801 },
{ SCRIPT_MONGOLIAN, 0x1804, 0x1804 },
{ SCRIPT_MONGOLIAN, 0x1806, 0x180E },
{ SCRIPT_MONGOLIAN, 0x1810, 0x1819 },
{ SCRIPT_MONGOLIAN, 0x1820, 0x1877 },
{ SCRIPT_MONGOLIAN, 0x1880, 0x18AA },
{ SCRIPT_TAMIL, 0xB82, 0xB83 },
{ SCRIPT_TAMIL, 0xB85, 0xB8A },
{ SCRIPT_TAMIL, 0xB8E, 0xB90 },
{ SCRIPT_TAMIL, 0xB92, 0xB95 },
{ SCRIPT_TAMIL, 0xB99, 0xB9A },
{ SCRIPT_TAMIL, 0xB9C, 0xB9C },
{ SCRIPT_TAMIL, 0xB9E, 0xB9F },
{ SCRIPT_TAMIL, 0xBA3, 0xBA4 },
{ SCRIPT_TAMIL, 0xBA8, 0xBAA },
{ SCRIPT_TAMIL, 0xBAE, 0xBB9 },
{ SCRIPT_TAMIL, 0xBBE, 0xBC2 },
{ SCRIPT_TAMIL, 0xBC6, 0xBC8 },
{ SCRIPT_TAMIL, 0xBCA, 0xBCD },
{ SCRIPT_TAMIL, 0xBD0, 0xBD0 },
{ SCRIPT_TAMIL, 0xBD7, 0xBD7 },
{ SCRIPT_TAMIL, 0xBE6, 0xBFA },
{ SCRIPT_GUJARATI, 0xA81, 0xA83 },
{ SCRIPT_GUJARATI, 0xA85, 0xA8D },
{ SCRIPT_GUJARATI, 0xA8F, 0xA91 },
{ SCRIPT_GUJARATI, 0xA93, 0xAA8 },
{ SCRIPT_GUJARATI, 0xAAA, 0xAB0 },
{ SCRIPT_GUJARATI, 0xAB2, 0xAB3 },
{ SCRIPT_GUJARATI, 0xAB5, 0xAB9 },
{ SCRIPT_GUJARATI, 0xABC, 0xAC5 },
{ SCRIPT_GUJARATI, 0xAC7, 0xAC9 },
{ SCRIPT_GUJARATI, 0xACB, 0xACD },
{ SCRIPT_GUJARATI, 0xAD0, 0xAD0 },
{ SCRIPT_GUJARATI, 0xAE0, 0xAE3 },
{ SCRIPT_GUJARATI, 0xAE6, 0xAF1 },
{ SCRIPT_GUJARATI, 0xAF9, 0xAF9 },
{ SCRIPT_MALAYALAM, 0xD01, 0xD03 },
{ SCRIPT_MALAYALAM, 0xD05, 0xD0C },
{ SCRIPT_MALAYALAM, 0xD0E, 0xD10 },
{ SCRIPT_MALAYALAM, 0xD12, 0xD3A },
{ SCRIPT_MALAYALAM, 0xD3D, 0xD44 },
{ SCRIPT_MALAYALAM, 0xD46, 0xD48 },
{ SCRIPT_MALAYALAM, 0xD4A, 0xD4F },
{ SCRIPT_MALAYALAM, 0xD54, 0xD63 },
{ SCRIPT_MALAYALAM, 0xD66, 0xD7F },
{ SCRIPT_ARMENIAN, 0x531, 0x556 },
{ SCRIPT_ARMENIAN, 0x559, 0x55F },
{ SCRIPT_ARMENIAN, 0x561, 0x587 },
{ SCRIPT_ARMENIAN, 0x58A, 0x58A },
{ SCRIPT_ARMENIAN, 0x58D, 0x58F },
{ SCRIPT_ARMENIAN, 0xFB13, 0xFB17 },
{ SCRIPT_HANGUL, 0x1100, 0x11FF },
{ SCRIPT_HANGUL, 0x302E, 0x302F },
{ SCRIPT_HANGUL, 0x3131, 0x318E },
{ SCRIPT_HANGUL, 0x3200, 0x321E },
{ SCRIPT_HANGUL, 0x3260, 0x327E },
{ SCRIPT_HANGUL, 0xA960, 0xA97C },
{ SCRIPT_HANGUL, 0xAC00, 0xD7A3 },
{ SCRIPT_HANGUL, 0xD7B0, 0xD7C6 },
{ SCRIPT_HANGUL, 0xD7CB, 0xD7FB },
{ SCRIPT_HANGUL, 0xFFA0, 0xFFBE },
{ SCRIPT_HANGUL, 0xFFC2, 0xFFC7 },
{ SCRIPT_HANGUL, 0xFFCA, 0xFFCF },
{ SCRIPT_HANGUL, 0xFFD2, 0xFFD7 },
{ SCRIPT_HANGUL, 0xFFDA, 0xFFDC },
{ SCRIPT_GURMUKHI, 0xA01, 0xA03 },
{ SCRIPT_GURMUKHI, 0xA05, 0xA0A },
{ SCRIPT_GURMUKHI, 0xA0F, 0xA10 },
{ SCRIPT_GURMUKHI, 0xA13, 0xA28 },
{ SCRIPT_GURMUKHI, 0xA2A, 0xA30 },
{ SCRIPT_GURMUKHI, 0xA32, 0xA33 },
{ SCRIPT_GURMUKHI, 0xA35, 0xA36 },
{ SCRIPT_GURMUKHI, 0xA38, 0xA39 },
{ SCRIPT_GURMUKHI, 0xA3C, 0xA3C },
{ SCRIPT_GURMUKHI, 0xA3E, 0xA42 },
{ SCRIPT_GURMUKHI, 0xA47, 0xA48 },
{ SCRIPT_GURMUKHI, 0xA4B, 0xA4D },
{ SCRIPT_GURMUKHI, 0xA51, 0xA51 },
{ SCRIPT_GURMUKHI, 0xA59, 0xA5C },
{ SCRIPT_GURMUKHI, 0xA5E, 0xA5E },
{ SCRIPT_GURMUKHI, 0xA66, 0xA75 },
{ SCRIPT_CYRILLIC, 0x400, 0x484 },
{ SCRIPT_CYRILLIC, 0x487, 0x52F },
{ SCRIPT_CYRILLIC, 0x1C80, 0x1C88 },
{ SCRIPT_CYRILLIC, 0x1D2B, 0x1D2B },
{ SCRIPT_CYRILLIC, 0x1D78, 0x1D78 },
{ SCRIPT_CYRILLIC, 0x2DE0, 0x2DFF },
{ SCRIPT_CYRILLIC, 0xA640, 0xA69F },
{ SCRIPT_CYRILLIC, 0xFE2E, 0xFE2F },
{ SCRIPT_DEVANAGARI, 0x900, 0x950 },
{ SCRIPT_DEVANAGARI, 0x953, 0x963 },
{ SCRIPT_DEVANAGARI, 0x966, 0x97F },
{ SCRIPT_DEVANAGARI, 0xA8E0, 0xA8FD },
{ SCRIPT_HEBREW, 0x591, 0x5C7 },
{ SCRIPT_HEBREW, 0x5D0, 0x5EA },
{ SCRIPT_HEBREW, 0x5F0, 0x5F4 },
{ SCRIPT_HEBREW, 0xFB1D, 0xFB36 },
{ SCRIPT_HEBREW, 0xFB38, 0xFB3C },
{ SCRIPT_HEBREW, 0xFB3E, 0xFB3E },
{ SCRIPT_HEBREW, 0xFB40, 0xFB41 },
{ SCRIPT_HEBREW, 0xFB43, 0xFB44 },
{ SCRIPT_HEBREW, 0xFB46, 0xFB4F },
{ SCRIPT_THAI, 0xE01, 0xE3A },
{ SCRIPT_THAI, 0xE40, 0xE5B },
{ SCRIPT_SYRIAC, 0x700, 0x70D },
{ SCRIPT_SYRIAC, 0x70F, 0x74A },
{ SCRIPT_SYRIAC, 0x74D, 0x74F },
{ SCRIPT_KANNADA, 0xC80, 0xC83 },
{ SCRIPT_KANNADA, 0xC85, 0xC8C },
{ SCRIPT_KANNADA, 0xC8E, 0xC90 },
{ SCRIPT_KANNADA, 0xC92, 0xCA8 },
{ SCRIPT_KANNADA, 0xCAA, 0xCB3 },
{ SCRIPT_KANNADA, 0xCB5, 0xCB9 },
{ SCRIPT_KANNADA, 0xCBC, 0xCC4 },
{ SCRIPT_KANNADA, 0xCC6, 0xCC8 },
{ SCRIPT_KANNADA, 0xCCA, 0xCCD },
{ SCRIPT_KANNADA, 0xCD5, 0xCD6 },
{ SCRIPT_KANNADA, 0xCDE, 0xCDE },
{ SCRIPT_KANNADA, 0xCE0, 0xCE3 },
{ SCRIPT_KANNADA, 0xCE6, 0xCEF },
{ SCRIPT_KANNADA, 0xCF1, 0xCF2 },
{ SCRIPT_LAO, 0xE81, 0xE82 },
{ SCRIPT_LAO, 0xE84, 0xE84 },
{ SCRIPT_LAO, 0xE87, 0xE88 },
{ SCRIPT_LAO, 0xE8A, 0xE8A },
{ SCRIPT_LAO, 0xE8D, 0xE8D },
{ SCRIPT_LAO, 0xE94, 0xE97 },
{ SCRIPT_LAO, 0xE99, 0xE9F },
{ SCRIPT_LAO, 0xEA1, 0xEA3 },
{ SCRIPT_LAO, 0xEA5, 0xEA5 },
{ SCRIPT_LAO, 0xEA7, 0xEA7 },
{ SCRIPT_LAO, 0xEAA, 0xEAB },
{ SCRIPT_LAO, 0xEAD, 0xEB9 },
{ SCRIPT_LAO, 0xEBB, 0xEBD },
{ SCRIPT_LAO, 0xEC0, 0xEC4 },
{ SCRIPT_LAO, 0xEC6, 0xEC6 },
{ SCRIPT_LAO, 0xEC8, 0xECD },
{ SCRIPT_LAO, 0xED0, 0xED9 },
{ SCRIPT_LAO, 0xEDC, 0xEDF },
{ SCRIPT_TELUGU, 0xC00, 0xC03 },
{ SCRIPT_TELUGU, 0xC05, 0xC0C },
{ SCRIPT_TELUGU, 0xC0E, 0xC10 },
{ SCRIPT_TELUGU, 0xC12, 0xC28 },
{ SCRIPT_TELUGU, 0xC2A, 0xC39 },
{ SCRIPT_TELUGU, 0xC3D, 0xC44 },
{ SCRIPT_TELUGU, 0xC46, 0xC48 },
{ SCRIPT_TELUGU, 0xC4A, 0xC4D },
{ SCRIPT_TELUGU, 0xC55, 0xC56 },
{ SCRIPT_TELUGU, 0xC58, 0xC5A },
{ SCRIPT_TELUGU, 0xC60, 0xC63 },
{ SCRIPT_TELUGU, 0xC66, 0xC6F },
{ SCRIPT_TELUGU, 0xC78, 0xC7F },
{ SCRIPT_KHMER, 0x1780, 0x17DD },
{ SCRIPT_KHMER, 0x17E0, 0x17E9 },
{ SCRIPT_KHMER, 0x17F0, 0x17F9 },
{ SCRIPT_KHMER, 0x19E0, 0x19FF },
{ SCRIPT_LATIN, 0x41, 0x5A },
{ SCRIPT_LATIN, 0x61, 0x7A },
{ SCRIPT_LATIN, 0xAA, 0xAA },
{ SCRIPT_LATIN, 0xBA, 0xBA },
{ SCRIPT_LATIN, 0xC0, 0xD6 },
{ SCRIPT_LATIN, 0xD8, 0xF6 },
{ SCRIPT_LATIN, 0xF8, 0x2B8 },
{ SCRIPT_LATIN, 0x2E0, 0x2E4 },
{ SCRIPT_LATIN, 0x1D00, 0x1D25 },
{ SCRIPT_LATIN, 0x1D2C, 0x1D5C },
{ SCRIPT_LATIN, 0x1D62, 0x1D65 },
{ SCRIPT_LATIN, 0x1D6B, 0x1D77 },
{ SCRIPT_LATIN, 0x1D79, 0x1DBE },
{ SCRIPT_LATIN, 0x1E00, 0x1EFF },
{ SCRIPT_LATIN, 0x2071, 0x2071 },
{ SCRIPT_LATIN, 0x207F, 0x207F },
{ SCRIPT_LATIN, 0x2090, 0x209C },
{ SCRIPT_LATIN, 0x212A, 0x212B },
{ SCRIPT_LATIN, 0x2132, 0x2132 },
{ SCRIPT_LATIN, 0x214E, 0x214E },
{ SCRIPT_LATIN, 0x2160, 0x2188 },
{ SCRIPT_LATIN, 0x2C60, 0x2C7F },
{ SCRIPT_LATIN, 0xA722, 0xA787 },
{ SCRIPT_LATIN, 0xA78B, 0xA7AE },
{ SCRIPT_LATIN, 0xA7B0, 0xA7B7 },
{ SCRIPT_LATIN, 0xA7F7, 0xA7FF },
{ SCRIPT_LATIN, 0xAB30, 0xAB5A },
{ SCRIPT_LATIN, 0xAB5C, 0xAB64 },
{ SCRIPT_LATIN, 0xFB00, 0xFB06 },
{ SCRIPT_LATIN, 0xFF21, 0xFF3A },
{ SCRIPT_LATIN, 0xFF41, 0xFF5A },
{ SCRIPT_TIBETAN, 0xF00, 0xF47 },
{ SCRIPT_TIBETAN, 0xF49, 0xF6C },
{ SCRIPT_TIBETAN, 0xF71, 0xF97 },
{ SCRIPT_TIBETAN, 0xF99, 0xFBC },
{ SCRIPT_TIBETAN, 0xFBE, 0xFCC },
{ SCRIPT_TIBETAN, 0xFCE, 0xFD4 },
{ SCRIPT_TIBETAN, 0xFD9, 0xFDA },
{ SCRIPT_MYANMAR, 0x1000, 0x109F },
{ SCRIPT_MYANMAR, 0xA9E0, 0xA9FE },
{ SCRIPT_MYANMAR, 0xAA60, 0xAA7F },
{ SCRIPT_OTHER, 0x2EA, 0x2EB },
{ SCRIPT_OTHER, 0x7C0, 0x7FA },
{ SCRIPT_OTHER, 0x800, 0x82D },
{ SCRIPT_OTHER, 0x830, 0x83E },
{ SCRIPT_OTHER, 0x840, 0x85B },
{ SCRIPT_OTHER, 0x85E, 0x85E },
{ SCRIPT_OTHER, 0x13A0, 0x13F5 },
{ SCRIPT_OTHER, 0x13F8, 0x13FD },
{ SCRIPT_OTHER, 0x1400, 0x169C },
{ SCRIPT_OTHER, 0x1700, 0x170C },
{ SCRIPT_OTHER, 0x170E, 0x1714 },
{ SCRIPT_OTHER, 0x1720, 0x1734 },
{ SCRIPT_OTHER, 0x1740, 0x1753 },
{ SCRIPT_OTHER, 0x1760, 0x176C },
{ SCRIPT_OTHER, 0x176E, 0x1770 },
{ SCRIPT_OTHER, 0x1772, 0x1773 },
{ SCRIPT_OTHER, 0x18B0, 0x18F5 },
{ SCRIPT_OTHER, 0x1900, 0x191E },
{ SCRIPT_OTHER, 0x1920, 0x192B },
{ SCRIPT_OTHER, 0x1930, 0x193B },
{ SCRIPT_OTHER, 0x1940, 0x1940 },
{ SCRIPT_OTHER, 0x1944, 0x196D },
{ SCRIPT_OTHER, 0x1970, 0x1974 },
{ SCRIPT_OTHER, 0x1980, 0x19AB },
{ SCRIPT_OTHER, 0x19B0, 0x19C9 },
{ SCRIPT_OTHER, 0x19D0, 0x19DA },
{ SCRIPT_OTHER, 0x19DE, 0x19DF },
{ SCRIPT_OTHER, 0x1A00, 0x1A1B },
{ SCRIPT_OTHER, 0x1A1E, 0x1A5E },
{ SCRIPT_OTHER, 0x1A60, 0x1A7C },
{ SCRIPT_OTHER, 0x1A7F, 0x1A89 },
{ SCRIPT_OTHER, 0x1A90, 0x1A99 },
{ SCRIPT_OTHER, 0x1AA0, 0x1AAD },
{ SCRIPT_OTHER, 0x1B00, 0x1B4B },
{ SCRIPT_OTHER, 0x1B50, 0x1B7C },
{ SCRIPT_OTHER, 0x1B80, 0x1BF3 },
{ SCRIPT_OTHER, 0x1BFC, 0x1C37 },
{ SCRIPT_OTHER, 0x1C3B, 0x1C49 },
{ SCRIPT_OTHER, 0x1C4D, 0x1C7F },
{ SCRIPT_OTHER, 0x1CC0, 0x1CC7 },
{ SCRIPT_OTHER, 0x2800, 0x28FF },
{ SCRIPT_OTHER, 0x2C00, 0x2C2E },
{ SCRIPT_OTHER, 0x2C30, 0x2C5E },
{ SCRIPT_OTHER, 0x2D30, 0x2D67 },
{ SCRIPT_OTHER, 0x2D6F, 0x2D70 },
{ SCRIPT_OTHER, 0x2D7F, 0x2D7F },
{ SCRIPT_OTHER, 0x3105, 0x312D },
{ SCRIPT_OTHER, 0x31A0, 0x31BA },
{ SCRIPT_OTHER, 0xA000, 0xA48C },
{ SCRIPT_OTHER, 0xA490, 0xA4C6 },
{ SCRIPT_OTHER, 0xA4D0, 0xA62B },
{ SCRIPT_OTHER, 0xA6A0, 0xA6F7 },
{ SCRIPT_OTHER, 0xA800, 0xA82B },
{ SCRIPT_OTHER, 0xA840, 0xA877 },
{ SCRIPT_OTHER, 0xA880, 0xA8C5 },
{ SCRIPT_OTHER, 0xA8CE, 0xA8D9 },
{ SCRIPT_OTHER, 0xA900, 0xA92D },
{ SCRIPT_OTHER, 0xA92F, 0xA953 },
{ SCRIPT_OTHER, 0xA95F, 0xA95F },
{ SCRIPT_OTHER, 0xA980, 0xA9CD },
{ SCRIPT_OTHER, 0xA9D0, 0xA9D9 },
{ SCRIPT_OTHER, 0xA9DE, 0xA9DF },
{ SCRIPT_OTHER, 0xAA00, 0xAA36 },
{ SCRIPT_OTHER, 0xAA40, 0xAA4D },
{ SCRIPT_OTHER, 0xAA50, 0xAA59 },
{ SCRIPT_OTHER, 0xAA5C, 0xAA5F },
{ SCRIPT_OTHER, 0xAA80, 0xAAC2 },
{ SCRIPT_OTHER, 0xAADB, 0xAAF6 },
{ SCRIPT_OTHER, 0xAB70, 0xABED },
{ SCRIPT_OTHER, 0xABF0, 0xABF9 },
{ SCRIPT_HAN, 0x2E80, 0x2E99 },
{ SCRIPT_HAN, 0x2E9B, 0x2EF3 },
{ SCRIPT_HAN, 0x2F00, 0x2FD5 },
{ SCRIPT_HAN, 0x3005, 0x3005 },
{ SCRIPT_HAN, 0x3007, 0x3007 },
{ SCRIPT_HAN, 0x3021, 0x3029 },
{ SCRIPT_HAN, 0x3038, 0x303B },
{ SCRIPT_HAN, 0x3400, 0x4DB5 },
{ SCRIPT_HAN, 0x4E00, 0x9FD5 },
{ SCRIPT_HAN, 0xF900, 0xFA6D },
{ SCRIPT_HAN, 0xFA70, 0xFAD9 },
{ SCRIPT_THAANA, 0x780, 0x7B1 },
{ SCRIPT_HIRAGANA, 0x3041, 0x3096 },
{ SCRIPT_HIRAGANA, 0x309D, 0x309F },
{ SCRIPT_KATAKANA, 0x30A1, 0x30FA },
{ SCRIPT_KATAKANA, 0x30FD, 0x30FF },
{ SCRIPT_KATAKANA, 0x31F0, 0x31FF },
{ SCRIPT_KATAKANA, 0x32D0, 0x32FE },
{ SCRIPT_KATAKANA, 0x3300, 0x3357 },
{ SCRIPT_KATAKANA, 0xFF66, 0xFF6F },
{ SCRIPT_KATAKANA, 0xFF71, 0xFF9D },
{ SCRIPT_ORIYA, 0xB01, 0xB03 },
{ SCRIPT_ORIYA, 0xB05, 0xB0C },
{ SCRIPT_ORIYA, 0xB0F, 0xB10 },
{ SCRIPT_ORIYA, 0xB13, 0xB28 },
{ SCRIPT_ORIYA, 0xB2A, 0xB30 },
{ SCRIPT_ORIYA, 0xB32, 0xB33 },
{ SCRIPT_ORIYA, 0xB35, 0xB39 },
{ SCRIPT_ORIYA, 0xB3C, 0xB44 },
{ SCRIPT_ORIYA, 0xB47, 0xB48 },
{ SCRIPT_ORIYA, 0xB4B, 0xB4D },
{ SCRIPT_ORIYA, 0xB56, 0xB57 },
{ SCRIPT_ORIYA, 0xB5C, 0xB5D },
{ SCRIPT_ORIYA, 0xB5F, 0xB63 },
{ SCRIPT_ORIYA, 0xB66, 0xB77 },
{ SCRIPT_BENGALI, 0x980, 0x983 },
{ SCRIPT_BENGALI, 0x985, 0x98C },
{ SCRIPT_BENGALI, 0x98F, 0x990 },
{ SCRIPT_BENGALI, 0x993, 0x9A8 },
{ SCRIPT_BENGALI, 0x9AA, 0x9B0 },
{ SCRIPT_BENGALI, 0x9B2, 0x9B2 },
{ SCRIPT_BENGALI, 0x9B6, 0x9B9 },
{ SCRIPT_BENGALI, 0x9BC, 0x9C4 },
{ SCRIPT_BENGALI, 0x9C7, 0x9C8 },
{ SCRIPT_BENGALI, 0x9CB, 0x9CE },
{ SCRIPT_BENGALI, 0x9D7, 0x9D7 },
{ SCRIPT_BENGALI, 0x9DC, 0x9DD },
{ SCRIPT_BENGALI, 0x9DF, 0x9E3 },
{ SCRIPT_BENGALI, 0x9E6, 0x9FB },
{ SCRIPT_RUNIC, 0x16A0, 0x16EA },
{ SCRIPT_RUNIC, 0x16EE, 0x16F8 },
{ SCRIPT_SINHALA, 0xD82, 0xD83 },
{ SCRIPT_SINHALA, 0xD85, 0xD96 },
{ SCRIPT_SINHALA, 0xD9A, 0xDB1 },
{ SCRIPT_SINHALA, 0xDB3, 0xDBB },
{ SCRIPT_SINHALA, 0xDBD, 0xDBD },
{ SCRIPT_SINHALA, 0xDC0, 0xDC6 },
{ SCRIPT_SINHALA, 0xDCA, 0xDCA },
{ SCRIPT_SINHALA, 0xDCF, 0xDD4 },
{ SCRIPT_SINHALA, 0xDD6, 0xDD6 },
{ SCRIPT_SINHALA, 0xDD8, 0xDDF },
{ SCRIPT_SINHALA, 0xDE6, 0xDEF },
{ SCRIPT_SINHALA, 0xDF2, 0xDF4 },
{ SCRIPT_COPTIC, 0x3E2, 0x3EF },
{ SCRIPT_COPTIC, 0x2C80, 0x2CF3 },
{ SCRIPT_COPTIC, 0x2CF9, 0x2CFF },
{ SCRIPT_GEORGIAN, 0x10A0, 0x10C5 },
{ SCRIPT_GEORGIAN, 0x10C7, 0x10C7 },
{ SCRIPT_GEORGIAN, 0x10CD, 0x10CD },
{ SCRIPT_GEORGIAN, 0x10D0, 0x10FA },
{ SCRIPT_GEORGIAN, 0x10FC, 0x10FF },
{ SCRIPT_GEORGIAN, 0x2D00, 0x2D25 },
{ SCRIPT_GEORGIAN, 0x2D27, 0x2D27 },
{ SCRIPT_GEORGIAN, 0x2D2D, 0x2D2D },
{ SCRIPT_GREEK, 0x370, 0x373 },
{ SCRIPT_GREEK, 0x375, 0x377 },
{ SCRIPT_GREEK, 0x37A, 0x37D },
{ SCRIPT_GREEK, 0x37F, 0x37F },
{ SCRIPT_GREEK, 0x384, 0x384 },
{ SCRIPT_GREEK, 0x386, 0x386 },
{ SCRIPT_GREEK, 0x388, 0x38A },
{ SCRIPT_GREEK, 0x38C, 0x38C },
{ SCRIPT_GREEK, 0x38E, 0x3A1 },
{ SCRIPT_GREEK, 0x3A3, 0x3E1 },
{ SCRIPT_GREEK, 0x3F0, 0x3FF },
{ SCRIPT_GREEK, 0x1D26, 0x1D2A },
{ SCRIPT_GREEK, 0x1D5D, 0x1D61 },
{ SCRIPT_GREEK, 0x1D66, 0x1D6A },
{ SCRIPT_GREEK, 0x1DBF, 0x1DBF },
{ SCRIPT_GREEK, 0x1F00, 0x1F15 },
{ SCRIPT_GREEK, 0x1F18, 0x1F1D },
{ SCRIPT_GREEK, 0x1F20, 0x1F45 },
{ SCRIPT_GREEK, 0x1F48, 0x1F4D },
{ SCRIPT_GREEK, 0x1F50, 0x1F57 },
{ SCRIPT_GREEK, 0x1F59, 0x1F59 },
{ SCRIPT_GREEK, 0x1F5B, 0x1F5B },
{ SCRIPT_GREEK, 0x1F5D, 0x1F5D },
{ SCRIPT_GREEK, 0x1F5F, 0x1F7D },
{ SCRIPT_GREEK, 0x1F80, 0x1FB4 },
{ SCRIPT_GREEK, 0x1FB6, 0x1FC4 },
{ SCRIPT_GREEK, 0x1FC6, 0x1FD3 },
{ SCRIPT_GREEK, 0x1FD6, 0x1FDB },
{ SCRIPT_GREEK, 0x1FDD, 0x1FEF },
{ SCRIPT_GREEK, 0x1FF2, 0x1FF4 },
{ SCRIPT_GREEK, 0x1FF6, 0x1FFE },
{ SCRIPT_GREEK, 0x2126, 0x2126 },
{ SCRIPT_GREEK, 0xAB65, 0xAB65 },
};
void InitScriptData(ui8 data[], size_t len) {
memset (data, 0, len * sizeof(ui8));
for (auto range : ScriptRanges) {
Y_ASSERT(range.Start <= range.End);
Y_ASSERT((unsigned)range.Script < 0x100);
size_t end = range.End;
if (end >= len)
end = len;
for (size_t j = range.Start; j <= end; ++j) {
data[j] = (ui8)range.Script;
}
}
}
}
| 41.043573 | 67 | 0.571899 | jochenater |
59ccd694bb7c96479c2108da5e8212eafff2c7f4 | 883 | cpp | C++ | Chapter01/Source_Code/GCC_CLANG/QtSimple.cpp | ngdzu/CPP-Reactive-Programming | e1a19feb40be086d47227587b8ed3d509b7518ca | [
"MIT"
] | 98 | 2018-07-03T08:55:31.000Z | 2022-03-21T22:16:58.000Z | Chapter01/Source_Code/GCC_CLANG/QtSimple.cpp | ngdzu/CPP-Reactive-Programming | e1a19feb40be086d47227587b8ed3d509b7518ca | [
"MIT"
] | 1 | 2020-11-30T10:38:58.000Z | 2020-12-15T06:56:20.000Z | Chapter01/Source_Code/GCC_CLANG/QtSimple.cpp | ngdzu/CPP-Reactive-Programming | e1a19feb40be086d47227587b8ed3d509b7518ca | [
"MIT"
] | 54 | 2018-07-06T02:09:27.000Z | 2021-11-10T08:42:50.000Z | /////////////////////////////////////
//
// The following program can be compiled using
// QtCreator or Qt Console.
//
#include <qapplication.h>
#include <qdialog.h>
#include <qmessagebox.h>
#include <qobject.h>
#include <qpushbutton.h>
class MyApp : public QDialog {
Q_OBJECT
public:
MyApp(QObject* /*parent*/ = 0):
button(this)
{
button.setText("Hello world!");
button.resize(100, 30);
// When the button is clicked, run button_clicked
connect(&button,
&QPushButton::clicked, this, &MyApp::button_clicked);
}
public slots:
void button_clicked() {
QMessageBox box;
box.setWindowTitle("Howdy");
box.setText("You clicked the button");
box.show();
box.exec();
}
protected:
QPushButton button;
};
int main(int argc, char** argv) {
QApplication app(argc, argv);
MyApp myapp;
myapp.show();
return app.exec();
}
// EOF QSimple.cpp | 19.195652 | 56 | 0.643262 | ngdzu |
59cd3c7d1c467290ec3474f3d3b31bce6aa04641 | 1,024 | cpp | C++ | UVA/vol-102/10205.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | 3 | 2017-05-12T14:45:37.000Z | 2020-01-18T16:51:25.000Z | UVA/vol-102/10205.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | UVA/vol-102/10205.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | /*
>>> ACM PROBLEM <<<
ID: 10205
Name: Stack 'em Up
Author: Arash Shakery
Email: arash.shakery@gmail.com
Language: C++
*/
#include <iostream>
#include <cstring>
#include <vector>
#include <string>
using namespace std;
char suits[][9]={"Clubs","Diamonds","Hearts","Spades"};
char nums[][6]={"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
string name(int x){
}
int main()
{
int T;cin>>T;
int n,i,j,ay,s,f=0;
int shuffle[100][52];
char line[10];
vector<int> cards,tc;
for(i=1;i<53;i++)tc.push_back(i);
while(T--){
if(f)cout<<endl;f=1;
cin>>n;
for(i=0;i<n;i++)
for(j=0;j<52;j++)
cin>>shuffle[i][j];
cards.clear();
for(i=1;i<53;i++)cards.push_back(i);
gets(line);
while(gets(line) && strlen(line)){
sscanf(line,"%d",&s);
for(i=0;i<52;i++)
tc[i]=cards[shuffle[s-1][i]-1];
cards=tc;
}
for(i=0;i<52;i++)
printf("%s of %s\n",nums[(cards[i]-1)%13],suits[(int)(cards[i]-1)/13]);
}
return 0;
}
| 18.285714 | 82 | 0.53418 | arash16 |
59cf718ba0bd0efa05e8ed87cd3eadd7926c1d57 | 6,070 | cpp | C++ | tests/client/AsyncClient.cpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 19 | 2017-03-28T02:17:42.000Z | 2021-02-12T03:26:58.000Z | tests/client/AsyncClient.cpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 3 | 2016-07-14T10:15:06.000Z | 2016-11-22T21:04:01.000Z | tests/client/AsyncClient.cpp | wnewbery/cpphttp | adfc148716bc65aff29e881d1872c9dea6fc6af9 | [
"MIT"
] | 9 | 2017-10-19T07:15:42.000Z | 2019-09-17T07:08:25.000Z | #include <boost/test/unit_test.hpp>
#include "client/AsyncClient.hpp"
#include "../TestSocket.hpp"
#include "../TestSocketFactory.hpp"
#include "net/Net.hpp"
#include <chrono>
using namespace http;
BOOST_AUTO_TEST_SUITE(TestClient)
BOOST_AUTO_TEST_CASE(construct)
{
TestSocketFactory socket_factory;
socket_factory.recv_buffer =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 10\r\n"
"\r\n"
"0123456789";
AsyncClientParams params;
params.host = "localhost";
params.port = 80;
params.tls = false;
params.max_connections = 5;
params.socket_factory = &socket_factory;
AsyncClient client(params);
client.exit();
client.start();
client.exit();
}
BOOST_AUTO_TEST_CASE(single)
{
TestSocketFactory socket_factory;
socket_factory.recv_buffer =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 10\r\n"
"\r\n"
"0123456789";
AsyncClientParams params;
params.host = "localhost";
params.port = 80;
params.tls = false;
params.max_connections = 5;
params.socket_factory = &socket_factory;
AsyncClient client(params);
AsyncRequest req;
req.method = GET;
req.raw_url = "/index.html";
auto response = client.queue(&req).get();
BOOST_CHECK_EQUAL(200, response->status.code);
}
BOOST_AUTO_TEST_CASE(sequential)
{
TestSocketFactory socket_factory;
socket_factory.recv_buffer =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 10\r\n"
"\r\n"
"0123456789";
AsyncClientParams params;
params.host = "localhost";
params.port = 80;
params.tls = false;
params.max_connections = 5;
params.socket_factory = &socket_factory;
AsyncClient client(params);
AsyncRequest req;
req.method = GET;
req.raw_url = "/index.html";
auto response = client.queue(&req).get();
BOOST_CHECK_EQUAL(200, response->status.code);
req.reset();
response = client.queue(&req).get();
BOOST_CHECK_EQUAL(200, response->status.code);
req.reset();
response = client.queue(&req).get();
BOOST_CHECK_EQUAL(200, response->status.code);
}
BOOST_AUTO_TEST_CASE(callback)
{
std::atomic<bool> done(false);
TestSocketFactory socket_factory;
socket_factory.recv_buffer =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 10\r\n"
"\r\n"
"0123456789";
AsyncClientParams params;
params.host = "localhost";
params.port = 80;
params.tls = false;
params.max_connections = 5;
params.socket_factory = &socket_factory;
AsyncClient client(params);
AsyncRequest req;
req.method = GET;
req.raw_url = "/index.html";
req.on_completion = [&done](AsyncRequest *, Response &) -> void
{
done = true;
};
client.queue(&req);
auto response = req.wait();
BOOST_CHECK_EQUAL(200, response->status.code);
BOOST_CHECK(done);
}
BOOST_AUTO_TEST_CASE(async_error)
{
std::atomic<bool> done(false);
class Factory : public SocketFactory
{
public:
virtual std::unique_ptr<http::Socket> connect(const std::string &host, uint16_t port, bool)override
{
throw ConnectionError(host, port);
}
};
Factory socket_factory;
AsyncClientParams params;
params.host = "localhost";
params.port = 80;
params.tls = false;
params.max_connections = 5;
params.socket_factory = &socket_factory;
AsyncClient client(params);
AsyncRequest req;
req.method = GET;
req.raw_url = "/index.html";
req.on_exception = [&done](AsyncRequest*) -> void
{
try
{
throw;
}
catch (const ConnectionError &)
{
done = true;
}
};
client.queue(&req);
BOOST_CHECK_THROW(req.wait(), ConnectionError);
BOOST_CHECK(done);
}
BOOST_AUTO_TEST_CASE(parallel)
{
class Factory : public TestSocketFactory
{
public:
using TestSocketFactory::TestSocketFactory;
std::mutex go;
virtual std::unique_ptr<http::Socket> connect(const std::string &host, uint16_t port, bool tls)override
{
++connect_count;
std::unique_lock<std::mutex> lock(go);
auto sock = std::unique_ptr<TestSocket>(new TestSocket());
sock->host = host;
sock->port = port;
sock->tls = tls;
sock->recv_buffer = recv_buffer;
last = sock.get();
return std::move(sock);
}
};
Factory socket_factory;
socket_factory.recv_buffer =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 10\r\n"
"Connection: keep-alive\r\n"
"\r\n"
"0123456789";
std::unique_lock<std::mutex> lock(socket_factory.go);
AsyncClientParams params;
params.host = "localhost";
params.port = 80;
params.tls = false;
params.max_connections = 4;
params.socket_factory = &socket_factory;
AsyncClient client(params);
auto req = []() -> AsyncRequest
{
AsyncRequest req;
req.method = GET;
req.raw_url = "/index.html";
return req;
};
auto a = req();
auto b = req();
auto c = req();
auto d = req();
auto e = req();
auto f = req();
client.queue(&a);
client.queue(&b);
client.queue(&c);
client.queue(&d);
client.queue(&e);
client.queue(&f);
std::this_thread::sleep_for(std::chrono::milliseconds(200));
BOOST_CHECK_EQUAL(4U, socket_factory.connect_count.load());
lock.unlock();
BOOST_CHECK_NO_THROW(a.wait());
BOOST_CHECK_NO_THROW(b.wait());
BOOST_CHECK_NO_THROW(c.wait());
BOOST_CHECK_NO_THROW(d.wait());
BOOST_CHECK_NO_THROW(e.wait());
BOOST_CHECK_NO_THROW(f.wait());
BOOST_CHECK_EQUAL(4U, socket_factory.connect_count.load());
}
BOOST_AUTO_TEST_SUITE_END()
| 23.897638 | 111 | 0.616145 | wnewbery |
59d05737552d1ab4760216fea10dbde39c6b85d5 | 9,110 | hpp | C++ | Support/Modules/GSRoot/Singleton.hpp | graphisoft-python/TextEngine | 20c2ff53877b20fdfe2cd51ce7abdab1ff676a70 | [
"Apache-2.0"
] | 3 | 2019-07-15T10:54:54.000Z | 2020-01-25T08:24:51.000Z | Support/Modules/GSRoot/Singleton.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | null | null | null | Support/Modules/GSRoot/Singleton.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | 1 | 2020-09-26T03:17:22.000Z | 2020-09-26T03:17:22.000Z |
// *****************************************************************************
//
// Declaration and implementation of Singleton class
//
// Module: GSRoot
// Namespace: GS
// Contact person: SN
//
// *****************************************************************************
#ifndef GS_SINGLETON_HPP
#define GS_SINGLETON_HPP
#pragma once
// --- Includes ----------------------------------------------------------------
#include "Guard.hpp"
#include "SingletonLock.hpp"
#include "MemoryBarrier.hpp"
// --- StaticLocalInstantiationPolicy class ------------------------------------
namespace GS {
class StaticLocalInstantiationPolicy {
// Static implementation:
protected:
template<typename T>
static void Create (T*& ptr);
};
////////////////////////////////////////////////////////////////////////////////
// StaticLocalInstantiationPolicy implementation
////////////////////////////////////////////////////////////////////////////////
// Static implementation
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// Create
// -----------------------------------------------------------------------------
template<typename T>
inline void StaticLocalInstantiationPolicy::Create (T*& ptr)
{
// Create an instance of the specified type, using a static local variable.
// The instance will be destroyed by the system.
static T instance;
ptr = &instance;
}
}
// --- StaticInstantiationHelper class -----------------------------------------
namespace GS {
template<typename T>
class StaticInstantiationHelper {
// Friend classes:
friend class StaticInstantiationPolicy;
// Static data members:
private:
static T instance;
};
template <typename T>
T StaticInstantiationHelper<T>::instance;
}
// --- StaticInstantiationPolicy class -----------------------------------------
namespace GS {
class StaticInstantiationPolicy {
// Static implementation:
protected:
template<typename T>
static void Create (T*& ptr);
};
////////////////////////////////////////////////////////////////////////////////
// StaticInstantiationPolicy implementation
////////////////////////////////////////////////////////////////////////////////
// Static implementation
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// Create
// -----------------------------------------------------------------------------
template<typename T>
inline void StaticInstantiationPolicy::Create (T*& ptr)
{
// Create an instance of the specified type using a statically allocated
// instance.
ptr = &StaticInstantiationHelper<T>::instance;
}
}
// --- SingletonDestroyer class ------------------------------------------------
namespace GS {
template<typename T>
class SingletonDestroyer {
// Data members:
private:
T* m_singleton;
// Construction / destruction:
public:
explicit SingletonDestroyer (T* singleton);
private:
SingletonDestroyer (const SingletonDestroyer&); // Disabled
public:
~SingletonDestroyer ();
// Operator overloading:
private:
const SingletonDestroyer& operator = (const SingletonDestroyer&); // Disabled
};
////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// Constructor
// -----------------------------------------------------------------------------
template<typename T>
inline SingletonDestroyer<T>::SingletonDestroyer (T* singleton) :
m_singleton (singleton)
{
DBASSERT (singleton != nullptr);
}
// -----------------------------------------------------------------------------
// Destructor
// -----------------------------------------------------------------------------
template<typename T>
inline SingletonDestroyer<T>::~SingletonDestroyer ()
{
if (m_singleton != nullptr) {
try {
delete m_singleton;
}
catch (Exception&) {
DBBREAK ();
}
catch (...) {
DBBREAK ();
}
}
m_singleton = nullptr;
}
}
// --- LazyInstantiationPolicy class -------------------------------------------
namespace GS {
class LazyInstantiationPolicy {
// Static implementation:
protected:
template<typename T>
static void Create (T*& ptr);
};
////////////////////////////////////////////////////////////////////////////////
// LazyInstantiationPolicy implementation
////////////////////////////////////////////////////////////////////////////////
// Static implementation
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// Create
// -----------------------------------------------------------------------------
template<class T>
inline void LazyInstantiationPolicy::Create (T*& ptr)
{
// Create a new instance of the specified type, using new, that will be
// destroyed by the associated static SingletonDestroyer instance.
typedef SingletonDestroyer<T> SingletonDestroyerT;
static SingletonDestroyerT destroyer (ptr = new T);
}
}
// --- Synchronized class ------------------------------------------------------
namespace GS {
class Synchronized {
};
}
// --- Unsynchronized class ----------------------------------------------------
namespace GS {
class Unsynchronized {
};
}
// --- Singleton class ---------------------------------------------------------
namespace GS {
template<typename T, typename InstantiationPolicy = LazyInstantiationPolicy, typename SynchronizationPolicy = Unsynchronized>
class Singleton : public InstantiationPolicy {
// Construction / destruction:
public:
Singleton ();
private:
Singleton (const Singleton&); // Disabled
// Operator overloading:
private:
const Singleton& operator = (const Singleton&); // Disabled
// Static operations:
public:
static T& GetInstance ();
};
////////////////////////////////////////////////////////////////////////////////
// Singleton implementation
////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// Default constructor
// -----------------------------------------------------------------------------
template<typename T, typename InstantiationPolicy, typename SynchronizationPolicy>
inline Singleton<T, InstantiationPolicy, SynchronizationPolicy>::Singleton ()
{
// Empty constructor body
}
////////////////////////////////////////////////////////////////////////////////
// Static operations
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// GetInstance
// -----------------------------------------------------------------------------
template<typename T, typename InstantiationPolicy, typename SynchronizationPolicy>
inline T& Singleton<T, InstantiationPolicy, SynchronizationPolicy>::GetInstance ()
{
// Note: the use of the static locale storage helps to avoid static construction
// sequence issues. (regarding when the lock is created)
static T* ptr = nullptr;
if (ptr == nullptr) {
InstantiationPolicy::Create (ptr);
}
DBASSERT (ptr != nullptr);
return *ptr;
}
}
// --- Partial template specialization of Singleton class ----------------------
namespace GS {
template<typename T, typename InstantiationPolicy>
class Singleton<T, InstantiationPolicy, Synchronized> : public InstantiationPolicy {
// Static operations:
public:
static T& GetInstance ();
};
////////////////////////////////////////////////////////////////////////////////
// Singleton implementation
////////////////////////////////////////////////////////////////////////////////
// Static operations
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// GetInstance
// -----------------------------------------------------------------------------
template<typename T, typename InstantiationPolicy>
T& Singleton<T, InstantiationPolicy, Synchronized>::GetInstance ()
{
// Note: the use of the static locale storage helps to avoid static construction
// sequence issues. (regarding when the lock is created)
static T * volatile ptr = nullptr;
// Note: the following code uses the double-checking algorithm to avoid
// expensive locking.
GS::MemoryBarrierForVolatile ();
if (ptr == nullptr) {
synchronized (SingletonLock::GetLock ()) {
if (ptr == nullptr) {
T* tmp = nullptr;
InstantiationPolicy::Create (const_cast<T*&> (tmp));
GS::MemoryBarrierForVolatile ();
ptr = tmp;
}
}
}
DBASSERT (ptr != nullptr);
return *const_cast<T*> (ptr);
}
}
#endif // GS_SINGLETON_HPP
| 24.423592 | 125 | 0.45258 | graphisoft-python |
59d7e0a4b43a844c4405e7178ab4a04fb7555249 | 1,595 | cpp | C++ | src/Component/Power/InitBat.cpp | ut-issl/s2e-core | 900fae6b738eb8765cd98c48acb2b74f05dcc68c | [
"MIT"
] | 16 | 2021-12-28T18:30:01.000Z | 2022-03-26T12:59:48.000Z | src/Component/Power/InitBat.cpp | ut-issl/s2e-core | 900fae6b738eb8765cd98c48acb2b74f05dcc68c | [
"MIT"
] | 61 | 2022-01-04T22:56:36.000Z | 2022-03-31T13:19:29.000Z | src/Component/Power/InitBat.cpp | ut-issl/s2e-core | 900fae6b738eb8765cd98c48acb2b74f05dcc68c | [
"MIT"
] | 2 | 2022-03-03T03:39:25.000Z | 2022-03-12T04:50:30.000Z | #define _CRT_SECURE_NO_WARNINGS
#include "InitBat.hpp"
#include <string>
#include <vector>
#include "Interface/InitInput/IniAccess.h"
BAT InitBAT(ClockGenerator* clock_gen, int bat_id, const std::string fname) {
IniAccess bat_conf(fname);
const std::string st_bat_id = std::to_string(static_cast<long long>(bat_id));
const char* cs = st_bat_id.data();
char Section[30] = "BAT";
strcat(Section, cs);
int number_of_series;
number_of_series = bat_conf.ReadInt(Section, "number_of_series");
int number_of_parallel;
number_of_parallel = bat_conf.ReadInt(Section, "number_of_parallel");
double cell_capacity;
cell_capacity = bat_conf.ReadDouble(Section, "cell_capacity");
int approx_order;
approx_order = bat_conf.ReadInt(Section, "approx_order");
std::vector<double> cell_discharge_curve_coeffs;
for (int i = 0; i <= approx_order; ++i) {
cell_discharge_curve_coeffs.push_back(bat_conf.ReadDouble(Section, ("cell_discharge_curve_coeffs(" + std::to_string(i) + ")").c_str()));
}
double initial_dod;
initial_dod = bat_conf.ReadDouble(Section, "initial_dod");
double cc_charge_c_rate;
cc_charge_c_rate = bat_conf.ReadDouble(Section, "cc_charge_c_rate");
double cv_charge_voltage;
cv_charge_voltage = bat_conf.ReadDouble(Section, "cv_charge_voltage");
double bat_resistance;
bat_resistance = bat_conf.ReadDouble(Section, "bat_resistance");
BAT bat(clock_gen, number_of_series, number_of_parallel, cell_capacity, cell_discharge_curve_coeffs, initial_dod, cc_charge_c_rate,
cv_charge_voltage, bat_resistance);
return bat;
}
| 30.673077 | 140 | 0.759875 | ut-issl |
59d80f38c8254363b4e2489f86e3efcf0d6e0058 | 3,315 | cpp | C++ | Src/InputUtils.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | Src/InputUtils.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | Src/InputUtils.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | #include <common.h>
#pragma hdrstop
#include <InputUtils.h>
#include <InputHandler.h>
#include <InputController.h>
#include <GinGlobals.h>
#include <NullMouseController.h>
namespace Gin {
//////////////////////////////////////////////////////////////////////////
CPtrOwner<TUserAction> CInputTranslator::SetAction( int keyCode, bool isDown, CPtrOwner<TUserAction> action )
{
const int pos = getActionIndex( keyCode, isDown );
if( actions.Size() <= pos ) {
actions.IncreaseSize( pos + 1 );
}
swap( actions[pos], action );
return action;
}
CPtrOwner<TUserAction> CInputTranslator::DetachAction( int keyCode, bool isDown )
{
const int pos = getActionIndex( keyCode, isDown );
return pos < actions.Size() ? move( actions[pos] ) : nullptr;
}
//////////////////////////////////////////////////////////////////////////
CInputTranslatorSwitcher::CInputTranslatorSwitcher( const CInputTranslator* _newTranslator ) :
prevTranslator( GinInternal::GetDefaultInputController().GetCurrentTranslator() ),
newTranslator( _newTranslator )
{
GinInternal::GetDefaultInputController().SetCurrentTranslator( newTranslator );
}
CInputTranslatorSwitcher::~CInputTranslatorSwitcher()
{
assert( GinInternal::GetDefaultInputController().GetCurrentTranslator() == newTranslator );
GinInternal::GetDefaultInputController().SetCurrentTranslator( prevTranslator );
}
//////////////////////////////////////////////////////////////////////////
CMouseMoveSwitcher::CMouseMoveSwitcher( IMouseMoveController* _newController ) :
prevController( GinInternal::GetInputHandler().getMouseController() ),
newController( _newController )
{
if( newController == nullptr ) {
newController = CNullMouseMoveController::GetInstance();
}
GinInternal::GetInputHandler().setMouseController( newController );
}
CMouseMoveSwitcher::~CMouseMoveSwitcher()
{
assert( GinInternal::GetInputHandler().getMouseController() == newController );
GinInternal::GetInputHandler().setMouseController( prevController );
}
//////////////////////////////////////////////////////////////////////////
CTextTranslatorSwitcher::CTextTranslatorSwitcher( ITextTranslator& newValue ) :
prevTranslator( GinInternal::GetInputHandler().getTextTranslator() )
{
GinInternal::GetInputHandler().setTextTranslator( &newValue );
}
CTextTranslatorSwitcher::~CTextTranslatorSwitcher()
{
GinInternal::GetInputHandler().setTextTranslator( prevTranslator );
}
bool CTextTranslatorSwitcher::IsInTextMode()
{
return GinInternal::GetInputHandler().IsInTextMode();
}
//////////////////////////////////////////////////////////////////////////
CInputSwitcher::CInputSwitcher( CInputTranslator* newTranslator, IMouseMoveController* newController ) :
transSwt( newTranslator ),
moveSwt( newController )
{
}
CInputSwitcher::CInputSwitcher( CStringPart _settingsSectionName, IMouseMoveController* newController ) :
transSwt( &getTranslator( _settingsSectionName ) ),
moveSwt( newController )
{
}
const CInputTranslator& CInputSwitcher::getTranslator( CStringPart name )
{
return GinInternal::GetInputTranslator( name );
}
CInputSwitcher::~CInputSwitcher()
{
}
//////////////////////////////////////////////////////////////////////////
} // namespace Gin.
| 30.981308 | 110 | 0.652187 | Remag |
59d97fa30d562acd8a2600314707f596a259c6fe | 2,180 | hpp | C++ | src/sample_addons.hpp | simleo/pyecvl | c044dc2ddf9bb69e93ffe06113de9365dc84e168 | [
"MIT"
] | 2 | 2020-04-29T13:17:15.000Z | 2021-01-07T19:13:14.000Z | src/sample_addons.hpp | simleo/pyecvl | c044dc2ddf9bb69e93ffe06113de9365dc84e168 | [
"MIT"
] | 19 | 2020-01-16T11:55:07.000Z | 2022-02-28T11:27:40.000Z | src/sample_addons.hpp | deephealthproject/pyecvl | 3fb256a77ab6d7ff62219044d54b51d84471db6e | [
"MIT"
] | 2 | 2020-01-20T13:47:05.000Z | 2020-02-27T11:13:32.000Z | // Copyright (c) 2019-2021 CRS4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <pybind11/pybind11.h>
#include <ecvl/dataset_parser.h>
std::vector<std::string> getSampleLocation(ecvl::Sample &s) {
std::vector<std::string> loc;
for (const auto &path: s.location_) {
loc.push_back(std::string(path));
}
return loc;
}
void setSampleLocation(ecvl::Sample &s, std::vector<std::string> loc) {
std::vector<ecvl::filesystem::path> location_;
for (const auto &str: loc) {
location_.push_back(ecvl::filesystem::path(str));
}
s.location_ = location_;
}
ecvl::optional<std::string> getSampleLabelPath(ecvl::Sample &s) {
if (s.label_path_) {
std::string rval = *(s.label_path_);
return rval;
}
return std::nullopt;
}
void setSampleLabelPath(ecvl::Sample &s, std::string lp) {
s.label_path_ = ecvl::filesystem::path(lp);
}
template <typename type_, typename... options>
void sample_addons(pybind11::class_<type_, options...> &cl) {
cl.def_property("location_", getSampleLocation, setSampleLocation);
cl.def_property("label_path_", getSampleLabelPath, setSampleLabelPath);
}
| 34.603175 | 80 | 0.729358 | simleo |
59dacd31a9c2c21f71e45db0602c827ac200b05d | 10,482 | cpp | C++ | src/vm/ds/NumericVariant.cpp | normal-coder/polarphp | a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe | [
"PHP-3.01"
] | 1 | 2019-01-28T01:33:49.000Z | 2019-01-28T01:33:49.000Z | src/vm/ds/NumericVariant.cpp | normal-coder/polarphp | a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe | [
"PHP-3.01"
] | null | null | null | src/vm/ds/NumericVariant.cpp | normal-coder/polarphp | a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe | [
"PHP-3.01"
] | null | null | null | // This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2018 polarphp software foundation
// Copyright (c) 2017 - 2018 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/12/23.
#include "polarphp/vm/ds/NumericVariant.h"
#include "polarphp/vm/ds/DoubleVariant.h"
#include "polarphp/vm/ds/ArrayItemProxy.h"
#include <cmath>
namespace polar {
namespace vmapi {
NumericVariant::NumericVariant()
: Variant(0)
{}
NumericVariant::NumericVariant(std::int8_t value)
: Variant(value)
{}
NumericVariant::NumericVariant(std::int16_t value)
: Variant(value)
{}
NumericVariant::NumericVariant(std::int32_t value)
: Variant(value)
{}
#if SIZEOF_ZEND_LONG == 8
NumericVariant::NumericVariant(std::int64_t value)
: Variant(value)
{}
#endif
NumericVariant::NumericVariant(zval &other, bool isRef)
: NumericVariant(&other, isRef)
{}
NumericVariant::NumericVariant(zval &&other, bool isRef)
: NumericVariant(&other, isRef)
{}
NumericVariant::NumericVariant(zval *other, bool isRef)
{
zval *self = getUnDerefZvalPtr();
if (nullptr != other) {
if ((isRef && (Z_TYPE_P(other) == IS_LONG ||
(Z_TYPE_P(other) == IS_REFERENCE && Z_TYPE_P(Z_REFVAL_P(other)) == IS_LONG))) ||
(!isRef && (Z_TYPE_P(other) == IS_REFERENCE && Z_TYPE_P(Z_REFVAL_P(other)) == IS_LONG))) {
// for support pass ref arg when pass variant args
ZVAL_MAKE_REF(other);
zend_reference *ref = Z_REF_P(other);
GC_ADDREF(ref);
ZVAL_REF(self, ref);
} else {
// here the zval of other pointer maybe not initialize
ZVAL_DUP(self, other);
convert_to_long(self);
}
} else {
ZVAL_LONG(self, 0);
}
}
NumericVariant::NumericVariant(const NumericVariant &other)
: Variant(other)
{}
NumericVariant::NumericVariant(NumericVariant &other, bool isRef)
{
zval *self = getUnDerefZvalPtr();
if (!isRef) {
ZVAL_LONG(self, other.toLong());
} else {
zval *source = other.getUnDerefZvalPtr();
ZVAL_MAKE_REF(source);
ZVAL_COPY(self, source);
}
}
NumericVariant::NumericVariant(NumericVariant &&other) noexcept
: Variant(std::move(other))
{}
NumericVariant::NumericVariant(const Variant &other)
{
zval *from = const_cast<zval *>(other.getZvalPtr());
zval *self = getZvalPtr();
if (other.getType() == Type::Numeric) {
ZVAL_LONG(self, zval_get_long(from));
} else {
zval temp;
ZVAL_DUP(&temp, from);
convert_to_long(&temp);
ZVAL_COPY_VALUE(self, &temp);
}
}
NumericVariant::NumericVariant(Variant &&other)
: Variant(std::move(other))
{
if (getType() != Type::Long) {
convert_to_long(getUnDerefZvalPtr());
}
}
//NumericVariant::operator vmapi_long () const
//{
// return zval_get_long(const_cast<zval *>(getZvalPtr()));
//}
//NumericVariant::operator int () const
//{
// return zval_get_long(const_cast<zval *>(getZvalPtr()));
//}
vmapi_long NumericVariant::toLong() const noexcept
{
return zval_get_long(const_cast<zval *>(getZvalPtr()));
}
bool NumericVariant::toBoolean() const noexcept
{
return zval_get_long(const_cast<zval *>(getZvalPtr()));
}
NumericVariant &NumericVariant::operator =(std::int8_t other)
{
ZVAL_LONG(getZvalPtr(), static_cast<vmapi_long>(other));
return *this;
}
NumericVariant &NumericVariant::operator =(std::int16_t other)
{
ZVAL_LONG(getZvalPtr(), static_cast<vmapi_long>(other));
return *this;
}
NumericVariant &NumericVariant::operator =(std::int32_t other)
{
ZVAL_LONG(getZvalPtr(), static_cast<vmapi_long>(other));
return *this;
}
NumericVariant &NumericVariant::operator =(std::int64_t other)
{
ZVAL_LONG(getZvalPtr(), static_cast<vmapi_long>(other));
return *this;
}
NumericVariant &NumericVariant::operator =(double other)
{
ZVAL_LONG(getZvalPtr(), static_cast<vmapi_long>(other));
return *this;
}
NumericVariant &NumericVariant::operator =(const NumericVariant &other)
{
if (this != &other) {
ZVAL_LONG(getZvalPtr(), other.toLong());
}
return *this;
}
NumericVariant &NumericVariant::operator =(const DoubleVariant &other)
{
ZVAL_LONG(getZvalPtr(), static_cast<vmapi_long>(other.toDouble()));
return *this;
}
NumericVariant &NumericVariant::operator =(ArrayItemProxy &&other)
{
return operator =(other.toNumericVariant());
}
NumericVariant &NumericVariant::operator =(const Variant &other)
{
zval *self = getZvalPtr();
zval *from = const_cast<zval *>(other.getZvalPtr());
if (other.getType() == Type::Long) {
ZVAL_LONG(self, Z_LVAL_P(from));
} else {
zval temp;
ZVAL_DUP(&temp, from);
convert_to_long(&temp);
ZVAL_COPY_VALUE(self, &temp);
}
return *this;
}
NumericVariant &NumericVariant::operator ++()
{
ZVAL_LONG(getZvalPtr(), toLong() + 1);
return *this;
}
NumericVariant NumericVariant::operator ++(int)
{
NumericVariant ret(toLong());
ZVAL_LONG(getZvalPtr(), toLong() + 1);
return ret;
}
NumericVariant &NumericVariant::operator --()
{
ZVAL_LONG(getZvalPtr(), toLong() - 1);
return *this;
}
NumericVariant NumericVariant::operator --(int)
{
NumericVariant ret(toLong());
ZVAL_LONG(getZvalPtr(), toLong() - 1);
return ret;
}
NumericVariant &NumericVariant::operator +=(double value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() + std::lround(value));
return *this;
}
NumericVariant &NumericVariant::operator +=(const NumericVariant &value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() + value.toLong());
return *this;
}
NumericVariant &NumericVariant::operator -=(double value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() - std::lround(value));
return *this;
}
NumericVariant &NumericVariant::operator -=(const NumericVariant &value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() - value.toLong());
return *this;
}
NumericVariant &NumericVariant::operator *=(double value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() * std::lround(value));
return *this;
}
NumericVariant &NumericVariant::operator *=(const NumericVariant &value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() * value.toLong());
return *this;
}
NumericVariant &NumericVariant::operator /=(double value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() / std::lround(value));
return *this;
}
NumericVariant &NumericVariant::operator /=(const NumericVariant &value) noexcept
{
ZVAL_LONG(getZvalPtr(), toLong() / value.toLong());
return *this;
}
NumericVariant::~NumericVariant() noexcept
{}
bool operator ==(const NumericVariant &lhs, const NumericVariant &rhs) noexcept
{
return lhs.toLong() == rhs.toLong();
}
bool operator !=(const NumericVariant &lhs, const NumericVariant &rhs) noexcept
{
return lhs.toLong() != rhs.toLong();
}
bool operator <(const NumericVariant &lhs, const NumericVariant &rhs) noexcept
{
return lhs.toLong() < rhs.toLong();
}
bool operator <=(const NumericVariant &lhs, const NumericVariant &rhs) noexcept
{
return lhs.toLong() <= rhs.toLong();
}
bool operator >(const NumericVariant &lhs, const NumericVariant &rhs) noexcept
{
return lhs.toLong() > rhs.toLong();
}
bool operator >=(const NumericVariant &lhs, const NumericVariant &rhs) noexcept
{
return lhs.toLong() >= rhs.toLong();
}
bool operator ==(double lhs, const NumericVariant &rhs) noexcept
{
return (lhs - static_cast<double>(rhs.toLong())) == 0;
}
bool operator !=(double lhs, const NumericVariant &rhs) noexcept
{
return (lhs - static_cast<double>(rhs.toLong())) != 0;
}
bool operator <(double lhs, const NumericVariant &rhs) noexcept
{
return (lhs - static_cast<double>(rhs.toLong())) < 0;
}
bool operator <=(double lhs, const NumericVariant &rhs) noexcept
{
return (lhs - static_cast<double>(rhs.toLong())) <= 0;
}
bool operator >(double lhs, const NumericVariant &rhs) noexcept
{
return (lhs - static_cast<double>(rhs.toLong())) > 0;
}
bool operator >=(double lhs, const NumericVariant &rhs) noexcept
{
return (lhs - static_cast<double>(rhs.toLong())) >= 0;
}
bool operator ==(const NumericVariant &lhs, double rhs) noexcept
{
return (static_cast<double>(lhs.toLong()) - rhs) == 0;
}
bool operator !=(const NumericVariant &lhs, double rhs) noexcept
{
return (static_cast<double>(lhs.toLong()) - rhs) != 0;
}
bool operator <(const NumericVariant &lhs, double rhs) noexcept
{
return (static_cast<double>(lhs.toLong()) - rhs) < 0;
}
bool operator <=(const NumericVariant &lhs, double rhs) noexcept
{
return (static_cast<double>(lhs.toLong()) - rhs) <= 0;
}
bool operator >(const NumericVariant &lhs, double rhs) noexcept
{
return (static_cast<double>(lhs.toLong()) - rhs) > 0;
}
bool operator >=(const NumericVariant &lhs, double rhs) noexcept
{
return (static_cast<double>(lhs.toLong()) - rhs) >= 0;
}
double operator +(double lhs, const NumericVariant &rhs) noexcept
{
return lhs + rhs.toLong();
}
double operator -(double lhs, const NumericVariant &rhs) noexcept
{
return lhs - rhs.toLong();
}
double operator *(double lhs, const NumericVariant &rhs) noexcept
{
return lhs * rhs.toLong();
}
double operator /(double lhs, const NumericVariant &rhs) noexcept
{
return lhs / rhs.toLong();
}
double operator +(const NumericVariant &lhs, double rhs) noexcept
{
return lhs.toLong() + rhs;
}
double operator -(const NumericVariant &lhs, double rhs) noexcept
{
return lhs.toLong() - rhs;
}
double operator *(const NumericVariant &lhs, double rhs) noexcept
{
return lhs.toLong() * rhs;
}
double operator /(const NumericVariant &lhs, double rhs) noexcept
{
return lhs.toLong() / rhs;
}
vmapi_long operator +(const NumericVariant &lhs, NumericVariant rhs) noexcept
{
return lhs.toLong() + rhs.toLong();
}
vmapi_long operator -(const NumericVariant &lhs, NumericVariant rhs) noexcept
{
return lhs.toLong() + rhs.toLong();
}
vmapi_long operator *(const NumericVariant &lhs, NumericVariant rhs) noexcept
{
return lhs.toLong() + rhs.toLong();
}
vmapi_long operator /(const NumericVariant &lhs, NumericVariant rhs) noexcept
{
return lhs.toLong() + rhs.toLong();
}
vmapi_long operator %(const NumericVariant &lhs, NumericVariant rhs) noexcept
{
return lhs.toLong() + rhs.toLong();
}
} // vmapi
} // polar
| 24.263889 | 100 | 0.691471 | normal-coder |
59db45fa198c6034b549628f7da768b00013db4a | 382 | cpp | C++ | A-FF/BaseEntity.cpp | Aeomi/A-FF | f0f1d0fc71776880575020cd4d0a4506e3e11aea | [
"MIT"
] | null | null | null | A-FF/BaseEntity.cpp | Aeomi/A-FF | f0f1d0fc71776880575020cd4d0a4506e3e11aea | [
"MIT"
] | null | null | null | A-FF/BaseEntity.cpp | Aeomi/A-FF | f0f1d0fc71776880575020cd4d0a4506e3e11aea | [
"MIT"
] | null | null | null | #include "BaseEntity.h"
#include "RenderHandler.h"
#include "EntityHandler.h"
#include "Transform.h"
#include "Collider.h"
#include "Renderer.h"
BaseEntity::BaseEntity() {
_transform = new Transform();
_collider = new Collider();
_renderer = new Renderer(this);
EntityHandler::registerEntity(this);
}
BaseEntity::~BaseEntity() {}
void BaseEntity::update(double dt) {}
| 15.28 | 37 | 0.717277 | Aeomi |
59dc49779e45098555fc2ec43748426d7f416ff2 | 21,459 | cpp | C++ | src/bricklet_ambient_light_v3.cpp | davidplotzki/sensorlogger | 8ee255fba5f8560650e2b79fc967aeec8d8ec7b7 | [
"MIT"
] | null | null | null | src/bricklet_ambient_light_v3.cpp | davidplotzki/sensorlogger | 8ee255fba5f8560650e2b79fc967aeec8d8ec7b7 | [
"MIT"
] | null | null | null | src/bricklet_ambient_light_v3.cpp | davidplotzki/sensorlogger | 8ee255fba5f8560650e2b79fc967aeec8d8ec7b7 | [
"MIT"
] | null | null | null | /* ***********************************************************
* This file was automatically generated on 2021-05-06. *
* *
* C/C++ Bindings Version 2.1.32 *
* *
* If you have a bugfix for this file and want to commit it, *
* please fix the bug in the generator. You can find a link *
* to the generators git repository on tinkerforge.com *
*************************************************************/
#define IPCON_EXPOSE_INTERNALS
#include "bricklet_ambient_light_v3.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*Illuminance_CallbackFunction)(uint32_t illuminance, void *user_data);
#if defined _MSC_VER || defined __BORLANDC__
#pragma pack(push)
#pragma pack(1)
#define ATTRIBUTE_PACKED
#elif defined __GNUC__
#ifdef _WIN32
// workaround struct packing bug in GCC 4.7 on Windows
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52991
#define ATTRIBUTE_PACKED __attribute__((gcc_struct, packed))
#else
#define ATTRIBUTE_PACKED __attribute__((packed))
#endif
#else
#error unknown compiler, do not know how to enable struct packing
#endif
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetIlluminance_Request;
typedef struct {
PacketHeader header;
uint32_t illuminance;
} ATTRIBUTE_PACKED GetIlluminance_Response;
typedef struct {
PacketHeader header;
uint32_t period;
uint8_t value_has_to_change;
char option;
uint32_t min;
uint32_t max;
} ATTRIBUTE_PACKED SetIlluminanceCallbackConfiguration_Request;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetIlluminanceCallbackConfiguration_Request;
typedef struct {
PacketHeader header;
uint32_t period;
uint8_t value_has_to_change;
char option;
uint32_t min;
uint32_t max;
} ATTRIBUTE_PACKED GetIlluminanceCallbackConfiguration_Response;
typedef struct {
PacketHeader header;
uint32_t illuminance;
} ATTRIBUTE_PACKED Illuminance_Callback;
typedef struct {
PacketHeader header;
uint8_t illuminance_range;
uint8_t integration_time;
} ATTRIBUTE_PACKED SetConfiguration_Request;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetConfiguration_Request;
typedef struct {
PacketHeader header;
uint8_t illuminance_range;
uint8_t integration_time;
} ATTRIBUTE_PACKED GetConfiguration_Response;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetSPITFPErrorCount_Request;
typedef struct {
PacketHeader header;
uint32_t error_count_ack_checksum;
uint32_t error_count_message_checksum;
uint32_t error_count_frame;
uint32_t error_count_overflow;
} ATTRIBUTE_PACKED GetSPITFPErrorCount_Response;
typedef struct {
PacketHeader header;
uint8_t mode;
} ATTRIBUTE_PACKED SetBootloaderMode_Request;
typedef struct {
PacketHeader header;
uint8_t status;
} ATTRIBUTE_PACKED SetBootloaderMode_Response;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetBootloaderMode_Request;
typedef struct {
PacketHeader header;
uint8_t mode;
} ATTRIBUTE_PACKED GetBootloaderMode_Response;
typedef struct {
PacketHeader header;
uint32_t pointer;
} ATTRIBUTE_PACKED SetWriteFirmwarePointer_Request;
typedef struct {
PacketHeader header;
uint8_t data[64];
} ATTRIBUTE_PACKED WriteFirmware_Request;
typedef struct {
PacketHeader header;
uint8_t status;
} ATTRIBUTE_PACKED WriteFirmware_Response;
typedef struct {
PacketHeader header;
uint8_t config;
} ATTRIBUTE_PACKED SetStatusLEDConfig_Request;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetStatusLEDConfig_Request;
typedef struct {
PacketHeader header;
uint8_t config;
} ATTRIBUTE_PACKED GetStatusLEDConfig_Response;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetChipTemperature_Request;
typedef struct {
PacketHeader header;
int16_t temperature;
} ATTRIBUTE_PACKED GetChipTemperature_Response;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED Reset_Request;
typedef struct {
PacketHeader header;
uint32_t uid;
} ATTRIBUTE_PACKED WriteUID_Request;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED ReadUID_Request;
typedef struct {
PacketHeader header;
uint32_t uid;
} ATTRIBUTE_PACKED ReadUID_Response;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetIdentity_Request;
typedef struct {
PacketHeader header;
char uid[8];
char connected_uid[8];
char position;
uint8_t hardware_version[3];
uint8_t firmware_version[3];
uint16_t device_identifier;
} ATTRIBUTE_PACKED GetIdentity_Response;
#if defined _MSC_VER || defined __BORLANDC__
#pragma pack(pop)
#endif
#undef ATTRIBUTE_PACKED
static void ambient_light_v3_callback_wrapper_illuminance(DevicePrivate *device_p, Packet *packet) {
Illuminance_CallbackFunction callback_function;
void *user_data;
Illuminance_Callback *callback;
if (packet->header.length != sizeof(Illuminance_Callback)) {
return; // silently ignoring callback with wrong length
}
callback_function = (Illuminance_CallbackFunction)device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_V3_CALLBACK_ILLUMINANCE];
user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_V3_CALLBACK_ILLUMINANCE];
callback = (Illuminance_Callback *)packet;
(void)callback; // avoid unused variable warning
if (callback_function == NULL) {
return;
}
callback->illuminance = leconvert_uint32_from(callback->illuminance);
callback_function(callback->illuminance, user_data);
}
void ambient_light_v3_create(AmbientLightV3 *ambient_light_v3, const char *uid, IPConnection *ipcon) {
IPConnectionPrivate *ipcon_p = ipcon->p;
DevicePrivate *device_p;
device_create(ambient_light_v3, uid, ipcon_p, 2, 0, 0, AMBIENT_LIGHT_V3_DEVICE_IDENTIFIER);
device_p = ambient_light_v3->p;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_ILLUMINANCE] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_SET_ILLUMINANCE_CALLBACK_CONFIGURATION] = DEVICE_RESPONSE_EXPECTED_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_ILLUMINANCE_CALLBACK_CONFIGURATION] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_SET_CONFIGURATION] = DEVICE_RESPONSE_EXPECTED_FALSE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_CONFIGURATION] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_SPITFP_ERROR_COUNT] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_SET_BOOTLOADER_MODE] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_BOOTLOADER_MODE] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_SET_WRITE_FIRMWARE_POINTER] = DEVICE_RESPONSE_EXPECTED_FALSE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_WRITE_FIRMWARE] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_SET_STATUS_LED_CONFIG] = DEVICE_RESPONSE_EXPECTED_FALSE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_STATUS_LED_CONFIG] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_CHIP_TEMPERATURE] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_RESET] = DEVICE_RESPONSE_EXPECTED_FALSE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_WRITE_UID] = DEVICE_RESPONSE_EXPECTED_FALSE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_READ_UID] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[AMBIENT_LIGHT_V3_FUNCTION_GET_IDENTITY] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->callback_wrappers[AMBIENT_LIGHT_V3_CALLBACK_ILLUMINANCE] = ambient_light_v3_callback_wrapper_illuminance;
ipcon_add_device(ipcon_p, device_p);
}
void ambient_light_v3_destroy(AmbientLightV3 *ambient_light_v3) {
device_release(ambient_light_v3->p);
}
int ambient_light_v3_get_response_expected(AmbientLightV3 *ambient_light_v3, uint8_t function_id, bool *ret_response_expected) {
return device_get_response_expected(ambient_light_v3->p, function_id, ret_response_expected);
}
int ambient_light_v3_set_response_expected(AmbientLightV3 *ambient_light_v3, uint8_t function_id, bool response_expected) {
return device_set_response_expected(ambient_light_v3->p, function_id, response_expected);
}
int ambient_light_v3_set_response_expected_all(AmbientLightV3 *ambient_light_v3, bool response_expected) {
return device_set_response_expected_all(ambient_light_v3->p, response_expected);
}
void ambient_light_v3_register_callback(AmbientLightV3 *ambient_light_v3, int16_t callback_id, void (*function)(void), void *user_data) {
device_register_callback(ambient_light_v3->p, callback_id, function, user_data);
}
int ambient_light_v3_get_api_version(AmbientLightV3 *ambient_light_v3, uint8_t ret_api_version[3]) {
return device_get_api_version(ambient_light_v3->p, ret_api_version);
}
int ambient_light_v3_get_illuminance(AmbientLightV3 *ambient_light_v3, uint32_t *ret_illuminance) {
DevicePrivate *device_p = ambient_light_v3->p;
GetIlluminance_Request request;
GetIlluminance_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_ILLUMINANCE, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_illuminance = leconvert_uint32_from(response.illuminance);
return ret;
}
int ambient_light_v3_set_illuminance_callback_configuration(AmbientLightV3 *ambient_light_v3, uint32_t period, bool value_has_to_change, char option, uint32_t min, uint32_t max) {
DevicePrivate *device_p = ambient_light_v3->p;
SetIlluminanceCallbackConfiguration_Request request;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_SET_ILLUMINANCE_CALLBACK_CONFIGURATION, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.period = leconvert_uint32_to(period);
request.value_has_to_change = value_has_to_change ? 1 : 0;
request.option = option;
request.min = leconvert_uint32_to(min);
request.max = leconvert_uint32_to(max);
ret = device_send_request(device_p, (Packet *)&request, NULL, 0);
return ret;
}
int ambient_light_v3_get_illuminance_callback_configuration(AmbientLightV3 *ambient_light_v3, uint32_t *ret_period, bool *ret_value_has_to_change, char *ret_option, uint32_t *ret_min, uint32_t *ret_max) {
DevicePrivate *device_p = ambient_light_v3->p;
GetIlluminanceCallbackConfiguration_Request request;
GetIlluminanceCallbackConfiguration_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_ILLUMINANCE_CALLBACK_CONFIGURATION, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_period = leconvert_uint32_from(response.period);
*ret_value_has_to_change = response.value_has_to_change != 0;
*ret_option = response.option;
*ret_min = leconvert_uint32_from(response.min);
*ret_max = leconvert_uint32_from(response.max);
return ret;
}
int ambient_light_v3_set_configuration(AmbientLightV3 *ambient_light_v3, uint8_t illuminance_range, uint8_t integration_time) {
DevicePrivate *device_p = ambient_light_v3->p;
SetConfiguration_Request request;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_SET_CONFIGURATION, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.illuminance_range = illuminance_range;
request.integration_time = integration_time;
ret = device_send_request(device_p, (Packet *)&request, NULL, 0);
return ret;
}
int ambient_light_v3_get_configuration(AmbientLightV3 *ambient_light_v3, uint8_t *ret_illuminance_range, uint8_t *ret_integration_time) {
DevicePrivate *device_p = ambient_light_v3->p;
GetConfiguration_Request request;
GetConfiguration_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_CONFIGURATION, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_illuminance_range = response.illuminance_range;
*ret_integration_time = response.integration_time;
return ret;
}
int ambient_light_v3_get_spitfp_error_count(AmbientLightV3 *ambient_light_v3, uint32_t *ret_error_count_ack_checksum, uint32_t *ret_error_count_message_checksum, uint32_t *ret_error_count_frame, uint32_t *ret_error_count_overflow) {
DevicePrivate *device_p = ambient_light_v3->p;
GetSPITFPErrorCount_Request request;
GetSPITFPErrorCount_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_SPITFP_ERROR_COUNT, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_error_count_ack_checksum = leconvert_uint32_from(response.error_count_ack_checksum);
*ret_error_count_message_checksum = leconvert_uint32_from(response.error_count_message_checksum);
*ret_error_count_frame = leconvert_uint32_from(response.error_count_frame);
*ret_error_count_overflow = leconvert_uint32_from(response.error_count_overflow);
return ret;
}
int ambient_light_v3_set_bootloader_mode(AmbientLightV3 *ambient_light_v3, uint8_t mode, uint8_t *ret_status) {
DevicePrivate *device_p = ambient_light_v3->p;
SetBootloaderMode_Request request;
SetBootloaderMode_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_SET_BOOTLOADER_MODE, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.mode = mode;
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_status = response.status;
return ret;
}
int ambient_light_v3_get_bootloader_mode(AmbientLightV3 *ambient_light_v3, uint8_t *ret_mode) {
DevicePrivate *device_p = ambient_light_v3->p;
GetBootloaderMode_Request request;
GetBootloaderMode_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_BOOTLOADER_MODE, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_mode = response.mode;
return ret;
}
int ambient_light_v3_set_write_firmware_pointer(AmbientLightV3 *ambient_light_v3, uint32_t pointer) {
DevicePrivate *device_p = ambient_light_v3->p;
SetWriteFirmwarePointer_Request request;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_SET_WRITE_FIRMWARE_POINTER, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.pointer = leconvert_uint32_to(pointer);
ret = device_send_request(device_p, (Packet *)&request, NULL, 0);
return ret;
}
int ambient_light_v3_write_firmware(AmbientLightV3 *ambient_light_v3, uint8_t data[64], uint8_t *ret_status) {
DevicePrivate *device_p = ambient_light_v3->p;
WriteFirmware_Request request;
WriteFirmware_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_WRITE_FIRMWARE, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
memcpy(request.data, data, 64 * sizeof(uint8_t));
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_status = response.status;
return ret;
}
int ambient_light_v3_set_status_led_config(AmbientLightV3 *ambient_light_v3, uint8_t config) {
DevicePrivate *device_p = ambient_light_v3->p;
SetStatusLEDConfig_Request request;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_SET_STATUS_LED_CONFIG, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.config = config;
ret = device_send_request(device_p, (Packet *)&request, NULL, 0);
return ret;
}
int ambient_light_v3_get_status_led_config(AmbientLightV3 *ambient_light_v3, uint8_t *ret_config) {
DevicePrivate *device_p = ambient_light_v3->p;
GetStatusLEDConfig_Request request;
GetStatusLEDConfig_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_STATUS_LED_CONFIG, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_config = response.config;
return ret;
}
int ambient_light_v3_get_chip_temperature(AmbientLightV3 *ambient_light_v3, int16_t *ret_temperature) {
DevicePrivate *device_p = ambient_light_v3->p;
GetChipTemperature_Request request;
GetChipTemperature_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_CHIP_TEMPERATURE, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_temperature = leconvert_int16_from(response.temperature);
return ret;
}
int ambient_light_v3_reset(AmbientLightV3 *ambient_light_v3) {
DevicePrivate *device_p = ambient_light_v3->p;
Reset_Request request;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_RESET, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, NULL, 0);
return ret;
}
int ambient_light_v3_write_uid(AmbientLightV3 *ambient_light_v3, uint32_t uid) {
DevicePrivate *device_p = ambient_light_v3->p;
WriteUID_Request request;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_WRITE_UID, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.uid = leconvert_uint32_to(uid);
ret = device_send_request(device_p, (Packet *)&request, NULL, 0);
return ret;
}
int ambient_light_v3_read_uid(AmbientLightV3 *ambient_light_v3, uint32_t *ret_uid) {
DevicePrivate *device_p = ambient_light_v3->p;
ReadUID_Request request;
ReadUID_Response response;
int ret;
ret = device_check_validity(device_p);
if (ret < 0) {
return ret;
}
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_READ_UID, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
*ret_uid = leconvert_uint32_from(response.uid);
return ret;
}
int ambient_light_v3_get_identity(AmbientLightV3 *ambient_light_v3, char ret_uid[8], char ret_connected_uid[8], char *ret_position, uint8_t ret_hardware_version[3], uint8_t ret_firmware_version[3], uint16_t *ret_device_identifier) {
DevicePrivate *device_p = ambient_light_v3->p;
GetIdentity_Request request;
GetIdentity_Response response;
int ret;
ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_V3_FUNCTION_GET_IDENTITY, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response));
if (ret < 0) {
return ret;
}
memcpy(ret_uid, response.uid, 8);
memcpy(ret_connected_uid, response.connected_uid, 8);
*ret_position = response.position;
memcpy(ret_hardware_version, response.hardware_version, 3 * sizeof(uint8_t));
memcpy(ret_firmware_version, response.firmware_version, 3 * sizeof(uint8_t));
*ret_device_identifier = leconvert_uint16_from(response.device_identifier);
return ret;
}
#ifdef __cplusplus
}
#endif
| 28.310026 | 232 | 0.785265 | davidplotzki |
59dd89ff9e6cf68ba0d66c6d42daac72d1eea72b | 1,413 | hpp | C++ | lib/expected.hpp | 1984not-GmbH/molch | c7f1f646c800ef3388f36e8805a3b94d33d85b12 | [
"MIT"
] | 15 | 2016-04-12T17:12:19.000Z | 2019-08-14T17:46:17.000Z | lib/expected.hpp | 1984not-GmbH/molch | c7f1f646c800ef3388f36e8805a3b94d33d85b12 | [
"MIT"
] | 63 | 2016-03-22T14:35:31.000Z | 2018-07-04T22:17:07.000Z | lib/expected.hpp | 1984not-GmbH/molch | c7f1f646c800ef3388f36e8805a3b94d33d85b12 | [
"MIT"
] | 1 | 2017-08-17T09:27:30.000Z | 2017-08-17T09:27:30.000Z | /*
* Molch, an implementation of the axolotl ratchet based on libsodium
*
* ISC License
*
* Copyright (C) 2015-2018 1984not Security GmbH
* Author: Max Bruckner (FSMaxB)
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef LIB_EXPECTED_HPP
#define LIB_EXPECTED_HPP
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wmultiple-inheritance"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wsuggest-override"
#include <experimental/expected2.hpp>
#pragma GCC diagnostic pop
using std::experimental::expected;
using std::experimental::make_unexpected;
using std::experimental::unexpected;
#endif /* LIB_EXPECTED_HPP */
| 37.184211 | 75 | 0.776362 | 1984not-GmbH |
59e014034d3020e6f741c32e602d11ed2304a9da | 2,090 | cpp | C++ | BlackVision/LibBlackVision/Source/Engine/Models/Timeline/TimeEvaluatorBase.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | 1 | 2022-01-28T11:43:47.000Z | 2022-01-28T11:43:47.000Z | BlackVision/LibBlackVision/Source/Engine/Models/Timeline/TimeEvaluatorBase.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | BlackVision/LibBlackVision/Source/Engine/Models/Timeline/TimeEvaluatorBase.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "TimeEvaluatorBase.h"
#include "Dynamic/DefaultTimeline.h"
#include "Static/ConstTimeEvaluator.h"
#include "Static/OffsetTimeEvaluator.h"
#include "Serialization/IDeserializer.h"
#include "Serialization/BV/CloneViaSerialization.h"
#include "Assets/AssetDescsWithUIDs.h"
#include "Memory/MemoryLeaks.h"
namespace bv {
// serialization stuff
//template std::vector< std::shared_ptr< model::TimeEvaluatorBase< model::ITimeEvaluator > > > DeserializeArray( const IDeserializer&, std::string name );
namespace model {
// *******************************
//
ITimeEvaluatorPtr TimeEvaluatorBase< ITimeEvaluator >::Create ( const IDeserializer& dob )
{
auto type = dob.GetAttribute( "type" );
if( type == "default" )
return DefaultTimeline::Create( dob );
else if( type == "offset" )
return OffsetTimeEvaluator::Create( dob );
else if( type == "const" )
return ConstTimeEvaluator::Create( dob );
else
{
assert( false );
return nullptr;
}
}
// *******************************
//
ITimeEvaluatorPtr TimeEvaluatorBase< ITimeEvaluator >::CloneTyped () const
{
return CloneViaSerialization::Clone( this, "timeline", nullptr, nullptr );
}
// *******************************
//
template<>
ICloneablePtr TimeEvaluatorBase< ITimeEvaluator >::Clone () const
{
return CloneTyped();
}
// *******************************
//
ITimeEvaluatorPtr TimeEvaluatorBase< ITimeline >::CloneTyped () const
{
auto thisTE = reinterpret_cast< const TimeEvaluatorBase< ITimeEvaluator >* >( this );
auto clone = CloneViaSerialization::Clone< TimeEvaluatorBase< ITimeEvaluator > >( thisTE, "timeline", nullptr, nullptr );
return clone;
}
// *******************************
//
template<>
ICloneablePtr TimeEvaluatorBase< ITimeline >::Clone () const
{
return CloneTyped();
}
} }
| 26.455696 | 179 | 0.57512 | black-vision-engine |
59e023765cc73ca41365d790adc99deaed7423c9 | 739 | hpp | C++ | src/LibKyra/Statements/VarDeclarationStmt.hpp | LukasPietzschmann/Lou | 751dd68bda43e53604fb59e9d85c1e77554534ad | [
"MIT"
] | 3 | 2022-01-08T16:12:07.000Z | 2022-03-18T18:38:36.000Z | src/LibKyra/Statements/VarDeclarationStmt.hpp | LukasPietzschmann/Lou | 751dd68bda43e53604fb59e9d85c1e77554534ad | [
"MIT"
] | null | null | null | src/LibKyra/Statements/VarDeclarationStmt.hpp | LukasPietzschmann/Lou | 751dd68bda43e53604fb59e9d85c1e77554534ad | [
"MIT"
] | null | null | null | #pragma once
#include "../Expressions/Expression.hpp"
#include "../Token.hpp"
#include "Statement.hpp"
namespace Kyra {
struct Position;
class TypeExpr;
class VarDeclarationStmt : public Statement {
public:
VarDeclarationStmt(const Position& position,
Token identifier,
Expression::Ptr initializer,
std::shared_ptr<TypeExpr> type,
bool is_mutable = true);
~VarDeclarationStmt() override = default;
void accept(StatementVisitor& visitor) override;
const Token& get_identifier() const;
Expression::Ptr get_initializer() const;
std::shared_ptr<TypeExpr> get_type() const;
bool is_mutable() const;
private:
Token m_identifier;
Expression::Ptr m_initializer;
std::shared_ptr<TypeExpr> m_type;
bool m_is_mutable;
};
} | 23.09375 | 49 | 0.760487 | LukasPietzschmann |
59e478aded0f667bbfff21dc33c1242c48e51cc9 | 973 | hpp | C++ | TorchLib/Source/ReLU.hpp | DoDoENT/jtorch | 2f92d397c8dc6fd7f17fe682cb7ce38314086c8e | [
"BSD-2-Clause"
] | null | null | null | TorchLib/Source/ReLU.hpp | DoDoENT/jtorch | 2f92d397c8dc6fd7f17fe682cb7ce38314086c8e | [
"BSD-2-Clause"
] | null | null | null | TorchLib/Source/ReLU.hpp | DoDoENT/jtorch | 2f92d397c8dc6fd7f17fe682cb7ce38314086c8e | [
"BSD-2-Clause"
] | null | null | null | //
// Threshold.hpp
//
// Created by Jonathan Tompson on 4/1/13.
//
#pragma once
#include <string> // for string, istream
#include "TorchStage.hpp" // for ::THRESHOLD_STAGE, TorchStage, TorchStageType
namespace mtorch {
class TorchData;
class Threshold : public TorchStage {
public:
// Constructor / Destructor
Threshold();
virtual ~Threshold();
virtual TorchStageType type() const { return THRESHOLD_STAGE; }
virtual std::string name() const { return "Threshold"; }
virtual void forwardProp(TorchData& input, TorchData **output);
float threshold; // Single threshold value
float val; // Single output value (when input < threshold)
static TorchStage* loadFromStream( InputStream & stream ) noexcept;
protected:
void init(TorchData& input, TorchData **output);
// Non-copyable, non-assignable.
Threshold(Threshold&);
Threshold& operator=(const Threshold&);
};
}; // namespace mtorch
| 24.325 | 79 | 0.68037 | DoDoENT |
59e91ad6cf5506263f2b9e83649098d59b5b8013 | 858 | cpp | C++ | Binary Tree/Print_Nodes_k_Distance_From_Root.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 19 | 2018-12-02T05:59:44.000Z | 2021-07-24T14:11:54.000Z | Binary Tree/Print_Nodes_k_Distance_From_Root.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | null | null | null | Binary Tree/Print_Nodes_k_Distance_From_Root.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 13 | 2019-04-25T16:20:00.000Z | 2021-09-06T19:50:04.000Z | //Print all the nodes which are at 'k' distance from the root
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
//creates node for the tree
Node *create(int data)
{
try{
Node *node=new Node;
node->data=data;
node->left=NULL;
node->right=NULL;
return node;
}
catch(bad_alloc xa)
{
cout<<"Memory overflow!!";
return NULL;
}
}
//for getting the width of a particular level
void printNodes(Node *root,int k)
{
if(root==NULL)
return ;
if(k==1)
cout<<root->data<<" ";
else if(k>1)
printNodes(root->left,k-1);
printNodes(root->right,k-1);
}
int main()
{
Node *root=create(1);
root->left=create(2);
root->right=create(3);
root->left->left=create(4);
root->right->right=create(6);
root->left->right=create(5);
cout<<"Nodes at 'k' distance :";
printNodes(root,2);
return 0;
}
| 15.052632 | 61 | 0.649184 | susantabiswas |
59eed5a487ec1f5d409609c142de066b91021dc5 | 1,277 | cpp | C++ | algorithms_and_data_structures/term_1/lab_2/k.cpp | RevealMind/itmo | fc076d385fd46c50056cfb72d1990e10a1369f2b | [
"MIT"
] | 2 | 2020-07-15T10:42:55.000Z | 2020-07-20T08:40:56.000Z | algorithms_and_data_structures/term_1/lab_2/k.cpp | RevealMind/itmo | fc076d385fd46c50056cfb72d1990e10a1369f2b | [
"MIT"
] | 9 | 2021-05-09T02:35:45.000Z | 2022-01-22T13:19:03.000Z | algorithms_and_data_structures/term_1/lab_2/k.cpp | RevealMind/itmo | fc076d385fd46c50056cfb72d1990e10a1369f2b | [
"MIT"
] | 1 | 2022-02-18T07:57:31.000Z | 2022-02-18T07:57:31.000Z | #include<bits/stdc++.h>
int main()
{
freopen("kenobi.in","r", stdin);
freopen("kenobi.out","w", stdout);
std :: deque <int> arr1, arr2;
int x, n, k = 0;
std :: string cmd;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
std :: cin >> cmd;
switch(cmd[0]){
case 'a':
scanf("%d", &x);
arr2.push_back(x);
k++;
if(k % 2 == 0)
{
arr1.push_back(arr2.front());
arr2.pop_front();
}
break;
case 't':
if(!arr2.empty())
{
arr2.pop_back();
k--;
if(k % 2 == 1)
{
arr2.push_front(arr1.back());
arr1.pop_back();
}
}
break;
case 'm':
arr1.swap(arr2);
if(k % 2 == 1)
{
arr2.push_front(arr1.back());
arr1.pop_back();
}
break;
}
}
printf("%d\n", k);
for(int i = 0; i < arr1.size(); i++)
printf("%d ", arr1[i]);
for(int i = 0; i < arr2.size(); i++)
printf("%d ", arr2[i]);
}
| 24.09434 | 49 | 0.326547 | RevealMind |
59ef0f5f73d1d396299ca86910f5eb5529c36a50 | 10,411 | cpp | C++ | exec/compressible_mui/SPPARKS_MUI/app_potts_pin.cpp | PeculiarOvertones/FHDeX | 60e285101704196db24afe8b2461283753526fc5 | [
"BSD-3-Clause-LBNL"
] | 3 | 2018-06-25T13:23:13.000Z | 2021-12-28T21:31:54.000Z | exec/compressible_mui/SPPARKS_MUI/app_potts_pin.cpp | PeculiarOvertones/FHDeX | 60e285101704196db24afe8b2461283753526fc5 | [
"BSD-3-Clause-LBNL"
] | 44 | 2019-09-24T15:31:52.000Z | 2022-02-24T21:05:21.000Z | exec/compressible_mui/SPPARKS_MUI/app_potts_pin.cpp | PeculiarOvertones/FHDeX | 60e285101704196db24afe8b2461283753526fc5 | [
"BSD-3-Clause-LBNL"
] | 7 | 2019-10-01T15:47:08.000Z | 2022-02-22T23:04:58.000Z | /* ----------------------------------------------------------------------
SPPARKS - Stochastic Parallel PARticle Kinetic Simulator
http://www.cs.sandia.gov/~sjplimp/spparks.html
Steve Plimpton, sjplimp@sandia.gov, Sandia National Laboratories
Copyright (2008) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level SPPARKS directory.
------------------------------------------------------------------------- */
#include "spktype.h"
#include "math.h"
#include "string.h"
#include "stdlib.h"
#include "app_potts_pin.h"
#include "solve.h"
#include "random_mars.h"
#include "random_park.h"
#include "error.h"
#include <map>
using namespace SPPARKS_NS;
/* ---------------------------------------------------------------------- */
AppPottsPin::AppPottsPin(SPPARKS *spk, int narg, char **arg) :
AppPotts(spk,narg,arg)
{
// parse arguments for PottsPin class only, not children
if (strcmp(style,"potts/pin") != 0) return;
if (narg != 2) error->all(FLERR,"Illegal app_style command");
nspins = atoi(arg[1]);
if (nspins <= 0) error->all(FLERR,"Illegal app_style command");
dt_sweep = 1.0/nspins;
}
/* ----------------------------------------------------------------------
input script commands unique to this app
------------------------------------------------------------------------- */
void AppPottsPin::input_app(char *command, int narg, char **arg)
{
if (strcmp(command,"pin") == 0) {
if (narg != 3) error->all(FLERR,"Illegal pin command");
pfraction = atof(arg[0]);
multi = atoi(arg[1]);
nthresh = atoi(arg[2]);
if (pfraction < 0.0 || pfraction > 1.0)
error->all(FLERR,"Illegal pin command");
if (multi != 0 && multi != 1) error->all(FLERR,"Illegal pin command");
if (nthresh < 0) error->all(FLERR,"Illegal pin command");
pin_create();
} else error->all(FLERR,"Unrecognized command");
}
/* ----------------------------------------------------------------------
initialize before each run
check validity of site values
------------------------------------------------------------------------- */
void AppPottsPin::init_app()
{
delete [] sites;
delete [] unique;
sites = new int[1 + maxneigh];
unique = new int[1 + maxneigh];
int flag = 0;
for (int i = 0; i < nlocal; i++)
if (spin[i] < 1 || spin[i] > nspins+1) flag = 1;
int flagall;
MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world);
if (flagall) error->all(FLERR,"One or more sites have invalid values");
}
/* ----------------------------------------------------------------------
rKMC method
perform a site event with null bin rejection
flip to random spin from 1 to nspins, but not to a pinned site
------------------------------------------------------------------------- */
void AppPottsPin::site_event_rejection(int i, RandomPark *random)
{
// no events for a pinned site
if (spin[i] > nspins) return;
int oldstate = spin[i];
double einitial = site_energy(i);
// event = random spin from 1 to nspins, including self
int iran = (int) (nspins*random->uniform()) + 1;
if (iran > nspins) iran = nspins;
spin[i] = iran;
double efinal = site_energy(i);
// accept or reject via Boltzmann criterion
// null bin extends to nspins
if (efinal <= einitial) {
} else if (temperature == 0.0) {
spin[i] = oldstate;
} else if (random->uniform() > exp((einitial-efinal)*t_inverse)) {
spin[i] = oldstate;
}
if (spin[i] != oldstate) naccept++;
// set mask if site could not have changed
// if site changed, unset mask of sites with affected propensity
// OK to change mask of ghost sites since never used
if (Lmask) {
if (einitial < 0.5*numneigh[i]) mask[i] = 1;
if (spin[i] != oldstate)
for (int j = 0; j < numneigh[i]; j++)
mask[neighbor[i][j]] = 0;
}
}
/* ----------------------------------------------------------------------
KMC method
compute total propensity of owned site summed over possible events
------------------------------------------------------------------------- */
double AppPottsPin::site_propensity(int i)
{
// no events for a pinned site
if (spin[i] > nspins) return 0.0;
// events = spin flips to neighboring site different than self
// disallow flip to pinned site
// disallow wild flips = flips to value different than all neighs
int j,m,value;
int nevent = 0;
for (j = 0; j < numneigh[i]; j++) {
value = spin[neighbor[i][j]];
if (value == spin[i] || value > nspins) continue;
for (m = 0; m < nevent; m++)
if (value == unique[m]) break;
if (m < nevent) continue;
unique[nevent++] = value;
}
// for each flip:
// compute energy difference between initial and final state
// if downhill or no energy change, propensity = 1
// if uphill energy change, propensity = Boltzmann factor
int oldstate = spin[i];
double einitial = site_energy(i);
double efinal;
double prob = 0.0;
for (m = 0; m < nevent; m++) {
spin[i] = unique[m];
efinal = site_energy(i);
if (efinal <= einitial) prob += 1.0;
else if (temperature > 0.0) prob += exp((einitial-efinal)*t_inverse);
}
spin[i] = oldstate;
return prob;
}
/* ----------------------------------------------------------------------
KMC method
choose and perform an event for site
------------------------------------------------------------------------- */
void AppPottsPin::site_event(int i, RandomPark *random)
{
int j,m,value;
// pick one event from total propensity by accumulating its probability
// disallow flip to pinned site
// compare prob to threshhold, break when reach it to select event
// perform event
double threshhold = random->uniform() * propensity[i2site[i]];
double efinal;
int oldstate = spin[i];
double einitial = site_energy(i);
double prob = 0.0;
int nevent = 0;
for (j = 0; j < numneigh[i]; j++) {
value = spin[neighbor[i][j]];
if (value == oldstate || value > nspins) continue;
for (m = 0; m < nevent; m++)
if (value == unique[m]) break;
if (m < nevent) continue;
unique[nevent++] = value;
spin[i] = value;
efinal = site_energy(i);
if (efinal <= einitial) prob += 1.0;
else if (temperature > 0.0) prob += exp((einitial-efinal)*t_inverse);
if (prob >= threshhold) break;
}
// compute propensity changes for self and neighbor sites
// ignore update of neighbor sites with isite < 0
int nsites = 0;
int isite = i2site[i];
sites[nsites++] = isite;
propensity[isite] = site_propensity(i);
for (j = 0; j < numneigh[i]; j++) {
m = neighbor[i][j];
isite = i2site[m];
if (isite < 0) continue;
sites[nsites++] = isite;
propensity[isite] = site_propensity(m);
}
solve->update(nsites,sites,propensity);
}
/* ----------------------------------------------------------------------
change some sites to pinned sites
user params = pfraction, multi, nthresh
------------------------------------------------------------------------- */
void AppPottsPin::pin_create()
{
int i,j,m,nattempt,nme,npin,ndiff;
int flag,flags[2],flagall[2];
tagint iglobal;
int ndesired = static_cast<int> (pfraction*nglobal);
RandomPark *random = new RandomPark(ranmaster->uniform());
// single site inclusions
// only put local sites into hash
// nthresh = 0 for insertion anywhere
// nthresh > 0 for insertion at grain boundaries
if (!multi) {
std::map<tagint,int> hash;
for (i = 0; i < nlocal; i++)
hash.insert(std::pair<tagint,int> (id[i],i));
std::map<tagint,int>::iterator loc;
npin = 0;
while (npin < ndesired) {
nattempt = ndesired - npin;
for (i = 0; i < nattempt; i++) {
iglobal = random->tagrandom(nglobal);
loc = hash.find(iglobal);
if (loc != hash.end()) {
if (nthresh == 0) spin[loc->second] = nspins+1;
else {
m = loc->second;
ndiff = 0;
for (j = 0; j < numneigh[m]; j++)
if (spin[m] != spin[neighbor[m][j]]) ndiff++;
if (ndiff >= nthresh) spin[m] = nspins+1;
}
}
}
nme = 0;
for (i = 0; i < nlocal; i++)
if (spin[i] > nspins) nme++;
MPI_Allreduce(&nme,&npin,1,MPI_INT,MPI_SUM,world);
}
// multi site inclusions
// put local and ghost sites into hash
// nthresh = 0 for insertion anywhere
// nthresh > 0 for insertion at grain boundaries
} else if (multi) {
std::map<tagint,int> hash;
for (i = 0; i < nlocal+nghost; i++)
hash.insert(std::pair<tagint,int> (id[i],i));
std::map<tagint,int>::iterator loc;
tagint *list = new tagint[maxneigh+1];
npin = 0;
while (npin < ndesired) {
iglobal = random->tagrandom(nglobal);
loc = hash.find(iglobal);
if (loc != hash.end() && loc->second < nlocal) {
flag = 1;
i = loc->second;
if (spin[i] > nspins) flag = 0;
for (j = 0; j < numneigh[i]; j++)
if (spin[neighbor[i][j]] > nspins) flag = 0;
if (nthresh) {
ndiff = 0;
for (j = 0; j < numneigh[i]; j++)
if (spin[i] != spin[neighbor[i][j]]) ndiff++;
if (ndiff < nthresh) flag = 0;
}
if (flag) {
flags[0] = me+1;
flags[1] = numneigh[i] + 1;
spin[i] = nspins+1;
for (j = 0; j < numneigh[i]; j++) {
spin[neighbor[i][j]] = nspins+1;
list[j] = id[neighbor[i][j]];
}
list[j++] = id[i];
} else flags[0] = flags[1] = 0;
} else flags[0] = flags[1] = 0;
MPI_Allreduce(&flags,&flagall,2,MPI_INT,MPI_SUM,world);
if (flagall[0]) {
MPI_Bcast(list,flagall[1],MPI_INT,flagall[0]-1,world);
for (i = 0; i < flagall[1]; i++) {
loc = hash.find(list[i]);
if (loc != hash.end()) spin[loc->second] = nspins+1;
}
nme = 0;
for (i = 0; i < nlocal; i++)
if (spin[i] > nspins) nme++;
MPI_Allreduce(&nme,&npin,1,MPI_INT,MPI_SUM,world);
}
}
delete [] list;
}
delete random;
}
/* ----------------------------------------------------------------------
push new site onto stack and assign new id
------------------------------------------------------------------------- */
void AppPottsPin::push_new_site(int i, int* cluster_ids, int id,
std::stack<int>* cluststack)
{
int isite = spin[i];
if (isite != nspins+1) {
cluststack->push(i);
cluster_ids[i] = id;
}
}
| 28.839335 | 77 | 0.545961 | PeculiarOvertones |
59f44574beffa4bea5beeba69bcdd600dc02b603 | 7,666 | hh | C++ | include/BasePhantomBuilder.hh | ZiliasTheSaint/DoseInHumanBody | 26818b808ba3ad7740b321e9f82466c29f4385ee | [
"BSD-3-Clause"
] | 1 | 2019-07-27T11:22:16.000Z | 2019-07-27T11:22:16.000Z | include/BasePhantomBuilder.hh | ZiliasTheSaint/DoseInHumanBody | 26818b808ba3ad7740b321e9f82466c29f4385ee | [
"BSD-3-Clause"
] | null | null | null | include/BasePhantomBuilder.hh | ZiliasTheSaint/DoseInHumanBody | 26818b808ba3ad7740b321e9f82466c29f4385ee | [
"BSD-3-Clause"
] | 1 | 2019-10-12T05:41:52.000Z | 2019-10-12T05:41:52.000Z | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// Authors: S. Guatelli and M. G. Pia, INFN Genova, Italy
//
// D. Fulea, National Institute of Public Health Bucharest, Cluj-Napoca Regional Center, Romania
//
#ifndef BasePhantomBuilder_h
#define BasePhantomBuilder_h 1
#include "G4VPhysicalVolume.hh"
class G4VPhysicalVolume;
class BasePhantomBuilder
{
public:
BasePhantomBuilder();
virtual ~BasePhantomBuilder();
virtual void BuildHead(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfHead()=0;
virtual void BuildTrunk(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfTrunk()=0;
virtual void BuildUpperSpine(const G4String&,G4bool,G4bool) {return ;}virtual G4double getMassOfUpperSpine()=0;
virtual void BuildMiddleLowerSpine(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfMiddleLowerSpine()=0;
virtual void BuildLeftLeg(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLeftLeg()=0;
virtual void BuildRightLeg(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightLeg()=0;
virtual void BuildLeftLegBone(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLeftLegBone()=0;
virtual void BuildRightLegBone(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightLegBone()=0;
virtual void BuildLeftArmBone(const G4String&,G4bool,G4bool) {return ;}virtual G4double getMassOfLeftArmBone()=0;
virtual void BuildRightArmBone(const G4String&,G4bool,G4bool) {return ;}virtual G4double getMassOfRightArmBone()=0;
virtual void BuildSkull(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfSkull()=0;
virtual void BuildFacial(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfFacial()=0;
virtual void BuildRibCage(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRibCage()=0;
virtual void BuildPelvis(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfPelvis()=0;
virtual void BuildBrain(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfBrain()=0;
virtual void BuildHeart(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfHeart()=0;
virtual void BuildLeftLung(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLeftLung()=0;
virtual void BuildRightLung(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightLung()=0;
virtual void BuildStomach(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfStomach()=0;
virtual void BuildUpperLargeIntestine(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfUpperLargeIntestine()=0;
virtual void BuildLowerLargeIntestine(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLowerLargeIntestine()=0;
virtual void BuildEsophagus(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfEsophagus()=0;
virtual void BuildLeftClavicle(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLeftClavicle()=0;
virtual void BuildRightClavicle(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightClavicle()=0;
virtual void BuildLeftTesticle(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLeftTesticle()=0;
virtual void BuildRightTesticle(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightTesticle()=0;
virtual void BuildGallBladder(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfGallBladder()=0;
virtual void BuildSmallIntestine(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfSmallIntestine()=0;
virtual void BuildThymus(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfThymus()=0;
virtual void BuildLeftKidney(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLeftKidney()=0;
virtual void BuildRightKidney(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightKidney()=0;
virtual void BuildLeftAdrenal(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLeftAdrenal()=0;
virtual void BuildRightAdrenal(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightAdrenal()=0;
virtual void BuildLiver(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfLiver()=0;
virtual void BuildPancreas(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfPancreas()=0;
virtual void BuildSpleen(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfSpleen()=0;
virtual void BuildUrinaryBladder(const G4String& ,G4bool,G4bool) {return ;};virtual G4double getMassOfUrinaryBladder()=0;
virtual void BuildThyroid(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfThyroid()=0;
virtual void BuildLeftScapula(const G4String&,G4bool,G4bool){return;};virtual G4double getMassOfLeftScapula()=0;
virtual void BuildRightScapula(const G4String&,G4bool,G4bool){return;};virtual G4double getMassOfRightScapula()=0;
virtual void SetModel(G4String) {return ;};
virtual void SetMotherVolume(G4VPhysicalVolume*) {return;};
virtual G4VPhysicalVolume* GetPhantom() {return 0;};
virtual void SetScaleXY(G4double) {return ;};
virtual void SetScaleZ(G4double) {return ;};
virtual void SetAgeGroup(G4String) {return ;};
virtual void BuildLeftOvary(const G4String&,G4bool,G4bool ) {return ;};virtual G4double getMassOfLeftOvary()=0;
virtual void BuildRightOvary(const G4String&,G4bool,G4bool) {return ;};virtual G4double getMassOfRightOvary()=0;
virtual void BuildUterus(const G4String&,G4bool,G4bool){return;};virtual G4double getMassOfUterus()=0;
virtual void BuildLeftBreast(const G4String&,G4bool,G4bool){return;};virtual G4double getMassOfLeftBreast()=0;
virtual void BuildRightBreast(const G4String&,G4bool,G4bool){return;};virtual G4double getMassOfRightBreast()=0;
virtual void BuildVoxelLeftBreast(const G4String&,G4bool,G4bool){return;};//
virtual void BuildVoxelRightBreast(const G4String&,G4bool,G4bool){return;};//
};
#endif
| 71.64486 | 132 | 0.73102 | ZiliasTheSaint |
59f4fb64f1400e36b691da9296fd90d462ad6f89 | 919 | cxx | C++ | src/Cxx/Widgets/PlaneWidget.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 309 | 2017-05-21T09:07:19.000Z | 2022-03-15T09:18:55.000Z | src/Cxx/Widgets/PlaneWidget.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 379 | 2017-05-21T09:06:43.000Z | 2021-03-29T20:30:50.000Z | src/Cxx/Widgets/PlaneWidget.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 170 | 2017-05-17T14:47:41.000Z | 2022-03-31T13:16:26.000Z | #include <vtkPlaneWidget.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
int main(int, char *[])
{
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
vtkSmartPointer<vtkPlaneWidget> planeWidget =
vtkSmartPointer<vtkPlaneWidget>::New();
planeWidget->SetInteractor(renderWindowInteractor);
planeWidget->On();
renderWindowInteractor->Initialize();
renderer->ResetCamera();
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
| 27.029412 | 70 | 0.763874 | cvandijck |
59f523def5be92f9471c26d4892c30eefa45baa9 | 1,000 | cpp | C++ | moontamer/four_wheel_steering_odometry/src/four_wheel_steering_odometry_node.cpp | cagrikilic/simulation-environment | 459ded470c708a423fc8bcc6157b57399ae89c03 | [
"MIT"
] | 1 | 2021-11-20T14:57:44.000Z | 2021-11-20T14:57:44.000Z | moontamer/four_wheel_steering_odometry/src/four_wheel_steering_odometry_node.cpp | cagrikilic/simulation-environment | 459ded470c708a423fc8bcc6157b57399ae89c03 | [
"MIT"
] | null | null | null | moontamer/four_wheel_steering_odometry/src/four_wheel_steering_odometry_node.cpp | cagrikilic/simulation-environment | 459ded470c708a423fc8bcc6157b57399ae89c03 | [
"MIT"
] | 1 | 2021-11-20T14:57:48.000Z | 2021-11-20T14:57:48.000Z | /*
Ce noeud a pour but de récupérer les informations du topic Joint_States pour reconstruire les données odométriques du modèle bicyclette et de les publier dans un topic.
Ces données sont les braquages avant et arrière, les vitesses de braquage avant et arrière, la vitesse du véhicule, son accélération et son jerk.
*/
#include <ros/ros.h>
#include "four_wheel_steering_odometry.hpp"
int main(int argc, char **argv)
{
ros::init(argc, argv, "four_wheel_steering_odometry_node");
ros::NodeHandle nb;
OdometryJointMessage ojm(nb);
ojm.setVehicleParam();
ros::Subscriber sub = nb.subscribe("joint_states", 1, &OdometryJointMessage::odomJointCallback, &ojm);
ros::Publisher odom_msgs = nb.advertise<four_wheel_steering_msgs::FourWheelSteeringStamped>("odom_steer",1);
ros::Rate loop_rate(10);
while (ros::ok())
{
four_wheel_steering_msgs::FourWheelSteeringStamped msg;
ojm.odomMessage(msg);
odom_msgs.publish(msg);
loop_rate.sleep();
ros::spinOnce();
}
}
| 30.30303 | 168 | 0.75 | cagrikilic |
59f564a3289a564d897b5a9993ad1361af281e48 | 497 | cpp | C++ | modules/polygon/src/polygon.cpp | gurylev-nikita/devtools-course-practice | bab6ba4e39f04940e27c9ac148505eb152c05d17 | [
"CC-BY-4.0"
] | null | null | null | modules/polygon/src/polygon.cpp | gurylev-nikita/devtools-course-practice | bab6ba4e39f04940e27c9ac148505eb152c05d17 | [
"CC-BY-4.0"
] | 2 | 2021-03-12T15:09:25.000Z | 2021-04-19T21:01:31.000Z | modules/polygon/src/polygon.cpp | gurylev-nikita/devtools-course-practice | bab6ba4e39f04940e27c9ac148505eb152c05d17 | [
"CC-BY-4.0"
] | null | null | null | // Copyright 2021 Alibekov Murad
#include "include/polygon.h"
double Polygon::PolygonArea(const Points2D& polygon) {
double area = 0.;
int N = polygon.size();
if (N <= 2)
return area;
for (int i = 0; i < N - 1; i++)
area += polygon[i].first * polygon[i + 1].second
- polygon[i + 1].first * polygon[i].second;
area += polygon[N - 1].first * polygon[0].second
- polygon[0].first * polygon[N - 1].second;
return fabs(area) / 2;
}
| 23.666667 | 57 | 0.561368 | gurylev-nikita |
59f8dc85d8ddf23016ed928970ed83c4e7257cb2 | 68,021 | cpp | C++ | src/xrServerEntities/xrServer_Objects_ALife.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/xrServerEntities/xrServer_Objects_ALife.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/xrServerEntities/xrServer_Objects_ALife.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : xrServer_Objects_ALife.cpp
// Created : 19.09.2002
// Modified : 04.06.2003
// Author : Oles Shyshkovtsov, Alexander Maksimchuk, Victor Reutskiy and Dmitriy Iassenev
// Description : Server objects for ALife simulator
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "xrServer_Objects_ALife.h"
#include "xrServer_Objects_ALife_Monsters.h"
#include "game_base_space.h"
#include "Common/object_broker.h"
#include "restriction_space.h"
#include "xrCore/xr_token.h"
#ifdef XR_COMPILER_MSVC
#pragma warning(disable: 4100) // unreferenced formal parameter
#endif
#ifndef AI_COMPILER
#include "character_info.h"
#endif // AI_COMPILER
#include "xrCore/Animation/Bone.hpp"
#ifndef XRGAME_EXPORTS
LPCSTR GAME_CONFIG = "game.ltx";
#else // XRGAME_EXPORTS
#include "xrEngine/Render.h"
#endif // XRGAME_EXPORTS
#ifdef XRSE_FACTORY_EXPORTS
#include "ai_space.h"
#include "xrScriptEngine/script_engine.hpp"
#pragma warning(push)
#pragma warning(disable : 4995)
#include <luabind/luabind.hpp>
#include <shlwapi.h>
#pragma warning(pop)
#pragma comment(lib, "shlwapi.lib")
struct logical_string_predicate
{
static HRESULT AnsiToUnicode(LPCSTR pszA, LPVOID buffer, u32 const& buffer_size)
{
VERIFY(pszA);
VERIFY(buffer);
VERIFY(buffer_size);
u32 cCharacters = xr_strlen(pszA) + 1;
VERIFY(cCharacters * 2 <= buffer_size);
if (MultiByteToWideChar(CP_ACP, 0, pszA, cCharacters, (LPOLESTR)buffer, cCharacters))
return (NOERROR);
return (HRESULT_FROM_WIN32(GetLastError()));
}
bool operator()(LPCSTR const& first, LPCSTR const& second) const
{
u32 buffer_size0 = (xr_strlen(first) + 1) * 2;
LPCWSTR buffer0 = (LPCWSTR)xr_alloca(buffer_size0);
AnsiToUnicode(first, (LPVOID)buffer0, buffer_size0);
u32 buffer_size1 = (xr_strlen(second) + 1) * 2;
LPCWSTR buffer1 = (LPCWSTR)xr_alloca(buffer_size1);
AnsiToUnicode(second, (LPVOID)buffer1, buffer_size1);
return (StrCmpLogicalW(buffer0, buffer1) < 0);
}
bool operator()(shared_str const& first, shared_str const& second) const
{
u32 buffer_size0 = (first.size() + 1) * 2;
LPCWSTR buffer0 = (LPCWSTR)xr_alloca(buffer_size0);
AnsiToUnicode(first.c_str(), (LPVOID)buffer0, buffer_size0);
u32 buffer_size1 = (second.size() + 1) * 2;
LPCWSTR buffer1 = (LPCWSTR)xr_alloca(buffer_size1);
AnsiToUnicode(second.c_str(), (LPVOID)buffer1, buffer_size1);
return (StrCmpLogicalW(buffer0, buffer1) < 0);
}
}; // struct logical_string_predicate
#endif // XRSE_FACTORY_EXPORTS
bool SortStringsByAlphabetPred(const shared_str& s1, const shared_str& s2)
{
R_ASSERT(s1.size());
R_ASSERT(s2.size());
return (xr_strcmp(s1, s2) < 0);
};
struct story_name_predicate
{
IC bool operator()(const xr_rtoken& _1, const xr_rtoken& _2) const
{
VERIFY(_1.name.size());
VERIFY(_2.name.size());
return (xr_strcmp(_1.name, _2.name) < 0);
}
};
#ifdef XRSE_FACTORY_EXPORTS
SFillPropData::SFillPropData() { counter = 0; };
SFillPropData::~SFillPropData() { VERIFY(0 == counter); };
void SFillPropData::load()
{
// create ini
#ifdef XRGAME_EXPORTS
CInifile* Ini = pGameIni;
#else // XRGAME_EXPORTS
CInifile* Ini = nullptr;
string_path gm_name;
FS.update_path(gm_name, "$game_config$", GAME_CONFIG);
R_ASSERT3(FS.exist(gm_name), "Couldn't find file", gm_name);
Ini = xr_new<CInifile>(gm_name);
#endif // XRGAME_EXPORTS
// location type
LPCSTR N, V;
u32 k;
for (int i = 0; i < GameGraph::LOCATION_TYPE_COUNT; ++i)
{
VERIFY(locations[i].empty());
string256 caSection, T;
strconcat(sizeof(caSection), caSection, SECTION_HEADER, xr_itoa(i, T, 10));
R_ASSERT(Ini->section_exist(caSection));
for (k = 0; Ini->r_line(caSection, k, &N, &V); ++k)
locations[i].push_back(xr_rtoken(V, atoi(N)));
}
for (k = 0; Ini->r_line("graph_points_draw_color_palette", k, &N, &V); ++k)
{
u32 color;
if (1 == sscanf(V, "%x", &color))
{
location_colors[N] = color;
}
else
Msg("! invalid record format in [graph_points_draw_color_palette] %s=%s", N, V);
}
// level names/ids
VERIFY(level_ids.empty());
for (k = 0; Ini->r_line("levels", k, &N, &V); ++k)
level_ids.push_back(Ini->r_string_wb(N, "caption"));
// story names
{
VERIFY(story_names.empty());
LPCSTR section = "story_ids";
R_ASSERT(Ini->section_exist(section));
for (k = 0; Ini->r_line(section, k, &N, &V); ++k)
story_names.push_back(xr_rtoken(V, atoi(N)));
std::sort(story_names.begin(), story_names.end(), story_name_predicate());
story_names.insert(story_names.begin(), xr_rtoken("NO STORY ID", ALife::_STORY_ID(-1)));
}
// spawn story names
{
VERIFY(spawn_story_names.empty());
LPCSTR section = "spawn_story_ids";
R_ASSERT(Ini->section_exist(section));
for (k = 0; Ini->r_line(section, k, &N, &V); ++k)
spawn_story_names.push_back(xr_rtoken(V, atoi(N)));
std::sort(spawn_story_names.begin(), spawn_story_names.end(), story_name_predicate());
spawn_story_names.insert(spawn_story_names.begin(), xr_rtoken("NO SPAWN STORY ID", ALife::_SPAWN_STORY_ID(-1)));
}
#ifndef AI_COMPILER
// character profiles indexes
VERIFY(character_profiles.empty());
for (int i = 0; i <= CCharacterInfo::GetMaxIndex(); i++)
{
character_profiles.push_back(CCharacterInfo::IndexToId(i));
}
std::sort(character_profiles.begin(), character_profiles.end(), SortStringsByAlphabetPred);
#endif // AI_COMPILER
// destroy ini
#ifndef XRGAME_EXPORTS
xr_delete(Ini);
#endif // XRGAME_EXPORTS
luabind::object table;
R_ASSERT(GEnv.ScriptEngine->function_object("smart_covers.descriptions", table, LUA_TTABLE));
for (luabind::iterator I(table), E; I != E; ++I)
smart_covers.push_back(luabind::object_cast<LPCSTR>(I.key()));
std::sort(smart_covers.begin(), smart_covers.end(), logical_string_predicate());
};
void SFillPropData::unload()
{
for (int i = 0; i < GameGraph::LOCATION_TYPE_COUNT; ++i)
locations[i].clear();
level_ids.clear();
story_names.clear();
spawn_story_names.clear();
character_profiles.clear();
smart_covers.clear();
};
void SFillPropData::dec()
{
VERIFY(counter > 0);
--counter;
if (!counter)
unload();
};
void SFillPropData::inc()
{
VERIFY(counter < 0xffffffff);
if (!counter)
load();
++counter;
}
static SFillPropData fp_data;
#endif // #ifdef XRSE_FACTORY_EXPORTS
#ifndef XRGAME_EXPORTS
#ifdef XRSE_FACTORY_EXPORTS
void CSE_ALifeTraderAbstract::FillProps(LPCSTR pref, PropItemVec& items)
#else
void CSE_ALifeTraderAbstract::FillProps (LPCSTR /*pref*/, PropItemVec& /*items*/)
#endif
{
#ifdef XRSE_FACTORY_EXPORTS
PHelper().CreateU32(items, PrepareKey(pref, *base()->s_name, "Money"), &m_dwMoney, 0, u32(-1));
PHelper().CreateFlag32(
items, PrepareKey(pref, *base()->s_name, "Trader" DELIMITER "Infinite ammo"), &m_trader_flags, eTraderFlagInfiniteAmmo);
RListValue* value = PHelper().CreateRList(items, PrepareKey(pref, *base()->s_name, "npc profile"),
&m_sCharacterProfile, &*fp_data.character_profiles.begin(), fp_data.character_profiles.size());
value->OnChangeEvent.bind(this, &CSE_ALifeTraderAbstract::OnChangeProfile);
#endif // #ifdef XRSE_FACTORY_EXPORTS
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeGraphPoint
////////////////////////////////////////////////////////////////////////////
CSE_ALifeGraphPoint::CSE_ALifeGraphPoint(LPCSTR caSection) : CSE_Abstract(caSection)
{
//. s_gameid = GAME_DUMMY;
m_tLocations[0] = 0;
m_tLocations[1] = 0;
m_tLocations[2] = 0;
m_tLocations[3] = 0;
#ifdef XRSE_FACTORY_EXPORTS
fp_data.inc();
#endif // XRSE_FACTORY_EXPORTS
}
CSE_ALifeGraphPoint::~CSE_ALifeGraphPoint()
{
#ifdef XRSE_FACTORY_EXPORTS
fp_data.dec();
#endif // XRSE_FACTORY_EXPORTS
}
void CSE_ALifeGraphPoint::STATE_Read(NET_Packet& tNetPacket, u16 /*size*/)
{
tNetPacket.r_stringZ(m_caConnectionPointName);
if (m_wVersion < 33)
tNetPacket.r_u32();
else
tNetPacket.r_stringZ(m_caConnectionLevelName);
tNetPacket.r_u8(m_tLocations[0]);
tNetPacket.r_u8(m_tLocations[1]);
tNetPacket.r_u8(m_tLocations[2]);
tNetPacket.r_u8(m_tLocations[3]);
};
void CSE_ALifeGraphPoint::STATE_Write(NET_Packet& tNetPacket)
{
tNetPacket.w_stringZ(m_caConnectionPointName);
tNetPacket.w_stringZ(m_caConnectionLevelName);
tNetPacket.w_u8(m_tLocations[0]);
tNetPacket.w_u8(m_tLocations[1]);
tNetPacket.w_u8(m_tLocations[2]);
tNetPacket.w_u8(m_tLocations[3]);
};
void CSE_ALifeGraphPoint::UPDATE_Read(NET_Packet& /*tNetPacket*/) {}
void CSE_ALifeGraphPoint::UPDATE_Write(NET_Packet& /*tNetPacket*/) {}
#ifndef XRGAME_EXPORTS
void CSE_ALifeGraphPoint::FillProps(LPCSTR pref, PropItemVec& items)
{
#ifdef XRSE_FACTORY_EXPORTS
PHelper().CreateRToken8(items, PrepareKey(pref, *s_name, "Location" DELIMITER "1"), &m_tLocations[0],
&*fp_data.locations[0].begin(), fp_data.locations[0].size());
PHelper().CreateRToken8(items, PrepareKey(pref, *s_name, "Location" DELIMITER "2"), &m_tLocations[1],
&*fp_data.locations[1].begin(), fp_data.locations[1].size());
PHelper().CreateRToken8(items, PrepareKey(pref, *s_name, "Location" DELIMITER "3"), &m_tLocations[2],
&*fp_data.locations[2].begin(), fp_data.locations[2].size());
PHelper().CreateRToken8(items, PrepareKey(pref, *s_name, "Location" DELIMITER "4"), &m_tLocations[3],
&*fp_data.locations[3].begin(), fp_data.locations[3].size());
PHelper().CreateRList(items, PrepareKey(pref, *s_name, "Connection" DELIMITER "Level name"), &m_caConnectionLevelName,
&*fp_data.level_ids.begin(), fp_data.level_ids.size());
PHelper().CreateRText(items, PrepareKey(pref, *s_name, "Connection" DELIMITER "Point name"), &m_caConnectionPointName);
#endif // #ifdef XRSE_FACTORY_EXPORTS
}
void CSE_ALifeGraphPoint::on_render(CDUInterface* du, IServerEntityLEOwner* owner,
bool bSelected, const Fmatrix& parent, int priority, bool strictB2F)
{
#ifdef XRSE_FACTORY_EXPORTS
static const u32 IL[16] = {0, 1, 0, 2, 0, 3, 0, 4, 1, 3, 3, 2, 2, 4, 4, 1};
static const u32 IT[12] = {1, 3, 0, 3, 2, 0, 2, 4, 0, 4, 1, 0};
static const Fvector PT[5] =
{
{0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, -0.5f},
{0.0f, 0.0f, 0.5f},
{-0.5f, 0.0f, 0.0f},
{0.5f, 0.0f, 0.0f},
};
Fcolor C;
u32 cc;
string16 buff;
xr_sprintf(buff, "%03d_%03d_%03d_%03d", m_tLocations[0], m_tLocations[1], m_tLocations[2], m_tLocations[3]);
xr_map<shared_str, u32>::iterator it = fp_data.location_colors.find(buff);
if (it == fp_data.location_colors.end())
{
it = fp_data.location_colors.find("default");
}
if (it != fp_data.location_colors.end())
cc = it->second;
else
cc = 0x107f7f7f;
C.set(cc);
if (!bSelected)
C.a *= 0.6f;
du->DrawIndexedPrimitive(2 /*D3DPT_LINELIST*/, 8, parent.c, PT, 6, IL, 16, C.get());
C.mul_rgba(0.75f);
du->DrawIndexedPrimitive(4 /*D3DPT_TRIANGLELIST*/, 4, parent.c, PT, 6, IT, 12, C.get());
if (bSelected)
du->DrawSelectionBox(parent.c, Fvector().set(0.5f, 1.0f, 0.5f), nullptr);
#endif // #ifdef XRSE_FACTORY_EXPORTS
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeObject
////////////////////////////////////////////////////////////////////////////
CSE_ALifeObject::CSE_ALifeObject(LPCSTR caSection) : CSE_Abstract(caSection)
{
m_bOnline = false;
m_fDistance = 0.0f;
ID = ALife::_OBJECT_ID(-1);
m_tGraphID = GameGraph::_GRAPH_ID(-1);
m_tSpawnID = ALife::_SPAWN_ID(-1);
m_bDirectControl = true;
m_bALifeControl = true;
m_tNodeID = u32(-1);
m_flags.one();
m_story_id = INVALID_STORY_ID;
m_spawn_story_id = INVALID_SPAWN_STORY_ID;
#ifdef XRGAME_EXPORTS
m_alife_simulator = 0;
#endif
#ifdef XRSE_FACTORY_EXPORTS
fp_data.inc();
#endif // XRSE_FACTORY_EXPORTS
m_flags.set(flOfflineNoMove, false);
seed(u32(CPU::QPC() & 0xffffffff));
}
#ifdef XRGAME_EXPORTS
CALifeSimulator& CSE_ALifeObject::alife() const
{
VERIFY(m_alife_simulator);
return (*m_alife_simulator);
}
Fvector CSE_ALifeObject::draw_level_position() const { return (Position()); }
#endif
CSE_ALifeObject::~CSE_ALifeObject()
{
#ifdef XRSE_FACTORY_EXPORTS
fp_data.dec();
#endif // XRSE_FACTORY_EXPORTS
}
bool CSE_ALifeObject::move_offline() const { return (!m_flags.test(flOfflineNoMove)); }
void CSE_ALifeObject::move_offline(bool value) { m_flags.set(flOfflineNoMove, !value ? TRUE : FALSE); }
bool CSE_ALifeObject::visible_for_map() const { return (!!m_flags.test(flVisibleForMap)); }
void CSE_ALifeObject::visible_for_map(bool value) { m_flags.set(flVisibleForMap, value ? TRUE : FALSE); }
void CSE_ALifeObject::STATE_Write(NET_Packet& tNetPacket)
{
tNetPacket.w_u16(m_tGraphID);
tNetPacket.w_float(m_fDistance);
tNetPacket.w_u32(m_bDirectControl);
tNetPacket.w_u32(m_tNodeID);
tNetPacket.w_u32(m_flags.get());
tNetPacket.w_stringZ(m_ini_string);
tNetPacket.w_u32(m_story_id);
tNetPacket.w_u32(m_spawn_story_id);
}
void CSE_ALifeObject::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
if (m_wVersion >= 1)
{
if (m_wVersion > 24)
{
if (m_wVersion < 83)
{
tNetPacket.r_float(); // m_spawn_probability);
}
}
else
{
tNetPacket.r_u8();
/**
u8 l_ucTemp;
tNetPacket.r_u8 (l_ucTemp);
m_spawn_probability = (float)l_ucTemp;
**/
}
if (m_wVersion < 83)
{
tNetPacket.r_u32();
}
if (m_wVersion < 4)
{
u16 wDummy;
tNetPacket.r_u16(wDummy);
}
tNetPacket.r_u16(m_tGraphID);
tNetPacket.r_float(m_fDistance);
}
if (m_wVersion >= 4)
{
u32 dwDummy;
tNetPacket.r_u32(dwDummy);
m_bDirectControl = !!dwDummy;
}
if (m_wVersion >= 8)
tNetPacket.r_u32(m_tNodeID);
if ((m_wVersion > 22) && (m_wVersion <= 79))
tNetPacket.r_u16(m_tSpawnID);
if ((m_wVersion > 23) && (m_wVersion < 84))
{
shared_str temp;
tNetPacket.r_stringZ(temp); // m_spawn_control);
}
if (m_wVersion > 49)
{
tNetPacket.r_u32(m_flags.flags);
}
if (m_wVersion > 57)
{
if (m_ini_file)
xr_delete(m_ini_file);
tNetPacket.r_stringZ(m_ini_string);
}
if (m_wVersion > 61)
tNetPacket.r_u32(m_story_id);
if (m_wVersion > 111)
tNetPacket.r_u32(m_spawn_story_id);
}
void CSE_ALifeObject::UPDATE_Write(NET_Packet& /*tNetPacket*/) {}
void CSE_ALifeObject::UPDATE_Read(NET_Packet& /*tNetPacket*/) {};
#ifndef XRGAME_EXPORTS
void CSE_ALifeObject::FillProps(LPCSTR pref, PropItemVec& items)
{
#ifdef XRSE_FACTORY_EXPORTS
inherited::FillProps(pref, items);
PHelper().CreateRText(items, PrepareKey(pref, *s_name, "Custom data"), &m_ini_string);
if (m_flags.is(flUseSwitches))
{
PHelper().CreateFlag32(items, PrepareKey(pref, *s_name, "ALife" DELIMITER "Can switch online"), &m_flags, flSwitchOnline);
PHelper().CreateFlag32(
items, PrepareKey(pref, *s_name, "ALife" DELIMITER "Can switch offline"), &m_flags, flSwitchOffline);
}
PHelper().CreateFlag32(items, PrepareKey(pref, *s_name, "ALife" DELIMITER "Interactive"), &m_flags, flInteractive);
PHelper().CreateFlag32(items, PrepareKey(pref, *s_name, "ALife" DELIMITER "Used AI locations"), &m_flags, flUsedAI_Locations);
PHelper().CreateRToken32(items, PrepareKey(pref, *s_name, "ALife" DELIMITER "Story ID"), &m_story_id,
&*fp_data.story_names.begin(), fp_data.story_names.size());
PHelper().CreateRToken32(items, PrepareKey(pref, *s_name, "ALife" DELIMITER "Spawn Story ID"), &m_spawn_story_id,
&*fp_data.spawn_story_names.begin(), fp_data.spawn_story_names.size());
#endif // #ifdef XRSE_FACTORY_EXPORTS
}
#endif // #ifndef XRGAME_EXPORTS
u32 CSE_ALifeObject::ef_equipment_type() const
{
string16 temp;
CLSID2TEXT(m_tClassID, temp);
R_ASSERT3(false, "Invalid alife equipment type request, virtual function is not properly overloaded!", temp);
return (u32(-1));
// return (6);
}
u32 CSE_ALifeObject::ef_main_weapon_type() const
{
string16 temp;
CLSID2TEXT(m_tClassID, temp);
R_ASSERT3(false, "Invalid alife main weapon type request, virtual function is not properly overloaded!", temp);
return (u32(-1));
// return (5);
}
u32 CSE_ALifeObject::ef_weapon_type() const
{
// string16 temp; CLSID2TEXT(m_tClassID,temp);
// R_ASSERT3 (false,"Invalid alife weapon type request, virtual function is not properly overloaded!",temp);
// return (u32(-1));
return (0);
}
u32 CSE_ALifeObject::ef_detector_type() const
{
string16 temp;
CLSID2TEXT(m_tClassID, temp);
R_ASSERT3(false, "Invalid alife detector type request, virtual function is not properly overloaded!", temp);
return (u32(-1));
}
bool CSE_ALifeObject::used_ai_locations() const /* noexcept */
{ return !!m_flags.is(flUsedAI_Locations); }
bool CSE_ALifeObject::can_switch_online() const /* noexcept */
{ return match_configuration() && !!m_flags.is(flSwitchOnline); }
bool CSE_ALifeObject::can_switch_offline() const /* noexcept */
{ return !match_configuration() || !!m_flags.is(flSwitchOffline); }
bool CSE_ALifeObject::can_save() const /* noexcept */
{ return !!m_flags.is(flCanSave); }
bool CSE_ALifeObject::interactive() const /* noexcept */
{ return !!m_flags.is(flInteractive) && !!m_flags.is(flVisibleForAI) && !!m_flags.is(flUsefulForAI); }
void CSE_ALifeObject::use_ai_locations(bool value) { m_flags.set(flUsedAI_Locations, BOOL(value)); }
void CSE_ALifeObject::can_switch_online(bool value) /* noexcept */ { m_flags.set(flSwitchOnline, BOOL(value)); }
void CSE_ALifeObject::can_switch_offline(bool value) /* noexcept */ { m_flags.set(flSwitchOffline, BOOL(value)); }
void CSE_ALifeObject::interactive(bool value) /* noexcept */ { m_flags.set(flInteractive, BOOL(value)); }
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeGroupAbstract
////////////////////////////////////////////////////////////////////////////
CSE_ALifeGroupAbstract::CSE_ALifeGroupAbstract(LPCSTR /*caSection*/)
{
m_tpMembers.clear();
m_bCreateSpawnPositions = true;
m_wCount = 1;
m_tNextBirthTime = 0;
}
CSE_Abstract* CSE_ALifeGroupAbstract::init() { return (base()); }
CSE_ALifeGroupAbstract::~CSE_ALifeGroupAbstract() {}
void CSE_ALifeGroupAbstract::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
u16 m_wVersion = base()->m_wVersion;
u32 dwDummy;
tNetPacket.r_u32(dwDummy);
m_bCreateSpawnPositions = !!dwDummy;
tNetPacket.r_u16(m_wCount);
if (m_wVersion > 19)
load_data(m_tpMembers, tNetPacket);
};
void CSE_ALifeGroupAbstract::STATE_Write(NET_Packet& tNetPacket)
{
tNetPacket.w_u32(m_bCreateSpawnPositions);
tNetPacket.w_u16(m_wCount);
save_data(m_tpMembers, tNetPacket);
};
void CSE_ALifeGroupAbstract::UPDATE_Read(NET_Packet& tNetPacket)
{
u32 dwDummy;
tNetPacket.r_u32(dwDummy);
m_bCreateSpawnPositions = !!dwDummy;
};
void CSE_ALifeGroupAbstract::UPDATE_Write(NET_Packet& tNetPacket) { tNetPacket.w_u32(m_bCreateSpawnPositions); };
#ifndef XRGAME_EXPORTS
void CSE_ALifeGroupAbstract::FillProps(LPCSTR pref, PropItemVec& items)
{
PHelper().CreateU16(items, PrepareKey(pref, "ALife" DELIMITER "Count"), &m_wCount, 0, 0xff);
};
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeDynamicObject
////////////////////////////////////////////////////////////////////////////
CSE_ALifeDynamicObject::CSE_ALifeDynamicObject(LPCSTR caSection) : CSE_ALifeObject(caSection)
{
m_tTimeID = 0;
m_switch_counter = u64(-1);
}
CSE_ALifeDynamicObject::~CSE_ALifeDynamicObject() {}
void CSE_ALifeDynamicObject::STATE_Write(NET_Packet& tNetPacket) { inherited::STATE_Write(tNetPacket); }
void CSE_ALifeDynamicObject::STATE_Read(NET_Packet& tNetPacket, u16 size) { inherited::STATE_Read(tNetPacket, size); }
void CSE_ALifeDynamicObject::UPDATE_Write(NET_Packet& tNetPacket) { inherited::UPDATE_Write(tNetPacket); };
void CSE_ALifeDynamicObject::UPDATE_Read(NET_Packet& tNetPacket) { inherited::UPDATE_Read(tNetPacket); };
#ifndef XRGAME_EXPORTS
void CSE_ALifeDynamicObject::FillProps(LPCSTR pref, PropItemVec& values) { inherited::FillProps(pref, values); }
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeDynamicObjectVisual
////////////////////////////////////////////////////////////////////////////
CSE_ALifeDynamicObjectVisual::CSE_ALifeDynamicObjectVisual(LPCSTR caSection)
: CSE_ALifeDynamicObject(caSection), CSE_Visual()
{
if (pSettings->line_exist(caSection, "visual"))
set_visual(pSettings->r_string(caSection, "visual"));
}
CSE_ALifeDynamicObjectVisual::~CSE_ALifeDynamicObjectVisual() {}
CSE_Visual* CSE_ALifeDynamicObjectVisual::visual() { return (this); }
void CSE_ALifeDynamicObjectVisual::STATE_Write(NET_Packet& tNetPacket)
{
inherited1::STATE_Write(tNetPacket);
visual_write(tNetPacket);
}
void CSE_ALifeDynamicObjectVisual::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited1::STATE_Read(tNetPacket, size);
if (m_wVersion > 31)
visual_read(tNetPacket, m_wVersion);
}
void CSE_ALifeDynamicObjectVisual::UPDATE_Write(NET_Packet& tNetPacket) { inherited1::UPDATE_Write(tNetPacket); };
void CSE_ALifeDynamicObjectVisual::UPDATE_Read(NET_Packet& tNetPacket) { inherited1::UPDATE_Read(tNetPacket); };
#ifndef XRGAME_EXPORTS
void CSE_ALifeDynamicObjectVisual::FillProps(LPCSTR pref, PropItemVec& items)
{
inherited1::FillProps(pref, items);
inherited2::FillProps(pref, items);
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifePHSkeletonObject
////////////////////////////////////////////////////////////////////////////
CSE_ALifePHSkeletonObject::CSE_ALifePHSkeletonObject(LPCSTR caSection)
: CSE_ALifeDynamicObjectVisual(caSection), CSE_PHSkeleton(caSection)
{
m_flags.set(flUseSwitches, false);
m_flags.set(flSwitchOffline, false);
}
CSE_ALifePHSkeletonObject::~CSE_ALifePHSkeletonObject() {}
void CSE_ALifePHSkeletonObject::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited1::STATE_Read(tNetPacket, size);
if (m_wVersion >= 64)
inherited2::STATE_Read(tNetPacket, size);
}
void CSE_ALifePHSkeletonObject::STATE_Write(NET_Packet& tNetPacket)
{
inherited1::STATE_Write(tNetPacket);
inherited2::STATE_Write(tNetPacket);
}
void CSE_ALifePHSkeletonObject::load(NET_Packet& tNetPacket)
{
inherited1::load(tNetPacket);
inherited2::load(tNetPacket);
}
void CSE_ALifePHSkeletonObject::UPDATE_Write(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Write(tNetPacket);
inherited2::UPDATE_Write(tNetPacket);
};
void CSE_ALifePHSkeletonObject::UPDATE_Read(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Read(tNetPacket);
inherited2::UPDATE_Read(tNetPacket);
};
bool CSE_ALifePHSkeletonObject::can_save() const /* noexcept */ { return CSE_PHSkeleton::need_save(); }
bool CSE_ALifePHSkeletonObject::used_ai_locations() const /* noexcept */ { return false; }
#ifndef XRGAME_EXPORTS
void CSE_ALifePHSkeletonObject::FillProps(LPCSTR pref, PropItemVec& items)
{
inherited1::FillProps(pref, items);
inherited2::FillProps(pref, items);
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeSpaceRestrictor
////////////////////////////////////////////////////////////////////////////
CSE_ALifeSpaceRestrictor::CSE_ALifeSpaceRestrictor(LPCSTR caSection) : CSE_ALifeDynamicObject(caSection)
{
m_flags.set(flUseSwitches, false);
m_space_restrictor_type = RestrictionSpace::eDefaultRestrictorTypeNone;
m_flags.set(flUsedAI_Locations, false);
m_spawn_flags.set(flSpawnDestroyOnSpawn, false);
m_flags.set(flCheckForSeparator, true);
}
CSE_ALifeSpaceRestrictor::~CSE_ALifeSpaceRestrictor() {}
bool CSE_ALifeSpaceRestrictor::can_switch_offline() const /* noexcept */ { return false; }
bool CSE_ALifeSpaceRestrictor::used_ai_locations() const /* noexcept */ { return false; }
IServerEntityShape* CSE_ALifeSpaceRestrictor::shape() { return (this); }
void CSE_ALifeSpaceRestrictor::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited1::STATE_Read(tNetPacket, size);
cform_read(tNetPacket);
if (m_wVersion > 74)
m_space_restrictor_type = tNetPacket.r_u8();
}
void CSE_ALifeSpaceRestrictor::STATE_Write(NET_Packet& tNetPacket)
{
inherited1::STATE_Write(tNetPacket);
cform_write(tNetPacket);
tNetPacket.w_u8(m_space_restrictor_type);
}
void CSE_ALifeSpaceRestrictor::UPDATE_Read(NET_Packet& tNetPacket) { inherited1::UPDATE_Read(tNetPacket); }
void CSE_ALifeSpaceRestrictor::UPDATE_Write(NET_Packet& tNetPacket) { inherited1::UPDATE_Write(tNetPacket); }
const xr_token defaul_retrictor_types[] = {{"NOT A restrictor", RestrictionSpace::eRestrictorTypeNone},
{"NONE default restrictor", RestrictionSpace::eDefaultRestrictorTypeNone},
{"OUT default restrictor", RestrictionSpace::eDefaultRestrictorTypeOut},
{"IN default restrictor", RestrictionSpace::eDefaultRestrictorTypeIn}, {nullptr, 0}};
#ifndef XRGAME_EXPORTS
void CSE_ALifeSpaceRestrictor::FillProps(LPCSTR pref, PropItemVec& items)
{
inherited1::FillProps(pref, items);
PHelper().CreateToken8(
items, PrepareKey(pref, *s_name, "restrictor type"), &m_space_restrictor_type, defaul_retrictor_types);
PHelper().CreateFlag32(items, PrepareKey(pref, *s_name, "check for separator"), &m_flags, flCheckForSeparator);
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeLevelChanger
////////////////////////////////////////////////////////////////////////////
CSE_ALifeLevelChanger::CSE_ALifeLevelChanger(LPCSTR caSection) : CSE_ALifeSpaceRestrictor(caSection)
{
m_tNextGraphID = GameGraph::_GRAPH_ID(-1);
m_dwNextNodeID = u32(-1);
m_tNextPosition.set(0.f, 0.f, 0.f);
m_tAngles.set(0.f, 0.f, 0.f);
#ifdef XRSE_FACTORY_EXPORTS
fp_data.inc();
#endif // XRSE_FACTORY_EXPORTS
m_bSilentMode = FALSE;
}
CSE_ALifeLevelChanger::~CSE_ALifeLevelChanger()
{
#ifdef XRSE_FACTORY_EXPORTS
fp_data.dec();
#endif // XRSE_FACTORY_EXPORTS
}
void CSE_ALifeLevelChanger::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited::STATE_Read(tNetPacket, size);
if (m_wVersion < 34)
{
tNetPacket.r_u32();
tNetPacket.r_u32();
}
else
{
tNetPacket.r_u16(m_tNextGraphID);
tNetPacket.r_u32(m_dwNextNodeID);
tNetPacket.r_float(m_tNextPosition.x);
tNetPacket.r_float(m_tNextPosition.y);
tNetPacket.r_float(m_tNextPosition.z);
if (m_wVersion <= 53)
m_tAngles.set(0.f, tNetPacket.r_float(), 0.f);
else
tNetPacket.r_vec3(m_tAngles);
}
tNetPacket.r_stringZ(m_caLevelToChange);
tNetPacket.r_stringZ(m_caLevelPointToChange);
if (m_wVersion > 116)
m_bSilentMode = !!tNetPacket.r_u8();
}
void CSE_ALifeLevelChanger::STATE_Write(NET_Packet& tNetPacket)
{
inherited::STATE_Write(tNetPacket);
tNetPacket.w_u16(m_tNextGraphID);
tNetPacket.w_u32(m_dwNextNodeID);
tNetPacket.w_float(m_tNextPosition.x);
tNetPacket.w_float(m_tNextPosition.y);
tNetPacket.w_float(m_tNextPosition.z);
tNetPacket.w_vec3(m_tAngles);
tNetPacket.w_stringZ(m_caLevelToChange);
tNetPacket.w_stringZ(m_caLevelPointToChange);
tNetPacket.w_u8(m_bSilentMode ? 1 : 0);
}
void CSE_ALifeLevelChanger::UPDATE_Read(NET_Packet& tNetPacket) { inherited::UPDATE_Read(tNetPacket); }
void CSE_ALifeLevelChanger::UPDATE_Write(NET_Packet& tNetPacket) { inherited::UPDATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeLevelChanger::FillProps(LPCSTR pref, PropItemVec& items)
{
#ifdef XRSE_FACTORY_EXPORTS
inherited::FillProps(pref, items);
PHelper().CreateRList(items, PrepareKey(pref, *s_name, "Level to change"), &m_caLevelToChange,
&*fp_data.level_ids.begin(), fp_data.level_ids.size());
PHelper().CreateRText(items, PrepareKey(pref, *s_name, "Level point to change"), &m_caLevelPointToChange);
PHelper().CreateBOOL(items, PrepareKey(pref, *s_name, "Silent mode"), &m_bSilentMode);
#endif // #ifdef XRSE_FACTORY_EXPORTS
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeObjectPhysic
////////////////////////////////////////////////////////////////////////////
CSE_ALifeObjectPhysic::CSE_ALifeObjectPhysic(LPCSTR caSection)
: CSE_ALifeDynamicObjectVisual(caSection), CSE_PHSkeleton(caSection)
{
type = epotSkeleton;
mass = 10.f;
if (pSettings->section_exist(caSection) && pSettings->line_exist(caSection, "visual"))
{
set_visual(pSettings->r_string(caSection, "visual"));
if (pSettings->line_exist(caSection, "startup_animation"))
startup_animation = pSettings->r_string(caSection, "startup_animation");
}
if (pSettings->line_exist(caSection, "fixed_bones"))
fixed_bones = pSettings->r_string(caSection, "fixed_bones");
m_flags.set(flUseSwitches, false);
m_flags.set(flSwitchOffline, false);
m_flags.set(flUsedAI_Locations, false);
#ifdef XRGAME_EXPORTS
m_freeze_time = Device.dwTimeGlobal;
#ifdef DEBUG
m_last_update_time = Device.dwTimeGlobal;
#endif
#else
m_freeze_time = 0;
#endif
m_relevent_random.seed(u32(CPU::QPC() & u32(-1)));
}
CSE_ALifeObjectPhysic::~CSE_ALifeObjectPhysic() {}
void CSE_ALifeObjectPhysic::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
if (m_wVersion >= 14)
if (m_wVersion >= 16)
{
inherited1::STATE_Read(tNetPacket, size);
if (m_wVersion < 32)
visual_read(tNetPacket, m_wVersion);
}
else
{
CSE_ALifeObject::STATE_Read(tNetPacket, size);
visual_read(tNetPacket, m_wVersion);
}
if (m_wVersion >= 64)
inherited2::STATE_Read(tNetPacket, size);
tNetPacket.r_u32(type);
tNetPacket.r_float(mass);
if (m_wVersion > 9)
tNetPacket.r_stringZ(fixed_bones);
if (m_wVersion < 65 && m_wVersion > 28)
tNetPacket.r_stringZ(startup_animation);
if (m_wVersion < 64)
{
if (m_wVersion > 39) // > 39
tNetPacket.r_u8(_flags.flags);
if (m_wVersion > 56)
tNetPacket.r_u16(source_id);
if (m_wVersion > 60 && _flags.test(flSavedData))
{
data_load(tNetPacket);
}
}
set_editor_flag(flVisualAnimationChange);
}
void CSE_ALifeObjectPhysic::STATE_Write(NET_Packet& tNetPacket)
{
inherited1::STATE_Write(tNetPacket);
inherited2::STATE_Write(tNetPacket);
tNetPacket.w_u32(type);
tNetPacket.w_float(mass);
tNetPacket.w_stringZ(fixed_bones);
}
static inline bool check(const u8& mask, const u8& test) { return (!!(mask & test)); }
const u32 CSE_ALifeObjectPhysic::m_freeze_delta_time = 5000;
const u32 CSE_ALifeObjectPhysic::random_limit = 40;
#ifdef DEBUG
const u32 CSE_ALifeObjectPhysic::m_update_delta_time = 0;
#endif // #ifdef DEBUG
// if TRUE, then object sends update packet
BOOL CSE_ALifeObjectPhysic::Net_Relevant()
{
if (!freezed)
{
#ifdef XRGAME_EXPORTS
#ifdef DEBUG // this block of code is only for test
if (Device.dwTimeGlobal < (m_last_update_time + m_update_delta_time))
return FALSE;
#endif
#endif
return TRUE;
}
#ifdef XRGAME_EXPORTS
if (Device.dwTimeGlobal >= (m_freeze_time + m_freeze_delta_time))
return FALSE;
#endif
if (!prev_freezed)
{
prev_freezed = true; // i.e. freezed
return TRUE;
}
if (m_relevent_random.randI(random_limit))
return FALSE;
return TRUE;
}
void CSE_ALifeObjectPhysic::UPDATE_Read(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Read(tNetPacket);
inherited2::UPDATE_Read(tNetPacket);
if (tNetPacket.r_eof()) // backward compatibility
return;
//////////////////////////////////////////////////////////////////////////
tNetPacket.r_u8(m_u8NumItems);
if (!m_u8NumItems)
{
return;
}
mask_num_items num_items;
num_items.common = m_u8NumItems;
m_u8NumItems = num_items.num_items;
R_ASSERT2(m_u8NumItems < (u8(1) << 5), make_string("%d", m_u8NumItems));
/*if (check(num_items.mask,animated))
{
tNetPacket.r_float(m_blend_timeCurrent);
anim_use=true;
}
else
{
anim_use=false;
}*/
{
tNetPacket.r_vec3(State.force);
tNetPacket.r_vec3(State.torque);
tNetPacket.r_vec3(State.position);
tNetPacket.r_float(State.quaternion.x);
tNetPacket.r_float(State.quaternion.y);
tNetPacket.r_float(State.quaternion.z);
tNetPacket.r_float(State.quaternion.w);
State.enabled = check(num_items.mask, inventory_item_state_enabled);
if (!check(num_items.mask, inventory_item_angular_null))
{
tNetPacket.r_float(State.angular_vel.x);
tNetPacket.r_float(State.angular_vel.y);
tNetPacket.r_float(State.angular_vel.z);
}
else
State.angular_vel.set(0.f, 0.f, 0.f);
if (!check(num_items.mask, inventory_item_linear_null))
{
tNetPacket.r_float(State.linear_vel.x);
tNetPacket.r_float(State.linear_vel.y);
tNetPacket.r_float(State.linear_vel.z);
}
else
State.linear_vel.set(0.f, 0.f, 0.f);
/*if (check(num_items.mask,animated))
{
anim_use=true;
}*/
}
prev_freezed = freezed;
if (tNetPacket.r_eof()) // in case spawn + update
{
freezed = false;
return;
}
if (tNetPacket.r_u8())
{
freezed = false;
}
else
{
if (!freezed)
#ifdef XRGAME_EXPORTS
m_freeze_time = Device.dwTimeGlobal;
#else
m_freeze_time = 0;
#endif
freezed = true;
}
}
void CSE_ALifeObjectPhysic::UPDATE_Write(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Write(tNetPacket);
inherited2::UPDATE_Write(tNetPacket);
//////////////////////////////////////////////////////////////////////////
if (!m_u8NumItems)
{
tNetPacket.w_u8(0);
return;
}
mask_num_items num_items;
num_items.mask = 0;
num_items.num_items = m_u8NumItems;
R_ASSERT2(num_items.num_items < (u8(1) << 5), make_string("%d", num_items.num_items));
if (State.enabled)
num_items.mask |= inventory_item_state_enabled;
if (fis_zero(State.angular_vel.square_magnitude()))
num_items.mask |= inventory_item_angular_null;
if (fis_zero(State.linear_vel.square_magnitude()))
num_items.mask |= inventory_item_linear_null;
// if (anim_use) num_items.mask |= animated;
tNetPacket.w_u8(num_items.common);
/*if(check(num_items.mask,animated))
{
tNetPacket.w_float (m_blend_timeCurrent);
}*/
{
tNetPacket.w_vec3(State.force);
tNetPacket.w_vec3(State.torque);
tNetPacket.w_vec3(State.position);
tNetPacket.w_float(State.quaternion.x);
tNetPacket.w_float(State.quaternion.y);
tNetPacket.w_float(State.quaternion.z);
tNetPacket.w_float(State.quaternion.w);
if (!check(num_items.mask, inventory_item_angular_null))
{
tNetPacket.w_float(State.angular_vel.x);
tNetPacket.w_float(State.angular_vel.y);
tNetPacket.w_float(State.angular_vel.z);
}
if (!check(num_items.mask, inventory_item_linear_null))
{
tNetPacket.w_float(State.linear_vel.x);
tNetPacket.w_float(State.linear_vel.y);
tNetPacket.w_float(State.linear_vel.z);
}
}
//. Msg("--- Sync PH [%d].", ID);
tNetPacket.w_u8(1); // not freezed - doesn't mean anything..
#ifdef XRGAME_EXPORTS
#ifdef DEBUG
m_last_update_time = Device.dwTimeGlobal;
#endif
#endif
}
void CSE_ALifeObjectPhysic::load(NET_Packet& tNetPacket)
{
inherited1::load(tNetPacket);
inherited2::load(tNetPacket);
}
xr_token po_types[] = {
{"Box", epotBox}, {"Fixed chain", epotFixedChain}, {"Free chain", epotFreeChain}, {"Skeleton", epotSkeleton}, {nullptr, 0}};
#ifndef XRGAME_EXPORTS
void CSE_ALifeObjectPhysic::FillProps(LPCSTR pref, PropItemVec& values)
{
inherited1::FillProps(pref, values);
inherited2::FillProps(pref, values);
PHelper().CreateToken32(values, PrepareKey(pref, *s_name, "Type"), &type, po_types);
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Mass"), &mass, 0.1f, 10000.f);
PHelper().CreateFlag8(values, PrepareKey(pref, *s_name, "Active"), &_flags, flActive);
// motions & bones
PHelper().CreateChoose(values, PrepareKey(pref, *s_name, "Model" DELIMITER "Fixed bones"), &fixed_bones, smSkeletonBones, nullptr,
(void*)visual()->get_visual(), 8);
}
#endif // #ifndef XRGAME_EXPORTS
bool CSE_ALifeObjectPhysic::used_ai_locations() const /* noexcept */ { return false; }
bool CSE_ALifeObjectPhysic::can_save() const /* noexcept */ { return CSE_PHSkeleton::need_save(); }
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeObjectHangingLamp
////////////////////////////////////////////////////////////////////////////
CSE_ALifeObjectHangingLamp::CSE_ALifeObjectHangingLamp(LPCSTR caSection)
: CSE_ALifeDynamicObjectVisual(caSection), CSE_PHSkeleton(caSection)
{
flags.assign(flTypeSpot | flR1 | flR2);
range = 10.f;
color = 0xffffffff;
brightness = 1.f;
m_health = 100.f;
m_flags.set(flUseSwitches, false);
m_flags.set(flSwitchOffline, false);
m_virtual_size = 0.1f;
m_ambient_radius = 10.f;
m_ambient_power = 0.1f;
spot_cone_angle = deg2rad(120.f);
glow_radius = 0.7f;
m_volumetric_quality = 1.0f;
m_volumetric_intensity = 1.0f;
m_volumetric_distance = 1.0f;
}
CSE_ALifeObjectHangingLamp::~CSE_ALifeObjectHangingLamp() {}
void CSE_ALifeObjectHangingLamp::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
if (m_wVersion > 20)
inherited1::STATE_Read(tNetPacket, size);
if (m_wVersion >= 69)
inherited2::STATE_Read(tNetPacket, size);
if (m_wVersion < 32)
visual_read(tNetPacket, m_wVersion);
if (m_wVersion < 49)
{
shared_str s_tmp;
float f_tmp;
// model
tNetPacket.r_u32(color);
tNetPacket.r_stringZ(color_animator);
tNetPacket.r_stringZ(s_tmp);
tNetPacket.r_stringZ(s_tmp);
tNetPacket.r_float(range);
tNetPacket.r_angle8(f_tmp);
if (m_wVersion > 10)
tNetPacket.r_float(brightness);
if (m_wVersion > 11)
tNetPacket.r_u16(flags.flags);
if (m_wVersion > 12)
tNetPacket.r_float(f_tmp);
if (m_wVersion > 17)
tNetPacket.r_stringZ(startup_animation);
set_editor_flag(flVisualAnimationChange);
if (m_wVersion > 42)
{
tNetPacket.r_stringZ(s_tmp);
tNetPacket.r_float(f_tmp);
}
if (m_wVersion > 43)
{
tNetPacket.r_stringZ(fixed_bones);
}
if (m_wVersion > 44)
{
tNetPacket.r_float(m_health);
}
}
else
{
// model
tNetPacket.r_u32(color);
tNetPacket.r_float(brightness);
tNetPacket.r_stringZ(color_animator);
tNetPacket.r_float(range);
tNetPacket.r_u16(flags.flags);
tNetPacket.r_stringZ(startup_animation);
set_editor_flag(flVisualAnimationChange);
tNetPacket.r_stringZ(fixed_bones);
tNetPacket.r_float(m_health);
}
if (m_wVersion > 55)
{
tNetPacket.r_float(m_virtual_size);
tNetPacket.r_float(m_ambient_radius);
tNetPacket.r_float(m_ambient_power);
tNetPacket.r_stringZ(m_ambient_texture);
tNetPacket.r_stringZ(light_texture);
tNetPacket.r_stringZ(light_main_bone);
tNetPacket.r_float(spot_cone_angle);
tNetPacket.r_stringZ(glow_texture);
tNetPacket.r_float(glow_radius);
}
if (m_wVersion > 96)
{
tNetPacket.r_stringZ(light_ambient_bone);
}
else
{
light_ambient_bone = light_main_bone;
}
if (m_wVersion > 118)
{
tNetPacket.r_float(m_volumetric_quality);
tNetPacket.r_float(m_volumetric_intensity);
tNetPacket.r_float(m_volumetric_distance);
}
}
void CSE_ALifeObjectHangingLamp::STATE_Write(NET_Packet& tNetPacket)
{
inherited1::STATE_Write(tNetPacket);
inherited2::STATE_Write(tNetPacket);
// model
tNetPacket.w_u32(color);
tNetPacket.w_float(brightness);
tNetPacket.w_stringZ(color_animator);
tNetPacket.w_float(range);
tNetPacket.w_u16(flags.flags);
tNetPacket.w_stringZ(startup_animation);
tNetPacket.w_stringZ(fixed_bones);
tNetPacket.w_float(m_health);
tNetPacket.w_float(m_virtual_size);
tNetPacket.w_float(m_ambient_radius);
tNetPacket.w_float(m_ambient_power);
tNetPacket.w_stringZ(m_ambient_texture);
tNetPacket.w_stringZ(light_texture);
tNetPacket.w_stringZ(light_main_bone);
tNetPacket.w_float(spot_cone_angle);
tNetPacket.w_stringZ(glow_texture);
tNetPacket.w_float(glow_radius);
tNetPacket.w_stringZ(light_ambient_bone);
tNetPacket.w_float(m_volumetric_quality);
tNetPacket.w_float(m_volumetric_intensity);
tNetPacket.w_float(m_volumetric_distance);
}
void CSE_ALifeObjectHangingLamp::UPDATE_Read(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Read(tNetPacket);
inherited2::UPDATE_Read(tNetPacket);
}
void CSE_ALifeObjectHangingLamp::UPDATE_Write(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Write(tNetPacket);
inherited2::UPDATE_Write(tNetPacket);
}
void CSE_ALifeObjectHangingLamp::load(NET_Packet& tNetPacket)
{
inherited1::load(tNetPacket);
inherited2::load(tNetPacket);
}
void CSE_ALifeObjectHangingLamp::OnChangeFlag(PropValue* sender) { set_editor_flag(flUpdateProperties); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeObjectHangingLamp::FillProps(LPCSTR pref, PropItemVec& values)
{
inherited1::FillProps(pref, values);
inherited2::FillProps(pref, values);
PropValue* P = nullptr;
PHelper().CreateFlag16(values, PrepareKey(pref, *s_name, "Flags" DELIMITER "Physic"), &flags, flPhysic);
PHelper().CreateFlag16(values, PrepareKey(pref, *s_name, "Flags" DELIMITER "Cast Shadow"), &flags, flCastShadow);
PHelper().CreateFlag16(values, PrepareKey(pref, *s_name, "Flags" DELIMITER "Allow R1"), &flags, flR1);
PHelper().CreateFlag16(values, PrepareKey(pref, *s_name, "Flags" DELIMITER "Allow R2"), &flags, flR2);
P = PHelper().CreateFlag16(values, PrepareKey(pref, *s_name, "Flags" DELIMITER "Allow Ambient"), &flags, flPointAmbient);
P->OnChangeEvent.bind(this, &CSE_ALifeObjectHangingLamp::OnChangeFlag);
//
P = PHelper().CreateFlag16(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Type"), &flags, flTypeSpot, "Point", "Spot");
P->OnChangeEvent.bind(this, &CSE_ALifeObjectHangingLamp::OnChangeFlag);
PHelper().CreateColor(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Color"), &color);
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Brightness"), &brightness, 0.1f, 5.f);
PHelper().CreateChoose(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Color Animator"), &color_animator, smLAnim);
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Range"), &range, 0.1f, 1000.f);
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Virtual Size"), &m_virtual_size, 0.f, 100.f);
PHelper().CreateChoose(
values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Texture"), &light_texture, smTexture, "lights");
PHelper().CreateChoose(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Bone"), &light_main_bone, smSkeletonBones, nullptr,
(void*)visual()->get_visual());
if (flags.is(flTypeSpot))
{
PHelper().CreateAngle(
values, PrepareKey(pref, *s_name, "Light" DELIMITER "Main" DELIMITER "Cone Angle"), &spot_cone_angle, deg2rad(1.f), deg2rad(120.f));
// PHelper().CreateFlag16 (values, PrepareKey(pref,*s_name,"Light" DELIMITER "Main" DELIMITER "Volumetric"), &flags,
// flVolumetric);
P = PHelper().CreateFlag16(values, PrepareKey(pref, *s_name, "Flags" DELIMITER "Volumetric"), &flags, flVolumetric);
P->OnChangeEvent.bind(this, &CSE_ALifeObjectHangingLamp::OnChangeFlag);
}
if (flags.is(flPointAmbient))
{
PHelper().CreateFloat(
values, PrepareKey(pref, *s_name, "Light" DELIMITER "Ambient" DELIMITER "Radius"), &m_ambient_radius, 0.f, 1000.f);
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Ambient" DELIMITER "Power"), &m_ambient_power);
PHelper().CreateChoose(
values, PrepareKey(pref, *s_name, "Light" DELIMITER "Ambient" DELIMITER "Texture"), &m_ambient_texture, smTexture, "lights");
PHelper().CreateChoose(values, PrepareKey(pref, *s_name, "Light" DELIMITER "Ambient" DELIMITER "Bone"), &light_ambient_bone,
smSkeletonBones, nullptr, (void*)visual()->get_visual());
}
if (flags.is(flVolumetric))
{
PHelper().CreateFloat(
values, PrepareKey(pref, *s_name, "Light" DELIMITER "Volumetric" DELIMITER "Quality"), &m_volumetric_quality, 0.f, 1.f);
PHelper().CreateFloat(
values, PrepareKey(pref, *s_name, "Light" DELIMITER "Volumetric" DELIMITER "Intensity"), &m_volumetric_intensity, 0.f, 10.f);
PHelper().CreateFloat(
values, PrepareKey(pref, *s_name, "Light" DELIMITER "Volumetric" DELIMITER "Distance"), &m_volumetric_distance, 0.f, 1.f);
}
// fixed bones
PHelper().CreateChoose(values, PrepareKey(pref, *s_name, "Model" DELIMITER "Fixed bones"), &fixed_bones, smSkeletonBones, nullptr,
(void*)visual()->get_visual(), 8);
// glow
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Glow" DELIMITER "Radius"), &glow_radius, 0.01f, 100.f);
PHelper().CreateChoose(values, PrepareKey(pref, *s_name, "Glow" DELIMITER "Texture"), &glow_texture, smTexture, "glow");
// game
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Game" DELIMITER "Health"), &m_health, 0.f, 100.f);
}
#define VIS_RADIUS 0.25f
void CSE_ALifeObjectHangingLamp::on_render(
CDUInterface* du, IServerEntityLEOwner* owner, bool bSelected, const Fmatrix& parent, int priority, bool strictB2F)
{
inherited1::on_render(du, owner, bSelected, parent, priority, strictB2F);
if ((1 == priority) && (false == strictB2F))
{
u32 clr = bSelected ? 0x00FFFFFF : 0x00FFFF00;
Fmatrix main_xform, ambient_xform;
owner->get_bone_xform(*light_main_bone, main_xform);
main_xform.mulA_43(parent);
if (flags.is(flPointAmbient))
{
owner->get_bone_xform(*light_ambient_bone, ambient_xform);
ambient_xform.mulA_43(parent);
}
if (bSelected)
{
if (flags.is(flTypeSpot))
{
du->DrawSpotLight(main_xform.c, main_xform.k, range, spot_cone_angle, clr);
}
else
{
du->DrawLineSphere(main_xform.c, range, clr, true);
}
if (flags.is(flPointAmbient))
du->DrawLineSphere(ambient_xform.c, m_ambient_radius, clr, true);
}
du->DrawPointLight(main_xform.c, VIS_RADIUS, clr);
if (flags.is(flPointAmbient))
du->DrawPointLight(ambient_xform.c, VIS_RADIUS, clr);
}
}
#endif // #ifndef XRGAME_EXPORTS
bool CSE_ALifeObjectHangingLamp::used_ai_locations() const /* noexcept */ { return false; }
bool CSE_ALifeObjectHangingLamp::validate()
{
if (flags.test(flR1) || flags.test(flR2))
return (true);
Msg("! Render type is not set properly!");
return (false);
}
bool CSE_ALifeObjectHangingLamp::match_configuration() const /* noexcept */
{
R_ASSERT3(flags.test(flR1) || flags.test(flR2), "no renderer type set for hanging-lamp ", name_replace());
#ifdef XRGAME_EXPORTS
return (flags.test(flR1) && GEnv.Render->GenerationIsR1())
|| (flags.test(flR2) && GEnv.Render->GenerationIsR2OrHigher());
#else
return (true);
#endif
}
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeObjectSearchlight
////////////////////////////////////////////////////////////////////////////
CSE_ALifeObjectProjector::CSE_ALifeObjectProjector(LPCSTR caSection) : CSE_ALifeDynamicObjectVisual(caSection)
{
m_flags.set(flUseSwitches, false);
m_flags.set(flSwitchOffline, false);
}
CSE_ALifeObjectProjector::~CSE_ALifeObjectProjector() {}
void CSE_ALifeObjectProjector::STATE_Read(NET_Packet& tNetPacket, u16 size) { inherited::STATE_Read(tNetPacket, size); }
void CSE_ALifeObjectProjector::STATE_Write(NET_Packet& tNetPacket) { inherited::STATE_Write(tNetPacket); }
void CSE_ALifeObjectProjector::UPDATE_Read(NET_Packet& tNetPacket) { inherited::UPDATE_Read(tNetPacket); }
void CSE_ALifeObjectProjector::UPDATE_Write(NET_Packet& tNetPacket) { inherited::UPDATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeObjectProjector::FillProps(LPCSTR pref, PropItemVec& values) { inherited::FillProps(pref, values); }
#endif // #ifndef XRGAME_EXPORTS
bool CSE_ALifeObjectProjector::used_ai_locations() const /* noexcept */ { return false; }
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeSchedulable
////////////////////////////////////////////////////////////////////////////
CSE_ALifeSchedulable::CSE_ALifeSchedulable(LPCSTR caSection)
{
m_tpCurrentBestWeapon = nullptr;
m_tpBestDetector = nullptr;
m_schedule_counter = u64(-1);
}
CSE_ALifeSchedulable::~CSE_ALifeSchedulable() {}
bool CSE_ALifeSchedulable::need_update(CSE_ALifeDynamicObject* object)
{
return (!object ||
(object->m_bDirectControl && /**object->interactive() && **/ object->used_ai_locations() && !object->m_bOnline));
}
CSE_Abstract* CSE_ALifeSchedulable::init() { return (base()); }
u32 CSE_ALifeSchedulable::ef_creature_type() const
{
string16 temp;
CLSID2TEXT(base()->m_tClassID, temp);
R_ASSERT3(false, "Invalid alife creature type request, virtual function is not properly overloaded!", temp);
return (u32(-1));
}
u32 CSE_ALifeSchedulable::ef_anomaly_type() const
{
string16 temp;
CLSID2TEXT(base()->m_tClassID, temp);
R_ASSERT3(false, "Invalid alife anomaly type request, virtual function is not properly overloaded!", temp);
return (u32(-1));
}
u32 CSE_ALifeSchedulable::ef_weapon_type() const
{
string16 temp;
CLSID2TEXT(base()->m_tClassID, temp);
R_ASSERT3(false, "Invalid alife weapon type request, virtual function is not properly overloaded!", temp);
return (u32(-1));
}
u32 CSE_ALifeSchedulable::ef_detector_type() const
{
string16 temp;
CLSID2TEXT(base()->m_tClassID, temp);
R_ASSERT3(false, "Invalid alife detector type request, virtual function is not properly overloaded!", temp);
return (u32(-1));
}
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeHelicopter
////////////////////////////////////////////////////////////////////////////
CSE_ALifeHelicopter::CSE_ALifeHelicopter(LPCSTR caSection)
: CSE_ALifeDynamicObjectVisual(caSection), CSE_Motion(), CSE_PHSkeleton(caSection)
{
m_flags.set(flUseSwitches, false);
m_flags.set(flSwitchOffline, false);
m_flags.set(flInteractive, false);
}
CSE_ALifeHelicopter::~CSE_ALifeHelicopter() {}
CSE_Motion* CSE_ALifeHelicopter::motion() { return (this); }
void CSE_ALifeHelicopter::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited1::STATE_Read(tNetPacket, size);
CSE_Motion::motion_read(tNetPacket);
if (m_wVersion >= 69)
inherited3::STATE_Read(tNetPacket, size);
tNetPacket.r_stringZ(startup_animation);
tNetPacket.r_stringZ(engine_sound);
set_editor_flag(flVisualAnimationChange | flMotionChange);
}
void CSE_ALifeHelicopter::STATE_Write(NET_Packet& tNetPacket)
{
inherited1::STATE_Write(tNetPacket);
CSE_Motion::motion_write(tNetPacket);
inherited3::STATE_Write(tNetPacket);
tNetPacket.w_stringZ(startup_animation);
tNetPacket.w_stringZ(engine_sound);
}
void CSE_ALifeHelicopter::UPDATE_Read(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Read(tNetPacket);
inherited3::UPDATE_Read(tNetPacket);
}
void CSE_ALifeHelicopter::UPDATE_Write(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Write(tNetPacket);
inherited3::UPDATE_Write(tNetPacket);
}
void CSE_ALifeHelicopter::load(NET_Packet& tNetPacket)
{
inherited1::load(tNetPacket);
inherited3::load(tNetPacket);
}
bool CSE_ALifeHelicopter::can_save() const /* noexcept */ { return CSE_PHSkeleton::need_save(); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeHelicopter::FillProps(LPCSTR pref, PropItemVec& values)
{
inherited1::FillProps(pref, values);
inherited2::FillProps(pref, values);
inherited3::FillProps(pref, values);
PHelper().CreateChoose(values, PrepareKey(pref, *s_name, "Engine Sound"), &engine_sound, smSoundSource);
}
#endif // #ifndef XRGAME_EXPORTS
bool CSE_ALifeHelicopter::used_ai_locations() const /* noexcept */ { return false; }
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeCar
////////////////////////////////////////////////////////////////////////////
CSE_ALifeCar::CSE_ALifeCar(LPCSTR caSection) : CSE_ALifeDynamicObjectVisual(caSection), CSE_PHSkeleton(caSection)
{
if (pSettings->section_exist(caSection) && pSettings->line_exist(caSection, "visual"))
set_visual(pSettings->r_string(caSection, "visual"));
m_flags.set(flUseSwitches, false);
m_flags.set(flSwitchOffline, false);
health = 1.0f;
}
CSE_ALifeCar::~CSE_ALifeCar() {}
void CSE_ALifeCar::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited1::STATE_Read(tNetPacket, size);
if (m_wVersion > 65)
inherited2::STATE_Read(tNetPacket, size);
if ((m_wVersion > 52) && (m_wVersion < 55))
tNetPacket.r_float();
if (m_wVersion > 92)
health = tNetPacket.r_float();
if (health > 1.0f)
health /= 100.0f;
}
void CSE_ALifeCar::STATE_Write(NET_Packet& tNetPacket)
{
inherited1::STATE_Write(tNetPacket);
inherited2::STATE_Write(tNetPacket);
tNetPacket.w_float(health);
}
void CSE_ALifeCar::UPDATE_Read(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Read(tNetPacket);
inherited2::UPDATE_Read(tNetPacket);
}
void CSE_ALifeCar::UPDATE_Write(NET_Packet& tNetPacket)
{
inherited1::UPDATE_Write(tNetPacket);
inherited2::UPDATE_Write(tNetPacket);
}
bool CSE_ALifeCar::used_ai_locations() const /* noexcept */ { return false; }
bool CSE_ALifeCar::can_save() const /* noexcept */ { return CSE_PHSkeleton::need_save(); }
void CSE_ALifeCar::load(NET_Packet& tNetPacket)
{
inherited1::load(tNetPacket);
inherited2::load(tNetPacket);
}
void CSE_ALifeCar::data_load(NET_Packet& tNetPacket)
{
// inherited1::data_load(tNetPacket);
inherited2::data_load(tNetPacket);
// VERIFY(door_states.empty());
tNetPacket.r_vec3(o_Position);
tNetPacket.r_vec3(o_Angle);
door_states.clear();
u16 doors_number = tNetPacket.r_u16();
for (u16 i = 0; i < doors_number; ++i)
{
SDoorState ds;
ds.read(tNetPacket);
door_states.push_back(ds);
}
wheel_states.clear();
u16 wheels_number = tNetPacket.r_u16();
for (u16 i = 0; i < wheels_number; ++i)
{
SWheelState ws;
ws.read(tNetPacket);
wheel_states.push_back(ws);
}
health = tNetPacket.r_float();
}
void CSE_ALifeCar::data_save(NET_Packet& tNetPacket)
{
// inherited1::data_save(tNetPacket);
inherited2::data_save(tNetPacket);
tNetPacket.w_vec3(o_Position);
tNetPacket.w_vec3(o_Angle);
{
tNetPacket.w_u16(u16(door_states.size()));
xr_vector<SDoorState>::iterator i = door_states.begin(), e = door_states.end();
for (; e != i; ++i)
{
i->write(tNetPacket);
}
// door_states.clear();
}
{
tNetPacket.w_u16(u16(wheel_states.size()));
xr_vector<SWheelState>::iterator i = wheel_states.begin(), e = wheel_states.end();
for (; e != i; ++i)
{
i->write(tNetPacket);
}
// wheel_states.clear();
}
tNetPacket.w_float(health);
}
void CSE_ALifeCar::SDoorState::read(NET_Packet& P)
{
open_state = P.r_u8();
health = P.r_float();
}
void CSE_ALifeCar::SDoorState::write(NET_Packet& P)
{
P.w_u8(open_state);
P.w_float(health);
}
void CSE_ALifeCar::SWheelState::read(NET_Packet& P) { health = P.r_float(); }
void CSE_ALifeCar::SWheelState::write(NET_Packet& P) { P.w_float(health); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeCar::FillProps(LPCSTR pref, PropItemVec& values)
{
inherited1::FillProps(pref, values);
inherited2::FillProps(pref, values);
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Health"), &health, 0.f, 1.0f);
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeObjectBreakable
////////////////////////////////////////////////////////////////////////////
CSE_ALifeObjectBreakable::CSE_ALifeObjectBreakable(LPCSTR caSection) : CSE_ALifeDynamicObjectVisual(caSection)
{
m_health = 1.f;
m_flags.set(flUseSwitches, false);
m_flags.set(flSwitchOffline, false);
}
CSE_ALifeObjectBreakable::~CSE_ALifeObjectBreakable() {}
void CSE_ALifeObjectBreakable::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited::STATE_Read(tNetPacket, size);
tNetPacket.r_float(m_health);
}
void CSE_ALifeObjectBreakable::STATE_Write(NET_Packet& tNetPacket)
{
inherited::STATE_Write(tNetPacket);
tNetPacket.w_float(m_health);
}
void CSE_ALifeObjectBreakable::UPDATE_Read(NET_Packet& tNetPacket) { inherited::UPDATE_Read(tNetPacket); }
void CSE_ALifeObjectBreakable::UPDATE_Write(NET_Packet& tNetPacket) { inherited::UPDATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeObjectBreakable::FillProps(LPCSTR pref, PropItemVec& values)
{
inherited::FillProps(pref, values);
PHelper().CreateFloat(values, PrepareKey(pref, *s_name, "Health"), &m_health, 0.f, 100.f);
}
#endif // #ifndef XRGAME_EXPORTS
bool CSE_ALifeObjectBreakable::used_ai_locations() const /* noexcept */ { return false; }
bool CSE_ALifeObjectBreakable::can_switch_offline() const /* noexcept */ { return false; }
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeObjectClimable
////////////////////////////////////////////////////////////////////////////
CSE_ALifeObjectClimable::CSE_ALifeObjectClimable(LPCSTR caSection) : CSE_Shape(), CSE_ALifeDynamicObject(caSection)
{
// m_health = 100.f;
// m_flags.set (flUseSwitches,FALSE);
// m_flags.set (flSwitchOffline,FALSE);
material = "materials" DELIMITER "fake_ladders";
}
CSE_ALifeObjectClimable::~CSE_ALifeObjectClimable() {}
IServerEntityShape* CSE_ALifeObjectClimable::shape() { return (this); }
void CSE_ALifeObjectClimable::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
// inherited1::STATE_Read (tNetPacket,size);
if (m_wVersion == 99)
CSE_ALifeObject::STATE_Read(tNetPacket, size);
if (m_wVersion > 99)
inherited2::STATE_Read(tNetPacket, size);
cform_read(tNetPacket);
if (m_wVersion > 126)
tNetPacket.r_stringZ(material);
}
void CSE_ALifeObjectClimable::STATE_Write(NET_Packet& tNetPacket)
{
// inherited1::STATE_Write (tNetPacket);
inherited2::STATE_Write(tNetPacket);
cform_write(tNetPacket);
tNetPacket.w_stringZ(material);
}
void CSE_ALifeObjectClimable::UPDATE_Read(NET_Packet& /*tNetPacket*/)
{
// inherited1::UPDATE_Read (tNetPacket);
// inherited2::UPDATE_Read (tNetPacket);
}
void CSE_ALifeObjectClimable::UPDATE_Write(NET_Packet& /*tNetPacket*/)
{
// inherited1::UPDATE_Write (tNetPacket);
// inherited2::UPDATE_Write (tNetPacket);
}
#ifndef XRGAME_EXPORTS
void CSE_ALifeObjectClimable::FillProps(LPCSTR pref, PropItemVec& values)
{
// inherited1::FillProps (pref,values);
inherited2::FillProps(pref, values);
// PHelper().CreateFloat (values, PrepareKey(pref,*s_name,"Health"), &m_health, 0.f, 100.f);
}
void CSE_ALifeObjectClimable::set_additional_info(void* info)
{
LPCSTR material_name = (LPCSTR)info;
material = material_name;
}
#endif // #ifndef XRGAME_EXPORTS
bool CSE_ALifeObjectClimable::used_ai_locations() const /* noexcept */ { return false; }
bool CSE_ALifeObjectClimable::can_switch_offline() const /* noexcept */ { return false; }
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeMountedWeapon
////////////////////////////////////////////////////////////////////////////
CSE_ALifeMountedWeapon::CSE_ALifeMountedWeapon(LPCSTR caSection) : CSE_ALifeDynamicObjectVisual(caSection) {}
CSE_ALifeMountedWeapon::~CSE_ALifeMountedWeapon() {}
void CSE_ALifeMountedWeapon::STATE_Read(NET_Packet& tNetPacket, u16 size) { inherited::STATE_Read(tNetPacket, size); }
void CSE_ALifeMountedWeapon::STATE_Write(NET_Packet& tNetPacket) { inherited::STATE_Write(tNetPacket); }
void CSE_ALifeMountedWeapon::UPDATE_Read(NET_Packet& tNetPacket) { inherited::UPDATE_Read(tNetPacket); }
void CSE_ALifeMountedWeapon::UPDATE_Write(NET_Packet& tNetPacket) { inherited::UPDATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeMountedWeapon::FillProps(LPCSTR pref, PropItemVec& values) { inherited::FillProps(pref, values); }
#endif // #ifndef XRGAME_EXPORTS
CSE_ALifeStationaryMgun::CSE_ALifeStationaryMgun(LPCSTR caSection) : CSE_ALifeDynamicObjectVisual(caSection) {}
CSE_ALifeStationaryMgun::~CSE_ALifeStationaryMgun() {}
void CSE_ALifeStationaryMgun::UPDATE_Read(NET_Packet& tNetPacket)
{
inherited::UPDATE_Read(tNetPacket);
m_bWorking = !!tNetPacket.r_u8();
load_data(m_destEnemyDir, tNetPacket);
}
void CSE_ALifeStationaryMgun::UPDATE_Write(NET_Packet& tNetPacket)
{
inherited::UPDATE_Write(tNetPacket);
tNetPacket.w_u8(m_bWorking ? 1 : 0);
save_data(m_destEnemyDir, tNetPacket);
}
void CSE_ALifeStationaryMgun::STATE_Read(NET_Packet& tNetPacket, u16 size) { inherited::STATE_Read(tNetPacket, size); }
void CSE_ALifeStationaryMgun::STATE_Write(NET_Packet& tNetPacket) { inherited::STATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeStationaryMgun::FillProps(LPCSTR pref, PropItemVec& values) { inherited::FillProps(pref, values); }
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeTeamBaseZone
////////////////////////////////////////////////////////////////////////////
CSE_ALifeTeamBaseZone::CSE_ALifeTeamBaseZone(LPCSTR caSection) : CSE_ALifeSpaceRestrictor(caSection) { m_team = 0; }
CSE_ALifeTeamBaseZone::~CSE_ALifeTeamBaseZone() {}
void CSE_ALifeTeamBaseZone::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited::STATE_Read(tNetPacket, size);
tNetPacket.r_u8(m_team);
}
void CSE_ALifeTeamBaseZone::STATE_Write(NET_Packet& tNetPacket)
{
inherited::STATE_Write(tNetPacket);
tNetPacket.w_u8(m_team);
}
void CSE_ALifeTeamBaseZone::UPDATE_Read(NET_Packet& tNetPacket) { inherited::UPDATE_Read(tNetPacket); }
void CSE_ALifeTeamBaseZone::UPDATE_Write(NET_Packet& tNetPacket) { inherited::UPDATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeTeamBaseZone::FillProps(LPCSTR pref, PropItemVec& items)
{
inherited::FillProps(pref, items);
PHelper().CreateU8(items, PrepareKey(pref, *s_name, "team"), &m_team, 0, 16);
}
#endif // #ifndef XRGAME_EXPORTS
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeSmartZone
////////////////////////////////////////////////////////////////////////////
CSE_ALifeSmartZone::CSE_ALifeSmartZone(LPCSTR caSection)
: CSE_ALifeSpaceRestrictor(caSection), CSE_ALifeSchedulable(caSection)
{
}
CSE_ALifeSmartZone::~CSE_ALifeSmartZone() {}
CSE_Abstract* CSE_ALifeSmartZone::base() { return (this); }
const CSE_Abstract* CSE_ALifeSmartZone::base() const { return (this); }
CSE_Abstract* CSE_ALifeSmartZone::init()
{
inherited1::init();
inherited2::init();
return (this);
}
void CSE_ALifeSmartZone::STATE_Read(NET_Packet& tNetPacket, u16 size) { inherited1::STATE_Read(tNetPacket, size); }
void CSE_ALifeSmartZone::STATE_Write(NET_Packet& tNetPacket) { inherited1::STATE_Write(tNetPacket); }
void CSE_ALifeSmartZone::UPDATE_Read(NET_Packet& tNetPacket) { inherited1::UPDATE_Read(tNetPacket); }
void CSE_ALifeSmartZone::UPDATE_Write(NET_Packet& tNetPacket) { inherited1::UPDATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeSmartZone::FillProps(LPCSTR pref, PropItemVec& items) { inherited1::FillProps(pref, items); }
#endif // #ifndef XRGAME_EXPORTS
void CSE_ALifeSmartZone::update() {}
float CSE_ALifeSmartZone::detect_probability() { return (0.f); }
void CSE_ALifeSmartZone::smart_touch(CSE_ALifeMonsterAbstract* /*monster*/) {}
////////////////////////////////////////////////////////////////////////////
// CSE_ALifeInventoryBox
////////////////////////////////////////////////////////////////////////////
CSE_ALifeInventoryBox::CSE_ALifeInventoryBox(LPCSTR caSection) : CSE_ALifeDynamicObjectVisual(caSection)
{
m_can_take = true;
m_closed = false;
m_tip_text._set("inventory_box_use");
}
CSE_ALifeInventoryBox::~CSE_ALifeInventoryBox() {}
void CSE_ALifeInventoryBox::STATE_Read(NET_Packet& tNetPacket, u16 size)
{
inherited::STATE_Read(tNetPacket, size);
u16 m_wVersion = base()->m_wVersion;
if (m_wVersion > 124)
{
u8 temp;
tNetPacket.r_u8(temp);
m_can_take = (temp == 1);
tNetPacket.r_u8(temp);
m_closed = (temp == 1);
tNetPacket.r_stringZ(m_tip_text);
}
}
void CSE_ALifeInventoryBox::STATE_Write(NET_Packet& tNetPacket)
{
inherited::STATE_Write(tNetPacket);
tNetPacket.w_u8((m_can_take) ? 1 : 0);
tNetPacket.w_u8((m_closed) ? 1 : 0);
tNetPacket.w_stringZ(m_tip_text);
}
void CSE_ALifeInventoryBox::UPDATE_Read(NET_Packet& tNetPacket) { inherited::UPDATE_Read(tNetPacket); }
void CSE_ALifeInventoryBox::UPDATE_Write(NET_Packet& tNetPacket) { inherited::UPDATE_Write(tNetPacket); }
#ifndef XRGAME_EXPORTS
void CSE_ALifeInventoryBox::FillProps(LPCSTR pref, PropItemVec& values) { inherited::FillProps(pref, values); }
#endif // #ifndef XRGAME_EXPORTS
| 35.116675 | 148 | 0.665442 | clayne |
59fd2460f68cd9dd834253c7422a65ec613bb62b | 873 | cpp | C++ | glfw3_app/common/collada/dae_lights.cpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | 9 | 2015-09-22T21:36:57.000Z | 2021-04-01T09:16:53.000Z | glfw3_app/common/collada/dae_lights.cpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | null | null | null | glfw3_app/common/collada/dae_lights.cpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | 2 | 2019-02-21T04:22:13.000Z | 2021-03-02T17:24:32.000Z | //=====================================================================//
/*! @file
@brief collada lights のパーサー
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "dae_lights.hpp"
#include <boost/format.hpp>
namespace collada {
using namespace boost::property_tree;
using namespace std;
//-----------------------------------------------------------------//
/*!
@brief パース
@return エラー数(「0」なら成功)
*/
//-----------------------------------------------------------------//
int dae_lights::parse(utils::verbose& v, const boost::property_tree::ptree::value_type& element)
{
error_ = 0;
const std::string& s = element.first.data();
if(s != "library_lights") {
return error_;
}
if(v()) {
cout << s << ":" << endl;
}
const ptree& pt = element.second;
return error_;
}
}
| 21.292683 | 97 | 0.426117 | hirakuni45 |
59fed7843d8312e291e68c633fd451f0a4aeff92 | 248 | hpp | C++ | Vertex.hpp | Sqazine/soft-raster-examples | 743f975305de9b64ee135e844a23d2b2fcea3724 | [
"Apache-2.0"
] | null | null | null | Vertex.hpp | Sqazine/soft-raster-examples | 743f975305de9b64ee135e844a23d2b2fcea3724 | [
"Apache-2.0"
] | null | null | null | Vertex.hpp | Sqazine/soft-raster-examples | 743f975305de9b64ee135e844a23d2b2fcea3724 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Vec3.hpp"
#include "Vec2.hpp"
#include "Vec4.hpp"
struct Vertex
{
Vec4f position;
Vec2f texcoord;
Vec3f normal;
Vec3f tangent;
Vec3f binormal;
Vec4f color;
//用于光栅化时片元位置的插值
Vec3f fragPosWS;
};
| 14.588235 | 20 | 0.657258 | Sqazine |
94003a2ce9a8bef6b4f5ee2ac56fe3b2da2c5b77 | 648 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/anim/AnimNode_AnimSetTagValue.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/anim/AnimNode_AnimSetTagValue.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/anim/AnimNode_AnimSetTagValue.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/AnimNode_FloatValue.hpp>
#include <RED4ext/Scripting/Natives/Generated/red/TagList.hpp>
namespace RED4ext
{
namespace anim {
struct AnimNode_AnimSetTagValue : anim::AnimNode_FloatValue
{
static constexpr const char* NAME = "animAnimNode_AnimSetTagValue";
static constexpr const char* ALIAS = NAME;
red::TagList tags; // 48
uint8_t unk58[0x68 - 0x58]; // 58
};
RED4EXT_ASSERT_SIZE(AnimNode_AnimSetTagValue, 0x68);
} // namespace anim
} // namespace RED4ext
| 27 | 75 | 0.762346 | jackhumbert |
94005adf00144265ce730b3a466d16e607cafbaa | 269 | hxx | C++ | dev/ese/src/inc/_osu/timeu.hxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | 1 | 2021-02-02T07:04:07.000Z | 2021-02-02T07:04:07.000Z | dev/ese/src/inc/_osu/timeu.hxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | dev/ese/src/inc/_osu/timeu.hxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#ifndef _OSU_TIME_HXX_INCLUDED
#define _OSU_TIME_HXX_INCLUDED
typedef double DATESERIAL;
void UtilGetDateTime( DATESERIAL* pdt );
ERR ErrOSUTimeInit();
void OSUTimeTerm();
#endif
| 10.76 | 40 | 0.758364 | augustoproiete-forks |
940071b34ad2e1f8e02dfe9c480943349ceb55e5 | 4,803 | cpp | C++ | fk/upgrade_from_sd_worker.cpp | fieldkit/firmware | 09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6 | [
"BSD-3-Clause"
] | 10 | 2019-11-26T11:35:56.000Z | 2021-07-03T07:21:38.000Z | fk/upgrade_from_sd_worker.cpp | fieldkit/firmware | 09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6 | [
"BSD-3-Clause"
] | 1 | 2019-07-03T06:27:21.000Z | 2019-09-06T09:21:27.000Z | fk/upgrade_from_sd_worker.cpp | fieldkit/firmware | 09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6 | [
"BSD-3-Clause"
] | 1 | 2019-09-23T18:13:51.000Z | 2019-09-23T18:13:51.000Z | #include <samd51_common.h>
#include <loading.h>
#include <blake2b.h>
#include "modules/dyn/dyn.h"
#include "upgrade_from_sd_worker.h"
#include "hal/flash.h"
#include "storage/types.h"
#include "progress_tracker.h"
#include "gs_progress_callbacks.h"
#include "utilities.h"
#include "state_manager.h"
#include "graceful_shutdown.h"
#include "sd_copying.h"
#include "config.h"
extern const struct fkb_header_t fkb_header;
namespace fk {
FK_DECLARE_LOGGER("sdupgrade");
#if defined(linux)
fkb_header_t *fkb_try_header(void *ptr) {
return nullptr;
}
#endif
UpgradeFirmwareFromSdWorker::UpgradeFirmwareFromSdWorker(SdCardFirmware ¶ms) : params_(params) {
}
bool UpgradeFirmwareFromSdWorker::log_file_firmware(const char *path, fkb_header_t *header, Pool &pool) {
auto sd = get_sd_card();
if (!sd->begin()) {
logerror("error opening sd card");
return false;
}
if (!sd->is_file(path)) {
loginfo("no such file %s", path);
return false;
}
auto file = sd->open(path, OpenFlags::Read, pool);
if (file == nullptr || !file->is_open()) {
logerror("unable to open '%s'", path);
return false;
}
auto file_size = file->file_size();
loginfo("opened %zd bytes", file_size);
if (file_size == 0) {
logerror("empty file '%s'", path);
file->close();
return false;
}
file->seek_beginning();
auto HeaderSize = sizeof(fkb_header_t);
auto bytes_read = file->read((uint8_t *)header, HeaderSize);
file->close();
if (bytes_read != (int32_t)HeaderSize) {
logerror("error reading header '%s'", path);
return false;
}
auto fkbh = fkb_try_header((void *)header);
if (fkbh == NULL) {
logerror("error finding header '%s'", path);
return false;
}
fkb_log_header(fkbh);
return true;
}
void UpgradeFirmwareFromSdWorker::log_other_firmware() {
auto ptr = reinterpret_cast<uint8_t*>(OtherBankAddress + BootloaderSize);
auto fkbh = fkb_try_header(ptr);
if (fkbh == NULL) {
return;
}
fkb_log_header(fkbh);
}
void UpgradeFirmwareFromSdWorker::run(Pool &pool) {
auto bl_path = params_.bootloader;
auto main_path = params_.main;
// Why not do this?
// auto lock = sd_mutex.acquire(UINT32_MAX);
GlobalStateManager gsm;
switch (params_.operation) {
case SdCardFirmwareOperation::None: {
break;
}
case SdCardFirmwareOperation::Load: {
if (main_path != nullptr) {
fkb_header_t file_header;
if (!log_file_firmware(main_path, &file_header, pool)) {
gsm.notify("error inspecting fk");
return;
}
auto ptr = reinterpret_cast<uint8_t *>(PrimaryBankAddress + BootloaderSize);
auto running_fkbh = fkb_try_header(ptr);
if (running_fkbh == NULL) {
gsm.notify("fatal error");
return;
}
loginfo("running firmware");
fkb_log_header(running_fkbh);
if (params_.compare) {
loginfo("comparing firmware");
if (fkb_same_header(running_fkbh, &file_header)) {
gsm.notify(pool.sprintf("fw #%d", running_fkbh->firmware.number));
loginfo("same firmware");
return;
}
else {
loginfo("new firmware");
}
}
}
if (bl_path != nullptr && has_file(bl_path)) {
loginfo("loading bootloader");
if (!load_firmware(bl_path, OtherBankAddress, pool)) {
gsm.notify("error loading bl");
return;
}
}
else {
loginfo("bootloader skipped");
}
if (main_path != nullptr) {
loginfo("loading firmware");
if (!load_firmware(main_path, OtherBankAddress + BootloaderSize, pool)) {
gsm.notify("error loading fk");
return;
}
}
else {
loginfo("main skipped");
}
log_other_firmware();
fk_logs_flush();
if (params_.swap) {
gsm.notify("success, swap!");
fk_graceful_shutdown();
fk_delay(params_.delay);
fk_nvm_swap_banks();
}
else {
gsm.notify("success!");
}
break;
}
}
}
bool UpgradeFirmwareFromSdWorker::has_file(const char *path) {
auto sd = get_sd_card();
return sd->is_file(path);
}
bool UpgradeFirmwareFromSdWorker::load_firmware(const char *path, uint32_t address, Pool &pool) {
return copy_sd_to_flash(path, get_flash(), address, CodeMemoryPageSize, pool);
}
}
| 25.684492 | 105 | 0.578597 | fieldkit |
940391050131b5ee59593cac871b01db7aa773f0 | 9,235 | cpp | C++ | ArcGISRuntimeSDKQt_CppSamples/Routing/OfflineRouting/OfflineRouting.cpp | Pandinosaurus/arcgis-runtime-samples-qt | 87dc001e51a3e1279593fd8d6b6c1702225ad13c | [
"Apache-2.0"
] | 1 | 2021-05-06T06:39:41.000Z | 2021-05-06T06:39:41.000Z | ArcGISRuntimeSDKQt_CppSamples/Routing/OfflineRouting/OfflineRouting.cpp | Pandinosaurus/arcgis-runtime-samples-qt | 87dc001e51a3e1279593fd8d6b6c1702225ad13c | [
"Apache-2.0"
] | null | null | null | ArcGISRuntimeSDKQt_CppSamples/Routing/OfflineRouting/OfflineRouting.cpp | Pandinosaurus/arcgis-runtime-samples-qt | 87dc001e51a3e1279593fd8d6b6c1702225ad13c | [
"Apache-2.0"
] | null | null | null | // [WriteFile Name=OfflineRouting, Category=Routing]
// [Legal]
// Copyright 2020 Esri.
// 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.
// [Legal]
#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD
#include "OfflineRouting.h"
#include "ArcGISTiledLayer.h"
#include "CompositeSymbol.h"
#include "Envelope.h"
#include "GeometryEngine.h"
#include "Graphic.h"
#include "GraphicsOverlay.h"
#include "Map.h"
#include "MapQuickView.h"
#include "PictureMarkerSymbol.h"
#include "Polyline.h"
#include "RouteParameters.h"
#include "RouteResult.h"
#include "RouteTask.h"
#include "SimpleLineSymbol.h"
#include "SimpleRenderer.h"
#include "Stop.h"
#include "TextSymbol.h"
#include "TileCache.h"
#include <memory>
#include <QDir>
#include <QScopedPointer>
using namespace Esri::ArcGISRuntime;
// helper method to get cross platform data path
namespace
{
QString defaultDataPath()
{
QString dataPath;
#ifdef Q_OS_ANDROID
dataPath = "/sdcard";
#elif defined Q_OS_IOS
dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
dataPath = QDir::homePath();
#endif
return dataPath;
}
const QUrl pinUrl("qrc:/Samples/Routing/OfflineRouting/orange_symbol.png");
} // namespace
OfflineRouting::OfflineRouting(QObject* parent /* = nullptr */):
QObject(parent),
m_pinSymbol(new PictureMarkerSymbol(pinUrl, this)),
m_stopsOverlay(new GraphicsOverlay(this)),
m_routeOverlay(new GraphicsOverlay(this))
{
const QString folderLocation = QString("%1/ArcGIS/Runtime/Data/tpk/san_diego").arg(defaultDataPath());
if (!QFileInfo::exists(folderLocation))
{
qWarning() << "Please download required data.";
return;
}
const QString fileLocation = folderLocation + QString("/streetmap_SD.tpk");
TileCache* tileCache = new TileCache(fileLocation, this);
ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(tileCache, this);
Basemap* basemap = new Basemap(tiledLayer, this);
m_map = new Map(basemap, this);
m_map->setMinScale(100000);
SimpleLineSymbol* lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::blue, 2, this);
SimpleRenderer* routeRenderer = new SimpleRenderer(lineSymbol, this);
m_routeOverlay->setRenderer(routeRenderer);
m_pinSymbol->setHeight(50);
m_pinSymbol->setWidth(50);
m_pinSymbol->setOffsetY(m_pinSymbol->height() / 2);
const QString geodatabaseLocation = folderLocation + QString("/sandiego.geodatabase");
m_routeTask = new RouteTask(geodatabaseLocation, "Streets_ND", this);
m_routeTask->load();
}
OfflineRouting::~OfflineRouting() = default;
void OfflineRouting::init()
{
// Register the map view for QML
qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
qmlRegisterType<OfflineRouting>("Esri.Samples", 1, 0, "OfflineRoutingSample");
}
MapQuickView* OfflineRouting::mapView() const
{
return m_mapView;
}
QStringList OfflineRouting::travelModeNames() const
{
// if route task not initialized or loaded, then do not execute
if (!m_routeTask)
return { };
if(m_routeTask->loadStatus() != LoadStatus::Loaded)
return { };
QList<TravelMode> modesList = m_routeTask->routeTaskInfo().travelModes();
QStringList strList;
for (const TravelMode& mode : modesList)
{
strList << mode.name();
}
return strList;
}
void OfflineRouting::setTravelModeIndex(int index)
{
if (m_travelModeIndex == index)
return;
m_travelModeIndex = index;
emit travelModeIndexChanged();
}
int OfflineRouting::travelModeIndex() const
{
return m_travelModeIndex;
}
void OfflineRouting::connectSignals()
{
connect(m_routeTask, &RouteTask::createDefaultParametersCompleted, this, [this](QUuid, const RouteParameters& defaultParameters)
{
m_routeParameters = defaultParameters;
});
connect(m_routeTask, &RouteTask::doneLoading, this, [this](Error loadError)
{
if (loadError.isEmpty())
{
m_routeTask->createDefaultParameters();
emit travelModeNamesChanged();
}
else
{
qDebug() << loadError.message() << loadError.additionalMessage();
}
});
connect(m_mapView, &MapQuickView::identifyGraphicsOverlayCompleted, this, [this](QUuid, IdentifyGraphicsOverlayResult* rawIdentifyResult)
{
auto result = std::unique_ptr<IdentifyGraphicsOverlayResult>(rawIdentifyResult);
if (!result->error().isEmpty())
qDebug() << result->error().message() << result->error().additionalMessage();
m_selectedGraphic = nullptr;
if (!result->graphics().isEmpty())
{
// identify selected graphic in m_stopsOverlay
int index = m_stopsOverlay->graphics()->indexOf(result->graphics().at(0));
m_selectedGraphic = m_stopsOverlay->graphics()->at(index);
}
});
// check whether mouse pressed over an existing stop
connect(m_mapView, &MapQuickView::mousePressed, this, [this](QMouseEvent& e){
m_mapView->identifyGraphicsOverlay(m_stopsOverlay, e.x(), e.y(), 10, false);
});
// get stops from clicked locations
connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& e){
if (!m_selectedGraphic)
{
// return if point is outside of bounds
if (!GeometryEngine::within(m_mapView->screenToLocation(e.x(), e.y()), m_routableArea))
{
qWarning() << "Outside of routable area.";
return;
}
TextSymbol* textSymbol = new TextSymbol(QString::number(m_stopsOverlay->graphics()->size() + 1), Qt::white, 20, HorizontalAlignment::Center, VerticalAlignment::Bottom, this);
textSymbol->setOffsetY(m_pinSymbol->height() / 2);
CompositeSymbol* stopLabel = new CompositeSymbol(QList<Symbol*>{m_pinSymbol, textSymbol}, this);
Graphic* stopGraphic = new Graphic(m_mapView->screenToLocation(e.x(), e.y()), stopLabel, this);
m_stopsOverlay->graphics()->append(stopGraphic);
findRoute();
}
e.accept();
});
// mouseMoved is processed before identifyGraphicsOverlayCompleted, so must clear graphic upon mouseReleased
connect(m_mapView, &MapQuickView::mouseReleased, this, [this](QMouseEvent& e) {
if (m_selectedGraphic)
{
m_selectedGraphic = nullptr;
e.accept();
}
});
// if mouse is moved while pressing on a graphic, the click-and-pan effect of the MapView is prevented by e.accept()
connect(m_mapView, &MapQuickView::mouseMoved, this, [this](QMouseEvent&e){
if (m_selectedGraphic)
{
e.accept();
// return if point is outside of bounds
if (!GeometryEngine::within(m_mapView->screenToLocation(e.x(), e.y()), m_routableArea))
{
qWarning() << "Outside of routable area.";
return;
}
m_selectedGraphic->setGeometry(m_mapView->screenToLocation(e.x(), e.y()));
findRoute();
}
});
connect(m_routeTask, &RouteTask::solveRouteCompleted, this, [this](QUuid, const RouteResult routeResult){
if (routeResult.isEmpty())
return;
// clear old route
m_routeOverlay->graphics()->clear();
Polyline routeGeometry = routeResult.routes().first().routeGeometry();
Graphic* routeGraphic = new Graphic(routeGeometry, this);
m_routeOverlay->graphics()->append(routeGraphic);
});
}
void OfflineRouting::findRoute()
{
if(!m_taskWatcher.isDone())
return;
if (m_stopsOverlay->graphics()->size() > 1)
{
QList<Stop> stops;
for (const Graphic* graphic : *m_stopsOverlay->graphics())
{
stops << Stop(graphic->geometry());
}
// configure stops and travel mode
m_routeParameters.setStops(stops);
m_routeParameters.setTravelMode(m_routeTask->routeTaskInfo().travelModes().at(m_travelModeIndex));
m_taskWatcher = m_routeTask->solveRoute(m_routeParameters);
}
}
// Set the view (created in QML)
void OfflineRouting::setMapView(MapQuickView* mapView)
{
if (!mapView || mapView == m_mapView)
return;
m_mapView = mapView;
m_mapView->setMap(m_map);
m_mapView->graphicsOverlays()->append(m_stopsOverlay);
m_mapView->graphicsOverlays()->append(m_routeOverlay);
GraphicsOverlay* boundaryOverlay = new GraphicsOverlay(this);
m_routableArea = Envelope(Point(-13045352.223196, 3864910.900750,SpatialReference::webMercator()), Point(-13024588.857198, 3838880.505604, SpatialReference::webMercator()));
SimpleLineSymbol* boundarySymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Dash, Qt::green, 3, this);
Graphic* boundaryGraphic = new Graphic(m_routableArea, boundarySymbol, this);
boundaryOverlay->graphics()->append(boundaryGraphic);
m_mapView->graphicsOverlays()->append(boundaryOverlay);
connectSignals();
emit mapViewChanged();
}
void OfflineRouting::resetMap()
{
m_selectedGraphic = nullptr;
if (m_stopsOverlay)
m_stopsOverlay->graphics()->clear();
if(m_routeOverlay)
m_routeOverlay->graphics()->clear();
}
| 30.783333 | 180 | 0.716622 | Pandinosaurus |
9410a6bad10b0488a5716a813cba8f9f122d2061 | 3,655 | cpp | C++ | src/0-basics/init-d3d/main.cpp | yottaawesome/directx-playground | 6cf59cd42ebe1668eda8862f8ba7bb69ba102ff4 | [
"MIT"
] | null | null | null | src/0-basics/init-d3d/main.cpp | yottaawesome/directx-playground | 6cf59cd42ebe1668eda8862f8ba7bb69ba102ff4 | [
"MIT"
] | null | null | null | src/0-basics/init-d3d/main.cpp | yottaawesome/directx-playground | 6cf59cd42ebe1668eda8862f8ba7bb69ba102ff4 | [
"MIT"
] | null | null | null | #include "header.h"
#include <iostream>
#include <wrl.h>
using Microsoft::WRL::ComPtr;
int main(int argc, char* argv[])
{
try
{
RegisterWindowClass();
HWND hWnd = CreateMainWindow();
DXGI_FORMAT mBackBufferFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
UINT sampleCount = 4;
const UINT bufferCount = 2;
// Create Device
ComPtr<ID3D12Device> device = CreateAD3D12Device();
// Create Fence
UINT mRtvDescriptorSize = 0;
UINT mDsvDescriptorSize = 0;
UINT mCbvSrvUavDescriptorSize = 0;
ComPtr<ID3D12Fence> fence = CreateFence(device.Get(), mRtvDescriptorSize, mDsvDescriptorSize, mCbvSrvUavDescriptorSize);
UINT msaaQualityLevels = DetermineMSAAQualitySupport(device.Get(), mBackBufferFormat, sampleCount);
// Create Command Objects
CommandObjects commandObjects = { 0 };
CreateCommandObjects(device.Get(), commandObjects);
ComPtr<ID3D12CommandQueue> mCommandQueue = commandObjects.mCommandQueue;
ComPtr<ID3D12CommandAllocator> mDirectCmdListAlloc = commandObjects.mDirectCmdListAlloc;
ComPtr<ID3D12GraphicsCommandList> mCommandList = commandObjects.mCommandList;
// Create swap chain
IDXGIFactory4* mdxgiFactory;
CreateDXGIFactory1(IID_PPV_ARGS(&mdxgiFactory));
RECT r;
GetClientRect(hWnd, &r);
ComPtr<IDXGISwapChain> swapChain = CreateSwapChain(
mdxgiFactory,
mCommandQueue.Get(),
hWnd,
r.right,
r.bottom,
mBackBufferFormat,
bufferCount,
false,
sampleCount,
msaaQualityLevels);
// Create Descriptor Heaps
ComPtr<ID3D12DescriptorHeap> mRtvHeap;
ComPtr<ID3D12DescriptorHeap> mDsvHeap;
CreateRtvAndDsvDescriptorHeaps(device.Get(), bufferCount, mRtvHeap.GetAddressOf(), mDsvHeap.GetAddressOf());
ComPtr<ID3D12Resource> mSwapChainBuffer[bufferCount];
CreateRenderTargetView(device.Get(), swapChain.Get(), mRtvHeap.Get(), mRtvDescriptorSize, bufferCount, mSwapChainBuffer);
DXGI_FORMAT mDepthStencilFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
ComPtr<ID3D12Resource> mDepthStencilBuffer;
UINT64 mCurrentFence = 0;
ComPtr<ID3D12Fence> mFence;
ThrowIfFailed(device->CreateFence(0, D3D12_FENCE_FLAG_NONE,
IID_PPV_ARGS(&mFence)));
D3D12_VIEWPORT mScreenViewport;
D3D12_RECT mScissorRect;
CreateDepthAndStencilBuffer
(
device.Get(),
swapChain.Get(),
mRtvHeap.Get(),
mDsvHeap.Get(),
bufferCount,
r.right,
r.bottom,
mBackBufferFormat,
mSwapChainBuffer,
mRtvDescriptorSize,
false,
sampleCount,
4,
mDepthStencilFormat,
mDepthStencilBuffer,
mCommandList,
mCommandQueue.Get(),
mCurrentFence,
mFence.Get(),
mScreenViewport,
mScissorRect,
mDirectCmdListAlloc
);
UINT mCurrBuffer = 0;
MSG msg = { 0 };
while (msg.message != WM_QUIT)
{
// If there are Window messages then process them.
if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Otherwise, do animation/game stuff.
else
{
Draw(
mDirectCmdListAlloc,
mCommandList,
mScreenViewport,
mDsvHeap.Get(),
mScissorRect,
bufferCount,
mCommandQueue.Get(),
mCurrentFence,
mRtvDescriptorSize,
mFence.Get(),
mSwapChainBuffer,
mRtvHeap.Get(),
swapChain.Get(),
mCurrBuffer);
}
}
return (int)msg.wParam;
}
catch (DxException& error)
{
std::cout << "DxException! " << error.ToString() << std::endl;
return 1;
}
catch (std::runtime_error& error)
{
std::cout << "Exception: " << error.what() << std::endl;
return 1;
}
}
| 26.485507 | 124 | 0.687551 | yottaawesome |
9412cc3661a29eeb0d38fcaec79dac0a032b0fda | 309 | cpp | C++ | archive/1.12.03.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | archive/1.12.03.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | archive/1.12.03.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
bool jl(double a,int b){
if(a>=37.5&&b==1) return true;
else return false;
}
int main(){
int n,ans=0;
scanf("%d",&n);
for(int i=0;i<n;i++){
char a[10];
double b;
int c;
scanf("%s %lf %d",a,&b,&c);
if(jl(b,c)){
ans++;
printf("%s\n",a);
}
}
printf("%d",ans);
}
| 12.36 | 31 | 0.498382 | woshiluo |
9412ed794324257006b770e7629811d01e438cfb | 2,970 | cpp | C++ | CODECHEF/Long/MAY15/devhand.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | CODECHEF/Long/MAY15/devhand.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | CODECHEF/Long/MAY15/devhand.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <algorithm>
#include <cctype>
#include <vector>
#include <queue>
#include <tr1/unordered_map>
#include <cmath>
#include <map>
#include <bitset>
#include <set>
#include <iomanip>
#include <cstring>
#include <unistd.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector< ii > vii;
///////////////////////////////UTIL/////////////////////////////////
#define ALL(x) (x).begin(),x.end()
#define CLEAR0(v) memset(v, 0, sizeof(v))
#define CLEAR(v, x) memset(v, x, sizeof(v))
#define COPY(a, b) memcpy(a, b, sizeof(a))
#define CMP(a, b) memcmp(a, b, sizeof(a))
#define REP(i,n) for(int i = 0; i<n; i++)
#define REPP(i,a,n) for(int i = a; i<n; i++)
#define REPD(i,n) for(int i = n-1; i>-1; i--)
#define REPDP(i,a,n) for(int i = n-1; i>=a; i--)
#define pb push_back
#define pf push_front
#define sz size()
#define mp make_pair
/////////////////////////////NUMERICAL//////////////////////////////
#define INF 0x3f3f3f3f
/////////////////////////////BITWISE////////////////////////////////
#define CHECK(S, j) (S & (1 << j))
#define CHECKFIRST(S) (S & (-S))
#define SET(S, j) S |= (1 << j)
#define SETALL(S, j) S = (1 << j)-1
#define UNSET(S, j) S &= ~(1 << j)
#define TOOGLE(S, j) S ^= (1 << j)
///////////////////////////////64 BITS//////////////////////////////
#define LCHECK(S, j) (S & (1ULL << j))
#define LSET(S, j) S |= (1ULL << j)
#define LSETALL(S, j) S = (1ULL << j)-1ULL
#define LUNSET(S, j) S &= ~(1ULL << j)
#define LTOOGLE(S, j) S ^= (1ULL << j)
#define EPS 10e-20
#define MOD 1000000007
//__builtin_popcount(m)
//scanf(" %d ", &t);
int t;
ll n, k;
ll K[1000100];
ll x, y, d;
//inv modular de a mod b = m eh o x
void extendedEuclid(int a, int b){
if(b == 0){ x = 1; y = 0; d = a; return; }
extendedEuclid(b, a%b);
ll x1 = y;
ll y1 = x - (a/b) * y;
x = x1;
y = y1;
}
ll invMult(ll a, ll m){
extendedEuclid(a, m);
x = x%m;
if(x < 0) x += m;
return x;
}
ll calc(ll a, ll b){
if(b < a) swap(a, b);
ll div = invMult((k-1), MOD);
ll X = (((K[n+1] - 1LL)*div)%MOD) - 2LL - (((K[b]-1LL)*div)%MOD);
if(X < MOD) x += MOD;
ll res = X - ((X*invMult(K[b], MOD))%MOD) - ((X*invMult(K[a], MOD))%MOD);
if(res<0LL) res += MOD;
return res;
}
int main(){
scanf(" %d ", &t);
while(t--){
scanf(" %lld %lld ", &n, &k);
K[0] = 1LL;
REPP(i, 1, n+1) K[i] = (K[i-1]*k)%MOD;
ll ans = 0LL;
for(ll i = 1LL; i<=n; i++){
ll sum = 0LL;
for(ll j = 1LL; j<i; j++){
//ll x = (((K[i] * (K[j] - K[j-i]))%MOD)*(K[l]-K[l-j]-K[l-i]))%MOD;
//if(j < l) x *= (x*2LL)%MOD;
//cout << "i:" << i << " j:" << j << " l:" << l << " -----> " << calc(i, j, l) << endl;
ll X = (i >= j)? (K[j] * (K[i]-K[i-j]))%MOD : (K[i] * (K[j]-K[j-i]))%MOD;
if(X < 0LL) X += MOD;
ans = (ans + (X*calc(i, j))%MOD)%MOD;
}
}
while(ans < 0) ans += MOD;
printf("%lld\n", ans);
}
}
| 26.517857 | 91 | 0.49596 | henviso |
9413258b1c6e346bb18d88bbedc77325fb0086f7 | 703 | hpp | C++ | MessageLevelModel/sobel/utils.hpp | Blinded4Review/ASPDAC | f1567cff39b4f11fe61cd463fb742b990b927170 | [
"Apache-2.0"
] | null | null | null | MessageLevelModel/sobel/utils.hpp | Blinded4Review/ASPDAC | f1567cff39b4f11fe61cd463fb742b990b927170 | [
"Apache-2.0"
] | null | null | null | MessageLevelModel/sobel/utils.hpp | Blinded4Review/ASPDAC | f1567cff39b4f11fe61cd463fb742b990b927170 | [
"Apache-2.0"
] | null | null | null | #ifndef UTILS_H
#define UTILS_H
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
// get max
double get_max(const double x, const double y);
// general discrete distributions
size_t get_discrete(const gsl_rng *r, size_t K, const double *P);
// gaussian distribution
double get_gaussian(const gsl_rng *r, double sigma, double mu);
// bernoulli distribution
int get_bernoulli(const gsl_rng *r, double p);
// exponential distribution
double get_exponential(const gsl_rng *r, double mu);
// get P(X <= x) of exponential distribution
double get_exponential_P(double x, double mu);
// uniform distribution
int get_uniform(const gsl_rng * r, double a, double b);
#endif
| 21.96875 | 65 | 0.755334 | Blinded4Review |
941580d44e194d6f55bc3e72aedfe06c0fe47f7b | 383 | cpp | C++ | loops-fun/main.cpp | diegopacheco/cpp-playground | 5ff4391f4bb40f6395f8d990ac8ce8fbb3d0b020 | [
"Unlicense"
] | null | null | null | loops-fun/main.cpp | diegopacheco/cpp-playground | 5ff4391f4bb40f6395f8d990ac8ce8fbb3d0b020 | [
"Unlicense"
] | null | null | null | loops-fun/main.cpp | diegopacheco/cpp-playground | 5ff4391f4bb40f6395f8d990ac8ce8fbb3d0b020 | [
"Unlicense"
] | 1 | 2021-09-07T22:18:08.000Z | 2021-09-07T22:18:08.000Z | #include <iostream>
using namespace std;
void funWithWhile(){
cout << "Fun with While:" << endl;
int i = 0;
while (i < 10){
cout << i << "\n";
i++;
}
}
void funWithFor(){
cout << "Fun with For:" << endl;
for (int i = 0; i < 10; i++) {
cout << i << "\n";
}
}
int main(){
funWithWhile();
funWithFor();
return 0;
}
| 15.32 | 38 | 0.454308 | diegopacheco |
9415c8c50aae2460bfeab45ffc310f52ac0e08e7 | 1,007 | cpp | C++ | Competitive Programing Problem Solutions/Graph Theory/graph coloring when connected.cpp | BIJOY-SUST/ACM---ICPC | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | 1 | 2022-02-27T12:07:59.000Z | 2022-02-27T12:07:59.000Z | Competitive Programing Problem Solutions/Graph Theory/graph coloring when connected.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | Competitive Programing Problem Solutions/Graph Theory/graph coloring when connected.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int v;
bool isBipartite(int matrix[100][100],int n){
int color[v];
queue<int>q; ///0 1 0 1
q.push(n); ///1 0 1 0
memset(color,-1,sizeof(color)); ///0 1 0 1
color[n]=1; ///1 0 1 0
while(!q.empty()){
int u=q.front();
q.pop();
for(int i=0; i<v; i++){
if(matrix[u][i]==1 && color[i]==-1){
color[i]=1-color[u];
q.push(i);
}
else if(matrix[u][i]==1 && color[u]==color[i]){
return false;
}
}
}
return true;
}
int main(){
cin>>v;
int matrix[100][100];
for(int i=0;i<v;i++){
for(int j=0;j<v;j++){
cin>>matrix[i][j];
}
}
isBipartite(matrix,0) ? cout<<"YES"<<endl:cout<<"NO"<<endl;
return 0;
}
//4
//0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0
| 26.5 | 64 | 0.381331 | BIJOY-SUST |
941710f7592c7cf8ab2864f7d377a9f2441673d7 | 3,027 | hpp | C++ | RobWorkSim/src/rwsimlibs/gui/ContactTableWidget.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | 1 | 2021-12-29T14:16:27.000Z | 2021-12-29T14:16:27.000Z | RobWorkSim/src/rwsimlibs/gui/ContactTableWidget.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | RobWorkSim/src/rwsimlibs/gui/ContactTableWidget.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | /********************************************************************************
* Copyright 2016 The Robotics Group, The Maersk Mc-Kinney Moller Institute,
* Faculty of Engineering, University of Southern Denmark
*
* 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 RWSIMLIBS_GUI_CONTACTTABLEWIDGET_HPP_
#define RWSIMLIBS_GUI_CONTACTTABLEWIDGET_HPP_
/**
* @file ContactTableWidget.hpp
*
* \copydoc ContactTableWidget
*/
#include <rw/core/Ptr.hpp>
#include <rw/math/Vector3D.hpp>
#include <QTableWidget>
namespace rw { namespace graphics {
class GroupNode;
}} // namespace rw::graphics
namespace rw { namespace graphics {
class SceneGraph;
}} // namespace rw::graphics
namespace rwsim { namespace contacts {
class Contact;
}} // namespace rwsim::contacts
QT_BEGIN_NAMESPACE
/**
* @brief A table widget customised for rwsim::contacts::Contact types.
*/
class ContactTableWidget : public QTableWidget
{
Q_OBJECT
public:
/**
* @brief Constructor.
* @param parent [in] (optional) the owner of this widget.
*/
ContactTableWidget (QWidget* parent = 0);
//! @brief Destructor.
virtual ~ContactTableWidget ();
/**
* @brief Update the widget with a new contact set.
* @param contacts [in] a vector of contacts.
*/
virtual void setContacts (const std::vector< rwsim::contacts::Contact >& contacts);
/**
* @brief Add graphics as drawables to a scene-graph.
* @param root [in] the node to add drawables to.
* @param graph [in] the scene graph.
*/
virtual void showGraphics (rw::core::Ptr< rw::graphics::GroupNode > root,
rw::core::Ptr< rw::graphics::SceneGraph > graph);
//! @brief Select all contacts.
virtual void selectAll ();
signals:
//! @brief Signal is emitted if the graphics is updated.
void graphicsUpdated ();
public slots:
void clearContents ();
private slots:
void contactSetChanged (const QItemSelection& newSelection, const QItemSelection& oldSelection);
private:
QString toQString (const rw::math::Vector3D<>& vec);
QString toQString (const rwsim::contacts::Contact& contact);
private:
std::vector< rwsim::contacts::Contact > _contacts;
rw::core::Ptr< rw::graphics::GroupNode > _root;
rw::core::Ptr< rw::graphics::SceneGraph > _graph;
};
QT_END_NAMESPACE
#endif /* RWSIMLIBS_GUI_CONTACTTABLEWIDGET_HPP_ */
| 30.27 | 100 | 0.656095 | ZLW07 |
94173586915ead9c50b4fa91eaf7cae4a1a714ad | 2,752 | hpp | C++ | include/wee/core/zip.hpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2019-02-11T12:18:39.000Z | 2019-02-11T12:18:39.000Z | include/wee/core/zip.hpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:27:58.000Z | 2021-11-11T07:27:58.000Z | include/wee/core/zip.hpp | emdavoca/wee | 60344dd646a2e27d1cfdb1131dd679558d9cfa2b | [
"MIT"
] | 1 | 2021-11-11T07:22:12.000Z | 2021-11-11T07:22:12.000Z | #pragma once
#include <algorithm>
#include <iterator>
#include <iostream>
#include <tuple>
namespace wee {
template<typename T>
class zip_impl
{
public:
typedef std::vector<T> container_t;
template<typename... Args>
zip_impl(const T& head, const Args&... args)
: items_(head.size()),
min_(head.size())
{
zip_(head, args...);
}
inline operator container_t() const
{
return items_;
}
inline container_t operator()() const
{
return items_;
}
private:
template<typename... Args>
void zip_(const T& head, const Args&... tail)
{
// If the current item's size is less than
// // the one stored in min_, reset the min_
// // variable to the item's size
if (head.size() < min_) min_ = head.size();
for (std::size_t i = 0; i < min_; ++i)
{
// Use begin iterator and advance it instead
// of using the subscript operator adds support
// for lists. std::advance has constant complexity
// for STL containers whose iterators are
// RandomAccessIterators (e.g. vector or deque)
typename T::const_iterator itr = head.begin();
std::advance(itr, i);
items_[i].push_back(*itr);
}
// Recursive call to zip_(T, Args...)
// while the expansion of tail... is not empty
// else calls the overload with no parameters
return zip_(tail...);
}
inline void zip_()
{
// If min_ has shrunk since the
// constructor call
items_.resize(min_);
}
/*! Holds the items for iterating. */
container_t items_;
/*! The minimum number of values held by all items */
std::size_t min_;
};
template<typename T, typename... Args>
typename zip_impl<T>::container_t zip(const T& head, const Args&... tail)
{
return std::tie(zip_impl<T>(head, tail...));
}
}
| 30.577778 | 81 | 0.411701 | emdavoca |
94261c8e735a7a636bfbebbd2c944df435c91d4a | 737 | cc | C++ | build/ARM/python/_m5/param_O3Checker.cc | msharmavikram/gem5_experiments | 87353d28df55b9a6a5be6cbb19bce87a500ab3b4 | [
"BSD-3-Clause"
] | 5 | 2019-12-12T16:26:09.000Z | 2022-03-17T03:23:33.000Z | build/X86/python/_m5/param_O3Checker.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | build/X86/python/_m5/param_O3Checker.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | #include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "params/O3Checker.hh"
#include "python/pybind11/core.hh"
#include "sim/init.hh"
#include "sim/sim_object.hh"
#include "cpu/o3/checker.hh"
namespace py = pybind11;
static void
module_init(py::module &m_internal)
{
py::module m = m_internal.def_submodule("param_O3Checker");
py::class_<O3CheckerParams, CheckerCPUParams, std::unique_ptr<O3CheckerParams, py::nodelete>>(m, "O3CheckerParams")
.def(py::init<>())
.def("create", &O3CheckerParams::create)
;
py::class_<O3Checker, CheckerCPU, std::unique_ptr<O3Checker, py::nodelete>>(m, "O3Checker")
;
}
static EmbeddedPyBind embed_obj("O3Checker", module_init, "CheckerCPU");
| 26.321429 | 119 | 0.702849 | msharmavikram |
9428181d5f9dd6931046151f9c4e85cfda6f3554 | 1,610 | cpp | C++ | learncpp.com/09_Operator_Overloading/Question04/src/Main.cpp | KoaLaYT/Learn-Cpp | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | [
"MIT"
] | null | null | null | learncpp.com/09_Operator_Overloading/Question04/src/Main.cpp | KoaLaYT/Learn-Cpp | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | [
"MIT"
] | null | null | null | learncpp.com/09_Operator_Overloading/Question04/src/Main.cpp | KoaLaYT/Learn-Cpp | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | [
"MIT"
] | null | null | null | /**
* Chapter 9 :: Question 4
*
* implement a two point fixed floating number
*
* KoaLaYT 20:37 02/02/2020
*
*/
#include "FixedPoint2.h"
void testAddition() {
// h/t to reader Sharjeel Safdar for this function
std::cout << std::boolalpha;
std::cout << (FixedPoint2{0.75} + FixedPoint2{1.23} == FixedPoint2{1.98})
<< '\n'; // both positive, no decimal overflow
std::cout << (FixedPoint2{0.75} + FixedPoint2{1.50} == FixedPoint2{2.25})
<< '\n'; // both positive, with decimal overflow
std::cout << (FixedPoint2{-0.75} + FixedPoint2{-1.23} == FixedPoint2{-1.98})
<< '\n'; // both negative, no decimal overflow
std::cout << (FixedPoint2{-0.75} + FixedPoint2{-1.50} == FixedPoint2{-2.25})
<< '\n'; // both negative, with decimal overflow
std::cout << (FixedPoint2{0.75} + FixedPoint2{-1.23} == FixedPoint2{-0.48})
<< '\n'; // second negative, no decimal overflow
std::cout << (FixedPoint2{0.75} + FixedPoint2{-1.50} == FixedPoint2{-0.75})
<< '\n'; // second negative, possible decimal overflow
std::cout << (FixedPoint2{-0.75} + FixedPoint2{1.23} == FixedPoint2{0.48})
<< '\n'; // first negative, no decimal overflow
std::cout << (FixedPoint2{-0.75} + FixedPoint2{1.50} == FixedPoint2{0.75})
<< '\n'; // first negative, possible decimal overflow
}
int main() {
testAddition();
FixedPoint2 a{-0.48};
std::cout << a << '\n';
std::cout << -a << '\n';
std::cout << "Enter a number: "; // enter 5.678
std::cin >> a;
std::cout << "You entered: " << a << '\n';
return 0;
}
| 33.541667 | 78 | 0.579503 | KoaLaYT |
9429d01e1468a0ae36da7c95621233ccda44effb | 3,831 | cpp | C++ | src/InputManager.cpp | rage-of-the-elders/rage-of-the-elders | 8f07c37c174813beef1658277c3b1b31a8fe2020 | [
"MIT"
] | 7 | 2019-05-20T17:26:15.000Z | 2021-09-03T01:18:29.000Z | src/InputManager.cpp | rage-of-the-elders/rage-of-the-elders | 8f07c37c174813beef1658277c3b1b31a8fe2020 | [
"MIT"
] | 38 | 2019-05-20T17:18:23.000Z | 2019-07-12T01:53:47.000Z | src/InputManager.cpp | rage-of-the-elders/rage-of-the-elders | 8f07c37c174813beef1658277c3b1b31a8fe2020 | [
"MIT"
] | null | null | null | #define INCLUDE_SDL
#include "SDL_include.h"
#include "InputManager.h"
#include "Camera.h"
#include <cstring>
#include <iostream>
InputManager::InputManager() {
memset(this->mouseState, false, sizeof this->mouseState);
memset(this->mouseUpdate, 0, sizeof this->mouseUpdate);
this->updateCounter = 0;
this->quitRequested = false;
this->mouseX = 0;
this->mouseY = 0;
this->lastsPressKeys = "";
this->comboTimer = Timer();
}
InputManager::~InputManager() {
}
InputManager &InputManager::GetInstance() {
static InputManager inputManager;
return inputManager;
}
void InputManager::Update(float dt) {
SDL_Event event;
this->updateCounter++;
this->quitRequested = false;
this->comboTimer.Update(dt);
SDL_GetMouseState(&this->mouseX, &this->mouseY);
this->mouseX += Camera::position.x;
this->mouseY += Camera::position.y;
while (SDL_PollEvent(&event)) {
int keyId, buttonId;
if (not event.key.repeat) {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
buttonId = event.button.button;
this->mouseState[buttonId] = true;
this->mouseUpdate[buttonId] = this->updateCounter;
break;
case SDL_MOUSEBUTTONUP:
buttonId = event.button.button;
this->mouseState[buttonId] = false;
this->mouseUpdate[buttonId] = this->updateCounter;
break;
case SDL_KEYDOWN:
keyId = event.key.keysym.sym;
this->keyState[keyId] = true;
this->keyUpdate[keyId] = this->updateCounter;
MakeCombos(keyId);
break;
case SDL_KEYUP:
keyId = event.key.keysym.sym;
this->keyState[keyId] = false;
this->keyUpdate[keyId] = this->updateCounter;
break;
case SDL_QUIT:
this->quitRequested = true;
break;
default:
break;
}
}
}
}
void InputManager::SetLastsPressKeys(std::string lastsPressKeys) {
this->lastsPressKeys = lastsPressKeys;
}
void InputManager::MakeCombos(int buttonId) {
if(this->comboTimer.Get() > 0.4 ) {
this->lastsPressKeys = "";
this->comboTimer.Restart();
}
switch (buttonId)
{
case SDLK_a:
this->lastsPressKeys += "A";
break;
case SDLK_s:
this->lastsPressKeys += "S";
break;
case SDLK_d:
this->lastsPressKeys += "D";
break;
case SDLK_f:
this->lastsPressKeys += "F";
break;
case SDLK_g:
this->lastsPressKeys += "G";
break;
case SDLK_h:
this->lastsPressKeys += "H";
break;
case SDLK_j:
this->lastsPressKeys += "J";
break;
case SDLK_w:
this->lastsPressKeys += "W";
break;
default:
this->lastsPressKeys += "0";
break;
}
}
bool InputManager::KeyPress(int key) {
return (this->keyState[key] && (this->keyUpdate[key] == this->updateCounter));
}
bool InputManager::KeyRelease(int key) {
return (not this->keyState[key] && (this->keyUpdate[key] == this->updateCounter));
}
bool InputManager::IsKeyDown(int key) {
return this->keyState[key];
}
bool InputManager::MousePress(int button) {
return (this->mouseState[button] && (this->mouseUpdate[button] == this->updateCounter));
}
bool InputManager::MouseRelease(int button) {
return (not this->mouseState[button] && (this->mouseUpdate[button] == this->updateCounter));
}
bool InputManager::IsMouseDown(int button) {
return this->mouseState[button];
}
int InputManager::GetMouseX() {
return this->mouseX;
}
int InputManager::GetMouseY() {
return this->mouseY;
}
Vec2 InputManager::GetMousePosition() {
return Vec2(this->mouseX, this->mouseY);
}
bool InputManager::QuitRequested() {
return this->quitRequested;
}
std::string InputManager::GetLastsPressKeys() {
return this->lastsPressKeys;
}
| 23.648148 | 94 | 0.633255 | rage-of-the-elders |
942a04131e853de76706c5171ee407741a8f1167 | 2,216 | hpp | C++ | include/Lys/WorkingModule/WorkingTask.hpp | Tigole/Lys-Framework | c7a51261b78c69fbfd823c1d20617ef13ca83a39 | [
"MIT"
] | null | null | null | include/Lys/WorkingModule/WorkingTask.hpp | Tigole/Lys-Framework | c7a51261b78c69fbfd823c1d20617ef13ca83a39 | [
"MIT"
] | null | null | null | include/Lys/WorkingModule/WorkingTask.hpp | Tigole/Lys-Framework | c7a51261b78c69fbfd823c1d20617ef13ca83a39 | [
"MIT"
] | null | null | null | #ifndef _LYS_WORKING_TASK_HPP
#define _LYS_WORKING_TASK_HPP 1
#include <functional>
#include <queue>
#include <vector>
#include <mutex>
#include "Lys/Core/Core.hpp"
#include "WorkingThread.hpp"
namespace lys
{
class AWorkingTask
{
LYS_CLASS_NO_COPY(AWorkingTask)
friend WorkingThread;
public:
AWorkingTask(const char* name);
virtual ~AWorkingTask();
void mt_Call_Thread_Task(void);
const char* mt_Get_Name(void) const;
private:
virtual void mt_Call_Task(void) = 0;
void mt_Stop(void);
bool m_Working;
std::mutex m_Mutex;
const char* m_Name;
};
template <typename MsgType>
class WorkingTask : public AWorkingTask
{
public:
template<class C>
WorkingTask(const char* name, bool (C::*pmt_Callback)(MsgType&), C* obj)
: AWorkingTask(name),
m_Host_Job(std::bind(pmt_Callback, obj, std::placeholders::_1)),
m_Host_Mutex(),
m_Orders(),
m_Results()
{}
void mt_Push_Order(const MsgType& order)
{
m_Host_Mutex.lock();
m_Orders.push(order);
WorkingThread::smt_Get().mt_Add_Task(this);
m_Host_Mutex.unlock();
}
bool mt_Pop_Result(MsgType& result)
{
bool l_b_Ret = false;
m_Host_Mutex.lock();
if (m_Results.size() > 0)
{
result = m_Results.front();
m_Results.pop();
l_b_Ret = true;
}
m_Host_Mutex.unlock();
return l_b_Ret;
}
void mt_Call_Task(void) override
{
MsgType l_Data;
bool l_Work = false;
m_Host_Mutex.lock();
if (m_Orders.size() > 0)
{
l_Data = m_Orders.front();
m_Orders.pop();
l_Work = true;
}
m_Host_Mutex.unlock();
if (l_Work == true)
{
if (m_Host_Job(l_Data) == true)
{
m_Host_Mutex.lock();
m_Results.push(l_Data);
m_Host_Mutex.unlock();
}
}
}
private:
std::function<bool(MsgType&)> m_Host_Job;
std::mutex m_Host_Mutex;
std::queue<MsgType> m_Orders;
std::queue<MsgType> m_Results;
};
}
#endif // _LYS_WORKING_TASK_HPP
| 18.940171 | 76 | 0.581227 | Tigole |
9430a0925bf5b41f352e6cb040156c569600b822 | 1,733 | cc | C++ | app/gfx/insets_unittest.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | app/gfx/insets_unittest.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | app/gfx/insets_unittest.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 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 "app/gfx/insets.h"
#include <iostream>
#include "testing/gtest/include/gtest/gtest.h"
TEST(InsetsTest, InsetsDefault) {
gfx::Insets insets;
EXPECT_EQ(0, insets.top());
EXPECT_EQ(0, insets.left());
EXPECT_EQ(0, insets.bottom());
EXPECT_EQ(0, insets.right());
EXPECT_EQ(0, insets.width());
EXPECT_EQ(0, insets.height());
EXPECT_TRUE(insets.empty());
}
TEST(InsetsTest, Insets) {
gfx::Insets insets(1, 2, 3, 4);
EXPECT_EQ(1, insets.top());
EXPECT_EQ(2, insets.left());
EXPECT_EQ(3, insets.bottom());
EXPECT_EQ(4, insets.right());
EXPECT_EQ(6, insets.width()); // Left + right.
EXPECT_EQ(4, insets.height()); // Top + bottom.
EXPECT_FALSE(insets.empty());
}
TEST(InsetsTest, Set) {
gfx::Insets insets;
insets.Set(1, 2, 3, 4);
EXPECT_EQ(1, insets.top());
EXPECT_EQ(2, insets.left());
EXPECT_EQ(3, insets.bottom());
EXPECT_EQ(4, insets.right());
}
TEST(InsetsTest, Add) {
gfx::Insets insets;
insets.Set(1, 2, 3, 4);
insets += gfx::Insets(5, 6, 7, 8);
EXPECT_EQ(6, insets.top());
EXPECT_EQ(8, insets.left());
EXPECT_EQ(10, insets.bottom());
EXPECT_EQ(12, insets.right());
}
TEST(InsetsTest, Equality) {
gfx::Insets insets1;
insets1.Set(1, 2, 3, 4);
gfx::Insets insets2;
// Test operator== and operator!=.
EXPECT_FALSE(insets1 == insets2);
EXPECT_TRUE(insets1 != insets2);
insets2.Set(1, 2, 3, 4);
EXPECT_TRUE(insets1 == insets2);
EXPECT_FALSE(insets1 != insets2);
}
TEST(InsetsTest, ToString) {
gfx::Insets insets(1, 2, 3, 4);
EXPECT_EQ("1,2,3,4", insets.ToString());
}
| 25.115942 | 73 | 0.658973 | rwatson |
94322b1761f37df86914c6326a526f9da51fe1aa | 68 | cpp | C++ | examples/simple-sfml/main.cpp | snailbaron/wiggle | 10266aca77d8bbfc32965fc45c5601323a66573e | [
"MIT"
] | null | null | null | examples/simple-sfml/main.cpp | snailbaron/wiggle | 10266aca77d8bbfc32965fc45c5601323a66573e | [
"MIT"
] | null | null | null | examples/simple-sfml/main.cpp | snailbaron/wiggle | 10266aca77d8bbfc32965fc45c5601323a66573e | [
"MIT"
] | null | null | null | #include <wiggle.hpp>
#include <SFML/Graphics.hpp>
int main()
{
}
| 8.5 | 28 | 0.661765 | snailbaron |
9432509e1932de9c3d2de7287a5f29532a604de6 | 1,104 | cpp | C++ | cmps104a/asg4/symbol-table-code.cpp | isaiah-solo/ucsc-classes | a3e834ee26822827f7ea4977707ecf7e42e1b0c9 | [
"MIT"
] | 1 | 2018-05-11T19:14:47.000Z | 2018-05-11T19:14:47.000Z | cmps104a/asg4/symbol-table-code.cpp | isaiah-solo/ucsc-classes | a3e834ee26822827f7ea4977707ecf7e42e1b0c9 | [
"MIT"
] | null | null | null | cmps104a/asg4/symbol-table-code.cpp | isaiah-solo/ucsc-classes | a3e834ee26822827f7ea4977707ecf7e42e1b0c9 | [
"MIT"
] | 3 | 2019-04-19T03:38:47.000Z | 2019-06-02T20:59:21.000Z | // $Id: symbol-table-code.cpp,v 1.6 2015-05-13 14:40:56-07 - - $
#include <bitset>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
using attr_bitset = bitset<ATTR_bitset_size>;
using symbol_table = unordered_map<string*,symbol*>;
using symbol_entry = symbol_table::value_type;
struct symbol {
attr_bitset attributes;
symbol_table* fields;
size_t filenr, linenr, offset;
size_t blocknr;
vector<symbol*>* parameters;
};
int init_stack () {
symbol_table = new vector<symbol_table*>();
next_block = 1;
return 0;
}
int enter_block () {
++next_block;
symbol_stack.push_back(nullptr);
return 0;
}
int leave_block () {
auto return_value = symbol_stack.pop_back();
return 0;
}
int define_ident () {
symbol* new_symbol = new symbol();
new_symbol->fields = new unordered_map<string*, symbol*>();
symbol_stack.push_back(new_symbol);
return 0;
}
int search_ident () {
}
void traverse_ast (astree* child) {
for (auto itor = yyparse_astree->begin();
itor != yyparse_astree->end(); ++itor) {
traverse
}
}
| 20.072727 | 64 | 0.680254 | isaiah-solo |
94331746a3d8c8b2c373b7e9ba216331c5d36347 | 335 | cpp | C++ | baekjoon/1427.cpp | 3-24/Competitive-Programming | 8cb3b85bf89db2c173cb0b136de27f2983f335fc | [
"MIT"
] | 1 | 2019-07-15T00:27:37.000Z | 2019-07-15T00:27:37.000Z | baekjoon/1427.cpp | 3-24/Competitive-Programming | 8cb3b85bf89db2c173cb0b136de27f2983f335fc | [
"MIT"
] | null | null | null | baekjoon/1427.cpp | 3-24/Competitive-Programming | 8cb3b85bf89db2c173cb0b136de27f2983f335fc | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b){
return *(int *)b - *(int *)a;
}
int main(){
int arr[11];
int i = 0;
int n;
scanf("%d",&n);
while (n){
arr[i] = n % 10;
i++;
n/=10;
}
qsort(arr,i,sizeof(int),compare);
for (int j=0;j<i;j++){
printf("%d",arr[j]);
}
}
| 14.565217 | 42 | 0.495522 | 3-24 |
9435f506082f1fb33469b163d7d738784c661cc3 | 2,834 | cpp | C++ | typekits/rtt_ros2_rclcpp_typekit/src/ros2_duration_type.cpp | gborghesan/rtt_ros2_integration | 6c03adc69e1bac3c8ad07d19e1814054f30f6936 | [
"Apache-2.0"
] | 14 | 2020-06-12T14:48:40.000Z | 2022-03-22T08:57:41.000Z | typekits/rtt_ros2_rclcpp_typekit/src/ros2_duration_type.cpp | gborghesan/rtt_ros2_integration | 6c03adc69e1bac3c8ad07d19e1814054f30f6936 | [
"Apache-2.0"
] | 15 | 2020-06-12T15:57:09.000Z | 2021-09-08T18:26:19.000Z | typekits/rtt_ros2_rclcpp_typekit/src/ros2_duration_type.cpp | gborghesan/rtt_ros2_integration | 6c03adc69e1bac3c8ad07d19e1814054f30f6936 | [
"Apache-2.0"
] | 3 | 2020-12-02T09:11:23.000Z | 2021-11-29T11:06:27.000Z | // Copyright 2020 Intermodalics BVBA
//
// 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 "rtt_ros2_rclcpp_typekit/ros2_duration_type.hpp"
#include <cassert>
#include <string>
#include <vector>
#include "rtt/types/TemplateConstructor.hpp"
#include "rtt_ros2_rclcpp_typekit/time_conversions.hpp"
#include "rtt_ros2_rclcpp_typekit/time_io.hpp"
using namespace RTT; // NOLINT(build/namespaces)
using namespace RTT::types; // NOLINT(build/namespaces)
namespace rtt_ros2_rclcpp_typekit
{
WrappedDuration::WrappedDuration()
: rclcpp::Duration(0) {}
DurationTypeInfo::DurationTypeInfo()
: PrimitiveTypeInfo<WrappedDuration, true>("/rclcpp/Duration")
{}
bool DurationTypeInfo::installTypeInfoObject(TypeInfo * ti)
{
// aquire a shared reference to the this object
boost::shared_ptr<DurationTypeInfo> mthis =
boost::dynamic_pointer_cast<DurationTypeInfo>(
this->getSharedPtr());
assert(mthis);
// Allow base to install first
PrimitiveTypeInfo<WrappedDuration, true>::installTypeInfoObject(ti);
// ti->setStreamFactory(mthis);
// Conversions
const auto types = TypeInfoRepository::Instance();
{
const auto built_interfaces_msg_duration_ti =
types->getTypeInfo<builtin_interfaces::msg::Duration>();
assert(built_interfaces_msg_duration_ti != nullptr);
if (built_interfaces_msg_duration_ti != nullptr) {
built_interfaces_msg_duration_ti->addConstructor(newConstructor(&duration_to_msg, true));
}
ti->addConstructor(newConstructor(&msg_to_duration, true));
}
{
// Note: Define conversions for int64_t before double, because Orocos implicit converts from
// int64_t to double, but not from double to int64_t.
const auto int64_ti = types->getTypeInfo<int64_t>();
assert(int64_ti != nullptr);
if (int64_ti != nullptr) {
int64_ti->addConstructor(newConstructor(&duration_to_int64));
}
ti->addConstructor(newConstructor(&int64_to_duration, true));
}
{
const auto double_ti = types->getTypeInfo<double>();
assert(double_ti != nullptr);
if (double_ti != nullptr) {
double_ti->addConstructor(newConstructor(&duration_to_double));
}
ti->addConstructor(newConstructor(&double_to_duration, true));
}
// Don't delete us, we're memory-managed.
return false;
}
} // namespace rtt_ros2_rclcpp_typekit
| 33.341176 | 96 | 0.743825 | gborghesan |
943e1165f6af3582510740b7f76c632fbb768f7f | 2,707 | cpp | C++ | src/components/ImageListScroll.cpp | hhyyrylainen/DualViewPP | 1fb4a1db85a8509342e16d68c75d4ec7721ced9e | [
"MIT"
] | null | null | null | src/components/ImageListScroll.cpp | hhyyrylainen/DualViewPP | 1fb4a1db85a8509342e16d68c75d4ec7721ced9e | [
"MIT"
] | null | null | null | src/components/ImageListScroll.cpp | hhyyrylainen/DualViewPP | 1fb4a1db85a8509342e16d68c75d4ec7721ced9e | [
"MIT"
] | null | null | null | // ------------------------------------ //
#include "ImageListScroll.h"
using namespace DV;
// ------------------------------------ //
bool ImageListScroll::HasCount() const{
return false;
}
size_t ImageListScroll::GetCount() const{
return 0;
}
// ------------------------------------ //
bool ImageListScroll::SupportsRandomAccess() const{
return false;
}
std::shared_ptr<Image> ImageListScroll::GetImageAt(size_t index) const{
return nullptr;
}
size_t ImageListScroll::GetImageIndex(Image& image) const{
return 0;
}
// ------------------------------------ //
std::string ImageListScroll::GetDescriptionStr() const{
return "";
}
// ------------------------------------ //
// ImageListScrollVector
ImageListScrollVector::ImageListScrollVector(const std::vector<std::shared_ptr<Image>>
&images) :
Images(images)
{
}
// ------------------------------------ //
std::shared_ptr<Image> ImageListScrollVector::GetNextImage(std::shared_ptr<Image> current,
bool wrap /*= true*/)
{
if(!current)
return nullptr;
const auto index = GetImageIndex(*current);
if(index >= Images.size())
return nullptr;
if(index + 1 < Images.size()){
// Next is at index + 1
return Images[index + 1];
} else {
// current is the last image //
if(!wrap)
return nullptr;
return Images[0];
}
}
std::shared_ptr<Image> ImageListScrollVector::GetPreviousImage(std::shared_ptr<Image> current,
bool wrap /*= true*/)
{
if(!current)
return nullptr;
const auto index = GetImageIndex(*current);
if(index >= Images.size())
return nullptr;
if(index >= 1){
// Previous is at index - 1
return Images[index - 1];
} else {
// current is the first image //
if(!wrap)
return nullptr;
return Images[Images.size() - 1];
}
}
// ------------------------------------ //
bool ImageListScrollVector::HasCount() const{
return true;
}
size_t ImageListScrollVector::GetCount() const{
return Images.size();
}
bool ImageListScrollVector::SupportsRandomAccess() const{
return true;
}
std::shared_ptr<Image> ImageListScrollVector::GetImageAt(size_t index) const{
if(index >= Images.size())
return nullptr;
return Images[index];
}
size_t ImageListScrollVector::GetImageIndex(Image& image) const{
for(size_t i = 0; i < Images.size(); ++i){
if(Images[i].get() == &image)
return i;
}
return -1;
}
// ------------------------------------ //
std::string ImageListScrollVector::GetDescriptionStr() const{
return "list";
}
| 20.201493 | 94 | 0.550055 | hhyyrylainen |
9443fa9ac992ff66096fa61fbf6212eb44d24e31 | 10,878 | cxx | C++ | src/Clustering/StdClusterInfo.cxx | fermi-lat/CalRecon | 69e123b523770baa1fc9e8f3b78e211b1064b0c0 | [
"BSD-3-Clause"
] | null | null | null | src/Clustering/StdClusterInfo.cxx | fermi-lat/CalRecon | 69e123b523770baa1fc9e8f3b78e211b1064b0c0 | [
"BSD-3-Clause"
] | null | null | null | src/Clustering/StdClusterInfo.cxx | fermi-lat/CalRecon | 69e123b523770baa1fc9e8f3b78e211b1064b0c0 | [
"BSD-3-Clause"
] | null | null | null |
#include "StdClusterInfo.h"
/// This makes CalClusters out of associated CalXtalRecData pointers
Event::CalCluster* StdClusterInfo::fillClusterInfo(const XtalDataList* xTalVec)
{
int calnLayers = m_calReconSvc->getCalNLayers() ;
const Point p0(0.,0.,0.);
//Initialize variables
double ene = 0; // Total energy in this cluster
Vector pCluster(0.,0.,0.); // Cluster position
std::vector<double> eneLayer(calnLayers,0.); // Energy by layer
std::vector<Vector> pLayer(calnLayers); // Position by layer
std::vector<Vector> rmsLayer(calnLayers); // rms by layer
// Compute barycenter and various moments
// loop over all crystals in the current cluster
XtalDataList::const_iterator xTalIter;
for(xTalIter = xTalVec->begin(); xTalIter != xTalVec->end(); xTalIter++)
{
// get pointer to the reconstructed data for given crystal
Event::CalXtalRecData* recData = *xTalIter;
// get reconstructed values
double eneXtal = recData->getEnergy(); // crystal energy
Vector pXtal = recData->getPosition() - p0; // Vector of crystal position
int layer = (recData->getPackedId()).getLayer(); // layer number
// update energy of corresponding layer
eneLayer[layer] += eneXtal;
// update average position of corresponding layer
Vector ptmp = eneXtal*pXtal;
pLayer[layer] += ptmp;
// Vector containing squared coordinates, weighted by crystal energy
Vector ptmp_sqr(ptmp.x()*pXtal.x(), ptmp.y()*pXtal.y(), ptmp.z()*pXtal.z());
// update quadratic spread, which is proportional to eneXtal;
// this means, that position error in one crystal
// is assumed to be 1/sqrt(eneXtal)
rmsLayer[layer] += ptmp_sqr;
// update energy sum
ene += eneXtal;
// update cluster position
pCluster += ptmp;
}
// construct the cluster
Event::CalCluster* cl = new Event::CalCluster(0);
cl->setProducerName("StdClusterInfo") ;
cl->clear();
// Now take the means
// if energy sum is not zero - normalize cluster position
if(ene > 0.) {
pCluster /= ene;
cl->setStatusBit(Event::CalCluster::CENTROID) ;
}
// if energy is zero - set cluster position to non-physical value
else pCluster = Vector(-1000., -1000., -1000.);
// loop over calorimeter layers
int i ;
for( i = 0; i < calnLayers; i++)
{
// if energy in the layer is not zero - finalize calculations
if(eneLayer[i]>0)
{
// normalize position in the layer
pLayer[i] *= (1./eneLayer[i]);
// normalize quadratic spread in the laye
rmsLayer[i] *= (1./eneLayer[i]);
// Vector containing the squared average position in each component
Vector sqrLayer(pLayer[i].x()*pLayer[i].x(),
pLayer[i].y()*pLayer[i].y(),
pLayer[i].z()*pLayer[i].z());
// the precision of transverse coordinate measurement
// if there is no fluctuations: 1/sqrt(12) of crystal width
Vector d;
double csIWidth = m_calReconSvc->getCalCsIWidth() ;
if(i%2 == 1) d = Vector(csIWidth*csIWidth/12.,0.,0.);
else d = Vector(0.,csIWidth*csIWidth/12.,0.);
// subtracting the squared average position and adding
// the square of crystal width, divided by 12
rmsLayer[i] += d-sqrLayer;
}
// if energy in the layer is zero - reset position and spread Vectors
else
{
pLayer[i]=p0;
rmsLayer[i]=p0;
}
}
// Now sum the different rms to have one transverse and one longitudinal rms
double rms_trans = 0;
double rms_long = 0;
std::vector<Vector> posrel(calnLayers);
for(int ilayer = 0; ilayer < calnLayers ; ilayer++)
{
posrel[ilayer]=pLayer[ilayer]-pCluster;
// Sum alternatively the rms
if(ilayer%2)
{
rms_trans += rmsLayer[ilayer].y();
rms_long += rmsLayer[ilayer].x();
}
else
{
rms_trans += rmsLayer[ilayer].x();
rms_long += rmsLayer[ilayer].y();
}
}
// Compute direction using the positions and rms per layer
Vector caldir = fitDirection(pLayer, rmsLayer);
Event::CalXtalsParams xtalsParams;
Event::CalMomParams momParams(ene, 10*ene, pCluster.x(), pCluster.y(), pCluster.z(),
1.,0.,0.,1.,0.,1.,
caldir.x(), caldir.y(), caldir.z(), 1.,0.,0.,1.,0.,1.);
// Initial fit parameters
Event::CalFitParams fitParams(4, 0., pCluster.x(), pCluster.y(), pCluster.z(),
1.,0.,0.,1.,0.,1.,
caldir.x(), caldir.y(), caldir.z(), 1.,0.,0.,1.,0.,1.);
// initialize empty CalMSTreeParams container - CalMSTreePar
Event::CalMSTreeParams treeParams(0.,0.,0,0.,0.,0.,0.,0.,0.);
// Initialize an empty CalClassParamsContainer.
Event::CalClassParams classParams;
// Fill CalCluster data
cl->initialize(xtalsParams, treeParams, fitParams, momParams, classParams);
for( i = 0; i < calnLayers; i++)
{
Point layerPos(pLayer[i].x(), pLayer[i].y(), pLayer[i].z());
// Set the data for the vector
Event::CalClusterLayerData layerData(eneLayer[i], layerPos, rmsLayer[i]);
cl->push_back(layerData);
}
// Fill CalCluster data
//Event::CalCluster* cl = new Event::CalCluster(ene, pCluster + p0);
//cl->initialize(ene, eneLayer, pLayer, rmsLayer, rms_long, rms_trans, caldir, 0.);
return cl;
}
Vector StdClusterInfo::fitDirection(std::vector<Vector> pos, std::vector<Vector> sigma2)
//
// Purpose and Method:
// find the particle direction from average positions in each
// layer and their quadratic errors. The fit is made independently
// in XZ and YZ planes for odd and even layers, respectively.
// Then the 3-vector of particle direction is calculated from these
// 2 projections.
// Only position information based on the transversal crystal position
// is used. The position along the crystal, calculated from signal
// asymmetry is not used.
//
// Inputs:
// pos - average position for each calorimeter layer
// sigma2 - quadratic error of position measurement for each layer
// in each direction
// nlayers - number of calorimeter layers
//
// Returned value: 3-Vector of reconstructred particle direction
//
{
// sigma2.z() is useless here no matter its value.
double cov_xz = 0; // covariance x,z
double cov_yz = 0; // covariance y,z
double mx=0; // mean x
double my=0; // mean y
double mz1=0; // mean z for x pos
double mz2=0; // mean z for y pos
double norm1=0; // sum of weights for odd layers
double norm2=0; // sum of weights for even layers
double var_z1=0; // variance of z for odd layers
double var_z2=0; // variance of z for even layers
// number of layers with non-zero energy deposition
// in X and Y direction, respectively
int nlx=0,nly=0;
// "non-physical vector of direction, which is returned
// if fit is imposible due to insufficient number of hitted layers
Vector nodir(-1000.,-1000.,-1000.);
// loop over calorimeter layers
for(int il = 0; il < m_calReconSvc->getCalNLayers(); il++)
{
// For the moment forget about longitudinal position
// odd layers used for XZ fit
if(il % 2 == 1)
{
// only if the spread in X direction is not zero,
// which is the case if there is non-zero energy
// deposition in this layer
if (sigma2[il].x()>0.)
{
nlx++; // counting layers used for the fit in XZ plane
// calculate weighting coefficient for this layer
double err = 1/sigma2[il].x();
// calculate sums for least square linear fit in XZ plane
cov_xz += pos[il].x()*pos[il].z()*err;
var_z1 += pos[il].z()*pos[il].z()*err;
mx += pos[il].x()*err;
mz1 += pos[il].z()*err;
norm1 += err;
}
}
// even layers used for YZ fit
else
{
// only if the spread in Y direction is not zero,
// which is the case if there is non-zero energy
// deposition in this layer
if(sigma2[il].y()>0.)
{
nly++; // counting layers used for the fit in YZ plane
// calculate weighting coefficient for this layer
double err = 1/sigma2[il].y();
// calculate sums for least square linear fit in YZ plane
cov_yz += pos[il].y()*pos[il].z()*err;
var_z2 += pos[il].z()*pos[il].z()*err;
my += pos[il].y()*err;
mz2 += pos[il].z()*err;
norm2 += err;
}
}
}
// linear fit requires at least 2 hitted layers in both XZ and YZ planes
// otherwise non-physical direction is returned
// which means that direction hasn't been found
if(nlx <2 || nly < 2 )return nodir;
mx /= norm1;
mz1 /= norm1;
cov_xz /= norm1;
cov_xz -= mx*mz1;
var_z1 /= norm1;
var_z1 -= mz1*mz1;
// protection against dividing by 0 in the next statment
if(var_z1 == 0) return nodir;
// Now we have cov(x,z) and var(z) we can
// deduce slope in XZ plane
double tgthx = cov_xz/var_z1;
my /= norm2;
mz2 /= norm2;
cov_yz /= norm2;
cov_yz -= my*mz2;
var_z2 /= norm2;
var_z2 -= mz2*mz2;
// protection against dividing by 0 in the next statment
if(var_z2 == 0) return nodir;
// Now we have cov(y,z) and var(z) we can
// deduce slope in YZ plane
double tgthy = cov_yz/var_z2;
// combining slope in XZ and YZ planes to get normalized 3-vector
// of particle direction
double tgtheta_sqr = tgthx*tgthx+tgthy*tgthy;
double costheta = 1/sqrt(1+tgtheta_sqr);
Vector dir(costheta*tgthx,costheta*tgthy,costheta);
return dir;
}
| 35.782895 | 95 | 0.557088 | fermi-lat |
94467439712cf50e0e29c1cc4e4eb4daea955f94 | 1,028 | cc | C++ | components/services/storage/public/cpp/big_io_buffer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/services/storage/public/cpp/big_io_buffer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/services/storage/public/cpp/big_io_buffer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 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 "components/services/storage/public/cpp/big_io_buffer.h"
#include "mojo/public/cpp/base/big_buffer.h"
#include "net/base/io_buffer.h"
namespace storage {
BigIOBuffer::BigIOBuffer(mojo_base::BigBuffer buffer)
: net::IOBufferWithSize(nullptr, buffer.size()),
buffer_(std::move(buffer)) {
data_ = reinterpret_cast<char*>(buffer_.data());
}
BigIOBuffer::BigIOBuffer(size_t size)
: net::IOBufferWithSize(nullptr, size),
buffer_(mojo_base::BigBuffer(size)) {
data_ = reinterpret_cast<char*>(buffer_.data());
DCHECK(data_);
}
BigIOBuffer::~BigIOBuffer() {
// Must clear `data_` so base class doesn't attempt to delete[] a pointer
// it doesn't own.
data_ = nullptr;
size_ = 0UL;
}
mojo_base::BigBuffer BigIOBuffer::TakeBuffer() {
data_ = nullptr;
size_ = 0UL;
return std::move(buffer_);
}
} // namespace storage
| 26.358974 | 75 | 0.713035 | zealoussnow |
9448dfeac03bfb125821e227d926e331a3a84db3 | 11,730 | cc | C++ | src/XrdHttpLcmaps.cc | matyasselmeci/xrootd-lcmaps | c796009b20794e3d179776b03e8095a0c3e32631 | [
"Apache-2.0"
] | 3 | 2018-11-22T12:16:31.000Z | 2020-02-23T15:15:47.000Z | src/XrdHttpLcmaps.cc | matyasselmeci/xrootd-lcmaps | c796009b20794e3d179776b03e8095a0c3e32631 | [
"Apache-2.0"
] | 20 | 2017-07-25T03:15:21.000Z | 2021-05-31T14:38:27.000Z | src/XrdHttpLcmaps.cc | matyasselmeci/xrootd-lcmaps | c796009b20794e3d179776b03e8095a0c3e32631 | [
"Apache-2.0"
] | 10 | 2017-07-21T16:56:43.000Z | 2021-12-26T20:10:38.000Z |
#include <iostream>
#include <map>
#include <mutex>
#include <time.h>
#include <openssl/ssl.h>
#include <XrdHttp/XrdHttpSecXtractor.hh>
#include <XrdVersion.hh>
#include <XrdSec/XrdSecEntity.hh>
#include "GlobusSupport.hh"
extern "C" {
#include "lcmaps.h"
}
#include "XrdLcmapsConfig.hh"
#include "XrdLcmapsKey.hh"
#define policy_count 1
static const char default_db [] = "/etc/lcmaps.db";
static const char default_policy_name [] = "xrootd_policy";
static const char plugin_name [] = "XrdSecgsiAuthz";
// We always pass the certificate since it is verified by Globus later on.
static int proxy_app_verify_callback(X509_STORE_CTX *ctx, void *empty) {
return 1;
}
XrdVERSIONINFO(XrdHttpGetSecXtractor,"lcmaps");
// Someday we'll actually hook into the Xrootd logging system...
#define PRINT(y) std::cerr << y << "\n";
inline uint64_t monotonic_time() {
struct timespec tp;
#ifdef CLOCK_MONOTONIC_COARSE
clock_gettime(CLOCK_MONOTONIC_COARSE, &tp);
#else
clock_gettime(CLOCK_MONOTONIC, &tp);
#endif
return tp.tv_sec + (tp.tv_nsec >= 500000000);
}
/**
* Given an entry in the cache (`in`) that represents the same identity
* as the current connection (`out`), copy forward the portions of
* XrdSecEntity that are related to the user.
*
* This purposely doesn't overwrite host or creds.
*/
void
UpdateEntity(XrdSecEntity &out, XrdSecEntity const &in)
{
if (in.name) { free(out.name); out.name = strdup(in.name); }
if (in.vorg) { free(out.vorg); out.vorg = strdup(in.vorg); }
if (in.role) { free(out.role); out.role = strdup(in.role); }
if (in.grps) { free(out.grps); out.grps = strdup(in.grps); }
if (in.endorsements)
{
free(out.endorsements);
out.endorsements = strdup(in.endorsements);
}
if (in.moninfo) { free(out.moninfo); out.moninfo = strdup(in.moninfo); }
}
void
FreeEntity(XrdSecEntity *&ent)
{
free(ent->name);
free(ent->host);
free(ent->vorg);
free(ent->role);
free(ent->grps);
free(ent->creds);
free(ent->endorsements);
free(ent->moninfo);
delete ent;
}
class XrdMappingCache
{
public:
~XrdMappingCache()
{
for (KeyToEnt::iterator it = m_map.begin();
it != m_map.end();
it++)
{
FreeEntity(it->second.first);
}
}
/**
* Get the data associated with a particular key and store
* it into the entity object.
* If this returns false, then the key was not found.
*/
bool get(std::string key, struct XrdSecEntity &entity)
{
time_t now = monotonic_time();
std::lock_guard<std::mutex> guard(m_mutex);
if (now > m_last_clean + 100) {clean_tables();}
KeyToEnt::const_iterator iter = m_map.find(key);
if (iter == m_map.end()) {
return false;
}
UpdateEntity(entity, *iter->second.first);
return true;
}
/**
* Put the entity data into the map for a given key.
* Makes a copy of the caller's data if the key was not already present
* This function is thread safe.
*
* If result is false, then the key was already in the map.
*/
void try_put(std::string key, struct XrdSecEntity const &entity)
{
time_t now = monotonic_time();
std::lock_guard<std::mutex> guard(m_mutex);
XrdSecEntity *new_ent = new XrdSecEntity();
std::pair<KeyToEnt::iterator, bool> ret = m_map.insert(std::make_pair(key, std::make_pair(new_ent, now)));
if (ret.second)
{
ValueType &value = ret.first->second;
XrdSecEntity *ent = value.first;
UpdateEntity(*ent, entity);
}
else
{
delete new_ent;
}
}
static XrdMappingCache &GetInstance()
{
return m_cache;
}
private:
// No copying...
XrdMappingCache& operator=(XrdMappingCache const&);
XrdMappingCache(XrdMappingCache const&);
XrdMappingCache()
: m_last_clean(monotonic_time())
{
}
/**
* MUST CALL LOCKED
*/
void clean_tables()
{
m_last_clean = monotonic_time();
time_t expiry = m_last_clean + 100;
KeyToEnt::iterator it = m_map.begin();
while (it != m_map.end()) {
if (it->second.second < expiry) {
FreeEntity(it->second.first);
m_map.erase(it++);
} else {
++it;
}
}
}
typedef std::pair<XrdSecEntity*, time_t> ValueType;
typedef std::map<std::string, ValueType> KeyToEnt;
std::mutex m_mutex;
time_t m_last_clean;
KeyToEnt m_map;
static XrdMappingCache m_cache;
};
XrdMappingCache XrdMappingCache::m_cache;
class XrdHttpLcmaps : public XrdHttpSecXtractor
{
public:
virtual ~XrdHttpLcmaps() {}
virtual int GetSecData(XrdLink *, XrdSecEntity &entity, SSL *ssl)
{
static const char err_pfx[] = "ERROR in AuthzFun: ";
static const char inf_pfx[] = "INFO in AuthzFun: ";
//PRINT(inf_pfx << "Running security information extractor");
// Make sure to always clear out the entity first.
if (entity.name)
{
free(entity.name);
entity.name = NULL;
}
// Per OpenSSL docs, the ref count of peer_chain is not incremented.
// Hence, we do not free this later.
STACK_OF(X509) * peer_chain = SSL_get_peer_cert_chain(ssl);
// The refcount here is incremented.
X509 * peer_certificate = SSL_get_peer_certificate(ssl);
// No remote client? Add nothing to the entity, but do not
// fail.
if (!peer_certificate)
{
return 0;
}
// This one is a more difficult call. We should have disabled session reuse.
if (!peer_chain)
{
PRINT(inf_pfx << "No available peer certificate chain.");
X509_free(peer_certificate);
if (SSL_session_reused(ssl))
{
PRINT(inf_pfx << "SSL session was unexpectedly reused.");
return -1;
}
return 0;
}
STACK_OF(X509) * full_stack = sk_X509_new_null();
sk_X509_push(full_stack, peer_certificate);
for (int idx = 0; idx < sk_X509_num(peer_chain); idx++) {
sk_X509_push(full_stack, sk_X509_value(peer_chain, idx));
}
std::string key = GetKey(peer_certificate, peer_chain, entity);
if (!key.size()) { // Empty key indicates failure of verification.
sk_X509_free(full_stack);
X509_free(peer_certificate);
free(entity.moninfo);
free(entity.name);
free(entity.grps); entity.grps = NULL;
free(entity.endorsements); entity.endorsements = NULL;
free(entity.vorg); entity.vorg = NULL;
free(entity.role); entity.role = NULL;
entity.moninfo = strdup("Failed DN verification");
entity.name = NULL;
return -1;
}
XrdMappingCache &mcache = XrdMappingCache::GetInstance();
PRINT(inf_pfx << "Lookup with key " << key);
if (mcache.get(key, entity)) {
PRINT(inf_pfx << "Using cached entity with username " << entity.name);
sk_X509_free(full_stack);
X509_free(peer_certificate);
return 0;
}
if (!g_no_authz) {
// Grab the global mutex - lcmaps is not thread-safe.
std::lock_guard<std::mutex> guard(g_lcmaps_mutex);
char *poolindex = NULL;
uid_t uid = -1;
gid_t *pgid_list = NULL, *sgid_list = NULL;
int npgid = 0, nsgid = 0;
lcmaps_request_t request = NULL; // Typically, the RSL
// To manage const cast issues
const char * policy_name_env = getenv("LCMAPS_POLICY_NAME");
char * policy_name_copy = strdup(policy_name_env ? policy_name_env : default_policy_name);
int rc = lcmaps_run_with_stack_of_x509_and_return_account(
full_stack,
-1, // mapcounter
request,
policy_count,
&policy_name_copy,
&uid,
&pgid_list,
&npgid,
&sgid_list,
&nsgid,
&poolindex);
if (policy_name_copy) {
free(policy_name_copy);
}
sk_X509_free(full_stack);
X509_free(peer_certificate);
if (pgid_list) {free(pgid_list);}
if (sgid_list) {free(sgid_list);}
if (poolindex) {free(poolindex);}
// If there's a client cert but LCMAPS fails, we proceed with
// an anonymous / unmapped user as they may have additional
// per-file authorization.
//
// Previously, we denied the mapping as we didn't trust the
// verification routines outside those from LCMAPS. Currently,
// we enforce validation from both Globus and VOMS.
if (rc) {
PRINT(err_pfx << "LCMAPS failed or denied mapping");
return 0;
}
PRINT(inf_pfx << "Got uid " << uid);
struct passwd * pw = getpwuid(uid);
if (pw == NULL) {
return -1;
}
free(entity.moninfo);
entity.moninfo = strdup(key.c_str());
free(entity.name);
entity.name = strdup(pw->pw_name);
mcache.try_put(key, entity);
} else {
char chash[30] = {0};
std::string key_dn = key.substr(0, key.find(':'));
for (int idx = 0; idx < sk_X509_num(full_stack); idx++)
{
X509 *current_cert = sk_X509_value(full_stack, idx);
char *dn = X509_NAME_oneline(X509_get_subject_name(current_cert), NULL, 0);
if (!strcmp(key_dn.c_str(), dn))
{
snprintf(chash, sizeof(chash),
"%08lx.0",
X509_NAME_hash(X509_get_subject_name(current_cert)));
}
}
if (chash[0])
{
entity.name = strdup(chash);
}
sk_X509_free(full_stack);
X509_free(peer_certificate);
free(entity.moninfo);
entity.moninfo = strdup(key.c_str());
mcache.try_put(key, entity);
}
return 0;
}
virtual int Init(SSL_CTX *sslctx, int)
{
// NOTE(bbockelm): OpenSSL docs note that peer_chain is not available
// in reused sessions. We should build a session cache, but we just
// disable sessions for now.
SSL_CTX_set_session_cache_mode(sslctx, SSL_SESS_CACHE_OFF);
SSL_CTX_set_options(sslctx, SSL_OP_NO_TICKET);
// Always accept the certificate at the OpenSSL level. We'll do a standalone
// verification later with Globus.
SSL_CTX_set_cert_verify_callback(sslctx, proxy_app_verify_callback, NULL);
return 0;
}
XrdHttpLcmaps(XrdSysError *)
{
}
int Config(const char *cfg)
{
return XrdSecgsiAuthzConfig(cfg);
}
private:
XrdSysError *eDest;
static std::mutex m_mutex;
};
std::mutex XrdHttpLcmaps::m_mutex;
extern "C" XrdHttpSecXtractor *XrdHttpGetSecXtractor(XrdHttpSecXtractorArgs)
{
if (!globus_activate()) {return NULL;}
XrdHttpLcmaps *extractor = new XrdHttpLcmaps(eDest);
if (extractor->Config(parms)) {
delete extractor;
return NULL;
}
return extractor;
}
| 28.962963 | 114 | 0.576812 | matyasselmeci |
94495b4c1bb77f9089e667bb63463183a4aee49a | 786 | hpp | C++ | etl/_type_traits/conjunction.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | 4 | 2021-11-28T08:48:11.000Z | 2021-12-14T09:53:51.000Z | etl/_type_traits/conjunction.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | null | null | null | etl/_type_traits/conjunction.hpp | tobanteEmbedded/tetl | fc3272170843bcab47971191bcd269a86c5b5101 | [
"BSL-1.0"
] | null | null | null | /// \copyright Tobias Hienzsch 2019-2021
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
#ifndef TETL_TYPE_TRAITS_CONJUNCTION_HPP
#define TETL_TYPE_TRAITS_CONJUNCTION_HPP
#include "etl/_type_traits/bool_constant.hpp"
#include "etl/_type_traits/conditional.hpp"
namespace etl {
/// \group conjunction
template <typename... B>
inline constexpr bool conjunction_v = (B::value && ...);
/// \brief Forms the logical conjunction of the type traits B..., effectively
/// performing a logical AND on the sequence of traits.
/// \group conjunction
template <typename... B>
struct conjunction : bool_constant<conjunction_v<B...>> {
};
} // namespace etl
#endif // TETL_TYPE_TRAITS_CONJUNCTION_HPP | 30.230769 | 77 | 0.760814 | tobanteEmbedded |
944b4a65cb5a1f942b7044f7f5b83c5a6f845a69 | 10,080 | cpp | C++ | asc/src/input_structure.cpp | inquisitor101/ASC2D | 73ea575496340ad2486014525c6aec9c42c5d453 | [
"MIT"
] | null | null | null | asc/src/input_structure.cpp | inquisitor101/ASC2D | 73ea575496340ad2486014525c6aec9c42c5d453 | [
"MIT"
] | null | null | null | asc/src/input_structure.cpp | inquisitor101/ASC2D | 73ea575496340ad2486014525c6aec9c42c5d453 | [
"MIT"
] | null | null | null | #include "input_structure.hpp"
CInput::CInput
(
CConfig *config_container,
CGeometry *geometry_container
)
/*
* Constructor, used to initialize CInput class.
*/
{
// Extract number of zones.
nZone = config_container->GetnZone();
}
CInput::~CInput
(
void
)
/*
* Deconstructor for CInput class.
*/
{
}
void CInput::ReadSolutionRestartFile
(
CConfig *config_container,
CGeometry *geometry_container,
CElement **element_container,
CSolver **solver_container,
as3double &SimTime
)
/*
* Function that reads the solution from a restart file.
*/
{
// Report output.
std::cout << "\n reading data from restart file... ";
// Open restart file.
std::ifstream Restart_File( config_container->GetRestartFilename() );
// Check if file exists.
if(!Restart_File.is_open())
Terminate("CInput::ReadSolutionRestartFile", __FILE__, __LINE__,
"Restart file could not be opened!");
// Create temporary input data.
as3double input_XMin, input_XMax, input_YMin, input_YMax;
unsigned short input_nZone;
// Read header information.
AddScalarOption(Restart_File, "SimTime", SimTime);
AddScalarOption(Restart_File, "nZone", input_nZone);
AddScalarOption(Restart_File, "XMin", input_XMin);
AddScalarOption(Restart_File, "XMax", input_XMax);
AddScalarOption(Restart_File, "YMin", input_YMin);
AddScalarOption(Restart_File, "YMax", input_YMax);
// Extract main domain bound.
auto& DomainBound = config_container->GetDomainBound();
// Consistency check.
assert( input_nZone == nZone );
assert( input_XMin == DomainBound[0] );
assert( input_XMax == DomainBound[1] );
assert( input_YMin == DomainBound[2] );
assert( input_YMax == DomainBound[3] );
// Read data in every zone.
for(unsigned short iZone=0; iZone<nZone; iZone++){
// Create temporary input data.
unsigned long input_nElem, input_nxElem, input_nyElem, input_iElem;
unsigned short input_iZone, input_TypeSolver, input_TypeZone,
input_TypeDOFs, input_nPolySol, input_nDOFsSol1D,
input_nDOFsInt1D, input_TypeIC, input_TypeBufferLayer;
// Temporary storage of the solution being read in.
as3data1d<as3double> storage(nVar, nullptr);
// Extract data container in this zone.
auto& data_container = solver_container[iZone]->GetDataContainer();
// Boolean to indicate whether or not an interpolation is needed. Default, false.
bool Interpolate = false;
// Read general information.
AddScalarOption(Restart_File, "iZone", input_iZone);
AddScalarOption(Restart_File, "TypeIC", input_TypeIC);
AddScalarOption(Restart_File, "TypeSolver", input_TypeSolver);
AddScalarOption(Restart_File, "TypeBufferLayer", input_TypeBufferLayer);
AddScalarOption(Restart_File, "TypeZone", input_TypeZone);
AddScalarOption(Restart_File, "TypeDOFs", input_TypeDOFs);
AddScalarOption(Restart_File, "nPolySol", input_nPolySol);
AddScalarOption(Restart_File, "nDOFsSol1D", input_nDOFsSol1D);
AddScalarOption(Restart_File, "nDOFsInt1D", input_nDOFsInt1D);
AddScalarOption(Restart_File, "nElem", input_nElem);
AddScalarOption(Restart_File, "nxElem", input_nxElem);
AddScalarOption(Restart_File, "nyElem", input_nyElem);
// Extract current data from config file.
unsigned short TypeIC = config_container->GetTypeIC(iZone);
unsigned short TypeSolver = config_container->GetTypeSolver(iZone);
unsigned short TypeBufferLayer = config_container->GetTypeBufferLayer(iZone);
unsigned short TypeZone = config_container->GetTypeZone(iZone);
unsigned short TypeDOFs = config_container->GetTypeDOFs(iZone);
unsigned long nxElem = config_container->GetnxElemZone(iZone);
unsigned long nyElem = config_container->GetnyElemZone(iZone);
unsigned long nElem = solver_container[iZone]->GetnElem();
unsigned short nPolySol = element_container[iZone]->GetnPolySol();
unsigned short nDOFsSol1D = element_container[iZone]->GetnDOFsSol1D();
// Consistency check.
assert( iZone == input_iZone );
assert( TypeIC == input_TypeIC );
assert( TypeSolver == input_TypeSolver );
assert( TypeBufferLayer == input_TypeBufferLayer );
assert( TypeZone == input_TypeZone );
assert( nElem == input_nElem );
assert( nxElem == input_nxElem );
assert( nyElem == input_nyElem );
// Check if there need be no interpolation.
if( (nPolySol != input_nPolySol) || (TypeDOFs != input_TypeDOFs) ){
// Interpolation is required.
Interpolate = true;
// Extract basis of current data.
auto& rDOFsSol1D = element_container[iZone]->GetrDOFsSol1D();
// Reserve memory for the basis used in the restart file.
as3vector1d<as3double> rDOFsSolInput1D(input_nDOFsSol1D);
// Create basis for the solution from restart file.
element_container[iZone]->LocationDOFs1D(input_TypeDOFs, rDOFsSolInput1D);
// Reserve (transposed) interpolation polynomial between the restart file and current data.
lagrange1DTranspose.resize(input_nDOFsSol1D*nDOFsSol1D);
// Compute lagrange polynomial that interpolates from the nDOFsSol1D of the
// restart solution to this current zone.
element_container[iZone]->LagrangeBasisFunctions(rDOFsSolInput1D, rDOFsSol1D,
nullptr, nullptr,
lagrange1DTranspose.data(),
nullptr, nullptr, nullptr);
}
// Deduce the number of solution DOFs in 2D.
const unsigned short input_nDOFsSol2D = input_nDOFsSol1D*input_nDOFsSol1D;
// Reserve memory for the intermediary solution storage data. Note, this does not
// matter whether this is an interpolation procedure or not, since this is the input data.
for(unsigned short iVar=0; iVar<nVar; iVar++)
storage[iVar] = new as3double[input_nDOFsSol2D]();
// Loop over all elements and read the data.
for(unsigned long iElem=0; iElem<nElem; iElem++){
// Extract current data.
auto& data = data_container[iElem]->GetDataDOFsSol();
// Find the starting point for the data.
AddScalarOption(Restart_File, "DataDOFsSol", input_iElem);
// Consistency check.
assert( iElem == input_iElem );
// Temporary storage.
std::string line;
// Update line read.
getline(Restart_File, line);
std::stringstream ss(line);
// Read and copy the data in this element.
for(unsigned short iVar=0; iVar<nVar; iVar++){
for(unsigned short iNode=0; iNode<input_nDOFsSol2D; iNode++){
// Read new value and check the buffer is good.
std::string tmp; getline(ss, tmp, ','); if( !ss.good() ) break;
// Convert the string value read into a double.
std::stringstream convertor(tmp); convertor >> storage[iVar][iNode];
}
}
// Check whether an interpolation is needed or not. If not, just copy the data.
if( Interpolate )
// Interpolate solution.
TensorProductSolAndGradVolume(nDOFsSol1D, nVar, input_nDOFsSol1D,
lagrange1DTranspose.data(),
nullptr, storage.data(),
data.data(),
nullptr, nullptr);
else
// Copy solution.
for(unsigned short i=0; i<nVar; i++)
for(unsigned short l=0; l<input_nDOFsSol2D; l++)
data[i][l] = storage[i][l];
}
// If this is a PML zone, read the auxiliary data too.
if( TypeBufferLayer == PML_LAYER ){
// Loop over all elements and read the data.
for(unsigned long iElem=0; iElem<nElem; iElem++){
// Extract current data.
auto** data = &data_container[iElem]->GetDataDOFsSol()[nVar];
// Find the starting point for the data.
AddScalarOption(Restart_File, "DataDOFsSolAux", input_iElem);
// Consistency check.
assert( iElem == input_iElem );
// Temporary storage.
std::string line;
// Update line read.
getline(Restart_File, line);
std::stringstream ss(line);
// Read and copy the data in this element.
for(unsigned short iVar=0; iVar<nVar; iVar++){
for(unsigned short iNode=0; iNode<input_nDOFsSol2D; iNode++){
// Read new value and check the buffer is good.
std::string tmp; getline(ss, tmp, ','); if( !ss.good() ) break;
// Convert the string value read into a double.
std::stringstream convertor(tmp); convertor >> storage[iVar][iNode];
}
}
// Check whether an interpolation is needed or not. If not, just copy the data.
if( Interpolate )
// Interpolate solution.
TensorProductSolAndGradVolume(nDOFsSol1D, nVar, input_nDOFsSol1D,
lagrange1DTranspose.data(),
nullptr, storage.data(),
data,
nullptr, nullptr);
else
// Copy solution.
for(unsigned short i=0; i<nVar; i++)
for(unsigned short l=0; l<input_nDOFsSol2D; l++)
data[i][l] = storage[i][l];
}
}
// Peek to next character (used for determining end of file assertion).
Restart_File.peek();
// delete the temporary storage used.
for(unsigned short i=0; i<storage.size(); i++)
if( storage[i] ) delete [] storage[i];
}
// Make sure end of file is reached.
assert( Restart_File.eof() == true );
// Close file.
Restart_File.close();
// Report progress.
std::cout << "Done." << std::endl;
}
| 35.121951 | 97 | 0.632242 | inquisitor101 |
944fdb467148c7977f4755a671ec53a9a2796e7d | 5,347 | hpp | C++ | newweb/utility/ipc/generic_ipc_channel.hpp | cauthu/shadow-browser-plugin | e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298 | [
"BSD-3-Clause"
] | null | null | null | newweb/utility/ipc/generic_ipc_channel.hpp | cauthu/shadow-browser-plugin | e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298 | [
"BSD-3-Clause"
] | null | null | null | newweb/utility/ipc/generic_ipc_channel.hpp | cauthu/shadow-browser-plugin | e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298 | [
"BSD-3-Clause"
] | null | null | null | #ifndef generic_ipc_channel_hpp
#define generic_ipc_channel_hpp
// #include <event2/event.h>
// #include <event2/bufferevent.h>
#include <memory>
#include <map>
#include <set>
#include <boost/function.hpp>
#include "../object.hpp"
#include "../timer.hpp"
#include "../stream_channel.hpp"
#include "../generic_message_channel.hpp"
namespace myipc
{
/* msg ids are used to implement msgs that require responses. we refer
* to these msgs as "calls" (as in function calls). so these are like
* RPCs
*
* non-call msgs have id = 0. if a client makes a call, it must use
* only odd msg ids; server only even msg ids.
*
* the call reply msgs will specify the same id, so that the initiator
* of the call can know it's a reply
*
*
* NOTE!! currently only clients can make calls
*
*/
class GenericIpcChannel : public Object
, public myio::StreamChannelConnectObserver
, public myio::GenericMessageChannelObserver
{
public:
typedef std::unique_ptr<GenericIpcChannel, /*folly::*/Destructor> UniquePtr;
enum class ChannelStatus : short
{
READY,
CLOSED
};
/* status of response to a call() */
enum class RespStatus : short
{
RECV /* received the response */,
TIMEDOUT /* timed out waiting for resp msg */,
ERR /* some other error */
};
typedef boost::function<void(GenericIpcChannel*, ChannelStatus)> ChannelStatusCb;
typedef boost::function<void(GenericIpcChannel*, uint8_t type, uint16_t len,
const uint8_t*)> OnMsgCb;
/* if the status is RECV, then the resp msg can be obtained from
* the buf pointer. any other status, e.g., TIMEDOUT or ERR, then
* "len" will be 0 and the buf will be nullptr
*/
typedef boost::function<void(GenericIpcChannel*, RespStatus status, uint16_t len,
const uint8_t* buf)> OnRespStatusCb;
/* timed out waiting for response */
typedef boost::function<void(GenericIpcChannel*)> RespTimeoutCb;
/* for user of GenericIpcChannel: CalledCb notifies user of a call
* from the other IPC peer. the "uint32_t id" is the opaque that
* the user must specify in its response
*/
typedef boost::function<void(GenericIpcChannel*, uint32_t id, uint8_t type,
uint16_t len, const uint8_t*)> CalledCb;
/* will take ownership of the stream channel.
*
* this is assumed to be an IPC client (i.e., no CalledCb), and
* will call start_connecting() on the stream channel
*/
explicit GenericIpcChannel(struct event_base*,
myio::StreamChannel::UniquePtr,
OnMsgCb, ChannelStatusCb);
/* will take ownership of the stream channel.
*
* this is assumed to be an IPC server (i.e., specified CalledCb)
*/
explicit GenericIpcChannel(struct event_base*,
myio::StreamChannel::UniquePtr,
OnMsgCb, CalledCb, ChannelStatusCb);
void sendMsg(uint8_t type, uint16_t len, const uint8_t* buf);
void sendMsg(uint8_t type); // send empty msg
/* make a call to the other peer, expecting a response message of
* type "resp_type".
*
* "timeoutSecs" is optional timeout in seconds waiting for
* response */
void call(uint8_t type, uint16_t len, const uint8_t* buf,
uint8_t resp_type, OnRespStatusCb on_resp_status_cb,
const uint8_t *timeoutSecs=nullptr);
/* respond to a call */
void reply(uint32_t id, uint8_t type, uint16_t len, const uint8_t*);
protected:
virtual ~GenericIpcChannel() = default;
/**** implement StreamChannelConnectObserver interface *****/
virtual void onConnected(myio::StreamChannel*) noexcept override;
virtual void onConnectError(myio::StreamChannel*, int errorcode) noexcept override;
virtual void onConnectTimeout(myio::StreamChannel*) noexcept override;
/**** implement GeneriMessageChannelObserver interface *****/
virtual void onRecvMsg(myio::GenericMessageChannel*, uint8_t, uint32_t,
uint16_t, const uint8_t*) noexcept override;
virtual void onEOF(myio::GenericMessageChannel*) noexcept override;
virtual void onError(myio::GenericMessageChannel*, int) noexcept override;
////////
void _on_timeout_waiting_resp(Timer*, uint32_t id);
struct event_base* evbase_;
myio::StreamChannel::UniquePtr stream_ch_;
myio::GenericMessageChannel::UniquePtr gen_msg_ch_;
const bool is_client_;
OnMsgCb msg_cb_; /* for notifying user of non-reply msgs */
ChannelStatusCb channel_status_cb_;
CalledCb called_cb_;
uint32_t next_call_msg_id_;
/* map key is msg id */
struct CallInfo
{
uint8_t call_msg_type; /* save the msg type of the call */
uint8_t exp_resp_msg_type; /* expected response msg type */
OnRespStatusCb on_resp_status_cb;
Timer::UniquePtr timeout_timer;
};
std::map<uint32_t, CallInfo> pending_calls_;
/* to store ids of calls that have timed out so we can ignore the
* response when they arrive
*/
std::set<uint32_t> timed_out_call_ids_;
};
} // end myipc namespace
#endif /* generic_ipc_channel_hpp */
| 34.057325 | 87 | 0.66037 | cauthu |
9451c2e411c998ba5103437f2d36cced49ba0142 | 679 | hpp | C++ | core/stl_reader.hpp | fritzio/libstl | 0709e54e4b13576edf84e393db211fb77efd7f72 | [
"MIT"
] | null | null | null | core/stl_reader.hpp | fritzio/libstl | 0709e54e4b13576edf84e393db211fb77efd7f72 | [
"MIT"
] | null | null | null | core/stl_reader.hpp | fritzio/libstl | 0709e54e4b13576edf84e393db211fb77efd7f72 | [
"MIT"
] | null | null | null | #ifndef LIBSTL_STL_READER_HPP
#define LIBSTL_STL_READER_HPP
#include <string>
#include <vector>
#include <memory>
#include "triangle.hpp"
#include "parser_option.hpp"
#include "utilities/box.hpp"
namespace libstl {
class stl_reader {
const std::vector<triangle> surface_mesh;
const utilities::box<float, 3> bounding_box;
const std::array<float, 3> outside_point;
public:
template<typename option>
explicit stl_reader(const std::string& filename, option);
bool is_inside(const std::array<float, 3> point) const;
bool is_inside(const float x, const float y, const float z) const;
};
} // namespace stl_reader
#endif // LIBSTL_STL_READER_HPP
| 19.970588 | 70 | 0.734904 | fritzio |
9451e75afdce50f94f1228f43f8d04cdd947942b | 383 | cpp | C++ | GUIFramework/src/BaseComponents/StandardComponents/ScrollBars/BaseScrollBar.cpp | LazyPanda07/GUIFramework | bf20bd906ea46b791f499886c48fba97eb7fde38 | [
"MIT"
] | null | null | null | GUIFramework/src/BaseComponents/StandardComponents/ScrollBars/BaseScrollBar.cpp | LazyPanda07/GUIFramework | bf20bd906ea46b791f499886c48fba97eb7fde38 | [
"MIT"
] | 34 | 2021-06-09T23:17:37.000Z | 2022-03-03T12:09:21.000Z | GUIFramework/src/BaseComponents/StandardComponents/ScrollBars/BaseScrollBar.cpp | LazyPanda07/GUIFramework | bf20bd906ea46b791f499886c48fba97eb7fde38 | [
"MIT"
] | null | null | null | #include "headers.h"
#include "BaseScrollBar.h"
using namespace std;
namespace gui_framework
{
BaseScrollBar::BaseScrollBar(const wstring& scrollBarName, const utility::ComponentSettings& settings, const styles::ScrollBarStyles& styles, BaseComponent* parent) :
BaseComponent
(
standard_classes::scrollBar,
scrollBarName,
settings,
styles,
parent
)
{
}
}
| 18.238095 | 168 | 0.744125 | LazyPanda07 |
945283652800b96e55e7e7d16d98215205a54355 | 53 | hpp | C++ | src/boost_mpl_aux__reverse_fold_impl_body.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_aux__reverse_fold_impl_body.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_aux__reverse_fold_impl_body.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/aux_/reverse_fold_impl_body.hpp>
| 26.5 | 52 | 0.830189 | miathedev |
9453264e28e9a86483c9ccddfb89c74145e7e07e | 2,660 | cpp | C++ | src/Funcionario.cpp | viniciussslima/PetFera | d98ef1a12607eb5f469d5760107c6bf96761b21c | [
"MIT"
] | 1 | 2019-08-05T00:04:42.000Z | 2019-08-05T00:04:42.000Z | src/Funcionario.cpp | viniciussslima/PetFera | d98ef1a12607eb5f469d5760107c6bf96761b21c | [
"MIT"
] | 5 | 2019-06-13T20:03:29.000Z | 2019-06-21T15:07:59.000Z | src/Funcionario.cpp | viniciussslima/PetFera | d98ef1a12607eb5f469d5760107c6bf96761b21c | [
"MIT"
] | null | null | null | /**
* @file Funcionario.cpp
* @brief Implementação da classe Funcionario.
* @author
* Hudson Bruno Macedo Alves,
* João Vitor Kobata,
* Vinicius Santos Silva de Lima.
*/
#include "Funcionario.h"
using namespace std;
/**
* @brief Construtor padrão da classe Funcionario.
* Nesse caso o funcionário é contruido com o ID igual a 0.
*/
Funcionario::Funcionario():m_id(0){}
/**
* @brief construtor parametrizado da classe Funcionario.
* @param new_id Número que representa a identidade do funcionário.
* @param new_nome Palavra(s) que representa o nome do funcionário.
* @param new_cpf String que representa o cpf do funcionário.
* @param new_idade Número que representa a idade do funcionário.
* @param new_tipo_sanguinio String que representa o tipo sanguinio do funcionário (A, B, AB, O).
* @param new_fator_rh Carácter que representa o fator RH do funcionário (+, -).
* @param new_especialidade Palavra(s) que repreta(m) a especialidade do funcionário (Aves ou qualquer outro tipo de animail).
*/
Funcionario::Funcionario(int new_id, string new_nome, string new_cpf,
short new_idade, string new_tipo_sanguineo, char new_fator_rh,
string new_especialidade)
{
m_id = new_id;
m_nome = new_nome;
m_cpf = new_cpf;
m_idade = new_idade;
m_tipo_sanguineo = new_tipo_sanguineo;
m_fator_rh = new_fator_rh;
m_especialidade = new_especialidade;
}
/**
* @brief Destrutor da classe Funcionario.
*/
Funcionario::~Funcionario(){}
/**
* @brief Método que retorna o Id do funcionário.
* @return Retorna o ID do funcionário.
*/
int Funcionario::get_id() const
{
return m_id;
}
/**
* @brief Método que retorna o nome do funcionário.
* @return Retorna o nome do funcionário.
*/
string Funcionario::get_nome()
{
return m_nome;
}
/**
* @brief Método que retorna o CPF do funcionário.
* @return Retorna o COF do funcionário.
*/
string Funcionario::get_cpf()
{
return m_cpf;
}
/**
* @brief Método que retorna a idade do funcionário.
* @return Retorna a idade do funcionário.
*/
short Funcionario::get_idade()
{
return m_idade;
}
/**
* @brief Método que retorna o tipo sanguínio do funcionário.
* @return Retorna o tipo sanguínio do funcionário.
*/
string Funcionario::get_tipo_sanguineo()
{
return m_tipo_sanguineo;
}
/**
* @brief Método que retorna o fator RH do funcionário.
* @return Retorna o fator RH do funcionário.
*/
char Funcionario::get_rh()
{
return m_fator_rh;
}
/**
* @brief Método que retorna a especialidae do funcionário.
* @return Retorna a especialidade do funcionário.
*/
string Funcionario::get_especialidade()
{
return m_especialidade;
}
ostream& operator << (ostream& os, const Funcionario& b)
{
return b.print(os);
} | 21.451613 | 126 | 0.737594 | viniciussslima |
9455ec897a968cc908f398633dd6ba709e9f0413 | 3,349 | cpp | C++ | src/filter/Temperature.cpp | Kuhlwein/Demiurge | 0981f1d267efed87d51e2b328a93e1fa0be1158d | [
"MIT"
] | 6 | 2020-09-23T19:49:07.000Z | 2022-01-08T15:53:55.000Z | src/filter/Temperature.cpp | Kuhlwein/Demiurge | 0981f1d267efed87d51e2b328a93e1fa0be1158d | [
"MIT"
] | null | null | null | src/filter/Temperature.cpp | Kuhlwein/Demiurge | 0981f1d267efed87d51e2b328a93e1fa0be1158d | [
"MIT"
] | 1 | 2020-09-23T17:53:26.000Z | 2020-09-23T17:53:26.000Z | //
// Created by kuhlwein on 6/29/21.
//
#include <iostream>
#include "Project.h"
#include "Temperature.h"
void TemperatureMenu::update_self(Project *p) {
}
std::shared_ptr<BackupFilter> TemperatureMenu::makeFilter(Project *p) {
return std::make_shared<ProgressFilter>(p, [](Project* p){return p->get_terrain();}, std::move(std::make_unique<Temperature>(p)));
}
TemperatureMenu::TemperatureMenu() : FilterModal("Temperature") {
}
Temperature::~Temperature() {
}
Temperature::Temperature(Project *p) {
p->get_terrain()->swap(p->get_scratch1());
Shader* shader = Shader::builder()
.include(fragmentBase)
.include(pidShader)
.create("",R"(
fc = 50;
)");
ShaderProgram* setzero = ShaderProgram::builder()
.addShader(vertex2D->getCode(), GL_VERTEX_SHADER)
.addShader(shader->getCode(), GL_FRAGMENT_SHADER)
.link();
setzero->bind();
p->setCanvasUniforms(setzero);
p->apply(setzero,p->get_terrain());
}
void Temperature::run() {
for (int i=0;i<500000;i++) {
dispatchGPU([&i](Project *p) {
Shader *shader = Shader::builder()
.include(fragmentBase)
.include(cornerCoords)
.include(texturespace_gradient)
.create(R"(
uniform float M=0;
float eccentricity = 0.017;
float gamma = 23.44/180.0*M_PI;
float omega = 0;
float omega2 = 77.05/180.0*M_PI;
float dmean = 1.0;
float S0 = 1365;
float Q = 400;
float S(float A) {
return S0*(1+2*eccentricity*cos(A-omega));
}
float A(float M) {
return M + (2*eccentricity-pow(eccentricity,3)/4*sin(M) + 5.0/4*pow(eccentricity,2)*sin(2*M) + 13.0/12*pow(eccentricity,3)*sin(3*M));
}
float Ls(float A) {
return A - omega2;
}
float delta(float Ls) {
return asin(sin(gamma)*sin(Ls));
}
float h0(float phi, float delta) {
float h = sign(phi)==sign(delta) ? M_PI : 0.0;
if(abs(phi)<=M_PI/2-abs(delta)) h = acos(-tan(phi)*tan(delta));
return h;
}
float QDay(float phi, float M) {
float delt = delta(Ls(A(M)));
float h = h0(phi,delt);
return S(A(M))/M_PI * (h*sin(phi)*sin(delt)+cos(phi)*cos(delt)*sin(h));
}
)", R"(
float T = texture(img,st).r;
float terrain = texture(scratch1,st).r;
float alpha = terrain>0 ? 0.15 : 0.06;
alpha = 0.30;
float phi = tex_to_spheric(st).y;
//alpha = 0.354 + 0.12*0.5*(3*pow(sin(phi),2)-1);
float ASR = (1-alpha)*(QDay(phi,M) );//+QDay(phi,M+M_PI))/2;
float OLR = 210 + 2 * T;
OLR = 210*pow(T+273.15,4)/pow(273.4,4) * 0.93;
vec2 gradient = get_texture_laplacian(st);
float change = ASR - OLR + 0.55*1e6*(gradient.x + gradient.y);
float atmosphere = 1e7;
float C = atmosphere + (terrain>0 ? atmosphere*0.5 : 4*1.5 * atmosphere);
fc = T + change*3.154*1e7/15000/C;
)");
ShaderProgram *mainfilter = ShaderProgram::builder()
.addShader(vertex2D->getCode(), GL_VERTEX_SHADER)
.addShader(shader->getCode(), GL_FRAGMENT_SHADER)
.link();
for (int j=0; j<10; j++) {
mainfilter->bind();
p->setCanvasUniforms(mainfilter);
int id = glGetUniformLocation(mainfilter->getId(), "M");
glUniform1f(id, M_PI * 2 / 15000 * i);
p->apply(mainfilter, p->get_scratch2());
p->get_terrain()->swap(p->get_scratch2());
i++;
}
//
});
}
dispatchGPU([](Project* p){
std::cout << "finished\n;";
p->get_terrain()->swap(p->get_scratch2());
});
}
| 20.546012 | 135 | 0.62138 | Kuhlwein |
945a543d4c8ea0ad7bf7038f16d20c14ac098add | 6,023 | cpp | C++ | hexprinter.cpp | eva-rubio/CPU-simulator | b897e935c578b048e5945fda57f647a799f07655 | [
"MIT"
] | null | null | null | hexprinter.cpp | eva-rubio/CPU-simulator | b897e935c578b048e5945fda57f647a799f07655 | [
"MIT"
] | null | null | null | hexprinter.cpp | eva-rubio/CPU-simulator | b897e935c578b048e5945fda57f647a799f07655 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
// Eva Rubio
using namespace std;
/*
' #define ' - A type of Preprocessor Directive: MACRO.
Preprocessors are programs that process our source code before compilation.
Macros are a piece of code in a program which is given some name.
Whenever this name is encountered by the compiler,
the compiler REPLACES the name with the actual piece of code.
*/
#define MAIN_MEMLENGTH 32
#define MEMLENGTH 0xFFF
#define OPCODE 0xF000 // the opcode is the first 4 bits
#define OPERAND 0x0FFF // the operand is the last 12 bits
//OPCODE - 11110000 00000000 - 0xF000 - 61,440 - 16 bits
//00110000 00001000 - 0x3008 - 12,296 - IR
// UNSIGNED int. DECIMAL NUMBER.
// 16 bits long (2 Bytes)
// - largest number it can hold: 65,535
// - smallest number: 0.
/*
typedef : Used to give data type a new name
*/
typedef uint16_t WORD; // word is an (unsigned) int, 16 bits
void HexPrint(WORD val, int width);
struct cpu_t{
int PC; // this is the CPU's program counter
WORD ACC; // this is the CPU's accumulator
WORD IR; // this is the CPU's instruction register
// a few helpful methods. NOTHING in this struct should change.
WORD getOpcode(){
return (IR & OPCODE) >> 12;
}
WORD getOperand(){
return IR & OPERAND;
}
void init(){
PC=0;
ACC=0;
IR=0x0000;
}
};
/**
** initMachine() initializes the state of the virtual machine state.
** (1) zeros out the CPU registers
** (2) sets the program counter to the start of memory
** (3) fills memory with zeros
**/
void initMachine(cpu_t &cpu, WORD memory[])
{
cpu.init();
for(int i=0;i<MEMLENGTH;i++){
memory[i] = 0x0000;
}
}
/** this function will print a hex version of the value you give (an UNsigned 16bit int)
** it, front padded with as many zeros as needed to fit a width
** of 'width' --- for example HexPrint(23,2) prints 17
** and HexPrint(32,3) prints 020
** it does NOT print a newline
ADDS 0s IN FRONT UNTIL THERE ARE 'width' NUMBER AFTER 0x
ex. (3)0x3008
(4)0x3008
(5)0x03008
**/
void HexPrint(WORD val, int width)
{
/*
C++ defines some format flags for standard input and output,
which can be manipulated with the flags() function.
- ios::hex Numeric values are displayed in hexidecimal.
- ios::dec Numeric values are displayed in decimal.
*/
cout << "0x" ;
// switch to hex
cout.flags(ios::hex);
// set zero paddnig
cout.fill('0');
cout.width(width);
// print the val
cout << val ;
// switch back to decimal
cout.flags(ios::dec);
}
int main (int argc, char *argv[])
{
cpu_t cpu;
WORD memory[MEMLENGTH]; // this is the system memory
initMachine(cpu, memory); // clear out the virtual system
cpu.IR = 0x3a08;
cout << "PC: " << cpu.PC <<endl;
cout << "IR: ";
cout << cpu.IR << endl;
HexPrint(cpu.IR, 4);
cout << endl;
cout << "\t (Opcode:";
HexPrint(cpu.getOpcode(), 1);
cout << ")" << endl;
cout << "\t (Operand:";
HexPrint(cpu.getOperand(), 7);
cout << ")" << endl;
cout << "ACC: ";
HexPrint(cpu.ACC,4);
cout << endl;
WORD valueForACC;
WORD myMask = 0xf000;
WORD myOperand = cpu.getOperand();
if((myOperand & 0x800) != 0){
// operand is NEGATIVE
valueForACC = myOperand | myMask;
cout << "valueForACC: ";
HexPrint(valueForACC, 4);
cout << endl;
} else {
valueForACC = myOperand;
cout << "(positive) valueForACC: ";
HexPrint(valueForACC, 4);
cout << endl;
}
cpu.ACC = valueForACC;
cout << " NEW - - ACC: ";
HexPrint(cpu.ACC,4);
cout << endl;
cout << " ---------------------------------------- " << endl;
WORD address = 0xfff;
cpu.PC = address;
cout << " NEW - - PC: " << endl;
cout << cpu.PC << endl;
cout << "now in hex: " << endl;
HexPrint(cpu.PC,4);
cout << endl;
//----------------------
memory[12] = 0xfff;
cpu.ACC = cpu.ACC + memory[12];
cout << " ADDITION VALUE OF - - ACC: ";
HexPrint(cpu.ACC,4);
cout << endl;
/**
memory[0] = 0x0000;
memory[1] = 0x0001;
memory[2] = 1;
memory[3] = 0xf;
memory[4] = -10; //Hex signed 2's comple 0xFFF6
memory[5] = memory[4] + memory[2];
memory[6] = (-10 - (-5)); //Hex signed 2's compl 0xFFFB
**/
/*
cout << "memory contents:" << endl;
for(int i=0;i<MAIN_MEMLENGTH;i++){
cout << "mem[";
HexPrint(i,3);
cout << "] == ";
HexPrint(memory[i],4);
cout << endl;
}
for(int i=MAIN_MEMLENGTH;i<MEMLENGTH;i++){
if(memory[i]!=0){
cout << "mem[";
HexPrint(i,3);
cout << "] == ";
HexPrint(memory[i],4);
cout << endl;
}
}
int width1 = 10;
int width2 = 2;
int width3 = 3;
WORD unsigInt1 = 23;
cout << "HexPrint : unsigInt1 (23), width2 (2) " << endl;
HexPrint(unsigInt1, width2);
cout << endl;
cout << endl;
WORD unsigInt2 = 60000;
cout << "HexPrint : unsigInt2 (60000), width1 (10) " << endl;
HexPrint(unsigInt2, width1);
cout << endl;
cout << endl;
WORD unsigInt3 = 2;
cout << "HexPrint : unsigInt3 (2), width3 (3) " << endl;
HexPrint(unsigInt3, width3);
cout << endl;
uint16_t x;
uint16_t y;
uint16_t z;
cout << endl;
cout << "ints Byte size: " << sizeof(int) << endl;
cout << "unsigned ints Byte size: " << sizeof(unsigned int) << endl;
cout << "uint16_t Byte size: " << sizeof(uint16_t) << endl;
cout << "int16_t Byte size: " << sizeof(int16_t) << endl;
cout << endl;
cout << endl;
cout << "x? > ";
cin >> x;
cout << endl;
cout << "y? > ";
cin >> y;
cout << endl;
cout << " - x: " << x << endl;
cout << " - (int)x: " << (int)x << endl;
cout << " - (int16_t)x: " << (int16_t)x << endl;
cout << " - (uint16_t)x: " << (uint16_t)x << endl;
cout << " - x in hex: ";
HexPrint(x,4);
z = x + y;
cout << endl;
cout << endl;
cout << " - z: " << z << endl;
cout << " - (int)z: " << (int)z << endl;
cout << " - (int16_t)z: " << (int16_t)z << endl;
cout << " - (uint16_t)z: " << (uint16_t)z << endl;
cout << " - z in hex: ";
HexPrint(z,4);
*/
return 0;
} | 20.347973 | 88 | 0.589739 | eva-rubio |
945a574fc62b8a929ce2c32d8000ed47c0178891 | 947 | cpp | C++ | src/Projectile.cpp | tobiaswinter/asteroids-game | 761d1c7ae1ae03762b8b8c4dc18468b4df164d61 | [
"MIT"
] | null | null | null | src/Projectile.cpp | tobiaswinter/asteroids-game | 761d1c7ae1ae03762b8b8c4dc18468b4df164d61 | [
"MIT"
] | null | null | null | src/Projectile.cpp | tobiaswinter/asteroids-game | 761d1c7ae1ae03762b8b8c4dc18468b4df164d61 | [
"MIT"
] | null | null | null | #include "Projectile.h"
#include <random>
#include <iostream>
Projectile::Projectile(Participant* owner, Type type) : Rigidbody(type), owner(owner)
{
Reset();
}
Projectile::~Projectile()
{
}
void Projectile::Reset()
{
if (type == Asteroid)
{
radius = ASTEROID_RADIUS;
if (velocity.x < 0)
{
location.x = (ARENA_WIDTH / 2) + 20;
}
else
{
location.x = -((ARENA_WIDTH / 2) + 20);
}
if (velocity.y < 0)
{
location.y = (ARENA_HEIGHT / 2) - 20;
}
else
{
location.y = -((ARENA_HEIGHT / 2) - 20);
}
#if !IGNORE_Z_AXIS
if (velocity.z < 0)
{
location.z = (ARENA_DEPTH / 2) - 20;
}
else
{
location.z = -((ARENA_DEPTH / 2) - 20);
}
#endif
}
else if (type = Bullet)
{
radius = BULLET_RADIUS;
}
}
| 17.867925 | 85 | 0.459345 | tobiaswinter |
945b2ab4f7910a796ced6492bf74684995355e71 | 1,065 | hpp | C++ | software/include/species.hpp | A283le/ExoskeletonAI | dfb4ff5639d84dea69577764af2b151f309bbb3b | [
"Apache-2.0"
] | 7 | 2020-06-03T05:48:47.000Z | 2022-01-08T22:30:26.000Z | software/include/species.hpp | A283le/ExoskeletonAI | dfb4ff5639d84dea69577764af2b151f309bbb3b | [
"Apache-2.0"
] | 21 | 2018-01-16T17:05:30.000Z | 2018-04-01T18:14:18.000Z | software/include/species.hpp | A283le/ExoskeletonAI | dfb4ff5639d84dea69577764af2b151f309bbb3b | [
"Apache-2.0"
] | 6 | 2018-01-22T15:35:26.000Z | 2021-12-17T15:32:09.000Z | #ifndef SPECIES_HPP
#define SPECIES_HPP
/** @brief Class for the species.
This class will hold of the functions that deal
with species, and their necessary actions.
@author Dominguez, Alejandro
@date Feburary, 2018
*/
#include <iostream>
#include <list>
#include <network.hpp>
using namespace std;
class Species{
private:
int stale;/**< Indicates how long a function has been stale.*/
int fit_stale;
int max_fitness;/**<The maximum fitness of a species.*/
Network* fittest_net;/**<Network pointer to the fittest network.*/
list<Network *> networks;/**<A list of network pointers that stores networks.*/
protected:
int compute_excess(Network *, Network *);
int compute_disjoint(Network *, Network *);
float weight_diff_match_genes(Network *, Network *);
public:
Species();
~Species();
void mutate();
void run_networks();
void add_network(Network *);
bool is_stale();
bool test_species();
Network* get_fittest_net();
list<Network *>* get_networks();
};
#endif | 21.734694 | 83 | 0.675117 | A283le |
945b8d81ea5f1b8bedf56420c9ed0132918089a8 | 8,225 | cc | C++ | e2e/trt/src/inference_server.cc | stanford-futuredata/smol | 82e2356755133cd1516dfbbbc782707eca70a34c | [
"Apache-2.0"
] | 1 | 2021-11-29T01:24:03.000Z | 2021-11-29T01:24:03.000Z | e2e/trt/src/inference_server.cc | stanford-futuredata/smol | 82e2356755133cd1516dfbbbc782707eca70a34c | [
"Apache-2.0"
] | 1 | 2021-11-29T09:29:14.000Z | 2021-12-13T02:31:55.000Z | e2e/trt/src/inference_server.cc | stanford-futuredata/smol | 82e2356755133cd1516dfbbbc782707eca70a34c | [
"Apache-2.0"
] | 1 | 2021-12-13T06:55:18.000Z | 2021-12-13T06:55:18.000Z | #include <assert.h>
#include <future>
#include <numeric>
#include <thread>
#include "folly/MPMCQueue.h"
#include "omp.h"
#include "calibrator.h"
#include "inference_server.h"
static void add_resize(nvinfer1::INetworkDefinition *network, const size_t kBatchSize) {
using namespace nvinfer1;
// FIXME: 141, 224
nvinfer1::ITensor* old_input = network->getInput(0);
nvinfer1::ILayer* first_layer = network->getLayer(0);
nvinfer1::ITensor* new_input = network->addInput("thumbnail_im", nvinfer1::DataType::kFLOAT, nvinfer1::Dims4{kBatchSize, 3, 141, 141});
nvinfer1::IResizeLayer* resizeLayer = network->addResize(*new_input);
resizeLayer->setOutputDimensions(nvinfer1::Dims4(kBatchSize, 3, 224, 224));
resizeLayer->setResizeMode(nvinfer1::ResizeMode::kLINEAR);
nvinfer1::ITensor* resize_output = resizeLayer->getOutput(0);
first_layer->setInput(0, *resize_output);
network->removeTensor(*old_input);
}
nvinfer1::ICudaEngine* OnnxInferenceServer::CreateCudaEngine(
const std::string& kOnnxPath,
const std::string& kOnnxPathBS1,
BaseCalibrator *calibrator,
const bool kDoINT8,
const bool kAddResize) {
using namespace std;
using namespace nvinfer1;
using nvonnxparser::IParser;
unique_ptr<IBuilder, Destroy<IBuilder> > builder{createInferBuilder(gLogger)};
builder->setMaxBatchSize(kBatchSize_);
IBuilderConfig *config = builder->createBuilderConfig();
const auto explicitBatch = 1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
unique_ptr<INetworkDefinition, Destroy<INetworkDefinition> > network{builder->createNetworkV2(explicitBatch)};
unique_ptr<IParser, Destroy<IParser> > parser{nvonnxparser::createParser(*network, gLogger)};
if (!parser->parseFromFile(kOnnxPath.c_str(), static_cast<int>(ILogger::Severity::kINFO))) {
throw "ERROR: could not parse input engine.";
}
// FIXME: is this always correct?
const size_t kBatchSize = network->getInput(0)->getDimensions().d[0];
if (kAddResize) {
add_resize(network.get(), kBatchSize);
}
config->setMaxWorkspaceSize(MAX_WORKSPACE_SIZE);
if (kDoINT8) {
std::cerr << "Doing INT8" << std::endl;
config->setFlag(BuilderFlag::kINT8);
config->setInt8Calibrator(calibrator);
} else {
config->setFlag(BuilderFlag::kFP16);
}
return builder->buildEngineWithConfig(*network, *config);
}
nvinfer1::ICudaEngine* OnnxInferenceServer::GetCudaEngine(const std::string& kEnginePath) {
using namespace std;
using namespace nvinfer1;
ICudaEngine* engine{nullptr};
string buffer = readBuffer(kEnginePath);
if (buffer.size()) {
// Try to deserialize engine.
unique_ptr<IRuntime, Destroy<IRuntime>> runtime{createInferRuntime(gLogger)};
engine = runtime->deserializeCudaEngine(buffer.data(), buffer.size(), nullptr);
}
if (!engine) {
throw std::runtime_error("Failed to load engine");
}
return engine;
}
OnnxInferenceServer::OnnxInferenceServer(
const std::string& kEnginePath, const size_t kBatchSize, const bool kDoMemcpy) :
kBatchSize_(kBatchSize),
queue_(omp_get_max_threads() * 3), contexts(kNbStreams_),
kDoMemcpy_(kDoMemcpy) {
// TensorRT engine stuff
this->engine.reset(GetCudaEngine(kEnginePath));
LoadAndLaunch();
}
OnnxInferenceServer::OnnxInferenceServer(
const std::string& kOnnxPath, const std::string& kOnnxPathBS1,
const std::string& kCachePath,
const size_t kBatchSize, const bool kDoMemcpy,
const DataLoader *kLoader,
const std::vector<CompressedImage>& kCompressedImages,
const bool kDoINT8,
const bool kAddResize
) :
kBatchSize_(kBatchSize),
queue_(omp_get_max_threads() * 3), contexts(kNbStreams_),
kDoMemcpy_(kDoMemcpy) {
BaseCalibrator *calibrator = NULL;
if (kDoINT8) {
assert(kLoader != nullptr);
calibrator = new ImageCalibrator(kLoader, kCompressedImages, kBatchSize);
}
this->engine.reset(
CreateCudaEngine(kOnnxPath, kOnnxPathBS1,
calibrator,
kDoINT8, kAddResize));
// Cache engine
std::unique_ptr<nvinfer1::IHostMemory, nvinfer1::Destroy<nvinfer1::IHostMemory>> engine_plan{engine->serialize()};
nvinfer1::writeBuffer(engine_plan->data(), engine_plan->size(), kCachePath);
LoadAndLaunch();
}
OnnxInferenceServer::OnnxInferenceServer(
const std::string& kOnnxPath, const std::string& kOnnxPathBS1,
const std::string& kCachePath,
const size_t kBatchSize, const bool kDoMemcpy,
const VideoDataLoader *kLoader,
const std::vector<std::string>& kFileNames,
const bool kDoINT8,
const bool kAddResize
) :
kBatchSize_(kBatchSize),
queue_(omp_get_max_threads() * 3), contexts(kNbStreams_),
kDoMemcpy_(kDoMemcpy) {
BaseCalibrator *calibrator = NULL;
if (kDoINT8) {
assert(kLoader != nullptr);
calibrator = new VideoCalibrator(kLoader, kFileNames, kBatchSize);
}
this->engine.reset(
CreateCudaEngine(kOnnxPath, kOnnxPathBS1,
calibrator,
kDoINT8, kAddResize));
// Cache engine
std::unique_ptr<nvinfer1::IHostMemory, nvinfer1::Destroy<nvinfer1::IHostMemory>> engine_plan{engine->serialize()};
nvinfer1::writeBuffer(engine_plan->data(), engine_plan->size(), kCachePath);
LoadAndLaunch();
}
void OnnxInferenceServer::LoadAndLaunch() {
// Currently, we only support exactly one input/output tensor
assert(this->engine->getNbBindings() == 2);
assert(this->engine->bindingIsInput(0) ^ this->engine->bindingIsInput(1));
for (size_t j = 0; j < kNbStreams_; j++) {
for (size_t i = 0; i < this->engine->getNbBindings(); i++) {
nvinfer1::Dims dims{this->engine->getBindingDimensions(i)};
size_t size = std::accumulate(dims.d, dims.d + dims.nbDims, 1, std::multiplies<size_t>());
cudaMalloc(&this->bindings[j][i], size * sizeof(float));
if (!this->engine->bindingIsInput(i))
kOutputSingle_ = size / kBatchSize_;
}
this->contexts[j].reset(engine->createExecutionContext());
}
// Launch thread
for (size_t i = 0; i < kNbStreams_; i++)
threads_.push_back(std::thread([this, i]{ _RunInferenceThread(i); }));
}
void OnnxInferenceServer::_RunInferenceThread(const size_t idx) {
const int input_id = !contexts[idx]->getEngine().bindingIsInput(0);
QueueData input_data;
folly::MPMCQueue<Batch> *batch_queue;
size_t output_size, batch_size;
float *output_buf;
while (true) {
queue_.blockingRead(input_data);
std::tie(std::ignore, batch_size, output_buf, output_size, batch_queue) = input_data;
if (batch_size == 0) {
cudaStreamSynchronize(streams[idx]);
break;
}
Batch kData = std::move(std::get<0>(input_data));
if (kDoMemcpy_) {
cudaMemcpyAsync(bindings[idx][input_id],
kData.get()->data(),
kData.get()->size() * sizeof(float),
cudaMemcpyHostToDevice, streams[idx]);
}
contexts[idx]->enqueueV2(bindings[idx], streams[idx], nullptr);
if (kDoMemcpy_) {
cudaMemcpyAsync(output_buf,
bindings[idx][1 - input_id],
output_size * sizeof(float),
cudaMemcpyDeviceToHost, streams[idx]);
}
if (batch_queue != nullptr)
batch_queue->blockingWrite(std::move(kData));
}
}
void OnnxInferenceServer::RunInference(QueueData data) {
queue_.blockingWrite(std::move(data));
}
void OnnxInferenceServer::Sync() {
while (!queue_.isEmpty()) ;
std::this_thread::sleep_for(std::chrono::milliseconds(300));
for (size_t i = 0; i < kNbStreams_; i++)
cudaStreamSynchronize(streams[i]);
}
void OnnxInferenceServer::warmup(const size_t kResol) {
const size_t kWarmupIter = 100;
std::vector<float> output;
output.reserve(kBatchSize_ * kOutputSingle_);
for (size_t i = 0; i < kWarmupIter; i++) {
Batch data(
new BatchBase(3 * kResol * kResol * kBatchSize_));
RunInference(
std::make_tuple(std::move(data), kBatchSize_,
output.data(), output.size(),
nullptr));
}
Sync();
}
std::vector<std::vector<float> > OnnxInferenceServer::GetResults() {
std::vector<std::vector<float> > ret;
return ret;
}
| 34.128631 | 137 | 0.691915 | stanford-futuredata |
945c8acf3a5afff032341822a079b8196e8f3fa9 | 3,238 | cpp | C++ | src/Config/PropertiesMap.cpp | eiji-shimizu/eihire | 3996cf9d0c5d4fd8201141093aea6bb8017e7657 | [
"MIT"
] | null | null | null | src/Config/PropertiesMap.cpp | eiji-shimizu/eihire | 3996cf9d0c5d4fd8201141093aea6bb8017e7657 | [
"MIT"
] | null | null | null | src/Config/PropertiesMap.cpp | eiji-shimizu/eihire | 3996cf9d0c5d4fd8201141093aea6bb8017e7657 | [
"MIT"
] | null | null | null | #include "Config/PropertiesMap.h"
#include "Exception/Exception.h"
#include <filesystem>
#include <fstream>
#include <sstream>
namespace Eihire::Config {
namespace {
std::string getFileName(const std::string &filePath)
{
std::filesystem::path p{filePath};
return p.filename().generic_string();
}
} // namespace
PropertiesMap::PropertiesMap() = default;
PropertiesMap::~PropertiesMap() = default;
PropertiesMap::PropertiesMap(const PropertiesMap &) = default;
PropertiesMap &PropertiesMap::operator=(const PropertiesMap &) = default;
PropertiesMap::PropertiesMap(PropertiesMap &&) = default;
PropertiesMap &PropertiesMap::operator=(PropertiesMap &&) = default;
PropertiesMap::PropertiesMap(std::string filePath)
: filePath_{filePath},
fileName_{getFileName(filePath)}
{
// noop
}
void PropertiesMap::load()
{
std::ifstream ifs((filePath_));
if (!ifs) {
std::ostringstream oss("");
oss << "can't open file '" << filePath_ << "'.";
throw Exception::FileCannotOpenException(oss.str());
}
// ファイル読み込み開始
// この文以降でifsがbad状態になった場合に例外をスローさせる
ifs.exceptions(ifs.exceptions() | std::ios_base::badbit);
std::string line;
while (ifs) {
std::getline(ifs, line);
if (line.length() <= 0) {
continue;
}
std::ostringstream key("");
std::ostringstream value("");
bool isComment = false;
bool flg = false;
for (const char c : line) {
if (c == '#' || c == '!') {
isComment = true;
break;
}
if (flg == false && c == '=') {
flg = true;
continue;
}
if (flg)
value << c;
else
key << c;
}
if (!isComment) {
// コメント行でないのに'='が見つからなかった場合は構文エラー
if (!flg) {
std::ostringstream oss("");
oss << "parse error file'" << filePath_ << "'.";
throw Exception::ParseException(oss.str());
}
set(key.str(), value.str());
}
}
}
bool PropertiesMap::isContain(const std::string &key) const
{
auto it = properties_.find(key);
return it != properties_.end();
}
std::string PropertiesMap::get(const std::string &key) const
{
return properties_.at(key);
}
void PropertiesMap::set(const std::string &key, const std::string &value)
{
std::pair<std::string, std::string> e{key, value};
auto result = properties_.insert(std::make_pair(key, value));
if (!result.second) {
properties_.at(key) = value;
}
}
const std::string &PropertiesMap::fileName() const
{
return fileName_;
}
const std::map<std::string, std::string> &PropertiesMap::properties() const
{
return properties_;
}
} // namespace Eihire::Config
| 28.910714 | 79 | 0.512044 | eiji-shimizu |
9466c9f41e9d9a74e251d8536071f33b322a69fa | 929 | cpp | C++ | src/engine/graphics/model/vertex.cpp | dmfedorin/ubiquitility | f3a1062d2489ffd48889bff5fc8062c05706a946 | [
"MIT"
] | null | null | null | src/engine/graphics/model/vertex.cpp | dmfedorin/ubiquitility | f3a1062d2489ffd48889bff5fc8062c05706a946 | [
"MIT"
] | null | null | null | src/engine/graphics/model/vertex.cpp | dmfedorin/ubiquitility | f3a1062d2489ffd48889bff5fc8062c05706a946 | [
"MIT"
] | null | null | null | #include "vertex.hpp"
auto Vertex::get_binding_desc(
void) noexcept -> VkVertexInputBindingDescription
{
VkVertexInputBindingDescription binding_desc{};
binding_desc.binding = 0;
binding_desc.stride = sizeof(Vertex);
binding_desc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return binding_desc;
}
auto Vertex::get_attr_descs(
void) noexcept
-> std::array<VkVertexInputAttributeDescription, 2>
{
std::array<VkVertexInputAttributeDescription, 2> attr_descs{};
attr_descs[0].binding = 0;
attr_descs[0].location = 0;
attr_descs[0].format = VK_FORMAT_R32G32_SFLOAT;
attr_descs[0].offset = offsetof(Vertex, pos);
attr_descs[1].binding = 0;
attr_descs[1].location = 1;
attr_descs[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attr_descs[1].offset = offsetof(Vertex, color);
return attr_descs;
} | 29.03125 | 70 | 0.668461 | dmfedorin |
94692948c159d90e24d27363fd5e68a427bf936f | 1,581 | cpp | C++ | src/InlinePatterns/SimpleTagPattern.cpp | mugwort-rc/QMarkdown | cd865b41ef6038d32d109bdb0eae830ed1eb14a3 | [
"BSD-3-Clause"
] | null | null | null | src/InlinePatterns/SimpleTagPattern.cpp | mugwort-rc/QMarkdown | cd865b41ef6038d32d109bdb0eae830ed1eb14a3 | [
"BSD-3-Clause"
] | null | null | null | src/InlinePatterns/SimpleTagPattern.cpp | mugwort-rc/QMarkdown | cd865b41ef6038d32d109bdb0eae830ed1eb14a3 | [
"BSD-3-Clause"
] | null | null | null | #include "InlinePatterns/SimpleTagPattern.h"
#include "InlinePatterns/common.h"
namespace markdown
{
SimpleTagPattern::SimpleTagPattern(const QString &pattern, const QString &tag, const std::weak_ptr<Markdown> &md) :
Pattern(pattern, md),
tag(tag)
{}
SimpleTagPattern::~SimpleTagPattern()
{}
Element SimpleTagPattern::handleMatch(const ElementTree &, const QRegularExpressionMatch &m)
{
Element el = createElement(this->tag);
el->text = m.captured(3);
return el;
}
QString SimpleTagPattern::type(void) const
{ return "SimpleTagPattern"; }
SubstituteTagPattern::SubstituteTagPattern(const QString &pattern, const QString &tag, const std::weak_ptr<Markdown> &md) :
SimpleTagPattern(pattern, tag, md)
{}
Element SubstituteTagPattern::handleMatch(const ElementTree &, const QRegularExpressionMatch &)
{
return createElement(this->tag);
}
QString SubstituteTagPattern::type(void) const
{ return "SubstituteTagPattern"; }
DoubleTagPattern::DoubleTagPattern(const QString &pattern, const QString &tag, const std::weak_ptr<Markdown> &md) :
SimpleTagPattern(pattern, tag, md)
{}
Element DoubleTagPattern::handleMatch(const ElementTree &, const QRegularExpressionMatch &m)
{
QStringList tags = this->tag.split(",");
Element el1 = createElement(tags.at(0));
Element el2 = createSubElement(el1, tags.at(1));
el2->text = m.captured(3);
if ( ! m.captured(4).isEmpty() ) {
el2->tail = m.captured(4);
}
return el1;
}
QString DoubleTagPattern::type(void) const
{ return "DoubleTagPattern"; }
} // namespace markdown
| 26.79661 | 123 | 0.727388 | mugwort-rc |
9469376a9120212715f945fbf16eb07ba750a193 | 1,433 | cpp | C++ | test/memory/TestObjectPool.cpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | test/memory/TestObjectPool.cpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | test/memory/TestObjectPool.cpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | #include <vector>
#include <list>
#include <map>
#include "common/Log.hpp"
#include "common/Stopwatch.hpp"
#include "memory/ObjectPool.hpp"
template<size_t DUMP_SIZE>
class Test
{
public:
char dump[DUMP_SIZE];
Test() {}
~Test() {}
};
void testNewDelete();
void testMap();
template <typename T> void testStl();
int main()
{
testNewDelete();
testStl<std::vector<int, ObjectPool<int>>>();
testStl<std::list<int, ObjectPool<int>>>();
testMap();
return 0;
}
void testNewDelete()
{
const int TEST_LOOP_COUNTER = 2500000;
const int TEST_OBJECT_BYTES = 1024000;
ObjectPool<Test<TEST_OBJECT_BYTES>> pool;
Stopwatch s;
s.start();
for (int i = 0; i < TEST_LOOP_COUNTER; ++i)
{
{
// Test pool allocate de-allocate
Test<TEST_OBJECT_BYTES> *p = pool.allocate(1);
pool.construct(p, Test<TEST_OBJECT_BYTES>());
pool.destroy(p);
pool.deallocate(p, 1);
}
{ // Test defalut new delete
// Test<TEST_OBJECT_BYTES> *p = new Test<TEST_OBJECT_BYTES>;
// delete p;
}
}
s.stop();
LOGP("\nTotal time: " << s.getMicros() << " us");
}
void testMap()
{
std::map<int, int, std::less<int>, ObjectPool<int>> v;
for (int i = 0; i < 6; ++i)
{
LOGP("===========");
LOGP("map: insert " << i);
v[i] = i;
}
LOGP("===========");
}
template <typename T> void testStl()
{
T v;
for (int i = 0; i < 6; ++i)
{
LOGP("===========");
LOGP("push " << i);
v.push_back(i);
}
LOGP("===========");
}
| 16.101124 | 63 | 0.598744 | CltKitakami |
946aa8147a1642149d5040bad13609964b9d9e98 | 154 | cpp | C++ | ME625_NURBS_SweptSurfaces/vector3D.cpp | houes/ME625_NURBS_SweptSurfaces | 0b3062a0ae5c7dbb885ac35ad12bcf2afaeec66e | [
"MIT"
] | 3 | 2020-04-10T22:55:20.000Z | 2022-02-08T11:10:28.000Z | ME625_NURBS_SweptSurfaces/vector3D.cpp | houes/ME625_NURBS_SweptSurfaces | 0b3062a0ae5c7dbb885ac35ad12bcf2afaeec66e | [
"MIT"
] | null | null | null | ME625_NURBS_SweptSurfaces/vector3D.cpp | houes/ME625_NURBS_SweptSurfaces | 0b3062a0ae5c7dbb885ac35ad12bcf2afaeec66e | [
"MIT"
] | null | null | null | #include "vector3D.h"
vector3D vector3D::crossp(const vector3D &v) const
{
return vector3D( y*v.z - z*v.y,
z*v.x - x*v.z,
x*v.y - y*v.x );
} | 19.25 | 50 | 0.577922 | houes |
946c659c0d072af4cbd7920c2a715444029456f5 | 7,972 | cpp | C++ | src/libc9/gc_markcompact.cpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | 1 | 2015-02-13T02:03:29.000Z | 2015-02-13T02:03:29.000Z | src/libc9/gc_markcompact.cpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null | src/libc9/gc_markcompact.cpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null | #include "c9/channel9.hpp"
#include "c9/gc.hpp"
#include "c9/value.hpp"
#include "c9/string.hpp"
#include "c9/tuple.hpp"
#include "c9/message.hpp"
#include "c9/context.hpp"
#include "c9/variable_frame.hpp"
#include "c9/gc_markcompact.hpp"
namespace Channel9
{
GC::Markcompact::Markcompact()
: m_gc_phase(Running), m_alloced(0), m_used(0), m_data_blocks(0), m_next_gc(0.9*(1<<CHUNK_SIZE))
{
alloc_chunk();
m_cur_small_block = m_cur_medium_block = m_empty_blocks.back();
m_empty_blocks.pop_back();
m_pinned_block.init(0);
}
uint8_t *GC::Markcompact::next_slow(size_t alloc_size, size_t size, uint16_t type, bool new_alloc, bool small)
{
TRACE_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "Alloc %u type %x ...", (unsigned)size, type);
Block * block = (small ? m_cur_small_block : m_cur_medium_block);
while(1){
Data * data = block->alloc(size, type);
TRACE_QUIET_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "from block %p, got %p ... ", block, data);
if(data){
TRACE_QUIET_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "alloc return %p\n", data->m_data);
return data->m_data;
}
if(small && block != m_cur_medium_block){
//promote small to the medium block
block = m_cur_small_block = m_cur_medium_block;
}else{
if(m_empty_blocks.empty())
alloc_chunk();
block = m_empty_blocks.back();
m_empty_blocks.pop_back();
if(small){
m_cur_small_block = m_cur_medium_block = block;
}else{
//demote the medium block to small, possibly wasting a bit of space in the old small block
m_cur_small_block = m_cur_medium_block;
m_cur_medium_block = block;
}
}
TRACE_QUIET_PRINTF(TRACE_ALLOC, TRACE_DEBUG, "grabbing a new empty block: %p ... ", block);
}
}
bool GC::Markcompact::mark(void *obj, uintptr_t *from_ptr)
{
void *from = raw_tagged_ptr(*from_ptr);
// we should never be marking an object that's in the nursery here.
assert(is_tenure(from));
Data * d = Data::ptr_for(from);
switch(m_gc_phase)
{
case Marking: {
TRACE_PRINTF(TRACE_GC, TRACE_SPAM, "Marking %p -> %i %s\n", from, d->m_mark, d->m_mark ? "no-follow" : "follow");
if(d->m_mark)
return false;
m_dfs_marked++;
d->m_mark = true;
m_data_blocks++;
m_used += d->m_count + sizeof(Data);
Block * b = d->block();
if(b == NULL)
b = & m_pinned_block;
if(!b->m_mark)
{
b->m_mark = true;
b->m_in_use = 0;
}
b->m_in_use += d->m_count + sizeof(Data);
m_scan_list.push(d);
return false;
}
case Updating: {
void * to = forward.get(from);
TRACE_PRINTF(TRACE_GC, TRACE_SPAM, "Updating %p -> %p", from, to);
bool changed = (to != NULL);
if(changed)
{
m_dfs_updated++;
update_tagged_ptr(from_ptr, to);
d = Data::ptr_for(to);
}
TRACE_QUIET_PRINTF(TRACE_GC, TRACE_SPAM, ", d->m_mark = %i %s\n", d->m_mark, d->m_mark ? "follow" : "no-follow");
if(d->m_mark)
{
m_dfs_unmarked++;
d->m_mark = false;
m_scan_list.push(d);
}
return changed;
}
case Running:
case Compacting:
default:
assert(false && "Markcompact::mark should only be called when marking or updating");
return false;
}
}
void GC::Markcompact::collect()
{
m_gc_phase = Marking;
//switch pools
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Start GC, %" PRIu64 " bytes used in %" PRIu64 " data blocks, Begin Marking DFS\n", m_used, m_data_blocks);
m_used = 0;
m_data_blocks = 0;
DO_DEBUG {
for(std::deque<Chunk>::iterator c = m_chunks.begin(); c != m_chunks.end(); c++){
for(Block * b = c->begin(); b != c->end(); b = b->next()){
assert(!b->m_mark);
for(Data * d = b->begin(); d != b->end(); d = d->next())
assert(!d->m_mark);
}
}
}
m_dfs_marked = 0;
m_dfs_unmarked = 0;
m_dfs_updated = 0;
for(std::set<GCRoot*>::iterator it = m_roots.begin(); it != m_roots.end(); it++)
{
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Scan root %p\n", *it);
(*it)->scan();
}
while(!m_scan_list.empty()) {
Data * d = m_scan_list.top();
m_scan_list.pop();
scan(d);
}
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Marked %" PRIu64 " objects, Begin Compacting\n", m_dfs_marked);
m_gc_phase = Compacting;
forward.init(m_data_blocks); //big enough for all objects to move
//reclaim empty blocks right off the start
m_empty_blocks.clear();
for(std::deque<Chunk>::iterator c = m_chunks.begin(); c != m_chunks.end(); c++){
for(Block * b = c->begin(); b != c->end(); b = b->next()){
if(!b->m_mark){
DO_DEBUG
b->deadbeef();
b->m_next_alloc = 0;
b->m_in_use = 0;
m_empty_blocks.push_back(b);
}
}
}
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Found %u empty blocks\n", (unsigned)m_empty_blocks.size());
//set the current allocating block to an empty one
if(m_empty_blocks.empty())
alloc_chunk();
m_cur_small_block = m_cur_medium_block = m_empty_blocks.back();
m_empty_blocks.pop_back();
//compact blocks that have < 80% filled
uint64_t fragmented = 0;
uint64_t moved_bytes = 0;
uint64_t moved_blocks = 0;
uint64_t skipped = 0;
for(std::deque<Chunk>::iterator c = m_chunks.begin(); c != m_chunks.end(); c++)
{
for(Block * b = c->begin(); b != c->end(); b = b->next())
{
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Checking block %p:%p\n", &*c, b);
if(b->m_mark)
{
if(b->m_in_use < b->m_capacity*((double)FRAG_LIMIT/100))
{
for(Data * d = b->begin(); d != b->end(); d = d->next())
{
if(d->m_mark)
{
uint8_t * n = next(d->m_count, d->m_type, false);
memcpy(n, d->m_data, d->m_count);
forward.set(d->m_data, n);
moved_bytes += d->m_count + sizeof(Data);
moved_blocks++;
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Moved %p -> %p\n", d->m_data, n);
//set the mark bit so it gets traversed
Data::ptr_for(n)->m_mark = true;
}
}
b->m_next_alloc = 0;
b->m_in_use = 0;
}else{
skipped++;
fragmented += b->m_capacity - b->m_in_use;
}
b->m_mark = false;
}
}
}
//clear unused pinned objects
if(m_pinned_block.m_mark)
{
if(m_pinned_block.m_in_use < m_pinned_block.m_capacity*((double)FRAG_LIMIT/100))
{
std::vector<Data*> new_pinned_objs;
for(std::vector<Data*>::iterator i = m_pinned_objs.begin(); i != m_pinned_objs.end(); ++i)
{
if((*i)->m_mark)
new_pinned_objs.push_back(*i);
else
free(*i);
}
m_pinned_objs.swap(new_pinned_objs);
m_pinned_block.m_capacity = m_pinned_block.m_in_use;
}
m_pinned_block.m_mark = false;
}
m_gc_phase = Updating;
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Done compacting, %" PRIu64 " Data/%" PRIu64 " bytes moved, %" PRIu64 " Blocks/%" PRIu64 " bytes left fragmented, Begin Updating DFS\n", moved_blocks, moved_bytes, skipped, fragmented);
for(std::set<GCRoot*>::iterator it = m_roots.begin(); it != m_roots.end(); it++)
{
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Scan root %p\n", *it);
(*it)->scan();
}
while(!m_scan_list.empty()) {
Data * d = m_scan_list.top();
m_scan_list.pop();
scan(d);
}
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Updated %" PRIu64 " pointers, unmarked %" PRIu64 " objects, cleaning up\n", m_dfs_updated, m_dfs_unmarked);
assert(m_dfs_marked == m_dfs_unmarked);
DO_DEBUG {
for(std::deque<Chunk>::iterator c = m_chunks.begin(); c != m_chunks.end(); c++){
for(Block * b = c->begin(); b != c->end(); b = b->next()){
assert(!b->m_mark);
for(Data * d = b->begin(); d != b->end(); d = d->next())
assert(!d->m_mark);
}
}
}
//finishing up
forward.clear();
m_next_gc = std::max((1<<CHUNK_SIZE)*0.9, double(m_used) * GC_GROWTH_LIMIT);
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Sweeping CallableContext objects\n");
CallableContext::sweep();
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Done GC, %" PRIu64 " bytes used in %" PRIu64 " data blocks\n", m_used, m_data_blocks);
m_gc_phase = Running;
}
}
| 26.223684 | 222 | 0.626066 | stormbrew |
946f19f00cf4eab2d5a6005a896597dc4f44a60d | 6,775 | cpp | C++ | src/singletons/SettingsManager.cpp | nforro/chatterino2 | e9868fdd84bd5799b9689fc9d7ee4abed792ecec | [
"MIT"
] | null | null | null | src/singletons/SettingsManager.cpp | nforro/chatterino2 | e9868fdd84bd5799b9689fc9d7ee4abed792ecec | [
"MIT"
] | null | null | null | src/singletons/SettingsManager.cpp | nforro/chatterino2 | e9868fdd84bd5799b9689fc9d7ee4abed792ecec | [
"MIT"
] | null | null | null | #include "singletons/SettingsManager.hpp"
#include "Application.hpp"
#include "debug/Log.hpp"
#include "singletons/PathManager.hpp"
#include "singletons/ResourceManager.hpp"
#include "singletons/WindowManager.hpp"
namespace chatterino {
std::vector<std::weak_ptr<pajlada::Settings::ISettingData>> _settings;
void _actuallyRegisterSetting(std::weak_ptr<pajlada::Settings::ISettingData> setting)
{
_settings.push_back(setting);
}
SettingManager::SettingManager()
{
qDebug() << "init SettingManager";
this->wordFlagsListener.addSetting(this->showTimestamps);
this->wordFlagsListener.addSetting(this->showBadges);
this->wordFlagsListener.addSetting(this->enableBttvEmotes);
this->wordFlagsListener.addSetting(this->enableEmojis);
this->wordFlagsListener.addSetting(this->enableFfzEmotes);
this->wordFlagsListener.addSetting(this->enableTwitchEmotes);
this->wordFlagsListener.cb = [this](auto) {
this->updateWordTypeMask(); //
};
}
void SettingManager::initialize()
{
this->moderationActions.connect([this](auto, auto) { this->updateModerationActions(); });
this->timestampFormat.connect([](auto, auto) {
auto app = getApp();
app->windows->layoutChannelViews();
});
this->emoteScale.connect([](auto, auto) { getApp()->windows->forceLayoutChannelViews(); });
this->timestampFormat.connect([](auto, auto) { getApp()->windows->forceLayoutChannelViews(); });
this->alternateMessageBackground.connect(
[](auto, auto) { getApp()->windows->forceLayoutChannelViews(); });
this->separateMessages.connect(
[](auto, auto) { getApp()->windows->forceLayoutChannelViews(); });
this->collpseMessagesMinLines.connect(
[](auto, auto) { getApp()->windows->forceLayoutChannelViews(); });
}
MessageElement::Flags SettingManager::getWordFlags()
{
return this->wordFlags;
}
bool SettingManager::isIgnoredEmote(const QString &)
{
return false;
}
void SettingManager::load()
{
auto app = getApp();
QString settingsPath = app->paths->settingsDirectory + "/settings.json";
pajlada::Settings::SettingManager::load(qPrintable(settingsPath));
}
void SettingManager::updateWordTypeMask()
{
uint32_t newMaskUint = MessageElement::Text;
if (this->showTimestamps) {
newMaskUint |= MessageElement::Timestamp;
}
newMaskUint |=
enableTwitchEmotes ? MessageElement::TwitchEmoteImage : MessageElement::TwitchEmoteText;
newMaskUint |= enableFfzEmotes ? MessageElement::FfzEmoteImage : MessageElement::FfzEmoteText;
newMaskUint |=
enableBttvEmotes ? MessageElement::BttvEmoteImage : MessageElement::BttvEmoteText;
newMaskUint |= enableEmojis ? MessageElement::EmojiImage : MessageElement::EmojiText;
newMaskUint |= MessageElement::BitsAmount;
newMaskUint |= enableGifAnimations ? MessageElement::BitsAnimated : MessageElement::BitsStatic;
if (this->showBadges) {
newMaskUint |= MessageElement::Badges;
}
newMaskUint |= MessageElement::Username;
newMaskUint |= MessageElement::AlwaysShow;
newMaskUint |= MessageElement::Collapsed;
MessageElement::Flags newMask = static_cast<MessageElement::Flags>(newMaskUint);
if (newMask != this->wordFlags) {
this->wordFlags = newMask;
this->wordFlagsChanged.invoke();
}
}
void SettingManager::saveSnapshot()
{
rapidjson::Document *d = new rapidjson::Document(rapidjson::kObjectType);
rapidjson::Document::AllocatorType &a = d->GetAllocator();
for (const auto &weakSetting : _settings) {
auto setting = weakSetting.lock();
if (!setting) {
continue;
}
rapidjson::Value key(setting->getPath().c_str(), a);
rapidjson::Value val = setting->marshalInto(*d);
d->AddMember(key.Move(), val.Move(), a);
}
this->snapshot.reset(d);
Log("hehe: {}", pajlada::Settings::SettingManager::stringify(*d));
}
void SettingManager::recallSnapshot()
{
if (!this->snapshot) {
return;
}
const auto &snapshotObject = this->snapshot->GetObject();
for (const auto &weakSetting : _settings) {
auto setting = weakSetting.lock();
if (!setting) {
Log("Error stage 1 of loading");
continue;
}
const char *path = setting->getPath().c_str();
if (!snapshotObject.HasMember(path)) {
Log("Error stage 2 of loading");
continue;
}
setting->unmarshalValue(snapshotObject[path]);
}
}
std::vector<ModerationAction> SettingManager::getModerationActions() const
{
return this->_moderationActions;
}
void SettingManager::updateModerationActions()
{
auto app = getApp();
this->_moderationActions.clear();
static QRegularExpression newLineRegex("(\r\n?|\n)+");
static QRegularExpression replaceRegex("[!/.]");
static QRegularExpression timeoutRegex("^[./]timeout.* (\\d+)");
QStringList list = this->moderationActions.getValue().split(newLineRegex);
int multipleTimeouts = 0;
for (QString &str : list) {
if (timeoutRegex.match(str).hasMatch()) {
multipleTimeouts++;
if (multipleTimeouts > 1) {
break;
}
}
}
for (int i = 0; i < list.size(); i++) {
QString &str = list[i];
if (str.isEmpty()) {
continue;
}
auto timeoutMatch = timeoutRegex.match(str);
if (timeoutMatch.hasMatch()) {
if (multipleTimeouts > 1) {
QString line1;
QString line2;
int amount = timeoutMatch.captured(1).toInt();
if (amount < 60) {
line1 = QString::number(amount);
line2 = "s";
} else if (amount < 60 * 60) {
line1 = QString::number(amount / 60);
line2 = "m";
} else if (amount < 60 * 60 * 24) {
line1 = QString::number(amount / 60 / 60);
line2 = "h";
} else {
line1 = QString::number(amount / 60 / 60 / 24);
line2 = "d";
}
this->_moderationActions.emplace_back(line1, line2, str);
} else {
this->_moderationActions.emplace_back(app->resources->buttonTimeout, str);
}
} else if (str.startsWith("/ban ")) {
this->_moderationActions.emplace_back(app->resources->buttonBan, str);
} else {
QString xD = str;
xD.replace(replaceRegex, "");
this->_moderationActions.emplace_back(xD.mid(0, 2), xD.mid(2, 2), str);
}
}
}
} // namespace chatterino
| 29.714912 | 100 | 0.621993 | nforro |
20e161cb316498b0574394a4b65e75ff2bfbf59b | 10,838 | cpp | C++ | data/744.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/744.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/744.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | int Fdbtu
,ui//3
,RS
, xyWC , fiNac ,M , NFNo
,
Awep ,
J ,Kbl
,
yf, ccQ , FCrrd ,qfA0 ,
s13Xh ,g9,rYQA
,Z
,on , Vsy5Q, Hwc, AiG , qH
,//Eb
DH
,/*aqa*/ DU,lJZ//d
,pRlwI
, /*aI*/ tAP,FyD,NS ,d0OG
,Y3c
,
O1Q,
oyq,//
Va , yFufL
,
Hd
,
//zq
lqX,/*aRZ*/ iXv
,
xRV ,
BL6//
,DY ,EKsr,//qE
KZ,vLyB , fWeV,NmmZ, Ak
;void
f_f0 (){volatile int fAb /*i9Fl*/,
lE
//s
, WtfuH
, z8mh
,
ITx; Ak
= ITx +
fAb
+ lE/*z7ry*/+
WtfuH +z8mh
; { for
(int
i=1; i<1;++i) ;{if(true)
{ if
( true) if
(true )
{}else
return ;else
;
}
else
{
volatile int
YS ,pC,
q6uM ;
; if(
true )//J
//aXGJa
Fdbtu= q6uM+ YS+
pC;else ; }{return
; //T2
return ; {
}}
;
return ;
{
{{ } }{
int Lkjs;volatile int //A2
vQL,/*I*/ kti
, DS ; Lkjs =
DS
+
vQL
/*lk*/+kti ;;
//
}}}; /*P4e*/;
//k
} {volatile int NzofO ,
G5
/*77*/, CL, q ;
{{{
{}{
} }{ } }
{ volatile int
dZpxe
,Y2Z
;
ui = Y2Z +dZpxe ;
}
{
volatile int FB ,cv6m,
PCR,
dsYJ ;RS
=
dsYJ
+
FB+
cv6m//pv9
+PCR ; {//kt
{
}return
; {
}}} } {; {{ } if
(true ){{/**/} }else//9fo
{{
}}
{}{
{ }} ;
} { { }
} }
/*HJS*/
for/*ld*/ (int i=1;i<
2/*D*/ ;++i ) //
{
{
; ; } { ;for(int i=1
;i< 3 ;++i )
{
} }} if ( true)for(int i=1
;i<
4;++i/*zYT*/
)
{
{ return ; }for(int
i=1 ;
i<
5;++i )
{
{if
(
true)
{ /*U0cR*/;} else
; {}}if(true){volatile int vc ,
IC5XZo;xyWC=
IC5XZo + vc ;}
else
{for//CWFi
(int i=1;/*Wb*//*m*/i<6
;++i )
{ { };}}}} else fiNac
=q+ //Mjmu
NzofO + G5 +CL
;}{//KoeL
{ { int LC6;volatile int jRwJV//u2V
,O ; for(int i=1
;i<7 ;++i //YBGj
)
LC6=
O
+
jRwJV;return ; }{volatile int SEZs , FTnL,BgJ,
FO
,i7b//Otd
,/*a*/NR/*yu*/;{}{;
return ; ;}M=NR+SEZs+
FTnL ; {
}if (true) NFNo=BgJ
+ FO
+ i7b; else{ ;
}} //1
}{return ;//vy
{ for(int //C24
//HGK
i=1;
i<
8;++i ) return
; { }
}{ { } {
}/*i*/{}
}}return
; /*MT*/}return ;
}void
f_f1//ZU
(){
;{//
;return ;
return
;{return ;if
( true )
{{
}}
else{{
}}
{if
(
true ) return ;else { }if
(true); else {}} }
{volatile int N /*etzs*/
,Tw //DG
//
,
lk,
Q5pi//D3
/*0Cf*/,gM1m ;//0C
if ( true
) {/*V*/ volatile int
JIW ,
/*DC9*/ZB ,
UtL;//
Awep
= UtL +JIW + ZB;} //o
else J
=//am
gM1m+N/*4z*///
+Tw +lk +
Q5pi;{ { ;{} //s
}{ } { if(true){}else if
(true
) {}
else{//1a1
}
return ;
}}
{ ; {//UY
for (int i=1;i<
9 ;++i) ;} {}//
{ }} if/*Q*///u
(true)for (int /*H2J*/
i=1
;
i<10
;++i )
{//ttj
volatile int n3N
, dC
; Kbl
= dC + n3N;/*Hnh*/if
/*urHR*/(true
) { {}}else
{}
}
else {//NdM
{if ( true ){volatile int/*E*/ Wbr8; yf =Wbr8 ; }else {}
}} {//dJ
{} }for (int i=1;
i<
11;++i
){{
volatile int lN
,
DqO
, l;{ volatile int
MkKH
,
Ll
; if(true )ccQ
=
Ll
+MkKH /*wKg*/;else {//u
}//
}return ;
FCrrd=//pYS
l+lN+ DqO ;
} } }} {{int I7; volatile int H8zL,
QB2KD5D
,/*X*///Q
ZS8
,
WT4t //t
; {{ return
; }}
;I7
= WT4t/*b*/+H8zL +QB2KD5D//lrESx6
+ZS8 ;}if
(
true )
{
volatile int
DwC ,cdQ/**//*t*//*Xy*/,
e89 ,O6DD;;{int NI ;
volatile int EN ,
//1MZI
fYK
,TdOh //
, AF ,nx, HE,
UgNBa ;
NI/*00W2*/= UgNBa/*Zy*/+EN +fYK;
qfA0=TdOh+AF +nx+ HE;}s13Xh=O6DD+
DwC
+ cdQ
+ e89
;
}else for
(int
i=1/*Y*/;i< 12;++i )
{;{ ;
for(int
i=1 ; i<13
;++i
) {
{ }/*q7*/ }
return ; }{ if (
true )
;else ;
}} { volatile int w4
, eI5Qgv
, uN,w85
, IZ,bfNw
;
for
(int
i=1
; /*A6EsBf*/i<
14;++i) g9=bfNw +
w4 + eI5Qgv;/**/ rYQA=
//TAR8
uN
+
w85+IZ; {//Nw
{int S
;volatile int//V06
re
,upO ; S =
upO
+//e
re; return/*fiFBf*/ ; {;
}{
}} { }for/*pWHL*/ (int i=1;i<
15;++i
)
for(int i=1
; i<
16
;++i)
{
//Qq
{} {
} { /*p1r*/} //
}}} ;
{ //oL
int
bmu
;
volatile int HN,
QZ , HaHiNj , Haf , nt ;bmu= nt+ HN + QZ+
HaHiNj
+
Haf //sk
//4
;{ //i6
{//jhc
} {
{
volatile int VCl; Z
= VCl
;
return ;//GA
; }
;
}
}
{ /*cB*/{;//
}}}}{ int tD ;volatile int
i,
d ,nO7,
rXjcLRi ,dYXu7n
, vQFK, GzN//9
,ULh,J5eI
,
H1p,/*Q*/W2J
; if/*ASw*/
( true)
if( true )
for(int i=1;i< 17//nFB77
;++i
){
;{
{
return
;
; ;}}
return
; }
else{if ( true
)
/*4*/if(true )//KtC
; else
for//Z
(int i=1
; i< 18;++i
//0
)
;
else//6
{
for(int i=1
; i< 19
;++i
){ volatile int
TM ,En9 ;
on= En9 + TM;} }
//Oxm6
if(
true)for(int i=1; i<20 ;++i ) { volatile int IOYb
,/*sbc4*/ gYAQ , N7
, Gj
,
G1S,AlES ;Vsy5Q
= AlES +IOYb +gYAQ
;{
if (true) { } else return ; }{ }
{
} Hwc=N7 +
Gj + G1S ; }
else
; if
(
true
){if (true ) {
{ /*2*/{ } } for(int i=1; i</**/21 ;++i) ;} else{ return ;{
;}}return ;/**/{
} {
}
}
else {//
{{} {int P4tX; volatile int//
BY, x
; P4tX /**/=x +BY;} }
for(int i=1
;
i< 22;++i ) {
{ ;} } if(true){} else
for
(int i=1
; i< 23;++i
) { /*QVp*/}
}} else
{;/*Sv*/ return ; }{
int
/*4ij*/
Ny ;/**/volatile int ZY0,
Q
,/*Cw9*/br, EXD6k ,
YcpmZ ; for (int i=1 ;
i< 24 ;++i)for (int i=1 ;
i< 25;++i) ;return ;return
;Ny
=
YcpmZ
+ ZY0+Q
+ br
+EXD6k
; }{ return ;return ;}
tD
=W2J+i+ d + nO7
+
rXjcLRi; AiG=
dYXu7n+vQFK+ GzN
+
ULh + J5eI+H1p ;} ; //OOs
return ;//0zSnmQ3
} void
f_f2
()
{volatile int//hm
ABA ,utE /*H0*/ , Sul , YyJF,
PAJlI/*sju*/; { volatile int
tP8 ,yM/*4V*/, roTdX4, qZ1M ;qH=qZ1M +
tP8
+yM+roTdX4
;
if( true
)
{int VE5
; volatile int y1R
,
Ehr ,
VlF ;
if
(true
)
return /*t*/ ;else
if
( true)
for(int i=1;i<26;++i) {
{
;}if(true
)/*H*/return
;else
{ {
volatile int//tiH92
MAv//WxS
,qtQB , vxfKqKaj
,Zh70 //9V
; DH =Zh70+MAv//pB
;DU=qtQB
+vxfKqKaj;
} }
}else return ; VE5 =VlF +y1R/*Ze*/+Ehr;
;}else if
(true) { { ; }/*clMT6*/{{{ }} {
{//W
} }
/*rn*/{ }{ } }; }else
;{
;{
volatile int IO, bN ,ND;{ } if(true) {{for(int i=1;i< /*exp*/
27 ;++i ) { //
} } }else { } for(int i=1 ;
i</*Q*/28
;++i){ }{
if (
true)
{}else{ };
} for(int i=1
;
i<
29
;++i )lJZ =ND//l
+IO
+//8V
bN/*vx*/; }/*FB*/
{{{if(true
) {}else{ }{ }} {/*Yhx*/if (
true
) ; else if( true){} else if(
true)/*8*/ { } else{ volatile int
IdQzB /*V*/
;
if (true)pRlwI
=IdQzB
;else return ;}
} }{{}}} };/*bHz*/}return
;
/**/{
volatile int ooY ,
Smpa,
egm,Qn
, VBmVo //9
;
return ;{ int //eVLD
Yz;volatile int//
hMr
,F5 , PFF ,Sg ; {//A1
volatile int
Fb,uxjqz
,
UE2Lh,
XmU15;return//
;/*9*/ /**/tAP
= XmU15
+Fb
+uxjqz
+UE2Lh ;
return ; }
Yz//aXJ
= Sg+hMr+ F5
+ PFF; { for
(int i=1 ; i<30 ;++i ){ int
l8; volatile int ZLOR
,k; /*uA*/if/*lOI*/(//ESPa
true//D
) {//8
if(
true )for(int //Y
i=1//g5r
;i< 31 ;++i )return ;else
{} }else
l8=k+ ZLOR ;
}
}
{if
(
true) {{}
} else
for(int i=1 ;
i<
32;++i
){
}
}} for (int i=1 ;i<33 ;++i ) FyD=VBmVo +
ooY
+ Smpa /*P*/+
egm
+Qn/*GutW*///
; ;
}if(true)
NS=
PAJlI
+ ABA
//gX
//8
+utE
+
Sul +
YyJF ; //e4
/*P*/else return ;
return ; }
int main(){for
(int
i=1 ; i<
34;++i
){{{//BlOZ
;}
; } { volatile int
hP4T ,
MaG,vJk ,//Tg2
Ay ; d0OG =Ay +hP4T+ /**/MaG+
vJk;
;}{{{{}{
}
}if( true )
{
; if /**/(true) { } else return//O
807505154/*sG*///HC
; }
else if ( true ) {} else {}
}return 1339415509 ;
{{
{}
}
}{volatile int pAM/*NhV*/,oNY0P
,cK, y53
;
if
(true)Y3c
= y53 + pAM+ oNY0P/*k6*/ +
cK ;else return 1465670663/*TIY*/;
/*Xsury*/{/**/ } } }{{if
(/*g8*/true)
{ for
(int i=1
;i< 35;++i){}}else return 1660731687;}{
{{} } }} for(int i=1 ;
i<36;++i
){for
(int i=1;
i< 37;++i){{/**/{if(true ){ }else {}//
//4
{}}}{ }}
for
(int i=1;i<38
;++i) { {
{} } }}};if ( true)
{volatile int
em7/*dy*/,//HvJ
Myaz,
oLv,k9I
; if (true
)
O1Q= k9I
+ em7+Myaz+ oLv; else if ( /*h9*/true) /*5a6DKQ*/ if (true)
/*SwGcn*/{ return
1092554760
;/*EE*/{
volatile int HW5, Vp6Ob //3
, EEsu ,CQ8v
;
oyq= CQ8v
+
HW5 +
Vp6Ob+ EEsu;/*y*/}{
{ {} { }{ }
}}//BK
} else{volatile int
w,
Vv,
LV;/*d*/{ volatile int
kttXN
,
X94
; ; //hd
{{if(//YMX
true/*xv*/);else
if (
true )
{} else
if (true//W
)return 1229986376
;else
{}} }
;{volatile int hik0u,//q
BH;
for (int i=1 ;i<39 ;++i)
{ }Va = //yQi08
/**/BH+hik0u ;if(/*YN*/
true ) { }else return 777290998 ;
}if( true)return/*LuwEb0*/ 241275314; else
yFufL=X94
+ kttXN
;} { {//
return 1231160413; }//z
} {{
{ if(
true ) {
} else { } /**/return 975929238; }} }Hd
=LV+w
+
Vv
;
/*p*/
}else { {{}
}for
//Y
(int i=1 ;/*I6*/i< 40;++i )
{; {}/*2*/{
{ }}{ }{
/*n1*/}}{
volatile int oCUL, TtI9
,
R4
, No //m
;lqX //v
=No +
oCUL +
TtI9 + R4
;{ if
( true )if
/*RZsb*///dk
(
true) { } else for(int i=1;i<
41
;++i ){ }else
{
}
if /*M*/( true) { }
else {}} }
}
{return 2044098310/*NUY*/;/*7*/{
{{
}
;{//
} }//0Z
} ;} for(int
i=1
; i<42
;++i ) {
volatile int c2BU, c8,G, BFIB,MiR6
,
ZAH
,L7S,
Tx,vf2Zm ; iXv
=vf2Zm+c2BU
+c8 +
G
+
BFIB ;
{
{ }/**/}xRV
= MiR6/*1Q*/+//A
ZAH//T
+L7S+Tx ;
}{ //GsCz4
volatile int NCS,
mi ,MxJN /*FiTg*/ , CTL;
BL6= //iF
CTL+ NCS+mi +
MxJN
;
{ for(int i=1
; i< 43;++i )
; for (int i=1 ; i<44
;++i ){{
}
{} }} } } else
; {//73zh
for (int /*g*/i=1;i<
45
;++i
){{return
1009155463
;}
return 971526511
;{ {int
sflT;volatile int//xoW
sA, C8uLbh6 , F; sflT= F+ /*Nhy*/
sA
+C8uLbh6//
/*C2*/;} }
{for (int
i=1 ; i< 46 //TX
;++i
)
; //cnL
}}{
{
{
for
(int i=1//D
;i<
47;++i
)
{} }
}
;}/*hG*/return 54816217; }/*Nq*/return 2012331392
//Zd
; for
(int i=1
; i< 48
;++i) {
volatile int UsRn77
,
h3t2
,
wd2wML, ghgP//to
;
{ int lsK; volatile int qE, PiK,d9B ,hhq ; for(int i=1 ;
i<49 ;++i )if (/*XA2p*/true) {
volatile int
Pg4 , //p5
grqe;
return 741232928 ;DY = grqe +
Pg4; }else {
volatile int o , IKD
;{ }if
(
true) {
{//
} }
else EKsr
=
IKD
+
o//58
; };
lsK =hhq
+qE+PiK+ d9B;}if (true )
{{
volatile int Zvc,
uqH
;KZ//75Ps
=uqH+Zvc ; ; } for
(int i=1 ;
i< 50 ;++i
)
{{{}}} if/*q*/(
true ) for(int
i=1 ; i<
51 ;++i )
if( true
){ if (true ) { int hya ;
volatile int hcf,
M0//m
;{}{}/*wbL*/ hya
=M0/*2*///sYe
//gs
+ //P
hcf ; } else {
}{ } } else /*lk*/{ ;
} else { for(int i=1;//aUNd
i< 52;++i
){;
{//CkI
{ }
}
} { } }
{
{/*n*/return 948118808
//G
;
}} //yH
}else vLyB=ghgP+UsRn77
+ h3t2/*I*/ +wd2wML
;{ /*Jp*/{{ volatile int kqi
;//ty7J
for
(int i=1
;i<53;++i)fWeV=kqi;}{ }}{ { { }if(true//Q
)
for(int
i=1;i<54 ;++i){}
else{ } }return 938455650 ;/*gp*/}/*vtF*/ { {
}} } {volatile int
XfyN
/*kXq7*//*9*/,/*LC*/LP , k4, p;/*tE3Z*/{return
924800087 ;} if ( true)return 2049825890
;else {{}//jHC
}if (true
) for
(int i=1 ; i< 55
;++i)for(int i=1;i<
56 /*d9Z3*/;++i
) NmmZ=
p+
//7
XfyN+
LP+ k4
;
else{
return 1563165705/*r9*/;}{{
}
}}} }
| 10.411143 | 64 | 0.453128 | TianyiChen |
20e2d1a736f9b10866b71d51c0d8d221cc7da473 | 331 | cc | C++ | exercises/ESEMPI_BASE/esempio_cin3.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | 3 | 2021-11-05T16:25:50.000Z | 2022-02-10T14:06:00.000Z | exercises/ESEMPI_BASE/esempio_cin3.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | null | null | null | exercises/ESEMPI_BASE/esempio_cin3.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | 2 | 2018-10-31T14:53:40.000Z | 2020-01-09T22:34:37.000Z | using namespace std;
#include <iostream>
int main ()
{
char x;
double y;
int z;
cout << "dammi in sequenza un carattere, un intero ed un reale" << endl;
cin >> x;
cin >> z;
cin >> y;
cout << "x = " << x << ", z = " << z << ", y = " << y << endl;
return 0;
}
//NB: cosa succede se digito "prompt> A 3.5 3" ?
| 17.421053 | 75 | 0.513595 | mfranzil |
20e424f0ec449846174a9ce7873e219f0b96a115 | 1,737 | hh | C++ | include/Cc/Instruction.hh | Stalker2106x/Mini8BVM | d384ad30f6c870b32aa8e4b9d00705a1406779ad | [
"MIT"
] | 1 | 2021-11-30T06:52:58.000Z | 2021-11-30T06:52:58.000Z | include/Cc/Instruction.hh | Stalker2106x/Mini8BVM | d384ad30f6c870b32aa8e4b9d00705a1406779ad | [
"MIT"
] | null | null | null | include/Cc/Instruction.hh | Stalker2106x/Mini8BVM | d384ad30f6c870b32aa8e4b9d00705a1406779ad | [
"MIT"
] | null | null | null | #ifndef INSTRUCTION_HH_
#define INSTRUCTION_HH_
#include <string>
#include <bitset>
#include <algorithm>
#include "Cc/InstructionDef.hh"
#include "config.h"
#include "utils.hh"
template <wordSizeType CodeSize, wordSizeType OperandSize>
class Instruction
{
public:
Instruction(InstructionDef definition, std::string asmCode, size_t sep)
: _definition(definition)
{
try {
if (_definition.operandCount > 0)
{
if (sep == std::string::npos)
{
throw (std::runtime_error("no separator ' ' found"));
}
asmCode = asmCode.substr(sep+1, asmCode.length());
if (!asmCode.empty())
{
_operands.push_back(std::bitset<OperandSize>(int128FromString(asmCode)));
}
if (_operands.size() < _definition.operandCount)
{
throw (std::runtime_error("expected "+std::to_string(_definition.operandCount)+" operands, got " +std::to_string(_operands.size())));
}
}
} catch (std::runtime_error e) {
throw (std::runtime_error("Syntax error: "+std::string(e.what())));
}
}
std::string to_string()
{
std::string output;
output += _definition.code.to_string();
for (size_t i = 0; i < _operands.size(); i++)
{
output += _operands[i].to_string();
}
if (_definition.operandCount == 0) output += std::string(OperandSize, '0'); //Pad value
return (output);
}
private:
InstructionDef _definition;
std::vector<std::bitset<OperandSize>> _operands;
};
#endif /* INSTRUCTION_HH_ */ | 29.948276 | 153 | 0.558434 | Stalker2106x |
20e729ea133da29095b458fb36ee47e1c4794e58 | 792 | cpp | C++ | tests/TestConnection.cpp | qingqibing/mqttcpp | 941162574dce09e4b109efded39331ac34d9f79a | [
"BSD-3-Clause"
] | 37 | 2015-01-07T08:21:22.000Z | 2021-12-17T12:06:12.000Z | tests/TestConnection.cpp | qingqibing/mqttcpp | 941162574dce09e4b109efded39331ac34d9f79a | [
"BSD-3-Clause"
] | 4 | 2016-04-14T21:45:55.000Z | 2020-10-05T07:54:58.000Z | tests/TestConnection.cpp | qingqibing/mqttcpp | 941162574dce09e4b109efded39331ac34d9f79a | [
"BSD-3-Clause"
] | 18 | 2015-04-02T17:18:29.000Z | 2021-03-31T10:13:17.000Z | #include "TestConnection.hpp"
#include "Decerealiser.hpp"
using namespace std;
using namespace gsl;
void TestConnection::newMessage(span<const ubyte> bytes) {
switch(getMessageType(bytes)) {
case MqttType::CONNACK:
connected = true;
connectionCode = MqttConnack::Code::ACCEPTED;
break;
case MqttType::PUBLISH:
{
Decerealiser dec{bytes};
const auto hdr = dec.create<MqttFixedHeader>();
dec.reset();
const auto msg = dec.create<MqttPublish>(hdr);
payloads.emplace_back(msg.payload.begin(), msg.payload.end());
}
break;
default:
break;
}
lastMsg = Payload(bytes.begin(), bytes.end());
}
void TestConnection::disconnect() {
connected = false;
}
| 22.628571 | 74 | 0.609848 | qingqibing |
20e87cbc4eef81e118a052d281aba838728bb868 | 500 | hpp | C++ | source/Minesweeper.hpp | rincew1nd/Minesweeper-Switch | 6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467 | [
"MIT"
] | 8 | 2018-06-27T00:34:11.000Z | 2018-09-07T06:56:20.000Z | source/Minesweeper.hpp | rincew1nd/Minesweeper-Switch | 6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467 | [
"MIT"
] | null | null | null | source/Minesweeper.hpp | rincew1nd/Minesweeper-Switch | 6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467 | [
"MIT"
] | 2 | 2018-06-28T03:02:07.000Z | 2019-01-26T06:02:17.000Z | #pragma once
#include <switch.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "Engine/Defaults.hpp"
#include "Engine/Input.hpp"
#include "Scenes/GameScene.hpp"
class Minesweeper
{
public:
Minesweeper();
void Start();
private:
bool InitSDL();
void InitGame();
void DeinitSDL();
SDL_Window *_window;
SDL_Renderer *_renderer;
Input* _input;
GameScene* _gameScene;
Resources* _resources;
}; | 17.857143 | 32 | 0.6 | rincew1nd |
20f09bdb0db7add4d0b0d033fb7af3e5ae9f37d5 | 2,414 | cpp | C++ | game/scripting.cpp | NixonSiagian/samp-client | 7a10dfeddc806e199688c645b12f3bf37eaa4f61 | [
"FSFAP"
] | null | null | null | game/scripting.cpp | NixonSiagian/samp-client | 7a10dfeddc806e199688c645b12f3bf37eaa4f61 | [
"FSFAP"
] | null | null | null | game/scripting.cpp | NixonSiagian/samp-client | 7a10dfeddc806e199688c645b12f3bf37eaa4f61 | [
"FSFAP"
] | null | null | null | #include "../main.h"
#include "scripting.h"
#include "../chatwindow.h"
extern CChatWindow *pChatWindow;
GAME_SCRIPT_THREAD* gst;
char ScriptBuf[0xFF];
uintptr_t *pdwParamVars[18];
bool bExceptionDisplayed = false;
uint8_t ExecuteScriptBuf()
{
gst->dwScriptIP = (uintptr_t)ScriptBuf;
(( void (*)(GAME_SCRIPT_THREAD*))(g_libGTASA+0x2E1D2C+1))(gst);
return gst->condResult;
}
int ScriptCommand(const SCRIPT_COMMAND *pScriptCommand, ...)
{
va_list ap;
const char* p = pScriptCommand->Params;
va_start(ap, pScriptCommand);
memcpy(&ScriptBuf, &pScriptCommand->OpCode, 2);
int buf_pos = 2;
uint16_t var_pos = 0;
for(int i = 0; i < 18; i++)
gst->dwLocalVar[i] = 0;
while(*p)
{
switch(*p)
{
case 'i':
{
int i = va_arg(ap, int);
ScriptBuf[buf_pos] = 0x01;
buf_pos++;
memcpy(&ScriptBuf[buf_pos], &i, 4);
buf_pos += 4;
break;
}
case 'f':
{
float f = (float)va_arg(ap, double);
ScriptBuf[buf_pos] = 0x06;
buf_pos++;
memcpy(&ScriptBuf[buf_pos], &f, 4);
buf_pos += 4;
break;
}
case 'v':
{
uint32_t *v = va_arg(ap, uint32_t*);
ScriptBuf[buf_pos] = 0x03;
buf_pos++;
pdwParamVars[var_pos] = v;
gst->dwLocalVar[var_pos] = *v;
memcpy(&ScriptBuf[buf_pos], &var_pos, 2);
buf_pos += 2;
var_pos++;
break;
}
case 's': // If string... Updated 13th Jan 06.. (kyeman) SA string support
{
char* sz = va_arg(ap, char*);
unsigned char aLen = strlen(sz);
ScriptBuf[buf_pos] = 0x0E;
buf_pos++;
ScriptBuf[buf_pos] = aLen;
buf_pos++;
memcpy(&ScriptBuf[buf_pos],sz,aLen);
buf_pos += aLen;
break;
}
case 'z': // If the params need zero-terminating...
{
ScriptBuf[buf_pos] = 0x00;
buf_pos++;
break;
}
default:
{
return 0;
}
}
++p;
}
va_end(ap);
int result =0;
try {
result = ExecuteScriptBuf();
if (var_pos) // if we've used a variable...
{
for (int i=0; i<var_pos; i++) // For every passed variable...
{
*pdwParamVars[i] = gst->dwLocalVar[i]; // Retrieve variable from local var.
}
}
} catch(...) {
if(pChatWindow && !bExceptionDisplayed) {
pChatWindow->AddDebugMessage("Warning: error using opcode: 0x%X",pScriptCommand->OpCode);
bExceptionDisplayed = true;
}
}
return result;
}
void InitScripting()
{
gst = new GAME_SCRIPT_THREAD;
memset(gst, 0, sizeof(GAME_SCRIPT_THREAD));
} | 20.285714 | 92 | 0.612262 | NixonSiagian |
20f153b0a03d5461f0dd2af8abc4d9eb0a66d0f3 | 1,005 | cpp | C++ | 3.15/src/ca/client/baseNMIU.cpp | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | 3.15/src/ca/client/baseNMIU.cpp | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | 3.15/src/ca/client/baseNMIU.cpp | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"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 Versions 3.13.7
* and higher are distributed subject to a Software License Agreement found
* in file LICENSE that is included with this distribution.
\*************************************************************************/
/*
*
* L O S A L A M O S
* Los Alamos National Laboratory
* Los Alamos, New Mexico 87545
*
* Copyright, the Regents of the University of California.
*
* Author: Jeff Hill
*/
#define epicsAssertAuthor "Jeff Hill johill@lanl.gov"
#include "iocinf.h"
#include "nciu.h"
#include "netIO.h"
baseNMIU::~baseNMIU ()
{
}
void baseNMIU::forceSubscriptionUpdate (
epicsGuard < epicsMutex > &, nciu & )
{
}
| 25.125 | 75 | 0.567164 | A2-Collaboration |
20f275ff482d7073195d075c374e4a0969993714 | 2,639 | cpp | C++ | src/operators/kernel/arm/sigmoid_kernel.cpp | Ewenwan/paddle-mobile | 92491026748901143968d782b058d0af29ecbed7 | [
"Apache-2.0"
] | 1 | 2018-09-15T08:58:45.000Z | 2018-09-15T08:58:45.000Z | src/operators/kernel/arm/sigmoid_kernel.cpp | Ewenwan/paddle-mobile | 92491026748901143968d782b058d0af29ecbed7 | [
"Apache-2.0"
] | null | null | null | src/operators/kernel/arm/sigmoid_kernel.cpp | Ewenwan/paddle-mobile | 92491026748901143968d782b058d0af29ecbed7 | [
"Apache-2.0"
] | 2 | 2019-04-19T01:00:55.000Z | 2019-06-03T05:34:21.000Z | /* Copyright (c) 2018 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. */
#ifdef SIGMOID_OP
#include "../sigmoid_kernel.h"
#if __ARM_NEON
#include "../../math/math_func_neon.h"
#endif
namespace paddle_mobile {
namespace operators {
using framework::DDim;
using framework::Tensor;
void sigmoid(const Tensor *X, Tensor *Y) {
#if __ARM_NEON
const float *input = X->data<float>();
float *output = Y->mutable_data<float>();
const DDim &dDim = X->dims();
int axis_index = 1;
if (dDim.size() < 4) {
axis_index = 0;
}
DDim outer_ddim =
paddle_mobile::framework::slice_ddim(dDim, 0, axis_index + 1);
DDim inner_ddim =
paddle_mobile::framework::slice_ddim(dDim, axis_index + 1, dDim.size());
int out_size = paddle_mobile::framework::product(outer_ddim);
int inner_size = paddle_mobile::framework::product(inner_ddim);
DLOG << "outsize=" << out_size;
DLOG << "innersize=" << inner_size;
#pragma omp parallel for
for (int i = 0; i < out_size; ++i) {
const float *input_outer_ptr = input + i * inner_size;
float *output_outer_ptr = output + i * inner_size;
int nn = inner_size >> 2;
int remain = inner_size - (nn << 2);
float32x4_t _one = vdupq_n_f32(1.f);
for (; nn > 0; nn--) {
float32x4_t data = vld1q_f32(input_outer_ptr);
data = vnegq_f32(data);
data = exp_ps(data);
data = vaddq_f32(data, _one);
float32x4_t out_data = vrecpeq_f32(data);
out_data = vmulq_f32(vrecpsq_f32(data, out_data), out_data);
vst1q_f32(output_outer_ptr, out_data);
input_outer_ptr += 4;
output_outer_ptr += 4;
}
for (; remain > 0; remain--) {
*output_outer_ptr = 1.f / (1.f + exp(-*input_outer_ptr));
output_outer_ptr++;
input_outer_ptr++;
}
}
#endif
}
template <>
void SigmoidKernel<CPU, float>::Compute(const SigmoidParam ¶m) const {
const Tensor *in_x = param.InputX();
Tensor *out = param.Out();
auto x_dims = in_x->dims();
out->Resize(x_dims);
sigmoid(in_x, out);
}
template class SigmoidKernel<CPU, float>;
} // namespace operators
} // namespace paddle_mobile
#endif
| 29.988636 | 78 | 0.683971 | Ewenwan |
20f46db2fd4df5330804939d7b39154c4aa301ee | 1,293 | cpp | C++ | libs/libplatform/MouseGrabber.cpp | ps-group/modern-gl-samples | 53e075ec21418597b37c71c895111c0c77cab72b | [
"MIT"
] | 1 | 2017-06-20T06:56:57.000Z | 2017-06-20T06:56:57.000Z | libs/libplatform/MouseGrabber.cpp | ps-group/modern-gl-samples | 53e075ec21418597b37c71c895111c0c77cab72b | [
"MIT"
] | null | null | null | libs/libplatform/MouseGrabber.cpp | ps-group/modern-gl-samples | 53e075ec21418597b37c71c895111c0c77cab72b | [
"MIT"
] | null | null | null | #include "MouseGrabber.h"
#include <glm/vec2.hpp>
#if 0
namespace ps
{
MouseGrabber::MouseGrabber(SDL_Window& window)
: m_windowRef(window)
{
// Включаем режим спрятанного курсора.
SDL_SetRelativeMouseMode(SDL_TRUE);
}
bool MouseGrabber::OnMouseMove(const SDL_MouseMotionEvent &event)
{
const glm::ivec2 delta = { event.xrel, event.yrel };
bool filtered = false;
// Проверяем, является ли событие автосгенерированным
// из-за предыдущего программного перемещения мыши.
auto it = std::find(m_blacklist.begin(), m_blacklist.end(), delta);
if (it != m_blacklist.end())
{
m_blacklist.erase(it);
filtered = true;
}
else
{
WarpMouse();
}
return filtered;
}
void MouseGrabber::WarpMouse()
{
// Помещаем курсор в центр.
const glm::ivec2 windowCenter = GetWindowSize(m_windowRef) / 2;
SDL_WarpMouseInWindow(&m_windowRef, windowCenter.x, windowCenter.y);
// После перемещения возникает событие перемещения мыши.
// Мы можем предсказать параметры события и добавить их в чёрный список.
glm::ivec2 mousePos;
SDL_GetMouseState(&mousePos.x, &mousePos.y);
const glm::ivec2 reflectedPos = windowCenter - mousePos;
m_blacklist.push_back(reflectedPos);
}
} // namespace ps
#endif
| 23.944444 | 76 | 0.690642 | ps-group |
20f5633acd312d33282cbe15a1bc365c928414ec | 13,246 | cpp | C++ | src/examples/scene_factory.cpp | li-plus/tinypt | 6e9e3992dbc91ce8bd18bb812661ecb116ca1af8 | [
"MIT"
] | 3 | 2021-09-23T03:34:09.000Z | 2021-09-24T05:47:56.000Z | src/examples/scene_factory.cpp | li-plus/path-tracing | 6e9e3992dbc91ce8bd18bb812661ecb116ca1af8 | [
"MIT"
] | null | null | null | src/examples/scene_factory.cpp | li-plus/path-tracing | 6e9e3992dbc91ce8bd18bb812661ecb116ca1af8 | [
"MIT"
] | null | null | null | #include "scene_factory.h"
SceneFactory::SceneFactory() {
register_scene_builder("cornell_sphere", [] { return make_cornell_sphere(); });
register_scene_builder("cornell_box", [] { return make_cornell_box(); });
register_scene_builder("breakfast_room", [] { return make_breakfast_room(); });
register_scene_builder("living_room", [] { return make_living_room(); });
register_scene_builder("fireplace_room", [] { return make_fireplace_room(); });
register_scene_builder("rungholt", [] { return make_rungholt(); });
register_scene_builder("dabrovic_sponza", [] { return make_dabrovic_sponza(); });
register_scene_builder("salle_de_bain", [] { return make_salle_de_bain(); });
register_scene_builder("debug", [] { return make_debug(); });
register_scene_builder("debug2", [] { return make_debug2(); });
}
void SceneFactory::register_scene_builder(const std::string &name, std::function<tinypt::Scene()> scene_builder) {
_scene_builders[name] = std::move(scene_builder);
}
tinypt::Scene SceneFactory::make_scene(const std::string &name) const {
auto it = _scene_builders.find(name);
if (it == _scene_builders.end()) {
throw std::invalid_argument("scene not found: " + name);
}
return it->second();
}
tinypt::Scene SceneFactory::make_cornell_box() {
auto mesh = tinypt::TriangleMesh::from_obj("../resource/CornellBox/CornellBox-Original.obj");
tinypt::Camera camera;
camera.set_location({0, -3.5, 1});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {90, 0, 0}, true).matrix());
camera.set_resolution(1024, 1024);
camera.set_fov(tinypt::radians(42));
tinypt::Scene scene(camera, {mesh});
return scene;
}
tinypt::Scene SceneFactory::make_cornell_sphere() {
float x1 = 1, y1 = -170, z1 = 0;
float x2 = 99, y2 = 0, z2 = 81.6;
float xm = (x1 + x2) / 2, ym = (y1 + y2) / 2, zm = (z1 + z2) / 2;
float xs = x2 - x1, ys = y2 - y1, zs = z2 - z1;
auto left = std::make_shared<tinypt::Rectangle>();
left->set_location({x1, ym, zm});
left->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {0, 90, 0}, true).matrix());
left->set_dimension({zs, ys});
left->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .25, .25))));
auto right = std::make_shared<tinypt::Rectangle>();
right->set_location({x2, ym, zm});
right->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {0, 90, 0}, true).matrix());
right->set_dimension({zs, ys});
right->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.25, .25, .75))));
auto back = std::make_shared<tinypt::Rectangle>();
back->set_location({xm, y2, zm});
back->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {90, 0, 0}, true).matrix());
back->set_dimension({xs, zs});
back->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .75, .75))));
auto bottom = std::make_shared<tinypt::Rectangle>();
bottom->set_location({xm, ym, z1});
bottom->set_dimension({xs, ys});
bottom->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .75, .75))));
auto top = std::make_shared<tinypt::Rectangle>();
top->set_location({xm, ym, z2});
top->set_dimension({xs, ys});
top->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .75, .75))));
auto mirror_sphere = std::make_shared<tinypt::Sphere>();
mirror_sphere->set_location({27, -47, 16.5});
mirror_sphere->set_radius(16.5);
mirror_sphere->set_material(tinypt::Material(std::make_shared<tinypt::Metal>(tinypt::Vec3f(.999, .999, .999))));
auto glass_sphere = std::make_shared<tinypt::Sphere>();
glass_sphere->set_location({73, -78, 16.5});
glass_sphere->set_radius(16.5);
glass_sphere->set_material(
tinypt::Material(std::make_shared<tinypt::Dielectric>(tinypt::Vec3f(.999, .999, .999), 1.5)));
auto light = std::make_shared<tinypt::Circle>();
light->set_radius(18);
light->set_location({50, -81.6, 81.6 - 0.01});
light->set_material(
tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(0, 0, 0)), tinypt::Vec3f(12, 12, 12)));
// camera
auto w = tinypt::Vec3f(0, -1, 0.042612).normalized();
auto u = tinypt::Vec3f::UnitX();
auto v = w.cross(u);
tinypt::Mat3f cam_rot;
cam_rot << u, v, w;
tinypt::Camera camera;
camera.set_location({50, -295.6, 52});
camera.set_rotation(cam_rot);
camera.set_resolution(1024, 768);
camera.set_fov(tinypt::radians(39.32));
tinypt::Scene scene(camera, {left, right, back, bottom, top, mirror_sphere, glass_sphere, light});
return scene;
}
tinypt::Scene SceneFactory::make_breakfast_room() {
auto mesh = tinypt::TriangleMesh::from_obj("../resource/breakfast_room/breakfast_room.obj");
auto area_light = std::make_shared<tinypt::Rectangle>();
area_light->set_location({-0.596747, 1.83138, 7.02496});
area_light->set_dimension({11.3233, 6});
area_light->set_material(
tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(0, 0, 0)), tinypt::Vec3f(2, 2, 2)));
auto sunlight = std::make_shared<tinypt::DistantLight>();
sunlight->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {50.3857, -0.883569, 74.8117}, true).matrix());
sunlight->set_power(8);
sunlight->set_angle(tinypt::radians(2.2));
tinypt::Camera camera;
camera.set_location({-0.62, -7.59, 1.20});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {90, 0, 0}, true).matrix());
camera.set_resolution(1024, 1024);
camera.set_fov(tinypt::radians(49.1343));
tinypt::Scene scene(camera, {mesh, area_light}, {sunlight});
return scene;
}
tinypt::Scene SceneFactory::make_living_room() {
auto mesh = tinypt::TriangleMesh::from_obj("../resource/living_room/living_room.obj");
tinypt::Camera camera;
camera.set_location({2.2, -7.7, 1.9});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {82.6, 0, 20.7}, true).matrix());
camera.set_resolution(1920, 1080);
camera.set_fov(tinypt::radians(67));
tinypt::Scene scene(camera, {mesh});
return scene;
}
tinypt::Scene SceneFactory::make_fireplace_room() {
auto mesh = tinypt::TriangleMesh::from_obj("../resource/fireplace_room/fireplace_room.obj");
tinypt::Camera camera;
camera.set_location({5.0, 3.0, 1.1});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {90, 0, 113}, true).matrix());
camera.set_resolution(1920, 1080);
camera.set_fov(tinypt::radians(75));
tinypt::Scene scene(camera, {mesh});
return scene;
}
tinypt::Scene SceneFactory::make_rungholt() {
auto mesh = tinypt::TriangleMesh::from_obj("../resource/rungholt/rungholt.obj");
auto background = tinypt::Image::open("../resource/envmap/venice_sunset_4k.hdr", false).rgb();
auto env_rot = tinypt::Rotation::from_euler({0, 1, 2}, {0, 0, 220}, true).matrix();
auto env = std::make_shared<tinypt::EnvTexture>(background, env_rot);
auto sunlight = std::make_shared<tinypt::DistantLight>();
sunlight->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {-65, 0, 0}, true).matrix());
sunlight->set_color({1, 0.9, 0.27});
sunlight->set_power(8);
sunlight->set_angle(tinypt::radians(24));
tinypt::Camera camera;
camera.set_location({270, -209, 169});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {58, 0, 58}, true).matrix());
camera.set_resolution(1920, 1080);
camera.set_fov(tinypt::radians(75));
tinypt::Scene scene(camera, {mesh}, {sunlight}, std::move(env));
return scene;
}
tinypt::Scene SceneFactory::make_dabrovic_sponza() {
auto mesh = tinypt::TriangleMesh::from_obj("../resource/dabrovic_sponza/sponza.obj");
auto sunlight = std::make_shared<tinypt::DistantLight>();
sunlight->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {-10, -15, 98}, true).matrix());
sunlight->set_power(10);
sunlight->set_angle(tinypt::radians(20));
auto env = std::make_shared<tinypt::EnvTexture>(tinypt::rgb_color(86, 137, 190));
tinypt::Camera camera;
camera.set_location({-12, 1.2, 1.4});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {105, 0, 261}, true).matrix());
camera.set_resolution(1920, 1080);
camera.set_fov(tinypt::radians(81.8));
tinypt::Scene scene(camera, {mesh}, {sunlight}, std::move(env));
return scene;
}
tinypt::Scene SceneFactory::make_salle_de_bain() {
auto mesh = tinypt::TriangleMesh::from_obj("../resource/salle_de_bain/salle_de_bain.obj");
tinypt::Camera camera;
camera.set_location({7.8, -39, 15.5});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {87, 0, 21}, true).matrix());
camera.set_resolution(1080, 1080);
camera.set_fov(tinypt::radians(60));
tinypt::Scene scene(camera, {mesh});
return scene;
}
tinypt::Scene SceneFactory::make_debug() {
auto env_map = tinypt::Image::open("../resource/envmap/venice_sunset_4k.hdr", false).rgb();
auto env_rot = tinypt::Rotation::from_euler({0, 1, 2}, {-10, 10, 10}, true).matrix();
auto sphere = std::make_shared<tinypt::Sphere>();
sphere->set_location({0, 0, 0});
sphere->set_radius(1);
sphere->set_material(tinypt::Material(std::make_shared<tinypt::Metal>(tinypt::Vec3f(0.8, 0.8, 0.8))));
auto env = std::make_shared<tinypt::EnvTexture>(std::move(env_map), env_rot);
tinypt::Camera camera;
camera.set_location({4, -6, 1});
camera.set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {90, 0, 30}, true).matrix());
camera.set_fov(tinypt::radians(70));
camera.set_resolution(1920, 1080);
tinypt::Scene scene(camera, {sphere}, {}, env);
return scene;
}
tinypt::Scene SceneFactory::make_debug2() {
float x1 = 1, y1 = -170, z1 = 0;
float x2 = 99, y2 = 0, z2 = 81.6;
float xm = (x1 + x2) / 2, ym = (y1 + y2) / 2, zm = (z1 + z2) / 2;
float xs = x2 - x1, ys = y2 - y1, zs = z2 - z1;
auto left = std::make_shared<tinypt::Rectangle>();
left->set_location({x1, ym, zm});
left->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {0, 90, 0}, true).matrix());
left->set_dimension({zs, ys});
left->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .25, .25))));
auto right = std::make_shared<tinypt::Rectangle>();
right->set_location({x2, ym, zm});
right->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {0, 90, 0}, true).matrix());
right->set_dimension({zs, ys});
right->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.25, .25, .75))));
auto back = std::make_shared<tinypt::Rectangle>();
back->set_location({xm, y2, zm});
back->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {90, 0, 0}, true).matrix());
back->set_dimension({xs, zs});
back->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .75, .75))));
auto bottom = std::make_shared<tinypt::Rectangle>();
bottom->set_location({xm, ym, z1});
bottom->set_dimension({xs, ys});
bottom->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .75, .75))));
auto top = std::make_shared<tinypt::Rectangle>();
top->set_location({xm, ym, z2});
top->set_dimension({xs, ys});
top->set_material(tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(.75, .75, .75))));
auto mirror_sphere = std::make_shared<tinypt::Sphere>();
mirror_sphere->set_location({27, 16.5, 47});
mirror_sphere->set_radius(16.5);
mirror_sphere->set_material(tinypt::Material(std::make_shared<tinypt::Metal>(tinypt::Vec3f(.999, .999, .999))));
auto glass_sphere = std::make_shared<tinypt::Sphere>();
glass_sphere->set_location({73, 16.5, 78});
glass_sphere->set_radius(16.5);
glass_sphere->set_material(
tinypt::Material(std::make_shared<tinypt::Dielectric>(tinypt::Vec3f(.999, .999, .999), 1.5)));
auto light = std::make_shared<tinypt::Circle>();
light->set_radius(18);
light->set_location({50, 81.6 - 0.01, 81.6});
light->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {-90, 0, 0}, true).matrix());
light->set_material(
tinypt::Material(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(0, 0, 0)), tinypt::Vec3f(12, 12, 12)));
auto box = tinypt::TriangleMesh::from_obj(
"../resource/cube.obj",
std::make_shared<tinypt::Material>(std::make_shared<tinypt::Lambertian>(tinypt::Vec3f(0, .8, 0))));
box->set_location({20, 20, 20});
box->set_rotation(tinypt::Rotation::from_euler({0, 1, 2}, {10, 20, 30}, true).matrix());
// camera
auto w = tinypt::Vec3f(0, 0.042612, 1).normalized();
auto u = tinypt::Vec3f::UnitX();
auto v = w.cross(u);
tinypt::Mat3f cam_rot;
cam_rot << u, v, w;
tinypt::Camera camera;
camera.set_location({50, 52, 295.6});
camera.set_rotation(cam_rot);
camera.set_resolution(1024, 768);
camera.set_fov(tinypt::radians(39.32));
tinypt::Scene scene(camera, {left, right, back, bottom, top, light, box});
return scene;
}
| 45.363014 | 116 | 0.65801 | li-plus |
20f5a25594090fe2ef36d667fc018abcdadaf532 | 4,834 | cpp | C++ | UltraDV/Source/TTimeBevelTextView.cpp | ModeenF/UltraDV | 30474c60880de541b33687c96293766fe0dc4aef | [
"Unlicense"
] | null | null | null | UltraDV/Source/TTimeBevelTextView.cpp | ModeenF/UltraDV | 30474c60880de541b33687c96293766fe0dc4aef | [
"Unlicense"
] | null | null | null | UltraDV/Source/TTimeBevelTextView.cpp | ModeenF/UltraDV | 30474c60880de541b33687c96293766fe0dc4aef | [
"Unlicense"
] | null | null | null | //---------------------------------------------------------------------
//
// File: TTimeBevelTextView.cpp
//
// Author: Gene Z. Ragan
//
// Date: 03.24.98
//
// Desc: Enhanced version of TTimeBevelTextView drawn with a beveled
// indentation and a focus highlight
//
// Copyright ©1998 mediapede Software
//
//---------------------------------------------------------------------
// Includes
#include "BuildApp.h"
#include <app/Application.h>
#include <support/Debug.h>
#include <stdio.h>
#include <ctype.h>
#include "AppConstants.h"
#include "AppMessages.h"
#include "AppUtils.h"
#include "TTimeBevelTextView.h"
#include "TTimeTextView.h"
//---------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------
//
//
TTimeBevelTextView::TTimeBevelTextView( BRect bounds, char *name, uint32 resizing) : BView(bounds, name, resizing, B_WILL_DRAW)
{
// Perform default initialization
Init();
}
//---------------------------------------------------------------------
// Destructor
//---------------------------------------------------------------------
//
//
TTimeBevelTextView::~TTimeBevelTextView()
{
}
//---------------------------------------------------------------------
// Init
//---------------------------------------------------------------------
//
// Perform default initialization
//
void TTimeBevelTextView::Init()
{
// Create child TNumberTextView
BRect bounds = Bounds();
bounds.InsetBy(2, 2);
m_TextView = new TTimeTextView( NULL, 0, bounds, "TimeTextView", B_FOLLOW_ALL);
AddChild(m_TextView);
}
//---------------------------------------------------------------------
// Draw
//---------------------------------------------------------------------
//
// Draw contents
//
void TTimeBevelTextView::Draw(BRect inRect)
{
// Save colors
rgb_color saveColor = HighColor();
// Draw text
m_TextView->Draw(inRect);
// Draw standard Be Style bevel
BPoint startPt, endPt;
BRect bounds = Bounds();
bounds.InsetBy(1, 1);
SetHighColor(kBeShadow);
startPt.Set(bounds.left, bounds.bottom);
endPt.Set(bounds.left, bounds.top);
StrokeLine(startPt, endPt);
startPt.Set(bounds.left, bounds.top);
endPt.Set(bounds.right, bounds.top);
StrokeLine(startPt, endPt);
SetHighColor(kBeGrey);
startPt.Set(bounds.right, bounds.top);
endPt.Set(bounds.right, bounds.bottom);
StrokeLine(startPt, endPt);
startPt.Set(bounds.right, bounds.bottom);
endPt.Set(bounds.left, bounds.bottom);
StrokeLine(startPt, endPt);
bounds = Bounds();
SetHighColor(kBeShadow);
startPt.Set(bounds.left, bounds.bottom);
endPt.Set(bounds.left, bounds.top);
StrokeLine(startPt, endPt);
startPt.Set(bounds.left, bounds.top);
endPt.Set(bounds.right, bounds.top);
StrokeLine(startPt, endPt);
SetHighColor(kWhite);
startPt.Set(bounds.right, bounds.top);
endPt.Set(bounds.right, bounds.bottom);
StrokeLine(startPt, endPt);
startPt.Set(bounds.right, bounds.bottom);
endPt.Set(bounds.left, bounds.bottom);
StrokeLine(startPt, endPt);
// Restore color
SetHighColor(saveColor);
//BView::Draw(inRect);
}
//---------------------------------------------------------------------
// MouseDown
//---------------------------------------------------------------------
//
//
void TTimeBevelTextView::MouseDown(BPoint where)
{
BView::MouseDown(where);
}
//---------------------------------------------------------------------
// MouseUp
//---------------------------------------------------------------------
//
//
void TTimeBevelTextView::MouseUp(BPoint where)
{
BView::MouseUp(where);
}
//---------------------------------------------------------------------
// MouseMoved
//---------------------------------------------------------------------
//
//
void TTimeBevelTextView::MouseMoved(BPoint where, uint32 code, const BMessage *message)
{
BView::MouseMoved(where, code, message);
}
//---------------------------------------------------------------------
// KeyDown
//---------------------------------------------------------------------
//
//
void TTimeBevelTextView::KeyDown(const char *bytes, int32 numBytes)
{
BView::KeyDown(bytes, numBytes);
}
//---------------------------------------------------------------------
// MakeFocus
//---------------------------------------------------------------------
//
//
void TTimeBevelTextView::MakeFocus(bool focusState)
{
BView::MakeFocus(focusState);
}
#pragma mark -
#pragma mark === Message Handling ===
//---------------------------------------------------------------------
// MessageReceived
//---------------------------------------------------------------------
//
//
void TTimeBevelTextView::MessageReceived(BMessage *message)
{
switch(message->what)
{
default:
BView::MessageReceived(message);
break;
}
}
| 22.37963 | 134 | 0.477038 | ModeenF |