hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a4d5561da07e8715abdf458003a5f3d084d0eade
2,783
cpp
C++
Geometry/Geometry.cpp
odanado/ProconLib
b90e4109466c71d4ffac42f218f51b695104e37f
[ "MIT" ]
null
null
null
Geometry/Geometry.cpp
odanado/ProconLib
b90e4109466c71d4ffac42f218f51b695104e37f
[ "MIT" ]
1
2018-01-26T12:37:28.000Z
2018-01-26T12:37:28.000Z
Geometry/Geometry.cpp
odanado/ProconLib
b90e4109466c71d4ffac42f218f51b695104e37f
[ "MIT" ]
null
null
null
#include <complex> #include <vector> #include <cmath> #include <utility> #include <cassert> #include <cmath> const double EPS=1e-10; #define equals(a, b) (fabs((a)-(b))<EPS) #define X real() #define Y imag() using namespace std; typedef complex<double> Point; typedef complex<double> Vector; struct Segment { Point p1, p2; }; typedef Segment Line; struct Circle { Point c; double r; Circle(Point c=Point(), double r=0.0) : c(c),r(r){} }; typedef vector<Point> Polygon; double dot(Vector a, Vector b) { return a.X*b.X + a.Y*b.Y; } double cross(Vector a,Vector b) { return a.X*b.Y - a.Y*b.X; } Point project(Segment s, Point p) { Vector base = s.p2-s.p1; double r=dot(p-s.p1,base) / norm(base); return s.p1+base*r; } Point reflect(Segment s, Point p) { return p+(project(s,p)-p)*2.0; } enum CCW { COUNTER_CLOCKWISE=1, CLOCKWISE=-1, ONLINE_BACK=2, ONLINE_FRONT=-2, ON_SEGMENT=0, }; int ccw(Point p0, Point p1, Point p2) { Vector a=p1-p0; Vector b=p2-p0; if(cross(a,b)>EPS) return CCW::COUNTER_CLOCKWISE; if(cross(a,b)<-EPS) return CCW::CLOCKWISE; if(dot(a,b)<-EPS) return CCW::ONLINE_BACK; if(norm(a)<norm(b)) return CCW::ONLINE_FRONT; return CCW::ON_SEGMENT; } double getDistance(Point a,Point b) { return abs(a-b); } double getDistanceLP(Line l, Point p) { return abs(cross(l.p2-l.p1,p-l.p1)/abs(l.p2-l.p1)); } bool intersect(Point p1,Point p2,Point p3,Point p4) { return (ccw(p1,p2,p3)*ccw(p1,p2,p4)<=0&& ccw(p3,p4,p1)*ccw(p3,p4,p2)<=0); } bool intersect(Segment s1,Segment s2) { return intersect(s1.p1,s1.p2,s2.p1,s2.p2); } bool intersect(Circle c,Line l) { return getDistanceLP(l,c.r)<=c.r; } Point getCrossPoint(Segment s1,Segment s2) { Vector base=s2.p2-s2.p1; double d1=abs(cross(base,s1.p1-s2.p1)); double d2=abs(cross(base,s1.p2-s2.p1)); double t=d1/(d1+d2); return s1.p1+(s1.p2-s1.p1)*t; } pair<Point, Point> getCrossPoints(Circle c, Line l) { // assert(intersect(c,l)); Vector pr=project(l,c.c); Vector e=(l.p2-l.p1)/abs(l.p2-l.p1); double base=sqrt(c.r*c.r-norm(pr-c.c)); return make_pair(pr+e*base,pr-e*base); } pair<Point,Point> getCrossPoints(Circle c1, Circle c2) { double d=abs(c1.c-c2.c); double a=acos((c1.r*c1.r+d*d-c2.r*c2.r)/(2*c1.r*d)); double t=arg(c2.c-c1.c); return make_pair(c1.c+polar(c1.r,t+a),c1.c+polar(c1.r,t-a)); } // IN 2, ON 1, OUT 0 int contains(Polygon g, Point p) { int n=g.size(); bool x=false; for(int i=0;i<n;i++) { Point a=g[i]-p,b=g[(i+1)%n]-p; if(abs(cross(a,b))<EPS && dot(a,b)<EPS) return 1; if(a.Y>b.Y) swap(a,b); if(a.Y<EPS&&EPS<b.Y&&cross(a,b) > EPS) x=!x; } return x?2:0; }
21.742188
64
0.610133
odanado
a4d6621ecad3bd7488a8c90008a95c519c982242
2,183
cpp
C++
2016/main_pancakes.cpp
RomainBrault/GoogleCodeJam
d11bafaf77943c275fac4f08ab95b1f97788dea0
[ "MIT" ]
null
null
null
2016/main_pancakes.cpp
RomainBrault/GoogleCodeJam
d11bafaf77943c275fac4f08ab95b1f97788dea0
[ "MIT" ]
null
null
null
2016/main_pancakes.cpp
RomainBrault/GoogleCodeJam
d11bafaf77943c275fac4f08ab95b1f97788dea0
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> #define CHECK_STREAM(S, E) do { \ if (!(S)) goto E; \ } while (0) #define CHECK_END_STREAM(S, E) do { \ (S).ignore(2); \ if (!(S).eof()) goto E; \ } while (0) inline auto flip(auto && begin, auto && end) -> void { std::transform(begin, end, begin, [](bool b){return !b;}); std::reverse(begin, end); } auto main(int argc, char** argv) -> int { if (argc < 3) { std::cerr << "expected \'./programe filename\' n_threads " << std::endl; return -1; } std::ifstream file; file.open(argv[1]); size_t n; std::vector<std::vector<bool>> data; std::vector<size_t> iter; CHECK_STREAM(file >> n, PARSE_ERROR); data.resize(n); iter.resize(n); { std::string line; CHECK_STREAM(file.ignore(1), PARSE_ERROR); for (size_t i = 0; i < n; ++i) { CHECK_STREAM(std::getline(file, line), PARSE_ERROR); data[i].resize(line.size()); for (size_t j = 0; j < line.size(); ++j) { data[i][j] = (line[j] == '+' ? true : false); } } } CHECK_END_STREAM(file, PARSE_ERROR); #pragma omp parallel for num_threads(atoi(argv[2])) for (size_t i = 0; i < n; ++i) { auto dib = data[i].begin(); auto die = data[i].end(); iter[i] = 0; while (!std::all_of(dib, die, [](bool b){return b;})) { if (std::all_of(dib, die, [](bool b){return !b;})) { // flip(dib, die); ++iter[i]; break; } auto its = std::adjacent_find(data[i].begin(), data[i].end(), std::not_equal_to<bool>()); flip(dib, its + 1); ++iter[i]; } } for (size_t i = 0; i < n; ++i) { std::cout << "Case #" + std::to_string(i + 1) + ": " + std::to_string(iter[i]) << std::endl; } return 0; PARSE_ERROR: std::cerr << "error while parsing file" << std::endl; return -2; }
26.950617
80
0.479157
RomainBrault
a4d9a62f30604c37da3eedac837a6eed2eabf64c
3,126
cpp
C++
Source/URoboSim/Private/ROSCommunication/RROSClient.cpp
K4R-IAI/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
1
2021-04-11T13:03:58.000Z
2021-04-11T13:03:58.000Z
Source/URoboSim/Private/ROSCommunication/RROSClient.cpp
artnie/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
null
null
null
Source/URoboSim/Private/ROSCommunication/RROSClient.cpp
artnie/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
null
null
null
#include "ROSCommunication/RROSClient.h" #include "TimerManager.h" void URROSClient::Init(UObject* InOwner, TSharedPtr<FROSBridgeHandler> InHandler) { ROSHandler = InHandler; Init(InOwner); } void URROSClient::Init(UObject* InOwner, TArray<FString>* OutArray, TSharedPtr<FROSBridgeHandler> InHandler) { ROSHandler = InHandler; Init(InOwner, OutArray); } void URJointStateConfigurationClient::Init(UObject* InModel, TArray<FString>* OutArray) // void URJointStateConfigurationClient::Init(UObject* InControllerComp) { ARModel* Model = Cast<ARModel>(InModel); Request = MakeShareable(new rosapi::GetParam::Request(JointParamTopic, "")); // Create an empty response instance Response = MakeShareable(new rosapi::GetParam::Response()); ServiceClient = MakeShareable<FROSJointStateConfigurationClient>(new FROSJointStateConfigurationClient(OutArray,TEXT("rosapi/get_param"), TEXT("rosapi/GetParam"))); FTimerHandle MyTimerHandle; Model->GetWorldTimerManager().SetTimer(MyTimerHandle, this, &URJointStateConfigurationClient::CallService, 1.0f, false); } void URJointStateConfigurationClient::CallService() { ROSHandler->CallService(ServiceClient, Request, Response); } URJointControllerConfigurationClient::URJointControllerConfigurationClient() { JointParamTopic = TEXT("/whole_body_controller/joints"); LimitParamTopic = TEXT("/robot_description"); } void URJointControllerConfigurationClient::Init(UObject* InControllerComp) { // ARModel* Model = Cast<ARModel>(InModel); ControllerComp = Cast<URControllerComponent>(InControllerComp); CreateClient(); // ServiceClient = MakeShareable<FROSJointStateConfigurationClient>(new FROSJointStateConfigurationClient(OutArray,TEXT("rosapi/get_param"), TEXT("rosapi/GetParam"))); } void URJointControllerConfigurationClient::CreateClient() { URJointController* JointController = Cast<URJointController>(ControllerComp->ControllerList("JointController")); TMap<FString,float>* JointNames = &JointController->DesiredJointState; JointRequest = MakeShareable(new rosapi::GetParam::Request(JointParamTopic, "")); JointResponse = MakeShareable(new rosapi::GetParam::Response()); JointServiceClient = MakeShareable<FROSJointControllerConfigurationClient>(new FROSJointControllerConfigurationClient(JointNames,TEXT("rosapi/get_param"), TEXT("rosapi/GetParam"))); LimitRequest = MakeShareable(new rosapi::GetParam::Request(LimitParamTopic, "")); LimitResponse = MakeShareable(new rosapi::GetParam::Response()); JointLimitServiceClient = MakeShareable<FROSJointLimitControllerConfigurationClient>(new FROSJointLimitControllerConfigurationClient(JointNames, ControllerComp->GetOwner(), TEXT("rosapi/get_param"), TEXT("rosapi/GetParam"))); FTimerHandle MyTimerHandle; ControllerComp->GetOwner()->GetWorldTimerManager().SetTimer(MyTimerHandle, this, &URJointControllerConfigurationClient::CallService, 1.0f, false); } void URJointControllerConfigurationClient::CallService() { ROSHandler->CallService(JointServiceClient, JointRequest, JointResponse); ROSHandler->CallService(JointLimitServiceClient, LimitRequest, LimitResponse); }
42.821918
227
0.805182
K4R-IAI
a4e36ded1889c1218d51deccfe08aab87005f88d
189
hpp
C++
vendor/bindgen/tests/headers/class_use_as.hpp
mrkatebzadeh/rust-ibverbs
c0ea14f0e35be179a0370a7312b5fa07032adb27
[ "Apache-2.0", "MIT" ]
null
null
null
vendor/bindgen/tests/headers/class_use_as.hpp
mrkatebzadeh/rust-ibverbs
c0ea14f0e35be179a0370a7312b5fa07032adb27
[ "Apache-2.0", "MIT" ]
null
null
null
vendor/bindgen/tests/headers/class_use_as.hpp
mrkatebzadeh/rust-ibverbs
c0ea14f0e35be179a0370a7312b5fa07032adb27
[ "Apache-2.0", "MIT" ]
1
2021-02-02T10:49:21.000Z
2021-02-02T10:49:21.000Z
/** * <div rustbindgen="true" replaces="whatever"></div> */ struct whatever_replacement { int replacement; }; struct whatever { int b; }; struct container { whatever c; };
11.8125
53
0.62963
mrkatebzadeh
a4e6db96a8e708d2569e88055483edc164ef76ca
2,059
cpp
C++
src/plugins/azoth/plugins/vader/proto/balancer.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/azoth/plugins/vader/proto/balancer.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/azoth/plugins/vader/proto/balancer.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "balancer.h" #include <QTcpSocket> #include <QtDebug> namespace LC { namespace Azoth { namespace Vader { namespace Proto { Balancer::Balancer (QObject *parent) : QObject (parent) { } void Balancer::GetServer () { QTcpSocket *socket = new QTcpSocket (this); socket->connectToHost ("mrim.mail.ru", 443); connect (socket, SIGNAL (readyRead ()), this, SLOT (handleRead ())); connect (socket, SIGNAL (error (QAbstractSocket::SocketError)), this, SLOT (handleSocketError (QAbstractSocket::SocketError))); } void Balancer::handleRead () { QTcpSocket *socket = qobject_cast<QTcpSocket*> (sender ()); if (!socket->canReadLine ()) { qWarning () << Q_FUNC_INFO << "can't read line from socket, waiting more..."; return; } socket->deleteLater (); const QByteArray& line = socket->readAll ().trimmed (); const int pos = line.indexOf (':'); if (pos <= 0) { qWarning () << Q_FUNC_INFO << "got" << line; emit error (); return; } const QString& server = line.left (pos); const int port = line.mid (pos + 1).toInt (); if (port <= 0) { qWarning () << Q_FUNC_INFO << "invalid port" << server << port << line << line.mid (pos + 1); emit error (); return; } emit gotServer (server, port); disconnect (socket, 0, this, 0); } void Balancer::handleSocketError (QAbstractSocket::SocketError code) { QTcpSocket *socket = qobject_cast<QTcpSocket*> (sender ()); qWarning () << Q_FUNC_INFO << "socket error" << code << socket->errorString (); socket->deleteLater (); emit error (); } } } } }
20.79798
83
0.58135
Maledictus
a4e8b7dc052667dccaa504aed9b3441a363974c3
1,662
cc
C++
flens/examples/lapack-getrf.cc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
98
2015-01-26T20:31:37.000Z
2021-09-09T15:51:37.000Z
flens/examples/lapack-getrf.cc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
16
2015-01-21T07:43:45.000Z
2021-12-06T12:08:36.000Z
flens/examples/lapack-getrf.cc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
31
2015-01-05T08:06:45.000Z
2022-01-26T20:12:00.000Z
#include <cxxstd/iostream.h> /// /// With header __flens.cxx__ all of FLENS gets included. /// /// :links: __flens.cxx__ -> file:flens/flens.cxx #include <flens/flens.cxx> using namespace std; using namespace flens; typedef double T; int main() { /// /// Define some convenient typedef for the matrix types of our system of /// linear equations. /// typedef GeMatrix<FullStorage<T> > Matrix; /// /// We also need an extra vector type for the pivots. The type of the /// pivots is taken for the system matrix. /// typedef Matrix::IndexType IndexType; typedef DenseVector<Array<IndexType> > IndexVector; /// /// Define an underscore operator for convenient matrix slicing /// const Underscore<IndexType> _; /// /// Set up the baby problem ... /// const IndexType m = 4, n = 5; Matrix Ab(m, n); IndexVector piv(m); Ab = 2, 3, -1, 0, 20, -6, -5, 0, 2, -33, 2, -5, 6, -6, -43, 4, 6, 2, -3, 49; cout << "Ab = " << Ab << endl; /// /// Compute the $LU$ factorization with __lapack::trf__ /// lapack::trf(Ab, piv); /// /// Solve the system of linear equation $Ax =B$ using __blas::sm__ /// const auto A = Ab(_,_(1,m)); auto B = Ab(_,_(m+1,n)); blas::sm(Left, NoTrans, T(1), A.upper(), B); cout << "X = " << B << endl; cout << "piv = " << piv << endl; } /// /// :links: __lapack::trf__ -> file:flens/lapack/ge/trf.h /// __blas::sm__ -> file:flens/blas/level3/sm.h ///
23.408451
77
0.522262
stip
a4eaa9a6ff7ac962595c673154e98ef94fffc738
10,193
cpp
C++
parser/parserStrings.cpp
pat-laugh/websson-libraries
c5c99a98270dee45fcd9ec4e7f03e2e74e3b1ce2
[ "MIT" ]
null
null
null
parser/parserStrings.cpp
pat-laugh/websson-libraries
c5c99a98270dee45fcd9ec4e7f03e2e74e3b1ce2
[ "MIT" ]
33
2017-04-25T21:53:59.000Z
2017-07-14T13:30:29.000Z
parser/parserStrings.cpp
pat-laugh/websson-libraries
c5c99a98270dee45fcd9ec4e7f03e2e74e3b1ce2
[ "MIT" ]
null
null
null
//MIT License //Copyright 2017-2018 Patrick Laughrea #include "parserStrings.hpp" #include "containerSwitcher.hpp" #include "errors.hpp" #include "unicode.hpp" #include "utils/constants.hpp" #include "utils/utilsWebss.hpp" #include "various/utils.hpp" using namespace std; using namespace various; using namespace webss; static const char* ERROR_MULTILINE_STRING = "multiline-string is not closed"; static void checkEscapedChar(SmartIterator& it, StringBuilder& sb, StringList*& stringList); static inline void putChar(SmartIterator& it, StringBuilder& sb); static bool isEnd(SmartIterator& it, function<bool()> endCondition); static bool hasNextChar(SmartIterator& it, StringBuilder& sb, function<bool()> endCondition = []() { return false; }); static void checkStringSubstitution(Parser& parser, StringBuilder& sb, StringList*& stringList); static void pushStringList(StringList*& stringList, StringBuilder& sb, StringItem item); #define PatternCheckCharEscape \ if (*it == CHAR_ESCAPE) { checkEscapedChar(it, sb, stringList); continue; } #define PatternCheckCharSubstitution \ if (*it == CHAR_SUBSTITUTION) { checkStringSubstitution(parser, sb, stringList); continue; } #define PatternPutLastString { \ string s = sb.str(); \ if (!s.empty()) \ stringList->push(sb.str()); } #define _PatternReturnStringList \ if (stringList == nullptr) \ return sb.str(); \ PatternPutLastString #define PatternReturnStringListConcat \ _PatternReturnStringList \ return stringList->concat(); #define PatternReturnStringList \ _PatternReturnStringList \ return Webss(stringList, WebssType::STRING_LIST); string webss::parseStickyLineString(Parser& parser) { auto& it = parser.getItSafe(); StringBuilder sb; StringList* stringList = nullptr; if (parser.multilineContainer) while (it && !isJunk(*it)) { PatternCheckCharEscape; PatternCheckCharSubstitution; putChar(it, sb); } else { int countStartEnd = 1; char startChar = parser.con.getStartChar(), endChar = parser.con.getEndChar(); while (it && !isJunk(*it)) { PatternCheckCharEscape; PatternCheckCharSubstitution; if (*it == CHAR_SEPARATOR) break; if (*it == endChar) { if (--countStartEnd == 0) break; } else if (*it == startChar) ++countStartEnd; putChar(it, sb); } } PatternReturnStringListConcat; } string webss::parseStickyLineStringOption(Parser& parser) { auto& it = parser.getItSafe(); StringBuilder sb; StringList* stringList = nullptr; while (it && !isJunk(*it)) { PatternCheckCharEscape; putChar(it, sb); } PatternReturnStringListConcat; return sb; } Webss webss::parseLineString(Parser& parser) { auto& it = parser.getItSafe(); skipLineJunk(it); StringBuilder sb; StringList* stringList = nullptr; if (parser.multilineContainer) while (hasNextChar(it, sb)) { PatternCheckCharEscape; PatternCheckCharSubstitution; putChar(it, sb); } else { int countStartEnd = 1; char startChar = parser.con.getStartChar(); while (hasNextChar(it, sb, [&]() { return *it == CHAR_SEPARATOR || (parser.con.isEnd(*it) && --countStartEnd == 0); })) { PatternCheckCharEscape; PatternCheckCharSubstitution; if (*it == startChar) ++countStartEnd; putChar(it, sb); } } PatternReturnStringList; } static Webss parseMultilineStringRegularMultiline(Parser& parser) { auto& it = parser.getIt(); StringBuilder sb; StringList* stringList = nullptr; int countStartEnd = 0; bool addSpace = true; lineStart: if (*it == CHAR_START_DICTIONARY) ++countStartEnd; loopStart: do { if (*it == CHAR_ESCAPE) { checkEscapedChar(it, sb, stringList); if (hasNextChar(it, sb)) goto loopStart; addSpace = false; break; } PatternCheckCharSubstitution; putChar(it, sb); } while (hasNextChar(it, sb)); if (!it || !skipJunkToValid(++it)) throw runtime_error(WEBSSON_EXCEPTION(ERROR_MULTILINE_STRING)); if (*it == CHAR_END_DICTIONARY && countStartEnd-- == 0) { ++it; PatternReturnStringList; } if (addSpace) sb += ' '; else addSpace = true; goto lineStart; } static Webss parseMultilineStringRegular(Parser& parser) { auto& it = parser.getIt(); Parser::ContainerSwitcher switcher(parser, ConType::DICTIONARY, true); if (!skipJunk(it)) throw runtime_error(WEBSSON_EXCEPTION(ERROR_MULTILINE_STRING)); if (*it == CHAR_END_DICTIONARY) { ++it; return ""; } if (parser.multilineContainer) return parseMultilineStringRegularMultiline(parser); StringBuilder sb; StringList* stringList = nullptr; int countStartEnd = 1; bool addSpace = true; function<bool()> endCondition = [&]() { return *it == CHAR_END_DICTIONARY && --countStartEnd == 0; }; loopStart: while (hasNextChar(it, sb, endCondition)) { innerLoop: if (*it == CHAR_ESCAPE) { checkEscapedChar(it, sb, stringList); if (hasNextChar(it, sb, endCondition)) goto innerLoop; addSpace = false; break; } PatternCheckCharSubstitution; if (*it == CHAR_START_DICTIONARY) ++countStartEnd; putChar(it, sb); }; if (countStartEnd == 0) { ++it; PatternReturnStringList; } if (!it || !skipJunkToValid(++it)) throw runtime_error(WEBSSON_EXCEPTION(ERROR_MULTILINE_STRING)); if (addSpace) sb += ' '; else addSpace = true; goto loopStart; } Webss webss::parseMultilineString(Parser& parser) { auto& it = parser.getItSafe(); if (*it != CHAR_START_DICTIONARY) throw runtime_error(WEBSSON_EXCEPTION(ERROR_UNEXPECTED)); return parseMultilineStringRegular(parser); } Webss webss::parseCString(Parser& parser) { auto& it = parser.getItSafe(); ++it; StringBuilder sb; StringList* stringList = nullptr; while (it) { switch (*it) { case '\n': throw runtime_error(WEBSSON_EXCEPTION("can't have line break in cstring")); case CHAR_CSTRING: ++it; PatternReturnStringList; case CHAR_ESCAPE: checkEscapedChar(it, sb, stringList); continue; case CHAR_SUBSTITUTION: checkStringSubstitution(parser, sb, stringList); continue; default: sb += *it; //control Ascii chars, except tab and newline, are ignored case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: //case 0x09: case 0x0a: tab and newline case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: case 0x7f: ++it; break; } } throw runtime_error(WEBSSON_EXCEPTION("cstring is not closed")); } static void checkEscapedChar(SmartIterator& it, StringBuilder& sb, StringList*& stringList) { if (!++it) throw runtime_error(WEBSSON_EXCEPTION(ERROR_EXPECTED)); switch (*it) { case 'x': case 'u': case 'U': putEscapedHex(it, sb); return; case '0': sb += '\0'; break; case 'a': sb += '\a'; break; case 'b': sb += '\b'; break; case 'c': sb += 0x1b; break; case 'e': /* empty */ break; case 'f': sb += '\f'; break; case 'n': sb += '\n'; break; case 'r': sb += '\r'; break; case 's': sb += ' '; break; case 't': sb += '\t'; break; case 'v': sb += '\v'; break; case 'E': pushStringList(stringList, sb, StringType::FUNC_NEWLINE_FLUSH); break; case 'F': pushStringList(stringList, sb, StringType::FUNC_FLUSH); break; case 'N': pushStringList(stringList, sb, StringType::FUNC_NEWLINE); break; default: if (!isSpecialAscii(*it)) throw runtime_error(WEBSSON_EXCEPTION("invalid char escape")); sb += *it; break; } ++it; } static inline void putChar(SmartIterator& it, StringBuilder& sb) { sb += *it; ++it; } static bool isEnd(SmartIterator& it, function<bool()> endCondition) { return !it || *it == '\n' || endCondition(); } static bool hasNextChar(SmartIterator& it, StringBuilder& sb, function<bool()> endCondition) { if (isEnd(it, endCondition)) return false; if (isLineJunk(*it)) { StringBuilder spacesAndTabs; do { if (*it == ' ' || *it == '\t') spacesAndTabs += *it; if (isEnd(++it, endCondition)) return false; } while (isLineJunk(*it)); if (checkJunkOperators(it) && isEnd(it, endCondition)) return false; sb += spacesAndTabs; } return true; } static void checkTypeSubstitution(const Webss& webss) { auto type = webss.getType(); if (type != WebssType::PRIMITIVE_STRING && type != WebssType::STRING_LIST) throw runtime_error(WEBSSON_EXCEPTION("entity to substitute must be a string")); } static void checkSubstitutionBraces(Parser& parser, StringBuilder& sb, StringList*& stringList) { auto& it = parser.getIt(); Parser::ContainerSwitcher switcher(parser, ConType::DICTIONARY, false); if (!skipJunk(it)) throw runtime_error(WEBSSON_EXCEPTION(ERROR_EXPECTED)); if (*it != '}') { Webss webss = parser.parseValueOnly(); if (!skipJunk(it) || *it != '}') throw runtime_error(WEBSSON_EXCEPTION(ERROR_EXPECTED)); checkTypeSubstitution(webss); pushStringList(stringList, sb, move(webss)); parser.getItSafe(); //make sure tag iterator is unsafe after parseValueOnly call } ++it; } static void checkStringSubstitution(Parser& parser, StringBuilder& sb, StringList*& stringList) { auto& it = parser.getIt(); if (!++it) throw runtime_error(WEBSSON_EXCEPTION(ERROR_EXPECTED)); const Entity* ent; switch (*it) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ent = &parser.getEntityManager().at(CHAR_SUBSTITUTION + parseSubstitutionNumber(it)); break; case CHAR_FOREACH_SUBST_PARAM: ent = &parser.getEntityManager().at(string() + CHAR_SUBSTITUTION + CHAR_FOREACH_SUBST_PARAM); ++it; break; case '{': checkSubstitutionBraces(parser, sb, stringList); return; default: if (!isNameStart(*it)) throw runtime_error(WEBSSON_EXCEPTION("invalid substitution")); ent = &parser.getEntityManager().at(parseName(it)); break; } checkTypeSubstitution(ent->getContent()); pushStringList(stringList, sb, *ent); } static void pushStringList(StringList*& stringList, StringBuilder& sb, StringItem item) { if (stringList == nullptr) stringList = new StringList(); auto s = sb.str(); if (!s.empty()) { stringList->push(move(s)); sb.clear(); } stringList->push(move(item)); }
25.546366
121
0.700186
pat-laugh
a4efc43444a28275ec4bda268ec5458df99759a2
2,777
cpp
C++
src/win32/Splitter.cpp
NullPopPoLab/Play--Framework
ab4594f9ef548f1476c9017e122a05dfb91cc9d3
[ "BSD-2-Clause" ]
35
2015-02-19T20:11:05.000Z
2021-11-05T12:55:07.000Z
src/win32/Splitter.cpp
NullPopPoLab/Play--Framework
ab4594f9ef548f1476c9017e122a05dfb91cc9d3
[ "BSD-2-Clause" ]
24
2015-07-19T04:51:29.000Z
2022-03-31T00:36:45.000Z
src/win32/Splitter.cpp
Thunder07/Play--Framework
b0c8487656492f237f6613fccadbb8011b61bd4d
[ "BSD-2-Clause" ]
22
2015-02-16T03:36:00.000Z
2022-01-23T13:15:00.000Z
#include "win32/Splitter.h" #include <cassert> #define CLSNAME _T("CSplitter") using namespace Framework; using namespace Framework::Win32; CSplitter::CSplitter(HWND parentWnd, const RECT& rect, HCURSOR cursor, unsigned int edgePosition) : m_cursor(cursor) , m_edgePosition(edgePosition) { m_child[0] = nullptr; m_child[1] = nullptr; if(!DoesWindowClassExist(CLSNAME)) { WNDCLASSEX w; memset(&w, 0, sizeof(WNDCLASSEX)); w.cbSize = sizeof(WNDCLASSEX); w.lpfnWndProc = CWindow::WndProc; w.lpszClassName = CLSNAME; w.hbrBackground = (HBRUSH)GetSysColorBrush(COLOR_BTNFACE); w.hInstance = GetModuleHandle(NULL); w.hCursor = LoadCursor(NULL, IDC_ARROW); w.style = CS_VREDRAW | CS_HREDRAW; RegisterClassEx(&w); } Create(WS_EX_CONTROLPARENT, CLSNAME, _T(""), WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, rect, parentWnd, NULL); SetClassPtr(); } CSplitter::~CSplitter() { } void CSplitter::SetChild(unsigned int index, HWND hWnd) { m_child[index] = hWnd; ResizeChild(index); } void CSplitter::SetMasterChild(unsigned int masterChild) { assert(masterChild == 0 || masterChild == 1); m_masterChild = masterChild; } void CSplitter::SetEdgePosition(double fraction) { RECT clientRect = GetClientRect(); short x = (short)((double)clientRect.right * fraction); short y = (short)((double)clientRect.bottom * fraction); UpdateEdgePosition(x, y); ResizeChild(0); ResizeChild(1); } void CSplitter::SetFixed(bool fixed) { m_fixed = fixed; } long CSplitter::OnSize(unsigned int nX, unsigned int nY, unsigned int nType) { ResizeChild(0); ResizeChild(1); return TRUE; } long CSplitter::OnMouseMove(WPARAM wParam, int nX, int nY) { if(GetCapture() == m_hWnd) { UpdateEdgePosition(nX, nY); ResizeChild(0); ResizeChild(1); } auto edgeRect = GetEdgeRect(); if(!m_fixed && edgeRect.PtIn(nX, nY)) { SetCursor(m_cursor); } return TRUE; } long CSplitter::OnLeftButtonDown(int nX, int nY) { auto edgeRect = GetEdgeRect(); if(!m_fixed && edgeRect.PtIn(nX, nY)) { SetCapture(m_hWnd); SetCursor(m_cursor); } return TRUE; } long CSplitter::OnLeftButtonUp(int nX, int nY) { ReleaseCapture(); return TRUE; } LRESULT CSplitter::OnNotify(WPARAM wParam, NMHDR* pH) { return SendMessage(GetParent(), WM_NOTIFY, wParam, (LPARAM)pH); } void CSplitter::ResizeChild(unsigned int index) { if(m_child[index] == nullptr) return; auto paneRect = GetPaneRect(index); SetWindowPos(m_child[index], NULL, paneRect.Left(), paneRect.Top(), paneRect.Width(), paneRect.Height(), SWP_NOZORDER); SendMessage(GetParent(), WM_COMMAND, MAKEWPARAM(0, 0), reinterpret_cast<LPARAM>(m_hWnd)); }
21.695313
129
0.686712
NullPopPoLab
a4f2e3ed5215ed1211b6d81f823a6bcf844e5a6a
2,502
cpp
C++
examples/two_to_one_multi_put.cpp
abwilson/LowLatency
cefc780eccb0426f8fe99f5f59dce347c98f13aa
[ "MIT" ]
31
2015-06-26T16:38:18.000Z
2022-03-01T03:28:08.000Z
examples/two_to_one_multi_put.cpp
abwilson/LowLatency
cefc780eccb0426f8fe99f5f59dce347c98f13aa
[ "MIT" ]
1
2015-07-25T22:36:40.000Z
2015-07-25T22:36:40.000Z
examples/two_to_one_multi_put.cpp
abwilson/LowLatency
cefc780eccb0426f8fe99f5f59dce347c98f13aa
[ "MIT" ]
9
2015-06-26T18:44:31.000Z
2019-09-04T15:13:31.000Z
/* The MIT License (MIT) Copyright (c) 2015 Norman Wilson - Volcano Consultancy Ltd 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. This is comparing performance two threads feeding a single consumer implemented as either a shared put or as two separate disruptors with a selector combining the streams. This version does the former. Time for 100,000,000 iterations real 0m15.527s user 0m29.391s sys 0m0.113s This is about 3x the time of the selector version. */ #include <L3/static/disruptor.h> #include <L3/static/consume.h> #include <iostream> #include <thread> using Msg = size_t; using D = L3::Disruptor<Msg, 17>; using Get = D::Get<>; using Put = D::Put<L3::Barrier<Get>, L3::CommitPolicy::Shared>; int main() { struct Producer { Msg begin; Msg end; void operator()() { for(Msg i = begin; i < end; i += 2) Put() = i; } }; Msg iterations{100 * 1000 * 1000}; std::thread p1(Producer{3, iterations}); std::thread p2(Producer{2, iterations}); D::Msg oldOdd = 1; D::Msg oldEven = 0; for(size_t i = 2; i < iterations;) { for(auto msg: Get()) { ++i; D::Msg& old = msg & 0x1L ? oldOdd : oldEven; if(msg != old + 2) { std::cout << "old: " << old << ", new: " << msg << std::endl; return -1; } old = msg; } } std::cout << "Done" << std::endl; p1.join(); p2.join(); return 0; }
28.758621
78
0.659073
abwilson
a4f4431c70b2a43799ea38c3ffc08ec6f2fcccf4
6,475
cpp
C++
src/SnakeBlocks.cpp
fmaterak/Linux_terminal
35ccdd6e472880fa8765dba7f3d56809732ba98f
[ "MIT" ]
null
null
null
src/SnakeBlocks.cpp
fmaterak/Linux_terminal
35ccdd6e472880fa8765dba7f3d56809732ba98f
[ "MIT" ]
null
null
null
src/SnakeBlocks.cpp
fmaterak/Linux_terminal
35ccdd6e472880fa8765dba7f3d56809732ba98f
[ "MIT" ]
null
null
null
#include "SnakeBlocks.hpp" template<typename T> terminal::SnakeBlocks<T>::Iterator::Iterator(SnakeBlocks<T>& container, std::size_t block_idx): container(&container), block_idx(block_idx) { try { resolve(); } catch (std::out_of_range) { block = nullptr; } } template<typename T> typename terminal::SnakeBlocks<T>::Iterator& terminal::SnakeBlocks<T>::Iterator::operator++() { increment(); return *this; } template<typename T> typename terminal::SnakeBlocks<T>::Iterator terminal::SnakeBlocks<T>::Iterator::operator++(int) { auto tmp = *this; increment(); return tmp; } template<typename T> void terminal::SnakeBlocks<T>::Iterator::increment() { block_idx++; try { resolve(); } catch (std::out_of_range) { block = nullptr; } } template<typename T> typename terminal::SnakeBlocks<T>::Iterator terminal::SnakeBlocks<T>::Iterator::operator+(std::ptrdiff_t offset) const { return Iterator(*container, block_idx + offset); } template<typename T> T* terminal::SnakeBlocks<T>::Iterator::operator*() { return block; } template<typename T> typename terminal::SnakeBlocks<T>::Iterator& terminal::SnakeBlocks<T>::Iterator::resolve() { block = (*container)[block_idx]; return *this; } template<typename T> terminal::SnakeBlocks<T>::SnakeBlocks(std::size_t block_size, std::size_t initial_blocks): block_size(block_size), tail(0), state(0) { segments[0].head = 0; segments[0].tail = 0; blocks.reserve(initial_blocks); for (std::size_t i = 0; i < initial_blocks; i++) { blocks.push_back(new T[block_size]); } } // Advances segment head allocating new block if needed template<typename T> void terminal::SnakeBlocks<T>::advance_seg_head_edge(terminal::SnakeBlocks<T>::Segment& segment) { if (segment.head == blocks.size()) { blocks.push_back(new T[block_size]); } segment.head++; } template<typename T> void terminal::SnakeBlocks<T>::advance_head() { if (state == 0) { // if segment's size is smaller than the number of preceding unused blocks if ((segments[0].head - segments[0].tail) < segments[0].tail) { // wrap around: enter state 1, create new segment at the beginning state = 1; segments[1].tail = 0; segments[1].head = 1; } else { // there is only one segment, which may reach end advance_seg_head_edge(segments[0]); } } else if (state == 1) { if (segments[1].head == segments[0].tail) { // segment head reached previous segment's tail: enter state 2, create new segment at the end state = 2; segments[2].head = segments[2].tail = segments[0].head; // segment 2 has size 0 at the moment and may reach end advance_seg_head_edge(segments[2]); } else { // segment's head is in the middle, do plain advance (no allocation needed) segments[1].head++; } } // for these two cases the segment being advanced is at the end else if (state == 2) { advance_seg_head_edge(segments[2]); } else if (state == 3) { advance_seg_head_edge(segments[1]); } } template<typename T> void terminal::SnakeBlocks<T>::advance_tail() { // if the oldest segment is empty, do nothing if (segments[0].tail == segments[0].head) { return; } // advance the tail of the oldest segment and the reference point tail++; segments[0].tail++; // if the segment has been collapsed if (segments[0].tail == segments[0].head) { if (state == 0) { // move it back to the beginning segments[0].head = segments[0].tail = 0; } else if (state == 1) { // old segment is now gone, switch back to state 0 state = 0; segments[0] = segments[1]; } else if (state == 2) { // middle segment is now gone, switch to state 3 (the opposite of state 1) state = 3; segments[0] = segments[1]; segments[1] = segments[2]; } else if (state == 3) { // switch back to state 0 state = 0; segments[0] = segments[1]; } } } template<typename T> T* terminal::SnakeBlocks<T>::operator[](std::size_t index) { index -= tail; if (index >= 0) { short num_seg = num_segments(); for (short i = 0; i < num_seg; i++) { auto seg_size = segments[i].head - segments[i].tail; if (index < seg_size) { return blocks[segments[i].tail + index]; } else { index -= seg_size; } } } throw std::out_of_range("SnakeBlocks::operator[]: block index"); } template class terminal::SnakeBlocks<char>; template class terminal::SnakeBlocks<int>; // #include "LineBuffer.hpp" // template class terminal::SnakeBlocks<terminal::LineBuffer::CharAttr>; #ifdef SNAKE_BLOCKS_TEST_MAIN void print_snake_blocks(terminal::SnakeBlocks<char>& sb) { short num_segments = sb.num_segments(); std::cout << "tail: " << sb.tail << " state: " << sb.state << " blocks: ["; for (std::size_t i = 0; i < sb.blocks.size(); i++) { char segment = '.'; for (short s = 0; s < num_segments; s++) { if (sb.segments[s].head > i && sb.segments[s].tail <= i) { segment = '0' + s; break; } } std::cout << segment; } std::cout << "]\n"; } int main() { auto sb = terminal::SnakeBlocks<char>(1, 8); print_snake_blocks(sb); char action; while (true) { std::cout << "> "; std::cin >> action; if (action == 'h') { sb.advance_head(); print_snake_blocks(sb); } else if (action == 't') { sb.advance_tail(); print_snake_blocks(sb); } else if (action == 'q') { break; } } return 0; } #endif // std::size_t initial_blocks; // if (initial_capacity == 0) { // initial_blocks = 1; // } else { // initial_blocks = initial_capacity / block_size; // if (initial_capacity % block_size) { // initial_blocks++; // } // }
28.777778
120
0.563398
fmaterak
a4fb2e597ae1e7671eff7bd4923e53351ec0f321
4,161
cpp
C++
C_CPP/huf/Huf.cpp
dengchongsen/study_codes
29d74c05d340117f76aafcc320766248a0f8386b
[ "MulanPSL-1.0" ]
null
null
null
C_CPP/huf/Huf.cpp
dengchongsen/study_codes
29d74c05d340117f76aafcc320766248a0f8386b
[ "MulanPSL-1.0" ]
null
null
null
C_CPP/huf/Huf.cpp
dengchongsen/study_codes
29d74c05d340117f76aafcc320766248a0f8386b
[ "MulanPSL-1.0" ]
null
null
null
#include<iostream> #include<string> #include<cstring> using namespace std; const int MaxW = 9999999; // 假设结点权值不超过9999999 // 定义huffman树结点类 class HuffNode { public: int weight; // 权值 int parent; // 父结点下标 int leftchild; // 左孩子下标 int rightchild; // 右孩子下标 }; // 定义赫夫曼树类 class HuffMan { private: void MakeTree(); // 建树,私有函数,被公有函数调用 void SelectMin(int pos, int *s1, int*s2); // 从 1 到 pos 的位置找出权值最小的两个结点,把结点下标存在 s1 和 s2 中 public: int len; // 结点数量 int lnum; // 叶子数量 HuffNode *huffTree; // 赫夫曼树,用数组表示 string *huffCode; // 每个字符对应的赫夫曼编码 void MakeTree(int n, int wt[]); // 公有函数,被主函数main调用 void Coding(); // 公有函数,被主函数main调用 void Destroy(); }; // 构建huffman树 void HuffMan::MakeTree(int n, int wt[]) { // 参数是叶子结点数量和叶子权值 // 公有函数,对外接口 int i; lnum = n; len = 2 * n - 1; huffTree = new HuffNode[2 * n]; huffCode = new string[lnum + 1]; // 位置从 1 开始计算 // huffCode实质是个二维字符数组,第 i 行表示第 i 个字符对应的编码 // 赫夫曼树huffTree初始化 for(i = 1; i <= n; i ++) huffTree[i].weight = wt[i - 1]; // 第0号不用,从1开始编号 for(i = 1; i <= len; i ++) { if(i > n) huffTree[i].weight = 0; // 前n个结点是叶子,已经设置 huffTree[i].parent = 0; huffTree[i].leftchild = 0; huffTree[i].rightchild = 0; } MakeTree(); // 调用私有函数建树 } void HuffMan::SelectMin(int pos, int *s1, int *s2) { // 找出最小的两个权值的下标 // 函数采用地址传递的方法,找出两个下标保存在 s1 和 s2 中 int w1, w2, i; w1 = w2 = MaxW; // 初始化w1和w2为最大值,在比较中会被实际的权值替换 *s1 = *s2 = 0; for(i = 1; i <= pos; i ++) { // 比较过程如下: // 如果第 i 个结点的权值小于 w1,且第 i 个结点是未选择的结点,提示:如果第 i 结点未选择,它父亲为 0 // 把第 w1 和 s1 保存到 w2 和 s2,即原来的第一最小值变成第二最小值 // 把第 i 结点的权值和下标保存到 w1 和 s1,作为第一最小值 // 否则,如果第 i 结点的权值小于 w2,且第 i 结点是未选择的结点 // 把第 i 结点的权值和下标保存到 w2 和 s2,作为第二最小值 int w = huffTree[i].weight; int p = huffTree[i].parent; if( w<w1 && p==0){ w2 = w1; *s2 = *s1; w1 = w; *s1 = i; } else if( w<w2 && p==0){ w2 = w; *s2 = i; } } } void HuffMan::MakeTree() { // 私有函数,被公有函数调用 int i, s1, s2; for(i = lnum + 1; i <= len; i ++) { SelectMin(i - 1, &s1, &s2); // 找出两个最小权值的下标放入 s1 和 s2 中 // 将找出的两棵权值最小的子树合并为一棵子树,过程包括 // 结点 s1 和结点 s2 的父亲设为 i huffTree[s1].parent = i; huffTree[s2].parent = i; // 结点 i 的左右孩子分别设为 s1 和 s2 huffTree[i].leftchild = s1; huffTree[i].rightchild = s2; // 结点 i 的权值等于 s1 和 s2 的权值和 huffTree[i].weight = huffTree[s1].weight + huffTree[s2].weight; } } // 销毁赫夫曼树 void HuffMan::Destroy() { len = 0; lnum = 0; delete []huffTree; delete []huffCode; } // 赫夫曼编码 void HuffMan::Coding() { char *cd; int i, c, f, start; // 求 n 个结点的赫夫曼编码 cd = new char[lnum]; // 分配求编码的工作空间 cd[lnum - 1] = '\0'; // 编码结束符 for(i = 1; i <= lnum; ++ i) { // 逐个字符求赫夫曼编码 start = lnum - 1; // 编码结束符位置 // 参考课本P147算法6.12 HuffmanCoding代码 for( c=i, f=huffTree[i].parent; f!=0; c=f, f= huffTree[f].parent ){ start--; if(huffTree[f].leftchild == c){ cd[start] = '0'; } else{ cd[start] = '1'; } } /* for(int k=0; k<3; k++){ cout<<"======="; cout<<cd[k]<<"#####6"; } */ // cout<<"++++"<<cd[start]<<endl; huffCode[i].assign(&cd[start]); // 把cd中从start到末尾的编码复制到huffCode中 } delete []cd; // 释放工作空间 } // 主函数 int main() { int t, n, i, j; int wt[800]; HuffMan myHuff; cin >> t; for(i = 0; i < t; i ++) { cin >> n; for(int k=0; k<n; k++){ int temp; cin>>temp; wt[k] = temp; } myHuff.MakeTree(n,wt); myHuff.Coding(); for(j = 1; j <= n; j ++) { cout << myHuff.huffTree[j].weight << "-"; // 输出各权值 cout << myHuff.huffCode[j] << endl; // 输出各编码 } myHuff.Destroy(); } return 0; }
24.333333
92
0.485701
dengchongsen
a4ff03c671f411a6f871481ddc60d65aef354318
6,233
cpp
C++
raw-examples/win32/iocp/server.cpp
paoqi1997/pqnet
3413916bdc355b0a4eea8ef934a3ff658b047b19
[ "BSD-3-Clause" ]
null
null
null
raw-examples/win32/iocp/server.cpp
paoqi1997/pqnet
3413916bdc355b0a4eea8ef934a3ff658b047b19
[ "BSD-3-Clause" ]
null
null
null
raw-examples/win32/iocp/server.cpp
paoqi1997/pqnet
3413916bdc355b0a4eea8ef934a3ff658b047b19
[ "BSD-3-Clause" ]
null
null
null
#include <cstdio> #include <cstring> #include <iostream> #include <thread> #include <vector> #include <winsock2.h> unsigned int PORT = 12488; enum io_operation { IO_READ, IO_WRITE }; struct io_context { OVERLAPPED overlapped; SOCKET sockfd; WSABUF wsabuf; char buf[1024]; io_operation opType; }; std::size_t getNumberOfProcessors(); void routine(HANDLE handle, std::size_t id); int main(int argc, char *argv[]) { bool testFlag = argc != 2 ? false : std::atoi(argv[1]); WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } // WSASocketW SOCKET listenfd = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED); if (listenfd == INVALID_SOCKET) { printf("WSASocketW failed with error: %d\n", WSAGetLastError()); WSACleanup(); return 1; } sockaddr_in servaddr; std::memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); // bind if (bind(listenfd, reinterpret_cast<sockaddr*>(&servaddr), sizeof(servaddr)) == -1) { printf("bind failed with error: %d\n", WSAGetLastError()); closesocket(listenfd); WSACleanup(); return 1; } // listen if (listen(listenfd, SOMAXCONN) == -1) { printf("listen failed with error: %d\n", WSAGetLastError()); closesocket(listenfd); WSACleanup(); return 1; } std::size_t nThreads = getNumberOfProcessors(); HANDLE hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, DWORD(nThreads)); std::vector<std::thread> threads; for (std::size_t i = 0; i < nThreads; ++i) { threads.emplace_back(routine, hIOCP, i + 1); } while (!testFlag) { // accept SOCKET connfd = accept(listenfd, nullptr, nullptr); printf("Connection %d coming...\n", int(connfd)); if (CreateIoCompletionPort(reinterpret_cast<HANDLE>(connfd), hIOCP, 0, 0) == nullptr) { printf("CreateIoCompletionPort failed with error: %d\n", WSAGetLastError()); closesocket(connfd); break; } else { auto io_ctx = new io_context; std::memset(io_ctx->buf, 0, sizeof(io_ctx->buf)); std::memset(&io_ctx->overlapped, 0, sizeof(io_ctx->overlapped)); DWORD recvBytes = sizeof(io_ctx->buf); io_ctx->sockfd = connfd; io_ctx->wsabuf.buf = io_ctx->buf; io_ctx->wsabuf.len = recvBytes; io_ctx->opType = IO_READ; DWORD flags = 0; // 接着是读操作,投递WSARecv请求 int iResult = WSARecv( connfd, &io_ctx->wsabuf, 1, &recvBytes, &flags, &io_ctx->overlapped, nullptr ); if (iResult == SOCKET_ERROR && WSAGetLastError() != ERROR_IO_PENDING) { printf("WSARecv failed with error: %d\n", WSAGetLastError()); closesocket(connfd); delete io_ctx; break; } } } for (std::size_t i = 0; i < nThreads; ++i) { PostQueuedCompletionStatus(hIOCP, 0, SOCKET_ERROR, nullptr); } for (auto& t : threads) { t.join(); } CloseHandle(hIOCP); closesocket(listenfd); WSACleanup(); return 0; } std::size_t getNumberOfProcessors() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; } void routine(HANDLE handle, std::size_t id) { HANDLE hIOCP = handle; DWORD ioSize = 0; ULONG_PTR completionKey; LPOVERLAPPED lpoverlapped = nullptr; for (;;) { BOOL succ = GetQueuedCompletionStatus( hIOCP, &ioSize, &completionKey, &lpoverlapped, INFINITE ); auto io_ctx = reinterpret_cast<io_context*>(lpoverlapped); if (!succ) { if (ioSize == 0) { printf("Connection %d closing...\n", int(io_ctx->sockfd)); closesocket(io_ctx->sockfd); delete io_ctx; continue; } else { printf("GetQueuedCompletionStatus failed with error: %d\n", WSAGetLastError()); break; } } else if (completionKey == SOCKET_ERROR) { printf("Thread %zu exited.\n", id); break; } // 读操作完成 if (io_ctx->opType == IO_READ) { std::memset(&io_ctx->overlapped, 0, sizeof(io_ctx->overlapped)); DWORD sendBytes = DWORD(std::strlen(io_ctx->buf) + 1); io_ctx->wsabuf.buf = io_ctx->buf; io_ctx->wsabuf.len = sendBytes; io_ctx->opType = IO_WRITE; DWORD flags = 0; // 接着是写操作,投递WSASend请求 int iResult = WSASend( io_ctx->sockfd, &io_ctx->wsabuf, 1, &sendBytes, flags, &io_ctx->overlapped, nullptr ); if (iResult == SOCKET_ERROR && WSAGetLastError() != ERROR_IO_PENDING) { printf("WSASend failed with error: %d\n", WSAGetLastError()); closesocket(io_ctx->sockfd); delete io_ctx; continue; } printf("Recv: %s\n", io_ctx->buf); } // 写操作完成 else if (io_ctx->opType == IO_WRITE) { std::memset(&io_ctx->overlapped, 0, sizeof(io_ctx->overlapped)); DWORD recvBytes = sizeof(io_ctx->buf); io_ctx->wsabuf.buf = io_ctx->buf; io_ctx->wsabuf.len = recvBytes; io_ctx->opType = IO_READ; DWORD flags = 0; // 接着是读操作,投递WSARecv请求 int iResult = WSARecv( io_ctx->sockfd, &io_ctx->wsabuf, 1, &recvBytes, &flags, &io_ctx->overlapped, nullptr ); if (iResult == SOCKET_ERROR && WSAGetLastError() != ERROR_IO_PENDING) { printf("WSARecv failed with error: %d\n", WSAGetLastError()); closesocket(io_ctx->sockfd); delete io_ctx; continue; } } } }
30.257282
101
0.562811
paoqi1997
350774fcc5897c066f5d9f9caf9a6a5d2bf356b9
267
hpp
C++
src/query/iexpression.hpp
kele/graphbase
7f2eaced4b3ed8324f35edcc84c2eb774bb87ed3
[ "MIT" ]
null
null
null
src/query/iexpression.hpp
kele/graphbase
7f2eaced4b3ed8324f35edcc84c2eb774bb87ed3
[ "MIT" ]
3
2018-07-02T07:39:57.000Z
2019-10-11T20:20:09.000Z
src/query/iexpression.hpp
kele/graphbase
7f2eaced4b3ed8324f35edcc84c2eb774bb87ed3
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "query/value/value.hpp" namespace query { class Environment; class IExpression { public: virtual value::Value eval(std::shared_ptr<const Environment> env) const = 0; virtual ~IExpression() {} }; } // namespace query
14.052632
78
0.715356
kele
350ab8b5e014c5d547ac5476b978725611e30897
224
cpp
C++
test/Euler.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
null
null
null
test/Euler.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
6
2021-01-05T07:39:05.000Z
2021-01-05T07:44:31.000Z
test/Euler.test.cpp
yuruhi/library
fecbd92ec6c6997d50bf954c472ac4bfeff74de5
[ "Apache-2.0" ]
null
null
null
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/6/NTL/all/NTL_1_D" #include "./../math/Euler.cpp" #include <iostream> using namespace std; int main() { long long x; cin >> x; cout << Euler(x) << '\n'; }
22.4
84
0.660714
yuruhi
350fc45e7301eee359f4c11ffddf9ecf82b98dc2
163
cpp
C++
source/horizon/list/ListSeparator.cpp
NightYoshi370/Aether
87d2b81f5d3143e39c363a9c81c195d440d7a4e8
[ "MIT" ]
9
2020-05-06T20:23:22.000Z
2022-01-19T10:37:46.000Z
libs/Aether/source/horizon/list/ListSeparator.cpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
11
2020-03-22T03:40:50.000Z
2020-06-09T00:53:13.000Z
libs/Aether/source/horizon/list/ListSeparator.cpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
6
2020-05-03T06:59:36.000Z
2020-07-15T04:21:59.000Z
#include "Aether/horizon/list/ListSeparator.hpp" namespace Aether { ListSeparator::ListSeparator(unsigned int h) : Element() { this->setH(h); } };
23.285714
62
0.668712
NightYoshi370
35132acfc0d51ccf43049f550dd95b92d859183f
3,705
cpp
C++
lib/src/spec/priv/specwriterimpl.cpp
SMillerDev/apngasm
259640f81f0798fd1ca3cc513d77cf86d64376c4
[ "Zlib" ]
195
2015-01-05T19:27:31.000Z
2022-03-16T00:52:21.000Z
lib/src/spec/priv/specwriterimpl.cpp
SMillerDev/apngasm
259640f81f0798fd1ca3cc513d77cf86d64376c4
[ "Zlib" ]
47
2015-04-09T15:29:01.000Z
2022-03-27T00:11:34.000Z
lib/src/spec/priv/specwriterimpl.cpp
SMillerDev/apngasm
259640f81f0798fd1ca3cc513d77cf86d64376c4
[ "Zlib" ]
27
2015-02-05T02:09:08.000Z
2021-11-23T21:25:32.000Z
#include "specwriterimpl.h" #include "../../apngasm.h" #include "../../listener/apngasmlistener.h" #include <sstream> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/xml_parser.hpp> namespace apngasm { namespace spec { namespace priv { // Initialize AbstractSpecWriterImpl object. AbstractSpecWriterImpl::AbstractSpecWriterImpl(const APNGAsm* pApngasm, const listener::IAPNGAsmListener* pListener) : _pApngasm(pApngasm) , _pListener(pListener) { // nop } // Initialize JSONSpecWriterImpl object. JSONSpecWriterImpl::JSONSpecWriterImpl(const APNGAsm* pApngasm, const listener::IAPNGAsmListener* pListener) : AbstractSpecWriterImpl(pApngasm, pListener) { // nop } // Write APNGAsm object to spec file. // Return true if write succeeded. bool JSONSpecWriterImpl::write(const std::string& filePath, const std::string& imagePathPrefix) const { boost::property_tree::ptree root; // Write apngasm fields. // root.put("name", _pApngasm->name()); root.put("loops", _pApngasm->getLoops()); root.put("skip_first", _pApngasm->isSkipFirst()); { boost::property_tree::ptree child; std::vector<APNGFrame>& frames = const_cast<std::vector<APNGFrame>&>(_pApngasm->getFrames()); const int count = frames.size(); for (int i = 0; i < count; ++i) { const std::string file = _pListener->onCreatePngPath(imagePathPrefix, i); std::ostringstream delay; delay << frames[i].delayNum() << "/" << frames[i].delayDen(); boost::property_tree::ptree frame; frame.push_back(std::make_pair( file, boost::property_tree::ptree(delay.str()) )); child.push_back(std::make_pair("", frame)); } root.add_child("frames", child); } write_json(filePath, root); return true; } // Initialize XMLSpecWriterImpl object. XMLSpecWriterImpl::XMLSpecWriterImpl(const APNGAsm* pApngasm, const listener::IAPNGAsmListener* pListener) : AbstractSpecWriterImpl(pApngasm, pListener) { // nop } // Write APNGAsm object to spec file. // Return true if write succeeded. bool XMLSpecWriterImpl::write(const std::string& filePath, const std::string& imagePathPrefix) const { boost::property_tree::ptree root; // Write apngasm fields. // root.put("animation.<xmlattr>.name", _pApngasm->name()); root.put("animation.<xmlattr>.loops", _pApngasm->getLoops()); root.put("animation.<xmlattr>.skip_first", _pApngasm->isSkipFirst()); { boost::property_tree::ptree child; std::vector<APNGFrame>& frames = const_cast<std::vector<APNGFrame>&>(_pApngasm->getFrames()); // gununu... const int count = frames.size(); for(int i = 0; i < count; ++i) { const std::string file = _pListener->onCreatePngPath(imagePathPrefix, i); std::ostringstream delay; delay << frames[i].delayNum() << "/" << frames[i].delayDen(); boost::property_tree::ptree& frame = root.add("animation.frame", ""); frame.put("<xmlattr>.src", file); frame.put("<xmlattr>.delay", delay.str()); } } write_xml(filePath, root); return true; } } // namespace priv } // namespace spec } // namespace apngasm
35.625
124
0.584076
SMillerDev
352054bd496e0631b2ed0aa8eeb80d0ec5767e47
2,067
cpp
C++
main/tube-manager.cpp
NeilBetham/neon-dreams
710e8cb105915bb1dec176a0bedc88fb51dce7a6
[ "MIT" ]
null
null
null
main/tube-manager.cpp
NeilBetham/neon-dreams
710e8cb105915bb1dec176a0bedc88fb51dce7a6
[ "MIT" ]
null
null
null
main/tube-manager.cpp
NeilBetham/neon-dreams
710e8cb105915bb1dec176a0bedc88fb51dce7a6
[ "MIT" ]
null
null
null
#include "tube-manager.hpp" #include <esp_log.h> #include <sys/time.h> #include <time.h> TubeManager::TubeManager(TubeDriver& _td) : td(_td), poison_prev_int(300), poison_prev_dur(10) {}; void TubeManager::set_digits(uint8_t _one, uint8_t _two, uint8_t _three, uint8_t _four, uint8_t _five, uint8_t _six) { one = _one; two = _two; three = _three; four = _four; five = _five; six = _six; digits_set = true; } void TubeManager::tick_10ms() { if(!digits_set) { if(scan_count % 10 == 0) { if(scan_increment) { scan_pos++; } else { scan_pos--; } if(scan_pos >= 6) { scan_increment = false; scan_pos = 6; } else if(scan_pos <= 1) { scan_increment = true; scan_pos = 1; } // Update the tubes one = (0x02 >> scan_pos) & 0x01; two = (0x04 >> scan_pos) & 0x01; three = (0x08 >> scan_pos) & 0x01; four = (0x10 >> scan_pos) & 0x01; five = (0x20 >> scan_pos) & 0x01; six = (0x40 >> scan_pos) & 0x01; one = one > 0 ? one : -1; two = two > 0 ? two : -1; three = three > 0 ? three : -1; four = four > 0 ? four : -1; five = five > 0 ? five : -1; six = six > 0 ? six : -1; } scan_count++; td.set_tubes(one, two, three, four, five, six); return; } time_t now = 0; time(&now); if(poison_prev_active && ((now - poison_prev_start) < poison_prev_dur)) { td.set_tubes( one_index, (one_index + 1) % 10, (one_index + 2) % 10, (one_index + 3) % 10, (one_index + 4) % 10, (one_index + 5) % 10 ); one_index++; one_index %= 10; } else { td.set_tubes(one, two, three, four, five, six); poison_prev_active = false; } // Don't run prevention on startup if(now - 1200 > poison_prev_start){ poison_prev_start = now; return; } // Posion prevention is needed, run now if(now > poison_prev_start + poison_prev_int){ poison_prev_start = now; poison_prev_active = true; one_index = 0; } }
22.225806
118
0.557813
NeilBetham
3522c8f5360c851e99c3d9fb99c7d3ac90699c0f
1,541
cpp
C++
cpp/include/graph/articulation_points.cpp
kyuridenamida/competitive-library
a2bea434c4591359c208b865d2d4dc25574df24d
[ "MIT" ]
3
2017-04-09T10:12:31.000Z
2019-02-11T03:11:27.000Z
cpp/include/graph/articulation_points.cpp
kyuridenamida/competitive-library
a2bea434c4591359c208b865d2d4dc25574df24d
[ "MIT" ]
null
null
null
cpp/include/graph/articulation_points.cpp
kyuridenamida/competitive-library
a2bea434c4591359c208b865d2d4dc25574df24d
[ "MIT" ]
1
2019-11-29T06:11:10.000Z
2019-11-29T06:11:10.000Z
#pragma once #include "../util.hpp" template <typename Edge> pair<set<int>, vector<vector<Edge>>> articulation_points(const vector<vector<Edge>> &g) { const int n = g.size(); set<int> art; vector<vector<Edge>> connect; vector<Edge> st; vector<int> order(n, -1), low(n, -1); for (int i = 0; i < n; i++) { if (order[i] != -1) continue; int cnt = 0; function<void(int,int)> dfs = [&](int from, int parent) { low[from] = order[from] = cnt++; for (Edge e : g[from]) { const int to = e.to; if (to != parent && order[to] < order[from]) st.push_back(e); if (order[to] == -1) { dfs(to, from); low[from] = min(low[from], low[to]); if ((order[from] == 0 && order[to] != 1) || (order[from] != 0 && low[to] >= order[from])) art.insert(from); if (low[to] >= order[from]) { connect.push_back(vector<Edge>()); for (;;) { Edge edge = st.back(); st.pop_back(); connect.back().push_back(edge); if (edge.from == from && edge.to == to) break; } } } else { low[from] = min(low[from], order[to]); } } }; dfs(i, i); } return make_pair(move(art), move(connect)); } struct Edge { int from, to; Edge(int s, int t) : from(s), to(t) {} }; using Graph = vector<vector<Edge>>; void add_edge(Graph &g, int from, int to) { g[from].push_back(Edge(from, to)); g[to].push_back(Edge(to, from)); }
27.517857
89
0.499676
kyuridenamida
352547ead12141ae5203b8514806f65265ead9b9
4,294
cpp
C++
io_handler.cpp
bilyanhadzhi/travellers_app
5cb5b0bcd9b03771e55db5d28c052e10dbc460f7
[ "MIT" ]
null
null
null
io_handler.cpp
bilyanhadzhi/travellers_app
5cb5b0bcd9b03771e55db5d28c052e10dbc460f7
[ "MIT" ]
null
null
null
io_handler.cpp
bilyanhadzhi/travellers_app
5cb5b0bcd9b03771e55db5d28c052e10dbc460f7
[ "MIT" ]
2
2021-04-27T15:11:01.000Z
2021-06-07T11:31:56.000Z
#include <iostream> #include <cstring> #include "io_handler.hpp" #include "lib/string.hpp" #include "constants.hpp" void IOHandler::set_command(String command) { this->command = command; } void IOHandler::input_command() { std::cin >> this->command; } void IOHandler::input_args(std::istream& i_stream) { this->clean_args(); String args_string = ""; args_string.input(i_stream, true); if (args_string == "") { return; } String curr_arg; int args_str_len = args_string.get_len(); int i = 0; while (args_string[i] == ' ') { ++i; } while (i < args_str_len) { if (args_string[i] != ' ') { curr_arg += args_string[i]; ++i; } else { while (args_string[i] == ' ') { ++i; } curr_arg += '\0'; this->args.push(curr_arg); curr_arg = ""; } } if (curr_arg != "") { this->args.push(curr_arg); } return; } String IOHandler::get_command() const { return this->command; } Vector<String> IOHandler::get_args() const { return this->args; } void IOHandler::clean_args() { this->args.empty_vector(); } bool IOHandler::check_number_of_arguments(int num_of_args) const { return this->args.get_len() == num_of_args; } void IOHandler::print_prompt() const { std::cout << SHELL_PROMPT; } void IOHandler::print_message(String message, String prefix) const { if (prefix.get_len() > 0) { std::cout << prefix << ": "; } if (message.get_len() > 0) { std::cout << message << std::endl; } } void IOHandler::print_usage(String command, String usage, bool with_prefix) const { if (with_prefix) { std::cout << "Usage: "; } std::cout << command; if (usage.get_len() > 0) { std::cout << " " << usage << std::endl; } else { std::cout << " (no args)" << std::endl; } } void IOHandler::print_error(String desc) const { this->print_message(desc, "Error"); } void IOHandler::print_not_logged_in() const { this->print_error("No user is currently logged in"); } void IOHandler::print_error_explain(String desc) const { std::cout << " "; std::cout << desc << std::endl; } void IOHandler::print_unknown_command() const { this->print_message("Unknown command. Type 'help' for a list of commands."); } void IOHandler::print_success(String message) const { this->print_message(message, "Success"); } void IOHandler::print_help() const { this->print_message("\nTraveller's App commands:\n"); this->print_usage(COMMAND_REGISTER, USAGE_REGISTER, false); this->print_message(" – adds a new user.\n"); this->print_usage(COMMAND_LOG_IN, USAGE_LOG_IN, false); this->print_message(" – logs user in via username.\n"); this->print_usage(COMMAND_DESTINATIONS, "", false); this->print_message(" – displays all destinations with their name, number of visits and average rating.\n"); this->print_usage(COMMAND_ADD_DESTINATION, USAGE_ADD_DESTINATION, false); this->print_message(" – adds a new destination to the database.\n"); this->print_usage(COMMAND_DESTINATION_INFO, USAGE_DESTINATION_INFO, false); this->print_message(" – displays additional information about a destination, including visits by friends.\n"); this->print_usage(COMMAND_MY_TRIPS, "", false); this->print_message(" – displays all trips of current user.\n"); this->print_usage(COMMAND_ADD_TRIP, "", false); this->print_message(" – interactive command to add a new trip.\n"); this->print_usage(COMMAND_MY_FRIENDS, "", false); this->print_message(" – displays friends of current user.\n"); this->print_usage(COMMAND_ADD_FRIEND, USAGE_ADD_FRIEND, false); this->print_message(" – adds new friend for user.\n"); this->print_usage(COMMAND_LOG_OUT, "", false); this->print_message(" – logs current user out.\n"); this->print_usage(COMMAND_HELP, "", false); this->print_message(" – shows possible commands of application.\n"); this->print_usage(COMMAND_EXIT, "", false); this->print_message(" – exits the application.\n"); }
22.719577
115
0.620633
bilyanhadzhi
35329718a73df43768870b66ca112156b4d0d3d3
569
cpp
C++
src/primality/BailliePSW.cpp
Ghabriel/CryptographyUtils
37a6e6418025059d908d75b5329fc21339e20b2b
[ "Apache-2.0" ]
null
null
null
src/primality/BailliePSW.cpp
Ghabriel/CryptographyUtils
37a6e6418025059d908d75b5329fc21339e20b2b
[ "Apache-2.0" ]
null
null
null
src/primality/BailliePSW.cpp
Ghabriel/CryptographyUtils
37a6e6418025059d908d75b5329fc21339e20b2b
[ "Apache-2.0" ]
null
null
null
#include "primality/BailliePSW.hpp" #include "primality/MillerRabin.hpp" #include "primality/LucasTest.hpp" #include "utils.hpp" bool crypto::BailliePSW::test(NumberView n) const { if (n < 3 || n % 2 == 0) { return (n == 2); } if (!MillerRabin().test(n, {2})) { return false; } if (isPerfectSquare(n)) { return false; } Number d = 5; while (jacobiSymbol(d, n) != -1) { d = (d >= 0 ? -(d + 2) : -(d - 2)); } Number p = 1; Number q = (1 - d) / 4; return LucasTest().test(n, d, p, q); }
20.321429
51
0.513181
Ghabriel
353528f2d91877067e99a980fdb5f84c4c7e7cf6
15,111
cpp
C++
src/priority/test.cpp
tehwalris/mpi-myers-diff
9d6dafc9dc16dcf97b4c712dbb8c6dace25eeee5
[ "MIT" ]
2
2021-11-09T11:30:02.000Z
2022-01-13T17:47:49.000Z
src/priority/test.cpp
tehwalris/mpi-myers-diff
9d6dafc9dc16dcf97b4c712dbb8c6dace25eeee5
[ "MIT" ]
null
null
null
src/priority/test.cpp
tehwalris/mpi-myers-diff
9d6dafc9dc16dcf97b4c712dbb8c6dace25eeee5
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <iostream> #include <vector> #include <optional> #include <cassert> #include <algorithm> #include "../../lib/catch/catch_amalgamated.hpp" #include "strategy.hpp" #include "geometry.hpp" #include "side.hpp" #include "partition.hpp" #include "storage.hpp" template <class S> class TestStrategyFollower { public: std::vector<std::pair<CellLocation, Side>> sends; TestStrategyFollower( S *storage, int final_result_count) : storage(storage), final_result_count(final_result_count) {} inline void set(int d, int k, int v) { storage->set(d, k, v); } bool calculate(int d, int k) { assert(d >= 0 && abs(k) <= d); if (k > -d) { storage->get(d - 1, k - 1); } if (k < d) { storage->get(d - 1, k + 1); } storage->set(d, k, 0); // fake value num_calculated++; return num_calculated == final_result_count; } void send(int d, int k, Side to) { storage->get(d, k); sends.emplace_back(CellLocation(d, k), to); } int get_num_directly_calculated() { return num_calculated; } private: S *storage; int final_result_count; int num_calculated = 0; }; TEST_CASE("Strategy - concrete example (green)") { // This tests the strategy with the tasks of the green worker from the custom figure in our first (progress) presentation RoundRobinPartition partition(3, 1); ReceiveSideIterator left_receive_begin(partition, Side::Left); ReceiveSideIterator left_receive_end(partition); ReceiveSideIterator right_receive_begin(partition, Side::Right); ReceiveSideIterator right_receive_end(partition); PerSide future_receive_begins(left_receive_begin, right_receive_begin); PerSide future_receive_ends(left_receive_end, right_receive_end); SendSideIterator left_send_begin(partition, Side::Left); SendSideIterator left_send_end(partition); SendSideIterator right_send_begin(partition, Side::Right); SendSideIterator right_send_end(partition); PerSide future_send_begins(left_send_begin, right_send_begin); PerSide future_send_ends(left_send_end, right_send_end); const int d_max = 7; SimpleStorage storage(d_max); TestStrategyFollower<SimpleStorage> follower(&storage, 12); Strategy strategy(&follower, future_receive_begins, future_receive_ends, future_send_begins, future_send_ends, d_max, Strategy<void *, void *, void *>::no_diamond_height_limit); const int dummy = 0; REQUIRE(!strategy.is_done()); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 0); REQUIRE(follower.sends.size() == 0); strategy.receive(Side::Left, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 1); REQUIRE(follower.sends.size() == 1); strategy.receive(Side::Left, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 2); REQUIRE(follower.sends.size() == 2); strategy.receive(Side::Left, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 2); REQUIRE(follower.sends.size() == 2); strategy.receive(Side::Right, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 4); REQUIRE(follower.sends.size() == 2); strategy.receive(Side::Right, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 5); REQUIRE(follower.sends.size() == 3); REQUIRE(!strategy.is_blocked_waiting_for_receive()); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 6); REQUIRE(follower.sends.size() == 3); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 6); REQUIRE(follower.sends.size() == 3); REQUIRE(strategy.is_blocked_waiting_for_receive()); strategy.receive(Side::Right, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 7); REQUIRE(follower.sends.size() == 3); strategy.receive(Side::Left, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 8); REQUIRE(follower.sends.size() == 4); REQUIRE(!strategy.is_blocked_waiting_for_receive()); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 10); REQUIRE(follower.sends.size() == 4); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 10); REQUIRE(follower.sends.size() == 4); REQUIRE(strategy.is_blocked_waiting_for_receive()); strategy.receive(Side::Left, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 11); REQUIRE(follower.sends.size() == 4); REQUIRE(!strategy.is_done()); strategy.receive(Side::Right, dummy); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == 12); REQUIRE(follower.sends.size() == 4); REQUIRE(strategy.is_done()); REQUIRE(!strategy.is_blocked_waiting_for_receive()); REQUIRE(strategy.get_final_result_location().has_value()); std::vector<std::pair<CellLocation, Side>> expected_sends{ std::make_pair(CellLocation(1, 1), Side::Right), std::make_pair(CellLocation(2, 0), Side::Left), std::make_pair(CellLocation(4, 2), Side::Right), std::make_pair(CellLocation(5, -1), Side::Left), }; REQUIRE(follower.sends.size() == expected_sends.size()); for (int i = 0; i < expected_sends.size(); i++) { REQUIRE(follower.sends.at(i).first == expected_sends.at(i).first); REQUIRE(follower.sends.at(i).second == expected_sends.at(i).second); } } TEST_CASE("Strategy - whole pyramid") { const int d_max = 20; PerSide<std::vector<CellLocation>> future_receives(std::vector<CellLocation>{}, std::vector<CellLocation>{}); PerSide<std::vector<CellLocation>::const_iterator> future_receive_begins(future_receives.at(Side::Left).begin(), future_receives.at(Side::Right).begin()); PerSide<std::vector<CellLocation>::const_iterator> future_receive_ends(future_receives.at(Side::Left).end(), future_receives.at(Side::Right).end()); PerSide<std::vector<CellLocation>> future_sends(std::vector<CellLocation>{}, std::vector<CellLocation>{}); PerSide<std::vector<CellLocation>::const_iterator> future_send_begins(future_sends.at(Side::Left).begin(), future_sends.at(Side::Right).begin()); PerSide<std::vector<CellLocation>::const_iterator> future_send_ends(future_sends.at(Side::Left).end(), future_sends.at(Side::Right).end()); SimpleStorage storage(d_max); TestStrategyFollower<SimpleStorage> follower(&storage, -1); Strategy strategy(&follower, future_receive_begins, future_receive_ends, future_send_begins, future_send_ends, d_max, Strategy<void *, void *, void *>::no_diamond_height_limit); REQUIRE(!strategy.is_done()); REQUIRE(follower.get_num_directly_calculated() == 0); strategy.run(); REQUIRE(follower.get_num_directly_calculated() == ((d_max + 1) * (d_max + 1) + (d_max + 1)) / 2); } TEST_CASE("RoundRobinPartition - concrete example (green)") { // This tests the partition calculator with the tasks of the green worker from the custom figure in our first (progress) presentation RoundRobinPartition partition(3, 1); // d 0 REQUIRE(!partition.has_work()); REQUIRE(partition.should_send() == PerSide(false, false)); REQUIRE(partition.should_receive() == PerSide(false, false)); partition.next_d_layer(); // starting from d 1 std::vector<std::pair<int, int>> k_ranges{ std::make_pair(1, 1), std::make_pair(0, 0), std::make_pair(1, 1), std::make_pair(0, 2), std::make_pair(-1, 1), std::make_pair(0, 2), std::make_pair(-1, 3), }; std::vector<PerSide<bool>> should_sends{ PerSide(false, true), PerSide(true, false), PerSide(false, false), PerSide(false, true), PerSide(true, false), PerSide(false, false), PerSide(false, true), }; std::vector<PerSide<bool>> should_receives{ PerSide(true, false), PerSide(true, false), PerSide(false, true), PerSide(true, true), PerSide(true, false), PerSide(false, true), PerSide(true, true), }; assert(k_ranges.size() == should_sends.size() && should_sends.size() == should_receives.size()); for (int i = 0; i < k_ranges.size(); i++) { REQUIRE(partition.has_work()); REQUIRE(partition.get_k_range().first == k_ranges.at(i).first); REQUIRE(partition.get_k_range().second == k_ranges.at(i).second); REQUIRE(partition.should_send() == should_sends.at(i)); REQUIRE(partition.should_receive() == should_receives.at(i)); partition.next_d_layer(); } } TEST_CASE("RoundRobinPartition - concrete example (red)") { // This tests the partition calculator with the tasks of the red worker from the custom figure in our first (progress) presentation RoundRobinPartition partition(3, 0); // starting from d 0 std::vector<std::pair<int, int>> k_ranges{ std::make_pair(0, 0), std::make_pair(-1, -1), std::make_pair(-2, -2), std::make_pair(-3, -1), std::make_pair(-4, -2), std::make_pair(-5, -3), std::make_pair(-6, -2), std::make_pair(-7, -3), }; std::vector<PerSide<bool>> should_sends{ PerSide(false, true), PerSide(false, true), PerSide(false, false), PerSide(false, true), PerSide(false, true), PerSide(false, false), PerSide(false, true), PerSide(false, true), }; std::vector<PerSide<bool>> should_receives{ PerSide(false, false), PerSide(false, false), PerSide(false, false), PerSide(false, true), PerSide(false, false), PerSide(false, false), PerSide(false, true), PerSide(false, false), }; assert(k_ranges.size() == should_sends.size() && should_sends.size() == should_receives.size()); for (int i = 0; i < k_ranges.size(); i++) { REQUIRE(partition.has_work()); REQUIRE(partition.get_k_range().first == k_ranges.at(i).first); REQUIRE(partition.get_k_range().second == k_ranges.at(i).second); REQUIRE(partition.should_send() == should_sends.at(i)); REQUIRE(partition.should_receive() == should_receives.at(i)); partition.next_d_layer(); } } TEST_CASE("ReceiveSideIterator - concrete example (green)") { // This test uses tasks of the green worker from the custom figure in our first (progress) presentation PerSide<std::vector<CellLocation>> future_receives(std::vector<CellLocation>{}, std::vector<CellLocation>{}); future_receives.at(Side::Left).emplace_back(0, 0); future_receives.at(Side::Left).emplace_back(1, -1); future_receives.at(Side::Left).emplace_back(3, -1); future_receives.at(Side::Left).emplace_back(4, -2); future_receives.at(Side::Left).emplace_back(6, -2); future_receives.at(Side::Right).emplace_back(2, 2); future_receives.at(Side::Right).emplace_back(3, 3); future_receives.at(Side::Right).emplace_back(5, 3); future_receives.at(Side::Right).emplace_back(6, 4); for (Side side : {Side::Left, Side::Right}) { ReceiveSideIterator it(RoundRobinPartition(3, 1), side); for (CellLocation expected_receive : future_receives.at(side)) { REQUIRE(*it == expected_receive); it++; } } } TEST_CASE("SendSideIterator - concrete example (green)") { // This test uses tasks of the green worker from the custom figure in our first (progress) presentation PerSide<std::vector<CellLocation>> future_sends(std::vector<CellLocation>{}, std::vector<CellLocation>{}); future_sends.at(Side::Left).emplace_back(2, 0); future_sends.at(Side::Left).emplace_back(5, -1); future_sends.at(Side::Right).emplace_back(1, 1); future_sends.at(Side::Right).emplace_back(4, 2); for (Side side : {Side::Left, Side::Right}) { SendSideIterator it(RoundRobinPartition(3, 1), side); for (CellLocation expected_send : future_sends.at(side)) { REQUIRE(*it == expected_send); it++; } } } TEST_CASE("SendSideIterator - concrete example (blue)") { // This test uses tasks of the blue worker from the custom figure in our first (progress) presentation RoundRobinPartition partition(3, 2); SendSideIterator end_it(partition); SendSideIterator left_it(partition, Side::Left); assert(left_it != end_it); REQUIRE(*left_it == CellLocation(2, 2)); left_it++; REQUIRE(*left_it == CellLocation(3, 3)); left_it++; REQUIRE(*left_it == CellLocation(5, 3)); left_it++; REQUIRE(*left_it == CellLocation(6, 4)); left_it++; SendSideIterator right_it(partition, Side::Right); assert(right_it == end_it); } TEST_CASE("triangle_through_points") { REQUIRE(triangle_through_points(CellLocation(0, 0), CellLocation(0, 0)) == CellLocation(0, 0)); REQUIRE(triangle_through_points(CellLocation(5, 3), CellLocation(5, 3)) == CellLocation(5, 3)); REQUIRE(triangle_through_points(CellLocation(3, -3), CellLocation(2, 2)) == CellLocation(5, -1)); REQUIRE(triangle_through_points(CellLocation(3, -3), CellLocation(5, -1)) == CellLocation(5, -1)); REQUIRE(triangle_through_points(CellLocation(5, -1), CellLocation(2, 2)) == CellLocation(5, -1)); } TEST_CASE("intersect_diagonals") { // these are equivalent to the results form triangle_through_points REQUIRE(intersect_diagonals(CellLocation(0, 0), CellLocation(0, 0)) == CellLocation(0, 0)); REQUIRE(intersect_diagonals(CellLocation(5, 3), CellLocation(5, 3)) == CellLocation(5, 3)); REQUIRE(intersect_diagonals(CellLocation(3, -3), CellLocation(2, 2)) == CellLocation(5, -1)); REQUIRE(intersect_diagonals(CellLocation(3, -3), CellLocation(5, -1)) == CellLocation(5, -1)); REQUIRE(intersect_diagonals(CellLocation(5, -1), CellLocation(2, 2)) == CellLocation(5, -1)); // these are not valid with triangle_through_points REQUIRE(intersect_diagonals(CellLocation(0, 0), CellLocation(3, 1)) == CellLocation(2, 2)); REQUIRE(intersect_diagonals(CellLocation(7, -1), CellLocation(2, -2)) == CellLocation(4, -4)); REQUIRE(intersect_diagonals(CellLocation(7, -1), CellLocation(2, 2)) == CellLocation(6, -2)); } TEST_CASE("limit_diamond_height") { auto d = [](int top_d, int top_k, int bottom_d, int bottom_k) { return std::make_pair(CellLocation(top_d, top_k), CellLocation(bottom_d, bottom_k)); }; REQUIRE(limit_diamond_height(d(0, 0, 0, 0), 1) == d(0, 0, 0, 0)); REQUIRE(limit_diamond_height(d(52, -7, 52, -7), 1) == d(52, -7, 52, -7)); REQUIRE(limit_diamond_height(d(0, 0, 15, 8), 20) == d(0, 0, 15, 8)); REQUIRE(limit_diamond_height(d(0, 0, 8, -3), 9) == d(0, 0, 8, -3)); REQUIRE(limit_diamond_height(d(7, -2, 15, -4), 9) == d(7, -2, 15, -4)); REQUIRE(limit_diamond_height(d(0, 0, 6, 0), 3).second == d(0, 0, 2, 0).second); REQUIRE(limit_diamond_height(d(0, 0, 6, 0), 2).second == d(0, 0, 1, -1).second); REQUIRE(limit_diamond_height(d(0, 0, 4, 0), 2).second == d(0, 0, 1, -1).second); REQUIRE(limit_diamond_height(d(0, 0, 6, 0), 1).second == d(0, 0, 0, 0).second); REQUIRE(limit_diamond_height(d(0, 0, 6, -2), 6) == d(0, 0, 5, -1)); REQUIRE(limit_diamond_height(d(0, 0, 6, 2), 6) == d(0, 0, 5, 1)); REQUIRE(limit_diamond_height(d(0, 0, 6, 2), 1) == d(0, 0, 0, 0)); REQUIRE(limit_diamond_height(d(0, 0, 6, 2), 2).second == d(0, 0, 1, -1).second); REQUIRE(limit_diamond_height(d(0, 0, 2, 0), 2) == d(0, 0, 1, -1)); }
36.766423
179
0.688836
tehwalris
3535c4868f10aae85a3adf251a8027926752d063
2,283
hpp
C++
src/third-party/arduino-json-5.6.7/include/ArduinoJson/Polyfills/math.hpp
syahrialr/firebase-arduino
7144703dc6269bee4e60b60fa612f41aeeb5a75f
[ "Apache-2.0" ]
10
2017-08-18T20:02:40.000Z
2021-07-17T09:04:47.000Z
src/third-party/arduino-json-5.6.7/include/ArduinoJson/Polyfills/math.hpp
syahrialr/firebase-arduino
7144703dc6269bee4e60b60fa612f41aeeb5a75f
[ "Apache-2.0" ]
null
null
null
src/third-party/arduino-json-5.6.7/include/ArduinoJson/Polyfills/math.hpp
syahrialr/firebase-arduino
7144703dc6269bee4e60b60fa612f41aeeb5a75f
[ "Apache-2.0" ]
7
2018-02-07T08:51:34.000Z
2020-11-30T08:52:05.000Z
// Copyright Benoit Blanchon 2014-2016 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson // If you like this project, please add a star! #pragma once // If Visual Studo <= 2012 #if defined(_MSC_VER) && _MSC_VER <= 1700 #include <float.h> namespace ArduinoJson { namespace Polyfills { template <typename T> bool isNaN(T x) { return _isnan(x) != 0; } template <typename T> bool isInfinity(T x) { return !_finite(x); } } } #else #include <math.h> // GCC warning: "conversion to 'float' from 'double' may alter its value" #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) #pragma GCC diagnostic push #endif #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9) #pragma GCC diagnostic ignored "-Wfloat-conversion" #else #pragma GCC diagnostic ignored "-Wconversion" #endif #endif // Workaround for libs that #undef isnan or isinf // https://github.com/bblanchon/ArduinoJson/issues/284 #if !defined(isnan) || !defined(isinf) namespace std {} #endif namespace ArduinoJson { namespace Polyfills { template <typename T> bool isNaN(T x) { // Workaround for libs that #undef isnan // https://github.com/bblanchon/ArduinoJson/issues/284 #ifndef isnan using namespace std; #endif return isnan(x); } #if defined(_GLIBCXX_HAVE_ISNANL) && _GLIBCXX_HAVE_ISNANL template <> inline bool isNaN<double>(double x) { return isnanl(x); } #endif #if defined(_GLIBCXX_HAVE_ISNANF) && _GLIBCXX_HAVE_ISNANF template <> inline bool isNaN<float>(float x) { return isnanf(x); } #endif template <typename T> bool isInfinity(T x) { // Workaround for libs that #undef isinf // https://github.com/bblanchon/ArduinoJson/issues/284 #ifndef isinf using namespace std; #endif return isinf(x); } #if defined(_GLIBCXX_HAVE_ISINFL) && _GLIBCXX_HAVE_ISINFL template <> inline bool isInfinity<double>(double x) { return isinfl(x); } #endif #if defined(_GLIBCXX_HAVE_ISINFF) && _GLIBCXX_HAVE_ISINFF template <> inline bool isInfinity<float>(float x) { return isinff(x); } #endif #if defined(__GNUC__) #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) #pragma GCC diagnostic pop #endif #endif } } #endif
20.383929
74
0.685064
syahrialr
353fab28e754916226f82460c579ccf94178488a
3,951
cpp
C++
tests/v1/NullsTest.cpp
studiofuga/mSqliteCpp
d557d089bef57fd2ec5ece54d79ca8c34fbc6aca
[ "BSD-3-Clause" ]
3
2018-06-25T20:02:26.000Z
2021-07-08T09:38:33.000Z
tests/v1/NullsTest.cpp
studiofuga/mSqliteCpp
d557d089bef57fd2ec5ece54d79ca8c34fbc6aca
[ "BSD-3-Clause" ]
13
2018-05-05T09:38:39.000Z
2021-03-17T11:48:07.000Z
tests/v1/NullsTest.cpp
studiofuga/mSqliteCpp
d557d089bef57fd2ec5ece54d79ca8c34fbc6aca
[ "BSD-3-Clause" ]
null
null
null
/** @file * @author Federico Fuga <fuga@studiofuga.com> * @date 15/06/18 */ #include "msqlitecpp/v1/insertstatement.h" #include "msqlitecpp/v1/createstatement.h" #include "msqlitecpp/v1/selectstatement.h" #include <gtest/gtest.h> using namespace sqlite; class V1NullTest : public testing::Test { protected: std::shared_ptr<SQLiteStorage> db; public: V1NullTest() { db = std::make_shared<SQLiteStorage>(":memory:"); db->open(); } FieldDef<FieldType::Integer> fieldId{"id", PrimaryKey}; FieldDef<FieldType::Text> fieldText{"text"}; FieldDef<FieldType::Integer> fieldCount{"count"}; FieldDef<FieldType::Real> fieldValue{"value"}; }; TEST_F(V1NullTest, insert) { auto createTable = makeCreateTableStatement2(db, "Insert1", fieldId, fieldText, fieldCount, fieldValue); ASSERT_NO_THROW(createTable.execute()); auto insertStatement_2 = makeInsertStatement(fieldId, fieldText); insertStatement_2.replaceOnConflict(); ASSERT_NO_THROW(insertStatement_2.attach(db, "Insert1")); ASSERT_NO_THROW(insertStatement_2.insert(1, "Sample")); auto select = makeSelectStatement(fieldId, fieldText, fieldCount, fieldValue); select.attach(db, "Insert1"); select.prepare(); // check insert int rId, rCount; std::string rText; double rValue; select.exec([&rId, &rText, &rCount, &rValue](int id, std::string text, int count, double value) { rId = id; rText = text; rCount = count; rValue = value; return true; }); ASSERT_EQ(rId, 1); ASSERT_EQ(rText, "Sample"); ASSERT_EQ(rCount, 0); ASSERT_EQ(rValue, 0); auto insertStatement_3 = makeInsertStatement(fieldId, fieldText, fieldCount, fieldValue); insertStatement_3.replaceOnConflict(); ASSERT_NO_THROW(insertStatement_3.attach(db, "Insert1")); ASSERT_NO_THROW(insertStatement_3.insert(1, nullptr, 10, -4)); select.exec([&rId, &rText, &rCount, &rValue](int id, std::string text, int count, double value) { rId = id; rText = text; rCount = count; rValue = value; return true; }); ASSERT_EQ(rId, 1); ASSERT_EQ(rText, ""); ASSERT_EQ(rCount, 10); ASSERT_EQ(rValue, -4); ASSERT_NO_THROW(insertStatement_3.insert(1, nullptr, nullptr, nullptr)); select.exec([&rId, &rText, &rCount, &rValue](int id, std::string text, int count, double value) { rId = id; rText = text; rCount = count; rValue = value; return true; }); ASSERT_EQ(rId, 1); ASSERT_EQ(rText, ""); ASSERT_EQ(rCount, 0); ASSERT_EQ(rValue, 0); } #if defined(WITH_BOOST) TEST_F(V1NullTest, selectWithNulls) { auto createTable = makeCreateTableStatement2(db, "Insert1", fieldId, fieldText, fieldCount, fieldValue); ASSERT_NO_THROW(createTable.execute()); auto insertStatement_2 = makeInsertStatement(fieldId, fieldText); insertStatement_2.replaceOnConflict(); ASSERT_NO_THROW(insertStatement_2.attach(db, "Insert1")); ASSERT_NO_THROW(insertStatement_2.insert(1, "Sample")); auto select = makeSelectStatement(fieldId, fieldText, fieldCount, fieldValue); select.attach(db, "Insert1"); select.prepare(); boost::optional<int> rId, rCount; boost::optional<std::string> rText; boost::optional<double> rValue; select.execOpt([&rId, &rText, &rCount, &rValue](boost::optional<int> id, boost::optional<std::string> text, boost::optional<int> count, boost::optional<double> value) { rId = id; rText = text; rCount = count; rValue = value; return true; }); ASSERT_TRUE(rId.is_initialized()); ASSERT_TRUE(rText.is_initialized()); ASSERT_FALSE(rCount.is_initialized()); ASSERT_FALSE(rValue.is_initialized()); ASSERT_EQ(rId.value(), 1); ASSERT_EQ(rText.value(), "Sample"); } #endif
28.630435
111
0.65629
studiofuga
353ff98c4cbd09efe4fc222d45086320e92cd95c
47,426
cpp
C++
misc/Analyze.cpp
jwarsom/focus_assembler
190c3ce17c0f805babec5a9cbe053cea6316a112
[ "MIT" ]
null
null
null
misc/Analyze.cpp
jwarsom/focus_assembler
190c3ce17c0f805babec5a9cbe053cea6316a112
[ "MIT" ]
null
null
null
misc/Analyze.cpp
jwarsom/focus_assembler
190c3ce17c0f805babec5a9cbe053cea6316a112
[ "MIT" ]
null
null
null
/* * Analyze.cpp * * Created on: Aug. 6th, 2012 * Author: Julia Warnke */ #include<iostream> #include<vector> #include<string> #include <dirent.h> using namespace std; #include "MappingValues.h" #include "Dictionary.h" #include "Fragment_Index.h" #include "Graph.h" /* This program analyzes a series of overlap graphs according to various graph theoretic characteristics A list of features that I can implement: GC content in read in nodes Node Degree/Overlap Node Degree Node Density (ie. Node Size) Edge Density Gene Alignment Average Alignment Identity Cycles in the overlap graph Output cluster Zoom in and out */ //The help message void help_message(){ cerr<<"\n\n"; cerr<<"\t\t\t Overlap Graph Analyzer"<<endl; cerr<<"\t\t\tWritten by Julia Warnke\n"<<endl; cerr<<"Command line arguments\n"<<endl; cerr<<"--workDir :working directory :required"<<endl; cerr<<"Options\n"<<endl; cerr<<"help : This message"<<endl; cerr<<"displayCurrentGraph : Display the currently selected graph level."<<endl; cerr<<"displayCurrentNode : Display the currently selected node."<<endl; cerr<<"selectGraph (int) : Select a graph level."<<endl; cerr<<"selectNode (int) : Select a node in a graph."<<endl; cerr<<"avgGraphDegree : Display the average graph degree."<<endl; cerr<<"avgGraphOvlLen : Display the average graph overlap length."<<endl; cerr<<"avgGraphOvlIden : Display the average graph overlap identity."<<endl; cerr<<"avgGraphGCcontent : Display the average graph GC content."<<endl; cerr<<"avgGraphEdgeDen : Display the average graph edge density."<<endl; cerr<<"avgGraphClusterSize : Display the average graph cluster size."<<endl; cerr<<"selectClustersGCcontent (int) (min) (max) : Select "<<endl; cerr<<"selectClustersEdgeDen (int) (min) (max) : Select "<<endl; cerr<<"selectClustersSize (int) (min) (max) : Select"<<endl; cerr<<"selectClustersNodeDegree (int) (min) (max) : Select"<<endl; cerr<<"selectClustersAvgChildDegree (int) (min) (max) : Select"<<endl; cerr<<"selectClustersAvgIden (int) (min) (max) : Select"<<endl; cerr<<"selectClustersAvgOvlLen (int) (min) (max) : Select"<<endl; cerr<<"displayClusterGCcontent (int) (int) : Display"<<endl; cerr<<"displayClusterEdgeDen (int) (int) : Display"<<endl; cerr<<"displayClusterSize (int) (int) : Display"<<endl; cerr<<"displayClusterNodeDegree (int) (int) : Display"<<endl; cerr<<"displayClusterAvgChildDegree (int) (int) : Display"<<endl; cerr<<"displayClusterAvgIden (int) (int) : Display"<<endl; cerr<<"displayClusterAvgOvlLen (int) (int) : Display"<<endl; cerr<<"displayClusterNeighbors (int) (int) : Display"<<endl; cerr<<"displayClusterChildren (int) (int) : Display"<<endl; cerr<<""<<endl; cerr<<"\n\n"<<endl; cerr<<"Exiting program"<<endl; exit(help); } int countFiles(const char []); bool fileExists(const char []); void avgGraphDegree(string &, const int); void avgGraphOvlLen(string &); void avgGraphOvlIden(string &); void avgGraphGCcontent(string &); void avgGraphEdgeDen(string &, const int); void avgGraphClusterSize(string &, const int); void selectClustersGCcontent(string &, const int, const float ); //void selectClustersGenes(const int ); void selectClustersEdgeDen(string &, const int, const float, const bool); void selectClustersSize(string &, const int, const float, const bool); void selectClustersNodeDegree(string &, const int, const int, const bool); void selectClustersAvgChildDegree(string &, const int, const int, const bool); void selectClustersAvgIden(string &, const int, const float minIden, const bool); void selectClustersAvgOvlLen(string &, const int, const int ovlLen, const bool); //void selectGraphCycles(const int ); void displayClusterGCcontent(string &, const int, const int ); //void displayClusterGenes(string &, const int, const int ); void displayClusterEdgeDen(string &, const int, const int ); void displayClusterSize(string &, const int, const int ); void displayClusterNodeDegree(string &, const int, const int ); void displayClusterAvgChildDegree(string &, const int, const int ); void displayClusterAvgIden(string &, const int , const int); void displayClusterAvgOvlLen(string &, const int, const int ); void displayClusterNeighbors(string &, const int, const int ); void displayClusterChildren(string &, const int, const int ); int recoverClusters(string &, int * &, int, int); //The main function is used to communicate with //the user and retrieve commands for interrogating //and manipulating an overlap graph. int main (int argc, char * argv []) { string workDirS = "--workDir"; string workDir = "NO_WORK_DIR"; for(int i = 1; i < argc; i+=2) { //The working directory if(argv[i] == workDirS) { workDir = argv[i+1]; unsigned int pos = workDir.find_last_of("/"); if(pos == workDir.size()-1) workDir.erase(pos); //Check for overflows if(workDir.size() > 200) { cout<<"Please keep the working directory name less than 200 characters in length"<<endl; exit(bufOverflow); } } } if(workDir == "NO_WORK_DIR") { help_message(); } bool iterate = true; int graphLevel = 0; int currentNode = 0; char * cmd = new char [100]; //Collect Queries while(iterate) { cin>>cmd; char * ptr = strtok(cmd, " "); if(strcmp(ptr, "help") == 0) help_message(); if(strcmp(ptr, "AvgGraphDegree") == 0) avgGraphDegree(workDir, graphLevel); if(strcmp(ptr, "AvgGraphOvlLen") == 0) avgGraphOvlLen(workDir); if(strcmp(ptr, "AvgGraphOvlIden") == 0) avgGraphOvlIden(workDir); if(strcmp(ptr, "AvgGraphGCcontent") == 0) avgGraphGCcontent(workDir); if(strcmp(ptr, "avgGraphClusterSize") == 0) avgGraphClusterSize(workDir, graphLevel); if(strcmp(ptr, "avgGraphEdgeDen") == 0) avgGraphEdgeDen(workDir, graphLevel); if(strcmp(ptr, "selectGraph") == 0) { while(ptr != NULL) { ptr = strtok (NULL, " "); graphLevel = atoi(ptr); if(graphLevel != 0) break; } } if(strcmp(ptr, "selectNode") == 0) { while(ptr != NULL) { ptr = strtok (NULL, " "); currentNode = atoi(ptr); if(currentNode != 0) break; } } if(strcmp(ptr, "selectClustersGCcontent") == 0) { float minGC = 0; bool greaterThan = true; while(ptr != NULL) { ptr = strtok (NULL, " "); minGC = atof(ptr); if(strcmp(ptr, "max") == 0) greaterThan = false; if(strcmp(ptr, "min") == 0) greaterThan = true; } selectClustersGCcontent(workDir, graphLevel, minGC, greaterThan); } //if(strcmp(ptr, "selectClustersGenes") == 0) //selectClustersGenes(graphLevel); if(strcmp(ptr, "selectClustersEdgeDen") == 0) { float minDensity = 0; while(ptr != NULL) { ptr = strtok (NULL, " "); minDensity = atof(ptr); if(minDensity != 0) break; } selectClustersEdgeDen(workDir, graphLevel, minDensity); } if(strcmp(ptr, "selectClustersSize") == 0) { float minDensity = 0; while(ptr != NULL) { ptr = strtok (NULL, " "); minDensity = atof(ptr); if(minDensity != 0) break; } selectClustersSize(workDir, graphLevel, minDensity); } if(strcmp(ptr, "selectClustersNodeDegree") == 0) { int minDegree = 0; while(ptr != NULL) { ptr = strtok (NULL, " "); minDegree = atoi(ptr); if(minDegree != 0) break; } selectClustersNodeDegree(workDir, graphLevel, minDegree); } if(strcmp(ptr, "selectClustersAvgChildDegree") == 0) { int minDegree = 0; while(ptr != NULL) { ptr = strtok (NULL, " "); minDegree = atoi(ptr); if(minDegree != 0) break; } selectClustersAvgChildDegree(workDir, graphLevel, minDegree); } if(strcmp(ptr, "selectClustersAvgIden") == 0) { float minIden = 0; while(ptr != NULL) { ptr = strtok (NULL, " "); minIden = atof(ptr); if(minIden != 0) break; } selectClustersAvgIden(workDir, graphLevel, minIden); } if(strcmp(ptr, "selectClustersAvgOvlLen") == 0) { int minOvlLen = 0; while(ptr != NULL) { ptr = strtok (NULL, " "); minOvlLen = atoi(ptr); if(minOvlLen != 0) break; } selectClustersAvgOvlLen(workDir, graphLevel, minOvlLen); } if(strcmp(ptr, "displayClusterGCcontent") == 0) displayClusterGCcontent(workDir, graphLevel, currentNode); //if(strcmp(ptr, "displayClusterGenes") == 0) //displayClusterGenes(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterEdgeDen") == 0) displayClusterEdgeDen(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterSize") == 0) displayClusterSize(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterNodeDegree") == 0) displayClusterNodeDegree(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterNeighbors") == 0) displayClusterNeighbors(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterAvgIden") == 0) displayClusterAvgIden(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterAvgOvlLen") == 0) displayClusterAvgOvlLen(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterChildren") == 0) displayClusterChildren(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayClusterAvgChildDegree") == 0) displayClusterAvgChildDegree(workDir, graphLevel, currentNode); if(strcmp(ptr, "displayCurrentGraph") == 0) cout<<graphLevel<<endl; if(strcmp(ptr, "displayCurrentNode") == 0) cout<<currentNode<<endl; } delete [] cmd; return 0; } //void countFiles(const char []) //Description: This function counts files in a directory //Input: dir (cosnt char []) : The number of tasks that need to be finalized //Output:None //Return:None int countFiles(const char dir []) { DIR *pDir = opendir(dir); struct dirent * pDirent; //Count Files int numFiles = 0; while ((pDirent = readdir(pDir)) != NULL) if(strcmp(pDirent->d_name, ".") != 0 && strcmp(pDirent->d_name, "..") != 0) numFiles++; closedir(pDir); return numFiles; } //bool fileExists( char fileName [] ) //Description: This function checks to see if a file exists //Input: fileName (char []) the name of the file //Output:None //Return:None bool fileExists(const char fileName []) { FILE * pFile = fopen(fileName, "r"); if(pFile != '\0') { fclose(pFile); return true; } return false; } //avgGraphDegree(string &, const int) //Description: This function displays the average node degree of the //current graph selected. //Input: workDir (string &): The current work directory, graphLevel: The current graph level //Output:None //Return: None void avgGraphDegree(string & workDir, const int graphLevel) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); int numFiles = countFiles(graphDir); long long int numNodes = 0; double numEdges = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); if(fileExists(fileName)) { long long int intervalNodes = 0; long long int intervalEdges = 0; FILE * pFile = fopen(fileName, "r"); fread(&intervalNodes, sizeof(long long int), 1, pFile); fread(&intervalEdges, sizeof(long long int), 1, pFile); fclose(pFile); numNodes+=intervalNodes; numEdges+=intervalEdges; } delete [] fileName; } delete [] graphDir; float avgDegree = (2*numEdges)/numNodes; cout<<avgDegree<<endl; } //avgGraphOvlLen(string &, const int) //Description: This function displays the average ovl length of a graph //Input: workDir (string &): The current work directory //Output:None //Return: None void avgGraphOvlLen(string & workDir) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), 0); int numFiles = countFiles(graphDir); double numNodes = 0; double totalOvlLen = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); numNodes+=graph.getNumNodes(); for(int j = 0; j < graph.getNumEdges(); j++) { totalOvlLen+=graph.edgeOvlLen(j); } } delete [] fileName; } delete [] graphDir; float avgOvlLen = totalOvlLen/numNodes; cout<<avgOvlLen<<endl; } //avgGraphOvlLen(string &, const int) //Description: This function displays the average identity of the edges in a graph //Input: workDir (string &): The current work directory //Output:None //Return: None void avgGraphOvlIden(string & workDir) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), 0); int numFiles = countFiles(graphDir); double numNodes = 0; double totalOvlIden = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); numNodes+=graph.getNumNodes(); for(int j = 0; j < graph.getNumEdges(); j++) { totalOvlIden+=graph.edgeOvlIden(j); } } delete [] fileName; } delete [] graphDir; float avgOvlIden = totalOvlIden/numNodes; cout<<avgOvlIden<<endl; } //avgGraphGCcontent(string &, const int) //Description: This function displays the average GC content of the reads in a graph //Input: workDir (string &): The current work directory //Output:None //Return: None void avgGraphGCcontent(string & workDir) { char * fragmentDir = new char [1000]; sprintf(fragmentDir, "%s/Edges/Graph%d", workDir.c_str(), 0); int numFiles = countFiles(fragmentDir); double numNucleotides; double totalGCcounts = 0; int numSets = 0; char * fileName = new char [1000]; sprintf(fileName, "%s/sequences.job0.set%d", fragmentDir, numSets++); while(fileExists(fileName)) { sprintf(fileName, "%s/sequences.job0.set%d", fragmentDir, numSets++); } numSets-=1; int numJobs = numFiles/numSets; for(int i = 0; i < numJobs; i++) { for(int j = 0; j < numSets; j++) { sprintf(fileName, "%s/sequences.job%d.set%d", fragmentDir, i, j); FILE * pFile = fopen(fileName, "r"); Fragment_Index index; index.read(pFile); fclose(pFile); for(unsigned int j = 0; j < index.length(); j++) { if(index.at(j) == 'G' || index.at(j) == 'C') totalGCcounts++; numNucleotides++; } } } float percentGC = totalGCcounts/numNucleotides; cout<<percentGC<<endl; delete [] fragmentDir; delete [] fileName; } //avgGraphEdgeDen (string &, const int) //Description: This returns the average edge density of the clusters //Input: workDir (string &): The current work directory, graphLevel (const int): the current graph //Output:None //Return: None void avgGraphEdgeDen(string & workDir, const int graphLevel) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), 0); char * fileName = new char [1000]; sprintf(fileName, "%s/eDen", graphDir); int * eDen = '\0'; int * nDen = '\0'; int numNodes = 0; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); eDen = new int [numNodes]; fread(eDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } sprintf(fileName, "%s/nDen", graphDir); if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; delete [] eDen; return; } double eDenTotal = 0; for(int i = 0; i < numNodes; i++) { float density = (2*eDen[i])/(nDen[i] * (nDen[i]-1)); eDenTotal+=density; } delete [] eDen; delete [] nDen; delete [] graphDir; delete [] fileName; float avgDensity = eDenTotal/numNodes; cout<<avgDensity<<endl; } //avgGraphClusterSize(string &, const int) //Description: This function displays the average cluster size of a graph //Input: workDir (string &): The current work directory, graphLevel (const int): The current graph level //Output:None //Return: None void avgGraphClusterSize(string & workDir, const int graphLevel) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), 0); char * fileName = new char [1000]; sprintf(fileName, "%s/nDen", graphDir); int * nDen = '\0'; int numNodes = 0; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } double nWeightsTotal = 0; for(int i = 0; i < numNodes; i++) { nWeightsTotal+=nDen[i]; } delete [] nDen; delete [] graphDir; delete [] fileName; } //selectClustersGCcontent(string &, const int) //Description: This function selects clusters by their GC content //Input: workDir (string &): The current work directory, graphLevel (const int): //Output:None //Return: None void selectClustersGCcontent(string & workDir, const int graphLevel, const float minGC, const bool greaterThan) { char * fragmentDir = new char [1000]; sprintf(fragmentDir, "%s/Fragments", workDir.c_str()); int numFiles = countFiles(fragmentDir); int numSets = 0; char * fileName = new char [1000]; sprintf(fileName, "%s/sequences.job0.set%d", fragmentDir, numSets++); while(fileExists(fileName)) { sprintf(fileName, "%s/sequences.job0.set%d", fragmentDir, numSets++); } numSets-=1; int numJobs = numFiles/numSets; Fragment_Index index; for(int i = 0; i < numJobs; i++) { for(int j = 0; j < numSets; j++) { sprintf(fileName, "%s/sequences.job%d.set%d", fragmentDir, i, j); FILE * pFile = fopen(fileName, "r"); index.read(pFile); fclose(pFile); } } int size = 2 * index.numFragments(); int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int currentCluster = 0; float GCcount = 0; float length = 0; cout<<"Cluster, GC content"<<endl; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { pair<long long int, long long int> bounds; bounds = index.indexBounds(contigs[i]); length+=bounds.second-bounds.first; for(int j = bounds.first; j < bounds.second; j++) { if(index.at(j) == 'G' || index.at(j) == 'C') GCcount++; } }else{ float GCcontent = GCcount/length; if((GCcontent >= minGC && greaterThan) || (GCcontent < minGC && !greaterThan)) { cout<<currentCluster<<","<<GCcontent<<endl; } currentCluster++; length = 0; GCcount = 0; } } if(GCcount != 0 && length != 0) { float GCcontent = GCcount/length; if((GCcontent >= minGC && greaterThan) || (GCcontent < minGC && !greaterThan)) { cout<<currentCluster<<","<<GCcontent<<endl; } } delete [] contigs; delete [] fileName; delete [] fragmentDir; } //void selectClustersGenes(const int graphLevel); //selectClustersEdgeDen(string &, const int, const float) //Description: This function selects nodes based on their edge density //Input: workDir (string &): The working directory, graphLevel (const int): The current graph we are on, //minDensity (const float): The minimum density for nodes to be returned. //Output:None //Return: None void selectClustersEdgeDen(string & workDir, const int graphLevel, const float minDensity, const bool greaterThan) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/eDen", graphDir); int * eDen = '\0'; int * nDen = '\0'; int numNodes = 0; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); eDen = new int [numNodes]; fread(eDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } sprintf(fileName, "%s/nDen", graphDir); if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; delete [] eDen; return; } cout<<"Cluster, Edge Density"<<endl; for(int i = 0; i < numNodes; i++) { float density = (2*eDen[i])/(nDen[i] * (nDen[i]-1)); if((density >= minDensity && greaterThan) || (density < minDensity && !greaterThan)) cout<<i<<","<<density<<endl; } delete [] eDen; delete [] nDen; delete graphDir; delete [] fileName; } //selectGraphClusterSize(string &, const int, const float) //Description: This function selects nodes based on their edge density //Input: workDir (string &): The working directory, graphLevel (const int): The current graph we are on, //minWeight (const float): The minimum weight (number of child nodes) for a parent node //Output:None //Return: None void selectClustersSize(string & workDir, const int graphLevel, const float minWeight, const bool greaterThan) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), 0); char * fileName = new char [1000]; sprintf(fileName, "%s/nDen", graphDir); int * nDen = '\0'; int numNodes = 0; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } cout<<"Cluster, Weight"<<endl; for(int i = 0; i < numNodes; i++) { if((nDen[i] >= minWeight && greaterThan) || (nDen[i] < minWeight & !greaterThan)) cout<<i<<","<<nDen[i]<<endl; } delete [] nDen; delete [] graphDir; delete [] fileName; } //selectGraphAvgChildDegree(string &, const int, const float) //Description: This function selects nodes their children nodes average node degree in the graph. //Input: workDir (string &): The working directory, graphLevel (const int): The current graph we are on, //minDegree (const float): The minimum average child degree that a parent node can have //Output:None //Return: None void selectClustersAvgChildDegree(string & workDir, const int graphLevel, const int minDegree, const bool greaterThan) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph0", workDir.c_str()); int numFiles = countFiles(graphDir) - 2; long int numNodes = 0; { Graph graph; char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, numFiles-1); FILE * pFile = fopen(fileName, "r"); delete [] fileName; graph.read(pFile); numNodes = graph.getOffset() + graph.getNumNodes(); } int size = 2 * numNodes; int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int * nodeMap = new int [numNodes]; int numClusters = 0; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { nodeMap[contigs[i]] = numClusters; }else { numClusters++; } } delete [] contigs; float * degreeTotals = new float [numClusters]; for(int i = 0; i < numClusters; i++) degreeTotals[i] = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); for(int j = 0; j < graph.getNumNodes(); j++) { degreeTotals[nodeMap[j+graph.getOffset()]]+=graph.nodeDegree(j); } delete [] fileName; } delete [] nodeMap; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/nDen", graphDir); int * nDen = '\0'; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } cout<<"Cluster, Average Child Node Degree"<<endl; for(int i = 0; i < numNodes; i++) { float avgDegree = degreeTotals[i]/nDen[i]; if((avgDegree >= minDegree && greaterThan) || (avgDegree < minDegree && !greaterThan)) { cout<<i<<","<<avgDegree<<endl; } } delete [] degreeTotals; delete [] nDen; delete [] fileName; delete [] graphDir; } //selectClustersNodeDegree(string &, const int, const ing) //Description: This function selects nodes that have a node degree greater than a minimum //Input: workDir (string &): The working directory, graphLevel (const int): The current graph we are on, //minDegree (const int): The minimum degree that a node can have //Output:None //Return: None void selectClustersNodeDegree(string & workDir, const int graphLevel, const int minDegree, const bool greaterThan) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); int numFiles = countFiles(graphDir) - 2; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); cout<<"Cluster, Degree"<<endl; for(int j = 0; j < graph.getNumNodes(); j++) { if((graph.nodeDegree(j) >= minDegree && greaterThan) || (graph.nodeDegree(j) < minDegree && !greaterThan)) cout<<graph.getOffset() + j<<","<<graph.nodeDegree(j)<<endl; } delete [] fileName; } delete [] graphDir; } //selectClustersAvgIden(string &, const int, const float) //Description: This function selects nodes that have a node degree greater than a minimum //Input: workDir (string &): The working directory, graphLevel (const int): The current graph we are on, //minDegree (const float): The minimum degree that a node can have //Output:None //Return: None void selectClustersAvgIden(string & workDir, const int graphLevel, const float minIden, const bool greaterThan) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph0", workDir.c_str()); int numFiles = countFiles(graphDir) - 2; long int numNodes = 0; { Graph graph; char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, numFiles-1); FILE * pFile = fopen(fileName, "r"); delete [] fileName; graph.read(pFile); numNodes = graph.getOffset() + graph.getNumNodes(); } int size = 2 * numNodes; int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int * nodeMap = new int [numNodes]; int numClusters = 0; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { nodeMap[contigs[i]] = numClusters; }else { numClusters++; } } delete [] contigs; float * idenTotals = new float [numClusters]; for(int i = 0; i < numClusters; i++) idenTotals[i] = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); for(int j = 0; j < graph.getNumNodes(); j++) { for(int k = 0; k < graph.nodeDegree(j); k++) idenTotals[nodeMap[j+graph.getOffset()]] += graph.edgeOvlIden(j, k); } delete [] fileName; } delete [] nodeMap; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/eDen", graphDir); int * eDen = '\0'; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); eDen = new int [numNodes]; fread(eDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } cout<<"Cluster, Average Overlap Identity"<<endl; for(int i = 0; i < numNodes; i++) { float avgIden = idenTotals[i]/eDen[i]; if((avgIden >= minIden && greaterThan) || (avgIden < minIden && !greaterThan)) { cout<<i<<","<<avgIden<<endl; } } delete [] idenTotals; delete [] eDen; delete [] fileName; delete [] graphDir; } //selectClustersAvgOvlLen(string &, const int, const ing) //Description: This function selects nodes whose child nodes have an average overlap length greater //than a provided minimum //Input: workDir (string &): The working directory, graphLevel (const int): The current graph we are on, //minOvlLen (const float): The minimum average overlap length of the child node edges //Output:None //Return: None void selectClustersAvgOvlLen(string & workDir, const int graphLevel, const int minOvlLen, const bool greaterThan) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph0", workDir.c_str()); int numFiles = countFiles(graphDir) - 2; long int numNodes = 0; { Graph graph; char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, numFiles-1); FILE * pFile = fopen(fileName, "r"); delete [] fileName; graph.read(pFile); numNodes = graph.getOffset() + graph.getNumNodes(); } int size = 2 * numNodes; int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int * nodeMap = new int [numNodes]; int numClusters = 0; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { nodeMap[contigs[i]] = numClusters; }else { numClusters++; } } delete [] contigs; float * ovlLenTotals = new float [numClusters]; for(int i = 0; i < numClusters; i++) ovlLenTotals[i] = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); for(int j = 0; j < graph.getNumNodes(); j++) { for(int k = 0; k < graph.nodeDegree(j); k++) ovlLenTotals[nodeMap[j+graph.getOffset()]] += graph.edgeOvlLen(j, k); } delete [] fileName; } delete [] nodeMap; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/eDen", graphDir); int * eDen = '\0'; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); eDen = new int [numNodes]; fread(eDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } cout<<"Cluster, Average Overlap Identity"<<endl; for(int i = 0; i < numNodes; i++) { float avgOvlLen = ovlLenTotals[i]/eDen[i]; if((avgOvlLen >= minOvlLen && greaterThan) || (avgOvlLen < minOvlLen && !greaterThan)) { cout<<i<<","<<avgOvlLen<<endl; } } delete [] ovlLenTotals; delete [] eDen; delete [] fileName; delete [] graphDir; } //void selectGraphCycles(const int graphLevel); //selectClustersGCcontent(string &, const int, const float) //Description: This function selects nodes that have a node degree greater than a minimum //Input: workDir (string &): The working directory, graphLevel (const int): The current graph we are on, //minDegree (const float): The minimum degree that a node can have //Output:None //Return: None void displayClusterGCcontent(string & workDir, const int graphLevel, const int currentNode) { char * fragmentDir = new char [1000]; sprintf(fragmentDir, "%s/Fragments", workDir.c_str()); int numFiles = countFiles(fragmentDir); int numSets = 0; char * fileName = new char [1000]; sprintf(fileName, "%s/sequences.job0.set%d", fragmentDir, numSets++); while(fileExists(fileName)) { sprintf(fileName, "%s/sequences.job0.set%d", fragmentDir, numSets++); } numSets-=1; int numJobs = numFiles/numSets; Fragment_Index index; for(int i = 0; i < numJobs; i++) { for(int j = 0; j < numSets; j++) { sprintf(fileName, "%s/sequences.job%d.set%d", fragmentDir, i, j); FILE * pFile = fopen(fileName, "r"); index.read(pFile); fclose(pFile); } } int size = 2 * index.numFragments(); int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int currentCluster = 0; float GCcount = 0; float length = 0; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { if(currentCluster == currentNode) { pair<long long int, long long int> bounds; bounds = index.indexBounds(contigs[i]); length+=bounds.second-bounds.first; for(int j = bounds.first; j < bounds.second; j++) { if(index.at(j) == 'G' || index.at(j) == 'C') GCcount++; } } }else{ if(currentCluster == currentNode) { float GCcontent = GCcount/length; cout<<GCcontent<<endl; break; } currentCluster++; } } delete [] contigs; delete [] fileName; delete [] fragmentDir; } //void displayClusterEdgeDen(string &, const int, const int) //Description: This displays the edge density of a cluster //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterEdgeDen(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/eDen", graphDir); int * eDen = '\0'; int * nDen = '\0'; int numNodes = 0; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); eDen = new int [numNodes]; fread(eDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } sprintf(fileName, "%s/nDen", graphDir); if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; delete [] eDen; return; } cout<<"Cluster, Edge Density"<<endl; float density = (2*eDen[currentNode])/(nDen[currentNode] * (nDen[currentNode]-1)); cout<<density<<endl; delete [] eDen; delete [] nDen; delete graphDir; delete [] fileName; } //void displayClusterSize(string &, const int, const int) //Description: This displays the number of child nodes in a cluster //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterSize(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), 0); char * fileName = new char [1000]; sprintf(fileName, "%s/nDen", graphDir); int * nDen = '\0'; int numNodes = 0; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } cout<<nDen[currentNode]<<endl; delete [] nDen; delete [] graphDir; delete [] fileName; } //void displayClusterNodeDegree(string &, const int, const int) //Description: This displays a cluster's child node's average degree //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterNodeDegree(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); int numFiles = countFiles(graphDir) - 2; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); long long int numNodes; for(int i = 0; i < 2; i++) fread(&numNodes, sizeof(long long int), 1, pFile); long long int offset; for(int i = 0; i < 4; i++) fread(&offset, sizeof(long long int), 1, pFile); if(currentNode >= offset && currentNode < offset+numNodes) { fseek(pFile, 0, SEEK_SET); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); cout<<graph.nodeDegree(currentNode-offset)<<endl; } delete [] fileName; } delete [] graphDir; } //void displayClusterAvgIden(string &, const int, const int) //Description: This displays a node's average identity in a graph //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterAvgChildDegree(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph0", workDir.c_str()); int numFiles = countFiles(graphDir) - 2; long int numNodes = 0; { Graph graph; char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, numFiles-1); FILE * pFile = fopen(fileName, "r"); delete [] fileName; graph.read(pFile); numNodes = graph.getOffset() + graph.getNumNodes(); } int size = 2 * numNodes; int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int * nodeMap = new int [numNodes]; int numClusters = 0; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { nodeMap[contigs[i]] = numClusters; }else { numClusters++; } } delete [] contigs; float degreeTotal = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); for(int j = 0; j < graph.getNumNodes(); j++) { if(nodeMap[j+graph.getOffset()] == currentNode) degreeTotal+=graph.nodeDegree(j); } delete [] fileName; } delete [] nodeMap; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/nDen", graphDir); int * nDen = '\0'; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); nDen = new int [numNodes]; fread(nDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } float avgDegree = degreeTotal/nDen[currentNode]; cout<<avgDegree<<endl; delete [] nDen; delete [] fileName; delete [] graphDir; } //void displayClusterAvgIden(string &, const int, const int) //Description: This displays a node's average identity in a graph //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterAvgIden(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph0", workDir.c_str()); int numFiles = countFiles(graphDir) - 2; long int numNodes = 0; { Graph graph; char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, numFiles-1); FILE * pFile = fopen(fileName, "r"); delete [] fileName; graph.read(pFile); numNodes = graph.getOffset() + graph.getNumNodes(); } int size = 2 * numNodes; int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int * nodeMap = new int [numNodes]; int numClusters = 0; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { nodeMap[contigs[i]] = numClusters; }else { numClusters++; } } delete [] contigs; float idenTotal = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); for(int j = 0; j < graph.getNumNodes(); j++) { if(j + graph.getOffset() == currentNode) for(int k = 0; k < graph.nodeDegree(j); k++) idenTotal+= graph.edgeOvlIden(j, k); } delete [] fileName; } delete [] nodeMap; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/eDen", graphDir); int * eDen = '\0'; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); eDen = new int [numNodes]; fread(eDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } cout<<"Cluster, Average Overlap Identity"<<endl; float avgIden = idenTotal/eDen[currentNode]; cout<<avgIden<<endl; delete [] eDen; delete [] fileName; delete [] graphDir; } //void displayClusterAvgOvlLen(string &, const int, const int) //Description: This displays a clusters average overlap lengths //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterAvgOvlLen(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph0", workDir.c_str()); int numFiles = countFiles(graphDir) - 2; long int numNodes = 0; { Graph graph; char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, numFiles-1); FILE * pFile = fopen(fileName, "r"); delete [] fileName; graph.read(pFile); numNodes = graph.getOffset() + graph.getNumNodes(); } int size = 2 * numNodes; int * contigs = new int [size]; int count = recoverClusters(workDir, contigs, size, graphLevel); int * nodeMap = new int [numNodes]; int numClusters = 0; for(int i = 0; i < count; i++) { if(contigs[i] != -1) { nodeMap[contigs[i]] = numClusters; }else { numClusters++; } } delete [] contigs; float ovlLenTotal = 0; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); for(int j = 0; j < graph.getNumNodes(); j++) { if(j+graph.getOffset() == currentNode) for(int k = 0; k < graph.nodeDegree(j); k++) ovlLenTotal += graph.edgeOvlLen(j, k); } delete [] fileName; } delete [] nodeMap; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/eDen", graphDir); int * eDen = '\0'; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); numNodes = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); eDen = new int [numNodes]; fread(eDen, sizeof(int), numNodes, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } float avgOvlLen = ovlLenTotal/eDen[currentNode]; cout<<avgOvlLen<<endl; delete [] eDen; delete [] fileName; delete [] graphDir; } //void displayClusterNeighbors(string &, const int, const int) //Description: This displays a node's neighbors in the current graph //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterNeighbors(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); int numFiles = countFiles(graphDir) - 2; for(int i = 0; i < numFiles; i++) { char * fileName = new char [1000]; sprintf(fileName, "%s/graph%d", graphDir, i); FILE * pFile = fopen(fileName, "r"); long long int numNodes; for(int i = 0; i < 2; i++) fread(&numNodes, sizeof(long long int), 1, pFile); long long int offset; for(int i = 0; i < 4; i++) fread(&offset, sizeof(long long int), 1, pFile); if(currentNode >= offset && currentNode < offset+numNodes) { fseek(pFile, 0, SEEK_SET); Graph graph; graph.read(pFile); fclose(pFile); graph.set(); int j = graph.nodeDegree(currentNode-offset); for(int k = 0; k < j; k++) cout<<graph.edgeDest(currentNode-offset, k); } delete [] fileName; } } //void displayClusterChildren(string &, const int, const int) //Description: This displays a node's immediate children //Input: workDir (string &): the working directory, graphLevel (const int): the //current graph, currentNode (const int): The current node we are on //Output:None //Return:None void displayClusterChildren(string & workDir, const int graphLevel, const int currentNode) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); char * fileName = new char [1000]; sprintf(fileName, "%s/map", graphDir); int size = 0; int * map = '\0'; if(fileExists(fileName)) { FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); size = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); map = new int [size]; fread(map, sizeof(int), size, pFile); fclose(pFile); }else { cout<<"No density files found"<<endl; return; } cout<<map[currentNode * 2]; if(map[currentNode * 2 + 1] != -1) cout<<" "<<map[currentNode * 2 + 1]; cout<<endl; delete [] fileName; delete [] graphDir; delete [] map; } //void recoverClusters() //Description: This runs the the parent thread in a parallel program //Input: workDir (string &): the working directory, minMerge (int): //the minimum overlap length for merging, minDensity (double): The minimum inter-node //density //Output:None //Return:None int recoverClusters(string & workDir, int * & contigs, int size, int graphLevel) { char * graphDir = new char [1000]; sprintf(graphDir, "%s/Edges/Graph%d", workDir.c_str(), graphLevel); int count = 0; for(int i = graphLevel; i > 0; i--) { char * fileName = new char [1000]; sprintf(fileName, "%s/map", graphDir); FILE * pFile = fopen(fileName, "r"); fseek(pFile, 0, SEEK_END); int buffSize = ftell(pFile)/sizeof(int); fseek(pFile, 0, SEEK_SET); int * buff = new int [buffSize]; fread(buff, sizeof(int), buffSize, pFile); fclose(pFile); if(i == graphLevel) { for(int j = 0; j < buffSize; j+=2) { contigs[j] = j/2; contigs[j+1] = -1; } count = buffSize; } int * tmp = new int [size]; int cHold = count; count = 0; for(int j = 0; j < cHold; j++) { if(contigs[j] != -1) { tmp[count++] = buff[contigs[j]*2]; if(buff[contigs[j]*2+1] != -1) tmp[count++] = buff[contigs[j]*2+1]; }else{ tmp[count++] = -1; } } delete [] contigs; contigs = tmp; delete [] buff; delete [] fileName; } delete [] graphDir; return count; }
25.375067
118
0.661452
jwarsom
35426e2809a774ca228d726415924b82fa4e9e78
4,077
cpp
C++
SSV/Source/SSV/Client/MainControl/MainControlView.cpp
Shards-CP/SSV
5dda6d6e000114143f8d06606800e1aef3688079
[ "libpng-2.0" ]
null
null
null
SSV/Source/SSV/Client/MainControl/MainControlView.cpp
Shards-CP/SSV
5dda6d6e000114143f8d06606800e1aef3688079
[ "libpng-2.0" ]
null
null
null
SSV/Source/SSV/Client/MainControl/MainControlView.cpp
Shards-CP/SSV
5dda6d6e000114143f8d06606800e1aef3688079
[ "libpng-2.0" ]
null
null
null
#include "SSVPCH.h" #include "MainControlView.h" #include "Client/Core/Application.h" #include "Client/UI/Button.h" #include "Client/UI/Image.h" #include "Client/UI/TextLabel.h" #include "Client/UI/Textbox.h" #include "Client/Visualizer/SyntaxTreeView.h" namespace SSV::Client::MainControl { MainControlView::MainControlView(const std::string& name, const int32_t zIndex) : View(name, zIndex) { } void MainControlView::CreateWidgets() { m_SyntaxTextbox = CreateWidget<UI::Textbox>("SyntaxTextbox", 0); m_SyntaxTextbox->SetOnMouseLButtonDown([&]() { Core::Application::GetInstance().GetViewManager().SetKeyboardFocus(m_SyntaxTextbox); }); m_SyntaxTextbox->SetPlaceholderText(L"Enter sentence here... [S [NP [N' [N John]]] [VP [V' [V is] [NP [DET a] [N' [N student]]]]]]"); m_SyntaxTextbox->SetOnTextUpdatedDelegate([&](const std::wstring& text) { try { Core::Application::GetInstance().GetSyntaxTreeViewReference()->UpdateSourceSentence(text); m_SyntaxTextbox->m_SyntaxTree = Core::Application::GetInstance().GetSyntaxTreeViewReference()->GetSyntaxTree(); if (m_SyntaxTextbox->IsTextEmpty()) m_SyntaxParserStatusLabel->SetText(L"Ready", L"UI-Regular", 11.f); else m_SyntaxParserStatusLabel->SetText(L"Syntactic structure has successfully been visualized", L"UI-Regular", 11.f); m_SyntaxTextbox->SetLineColor(D2D1::ColorF(0x3d85c6, 1.f)); } catch (const Syntax::IllFormedInputException& e) { std::string errorString = e.what(); m_SyntaxParserStatusLabel->SetText(std::wstring(errorString.begin(), errorString.end()), L"UI-Regular", 11.f); m_SyntaxTextbox->SetLineColor(D2D1::ColorF(0xda4646, 1.f)); } }); m_SyntaxParserStatusLabel = CreateWidget<UI::TextLabel>("SyntaxParserStatusLabel", 10, L"Ready", L"UI-Regular", 11.f); m_SyntaxParserStatusLabel->SetTextAlignment(DWRITE_TEXT_ALIGNMENT::DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_PARAGRAPH_ALIGNMENT::DWRITE_PARAGRAPH_ALIGNMENT_CENTER); m_SyntaxParserStatusLabel->AllowRespondingToHit(false); m_ExportButton = CreateWidget<UI::Button>("ExportButton", 1); m_ExportButton->SetOnClickedDelegate([&]() { BeginExportSyntaxTree(Core::Application::GetInstance().GetSyntaxTreeViewReference()->GetVisualizerRenderInfo()); }); m_ExportImage = CreateWidget<UI::Image>("ExportImage", 5, L"SSV_ExportIcon"); m_ExportImage->AllowRespondingToHit(false); } void MainControlView::CalculateWidgetLayout(const D2D1_POINT_2L newViewLocation, const D2D1_SIZE_U newViewSize) { m_SyntaxTextbox->SetLocation({ 150, 24 }); m_SyntaxTextbox->SetSize({ newViewSize.width - 400, 50 }); m_SyntaxParserStatusLabel->SetSize({ newViewSize.width - 20 * 2, 22 }); m_SyntaxParserStatusLabel->SetLocation({ 40, static_cast<long>(newViewSize.height) - 22 }); m_ExportButton->SetSize({ 80, 50 }); m_ExportButton->SetLocation({ static_cast<long>(m_SyntaxTextbox->GetLocation().x + m_SyntaxTextbox->GetSize().width + m_ExportButtonXOffset), 24 }); m_ExportImage->SetSize({ 32, 32 }); m_ExportImage->SetLocation({ m_ExportButton->GetLocation().x + static_cast<long>(m_ExportButton->GetSize().width / 2) - 16, m_ExportButton->GetLocation().y + static_cast<long>(m_ExportButton->GetSize().height / 2) - 16 }); } void MainControlView::OnMouseLButtonDownOnView(const UI::Widget* hitWidget) { if (!hitWidget) { Core::Application::GetInstance().GetViewManager().SetKeyboardFocus(nullptr); } MarkViewAsDirty(); } void MainControlView::BeginExportSyntaxTree(const Visualizer::SyntaxTreeVisualizerRenderInfo& visualizerRenderInfo) { if (!Core::Application::GetInstance().GetSyntaxTreeViewReference()) return; // If we have nothing to render to pdf, show warning to the use and return if (visualizerRenderInfo.m_NodeRenderInfo.empty()) { MessageBoxW(Core::Application::GetInstance().GetMainWindow().GetWindowHandle(), L"No syntax tree to export.", L"Export Syntax Tree", MB_OK | MB_ICONERROR); return; } Core::Application::GetInstance().ToggleExportMenu(); } }
37.063636
224
0.737062
Shards-CP
354ca3e81cfb9ddea25df25b213661ae10882f7e
16,779
cpp
C++
source/toolkit/number/weakfloat.cpp
will-iam/Variant
5b6732134fd51cf6c2b90b51b7976be0693ba28d
[ "MIT" ]
8
2017-05-04T07:50:02.000Z
2019-05-17T02:27:20.000Z
source/toolkit/number/weakfloat.cpp
will-iam/Variant
5b6732134fd51cf6c2b90b51b7976be0693ba28d
[ "MIT" ]
null
null
null
source/toolkit/number/weakfloat.cpp
will-iam/Variant
5b6732134fd51cf6c2b90b51b7976be0693ba28d
[ "MIT" ]
null
null
null
#include "weakfloat.hpp" #include <limits> #include <iomanip> #ifndef ROUNDING #define ROUNDING FE_TONEAREST; #endif typedef weakfloat<PRECISION_WEAK_FLOAT, ROUNDING> wfloat; bool unit_test() { float fa(31.999999); float fb(32.000003); float fc = 32.0 + 32.0 * pow(2, (8 - PRECISION_WEAK_FLOAT)); float ulp32 = 32.0 * (1 + pow(2, (9 - PRECISION_WEAK_FLOAT))); float ulp16 = 16.0 * pow(2, (9 - PRECISION_WEAK_FLOAT)); wfloat wfa(fa); wfloat wfb(fb); wfloat wfc(fc); if (PRECISION_WEAK_FLOAT == 32) { float f1 = static_cast <float> (200. * (rand() / (float)RAND_MAX) - 2.0); float f2 = static_cast <float> (200. * (rand() / (float)RAND_MAX) - 2.0); unsigned int u = rand(); wfloat w1(f1), w2(f2); if (w1 != f1 || w2 != f2) { std::cout << "32: " << w1 << " != " << f1 << " || " << w2 << " != " << f2 << std::endl; return false; } if (w1 + w2 != f1 + f2) { std::cout << "32: " << w1 << " + " << w2 << " != " << f1 << " + " << f2 << std::endl; return false; } if (w1 - w2 != f1 - f2) { std::cout << "32: " << w1 << " - " << w2 << " != " << f1 << " - " << f2 << std::endl; return false; } if (w1 * w2 != f1 * f2) { std::cout << "32: " << w1 << " * " << w2 << " != " << f1 << " * " << f2 << std::endl; return false; } if (w1 / w2 != f1 / f2) { std::cout << "32: " << w1 << " / " << w2 << " != " << f1 << " / " << f2 << std::endl; return false; } if (w1 / u != f1 / u) { std::cout << "32: " << w1 << " / " << u << " != " << f1 << " / " << u << std::endl; return false; } if (rabs(w1 * w2) != fabsf(f1 * f2)) { std::cout << "32: |" << w1 << " * " << w2 << "| != |" << f1 << " * " << f2 << "|"<< std::endl; return false; } if (rsqrt(w1) != sqrtf(f1)) { std::cout << "32: sqrt(" << w1 << ")" << " != sqrt(" << f1 << ")" << std::endl; return false; } if (rcos(w2) != cosf(f2)) { std::cout << "32: " << w1 << " + " << w2 << " != " << f1 << " + " << f2 << std::endl; return false; } return true; } //FE_UPWARD, FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO if (ROUNDING == FE_TONEAREST) { if (wfa != 32.f) { std::cout << "ut+: " << fa << " -> " << wfa << " != " << 32.f << std::endl; return false; } if (PRECISION_WEAK_FLOAT == 31 && wfb != ulp32) { return false; } if (PRECISION_WEAK_FLOAT != 31 && wfb != 32.f) { std::cout << "ut+b: " << fb << " -> " << wfb << " != " << 32.f << std::endl; return false; } if (wfc != ulp32) { std::cout << "ut+c: " << fc << " -> " << wfc << " != " << ulp32 << std::endl; return false; } wfa = -fa; wfb = -fb; wfc = -fc; if (wfa != -32.f) { std::cout << "ut-: " << fa << " -> " << wfa << " != " << -32.f << std::endl; return false; } if (PRECISION_WEAK_FLOAT == 31 && wfb != -ulp32) { return false; } if (PRECISION_WEAK_FLOAT != 31 && wfb != -32.f) { std::cout << "ut-: " << fb << " -> " << wfb << " != " << -32.f << std::endl; return false; } if (wfc != -ulp32) { std::cout << "ut-: " << fc << " -> " << wfc << " != " << -ulp32 << std::endl; return false; } } if (ROUNDING == FE_UPWARD) { if (wfa != 32.f) { std::cout << "ut+a: " << fa << " -> " << wfa << " != " << 32.f << std::endl; return false; } if (wfb != ulp32) { std::cout << "ut+b: " << fb << " -> " << wfb << " != " << ulp32 << std::endl; return false; } if (wfc != ulp32) { std::cout << "ut+c: " << fc << " -> " << wfc << " != " << ulp32 << std::endl; return false; } wfa = -fa; wfb = -fb; wfc = -fc; if (wfa != -32.f + ulp16) { std::cout << "ut-: " << fa << " -> " << wfa << " != " << -32.f + ulp16<< std::endl; return false; } if (wfb != -32.f) { std::cout << "ut-: " << fb << " -> " << wfb << " != " << -32.f << std::endl; return false; } if (wfc != -32.f) { std::cout << "ut-: " << fc << " -> " << wfc << " != " << 32.f << std::endl; return false; } } if (ROUNDING == FE_DOWNWARD) { if (wfa != 32.f - ulp16) { std::cout << "ut: " << fa << " -> " << wfa << " != " << 32.f - ulp16 << std::endl; return false; } if (wfb != 32.f) return false; if (wfc != 32.f) return false; wfa = -fa; wfb = -fb; wfc = -fc; if (wfa != -32.f) { std::cout << "ut-: " << fa << " -> " << wfa << " != " << -32.f << std::endl; return false; } if (wfb != -ulp32) { std::cout << "ut-: " << fb << " -> " << wfb << " != " << -ulp32 << std::endl; return false; } if (wfc != -ulp32) { std::cout << "ut-: " << fc << " -> " << wfc << " != " << -ulp32 << std::endl; return false; } } if (ROUNDING == FE_TOWARDZERO) { if (wfa != 32.f - ulp16) { std::cout << "ut: " << fa << " -> " << wfa << " != " << 32.f - ulp16 << std::endl; return false; } if (wfb != 32.f) return false; if (wfc != 32.f) return false; wfa = -fa; wfb = -fb; wfc = -fc; if (wfa != -32.f + ulp16) { std::cout << "ut: " << fa << " -> " << wfa << " != " << -32.f + ulp16 << std::endl; return false; } if (wfb != -32.f) return false; if (wfc != -32.f) return false; } return true; } bool test_weak_float() { return unit_test(); std::cout << " !~ ------------ Weak float " << PRECISION_WEAK_FLOAT << " test ------------ ~! " << std::endl; constexpr int max_digits10 = std::min(std::numeric_limits<float>::max_digits10, (int)std::ceil((PRECISION_WEAK_FLOAT - 9) * std::log10(2) + 2)); srand (time(NULL)); float m = std::numeric_limits<float>::max(); wfloat w1(m); std::cout << std::setprecision(std::numeric_limits<float>::max_digits10); std::cout << "\tXX | " << std::defaultfloat << m << " | " << std::hexfloat << m << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w1 << " | " << std::hexfloat << w1 << std::endl; float f1 = static_cast <float> (100. * rand() / (float)RAND_MAX); float f2 = static_cast <float> (100. * rand() / (float)RAND_MAX); float f3 = static_cast <float> (-100. * rand() / (float)RAND_MAX); float f4 = static_cast <float> (-100. * rand() / (float)RAND_MAX); unsigned int u = rand(); w1 = f1; wfloat w2(f2); wfloat wr3(f3); wfloat wr4(f4); std::cout << "\tXX | " << std::defaultfloat << f1 << " | " << std::hexfloat << f1 << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w1 << " | " << std::hexfloat << w1 << std::endl; std::cout << "\tXX | " << std::defaultfloat << f2 << " | " << std::hexfloat << f2 << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w2 << " | " << std::hexfloat << w2 << std::endl; std::cout << "\tXX | " << std::defaultfloat << f3 << " | " << std::hexfloat << f3 << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << wr3 << " | " << std::hexfloat << wr3 << std::endl; std::cout << "\tXX | " << std::defaultfloat << f4 << " | " << std::hexfloat << f4 << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << wr4 << " | " << std::hexfloat << wr4 << std::endl; std::cout << "\tXX | " << std::defaultfloat << f1 << " + " << f2 << " = " << (f1 + f2) << " | " << std::hexfloat << (f1 + f2) << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w1 << " + " << w2 << " = " << (w1 + w2) << " | " << std::hexfloat << (w1 + w2) << std::endl; auto w3 = w1 + w2; if (w3.truncated() == false) return false; std::cout << "\tXX | " << std::defaultfloat << f1 << " - " << f2 << " = " << (f1 - f2) << " | " << std::hexfloat << (f1 - f2) << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w1 << " - " << w2 << " = " << (w1 - w2) << " | " << std::hexfloat << (w1 - w2) << std::endl; w3 = w1 - w2; if (w3.truncated() == false) return false; std::cout << "\tXX | " << std::defaultfloat << f1 << " * " << f2 << " = " << (f1 * f2) << " | " << std::hexfloat << (f1 * f2) << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w1 << " * " << w2 << " = " << (w1 * w2) << " | " << std::hexfloat << (w1 * w2) << std::endl; w3 = w1 * w2; if (w3.truncated() == false) return false; std::cout << "\tXX | " << std::defaultfloat << f1 << " / " << f2 << " = " << (f1 / f2) << " | " << std::hexfloat << (f1 / f2) << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w1 << " / " << w2 << " = " << (w1 / w2) << " | " << std::hexfloat << (w1 / w2) << std::endl; w3 = w1 / w2; if (w3.truncated() == false) return false; std::cout << "\tXX | " << std::defaultfloat << f1 << " / " << u << " = " << (f1 / u) << " | " << std::hexfloat << (f1 / u) << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::defaultfloat << w1 << " / " << u << " = " << (w1 / u) << " | " << std::hexfloat << (w1 / u) << std::endl; w3 = w1 * w2; if (w3.truncated() == false) return false; std::cout << std::defaultfloat; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::setprecision(max_digits10) << w1 << "(" << max_digits10 << ") | " << std::setprecision(std::numeric_limits<float>::max_digits10) << w1 << "(" << std::numeric_limits<float>::max_digits10 << ")" << std::endl; std::cout << "\t" << PRECISION_WEAK_FLOAT << " | " << std::setprecision(max_digits10) << w2 << "(" << max_digits10 << ") | " << std::setprecision(std::numeric_limits<float>::max_digits10) << w2 << "(" << std::numeric_limits<float>::max_digits10 << ")" << std::endl; float fa(31.999999); float fb(32.000003); float fc = 32.0 + 32.0 * pow(2, (8 - PRECISION_WEAK_FLOAT)); std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fa << " -> " << std::setprecision(max_digits10) << wfloat(fa); std::cout << ", h:" << std::hexfloat << fa <<" -> " << wfloat(fa) << std::endl; std::cout << std::defaultfloat; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << 44.f << " -> " << std::setprecision(max_digits10) << wfloat(44.f); std::cout << ", h:" << std::hexfloat << 44.f <<" -> " << wfloat(44.f) << std::endl; std::cout << std::defaultfloat; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fb << " -> " << std::setprecision(max_digits10) << wfloat(fb); std::cout << ", h:" << std::hexfloat << fb <<" -> " << wfloat(fb) << std::endl; std::cout << std::defaultfloat; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fc << " -> " << std::setprecision(max_digits10) << wfloat(fc); std::cout << ", h:" << std::hexfloat << fc <<" -> " << wfloat(fc) << std::endl; std::cout << std::defaultfloat; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fa << " -> " << std::setprecision(max_digits10) << wfloat(-fa); std::cout << ", h:" << std::hexfloat << -fa <<" -> " << wfloat(-fa) << std::endl; std::cout << std::defaultfloat; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fb << " -> " << std::setprecision(max_digits10) << wfloat(-fb); std::cout << ", h:" << std::hexfloat << -fb <<" -> " << wfloat(-fb) << std::endl; std::cout << std::defaultfloat; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fc << " -> " << std::setprecision(max_digits10) << wfloat(-fc); std::cout << ", h:" << std::hexfloat << -fc <<" -> " << wfloat(-fc) << std::endl; std::cout << std::defaultfloat; fa = 1.999999e29; fb = 2.000003e29; fc = (2. + pow(2, (8 - PRECISION_WEAK_FLOAT))) * powf(2.0, 29); std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fa << " -> " << std::setprecision(max_digits10) << wfloat(fa) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fb << " -> " << std::setprecision(max_digits10) << wfloat(fb) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fc << " -> " << std::setprecision(max_digits10) << wfloat(fc) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fa << " -> " << std::setprecision(max_digits10) << wfloat(-fa) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fb << " -> " << std::setprecision(max_digits10) << wfloat(-fb) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fc << " -> " << std::setprecision(max_digits10) << wfloat(-fc) << std::endl; fa = 1.999999e-29; fb = 2.000003e-29; fc = (2. + pow(2, (8 - PRECISION_WEAK_FLOAT))) * powf(2.0, -29); std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fa << " -> " << std::setprecision(max_digits10) << wfloat(fa) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fb << " -> " << std::setprecision(max_digits10) << wfloat(fb) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << fc << " -> " << std::setprecision(max_digits10) << wfloat(fc) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fa << " -> " << std::setprecision(max_digits10) << wfloat(-fa) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fb << " -> " << std::setprecision(max_digits10) << wfloat(-fb) << std::endl; std::cout << "\tROUNDING<" << PRECISION_WEAK_FLOAT << ">: " << std::setprecision(std::numeric_limits<float>::max_digits10) << -fc << " -> " << std::setprecision(max_digits10) << wfloat(-fc) << std::endl; std::cout << std::endl; /* std::cout << "float::digits = " << std::numeric_limits<float>::digits << std::endl; std::cout << "float::digits10 = " << std::numeric_limits<float>::digits10 << std::endl; std::cout << "float::max_digits10 = " << std::numeric_limits<float>::max_digits10 << std::endl; std::cout << "(PRECISION_WEAK_FLOAT - 8) * std::log10(2) + 1 = " << (PRECISION_WEAK_FLOAT - 8) << " * " << std::log10(2) << " + 1 = "; std::cout << (PRECISION_WEAK_FLOAT - 8) * std::log10(2) + 1 << std::endl; std::cout << "Number::max_digits10 = " << max_digits10 << std::endl; */ /* for (int i = 10; i < 33; ++i) { int p = std::min(std::numeric_limits<float>::max_digits10, (int)std::ceil((i - 9) * std::log10(2) + 2)); std::cout << i << " -> " << p << std::endl; } */ std::cout << " !~ ------------ Weak float " << PRECISION_WEAK_FLOAT << " end ------------ ~! " << std::endl; return true; }
45.844262
269
0.472793
will-iam
354fb539247f27ae5a13485e90ebe8e37767d52a
4,546
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/NCLPhysicalAddress/CPP/NCLPhysicalAddress.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/NCLPhysicalAddress/CPP/NCLPhysicalAddress.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/NCLPhysicalAddress/CPP/NCLPhysicalAddress.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
#using <system.dll> using namespace System; using namespace System::Net::NetworkInformation; using namespace System::Collections; // <snippet1> void DisplayAddressNone() { PhysicalAddress^ none = PhysicalAddress::None; Console::WriteLine( L"None: {0}", none ); array<Byte>^bytes = none->GetAddressBytes(); System::Collections::IEnumerator^ myEnum = bytes->GetEnumerator(); while ( myEnum->MoveNext() ) { Byte b = safe_cast<Byte>(myEnum->Current); Console::Write( L"{0} ", b.ToString() ); } Console::WriteLine(); } // </snippet1> // <snippet2> void ShowNetworkInterfaces() { IPGlobalProperties^ computerProperties = IPGlobalProperties::GetIPGlobalProperties(); array<NetworkInterface^>^nics = NetworkInterface::GetAllNetworkInterfaces(); Console::WriteLine( L"Interface information for {0}.{1} ", computerProperties->HostName, computerProperties->DomainName ); if ( nics == nullptr || nics->Length < 1 ) { Console::WriteLine( L" No network interfaces found." ); return; } Console::WriteLine( L" Number of interfaces .................... : {0}", (nics->Length).ToString() ); IEnumerator^ myEnum1 = nics->GetEnumerator(); while ( myEnum1->MoveNext() ) { NetworkInterface^ adapter = safe_cast<NetworkInterface^>(myEnum1->Current); IPInterfaceProperties^ properties = adapter->GetIPProperties(); Console::WriteLine(); Console::WriteLine( adapter->Description ); Console::WriteLine( String::Empty->PadLeft( adapter->Description->Length, '=' ) ); Console::WriteLine( L" Interface type .......................... : {0}", adapter->NetworkInterfaceType ); Console::Write( L" Physical address ........................ : " ); PhysicalAddress^ address = adapter->GetPhysicalAddress(); array<Byte>^bytes = address->GetAddressBytes(); for ( int i = 0; i < bytes->Length; i++ ) { // Display the physical address in hexadecimal. Console::Write( L"{0}", bytes[ i ].ToString( L"X2" ) ); // Insert a hyphen after each byte, unless we are at the end of the // address. if ( i != bytes->Length - 1 ) { Console::Write( L"-" ); } } Console::WriteLine(); } } // </snippet2> // <snippet3> void ParseTest() { PhysicalAddress^ address = PhysicalAddress::Parse( L"AC1EBA22" ); Console::WriteLine( L"Address parsed as {0}", address->ToString() ); PhysicalAddress^ address2 = PhysicalAddress::Parse( L"ac1eba22" ); Console::WriteLine( L"Address2 parsed as {0}", address2->ToString() ); bool test = address->Equals( address2 ); Console::WriteLine( L"Equal? {0}", test ); } // </snippet3> // <snippet4> array<PhysicalAddress^>^ StoreNetworkInterfaceAddresses() { IPGlobalProperties^ computerProperties = IPGlobalProperties::GetIPGlobalProperties(); array<NetworkInterface^>^nics = NetworkInterface::GetAllNetworkInterfaces(); if ( nics == nullptr || nics->Length < 1 ) { Console::WriteLine( L" No network interfaces found." ); return nullptr; } array<PhysicalAddress^>^ addresses = gcnew array<PhysicalAddress^>(nics->Length); int i = 0; IEnumerator^ myEnum2 = nics->GetEnumerator(); while ( myEnum2->MoveNext() ) { NetworkInterface^ adapter = safe_cast<NetworkInterface^>(myEnum2->Current); IPInterfaceProperties^ properties = adapter->GetIPProperties(); PhysicalAddress^ address = adapter->GetPhysicalAddress(); array<Byte>^bytes = address->GetAddressBytes(); PhysicalAddress^ newAddress = gcnew PhysicalAddress( bytes ); addresses[ i++ ] = newAddress; } return addresses; } // </snippet4> //<snippet5> PhysicalAddress^ StrictParseAddress( String^ address ) { PhysicalAddress^ newAddress = PhysicalAddress::Parse( address ); if ( PhysicalAddress::None->Equals( newAddress ) ) return nullptr; return newAddress; } //</snippet5> int main() { DisplayAddressNone(); ShowNetworkInterfaces(); ParseTest(); /* PhysicalAddress[] addresses = StoreNetworkInterfaceAddresses(); foreach (PhysicalAddress address in addresses) { Console.WriteLine(address.ToString()); } */ PhysicalAddress^ a = StrictParseAddress( nullptr ); Console::WriteLine( a == nullptr ? L"null" : a->ToString() ); }
32.241135
130
0.623845
hamarb123
35554a19275e6f8d133ce9b9c4aaa4cf0a793bbd
499
cpp
C++
0000/50/53c.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
0000/50/53c.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
0000/50/53c.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <vector> void answer(const std::vector<unsigned>& v) { const char* separator = ""; for (const unsigned x : v) { std::cout << separator << x; separator = " "; } std::cout << '\n'; } void solve(unsigned n) { std::vector<unsigned> p(n); for (size_t i = 0; i < n; i += 2) { p[i+0] = 1 + i/2; p[i+1] = n - i/2; } answer(p); } int main() { unsigned n; std::cin >> n; solve(n); return 0; }
14.257143
43
0.476954
actium
35569efaa927537d24041fad3667e30b904bc76b
749
hpp
C++
src/Hukan/graphics/Window/Win32/WindowWin32.hpp
eUltrabyte/Hukan
c3d4e2f53964b54ac7e6f319586095bdb8ae107d
[ "MIT" ]
6
2021-11-05T14:47:12.000Z
2022-02-06T21:27:56.000Z
src/Hukan/graphics/Window/Win32/WindowWin32.hpp
eUltrabyte/Hukan
c3d4e2f53964b54ac7e6f319586095bdb8ae107d
[ "MIT" ]
null
null
null
src/Hukan/graphics/Window/Win32/WindowWin32.hpp
eUltrabyte/Hukan
c3d4e2f53964b54ac7e6f319586095bdb8ae107d
[ "MIT" ]
2
2021-11-05T12:08:58.000Z
2021-12-09T20:54:29.000Z
#pragma once #include "../Window.hpp" #if defined(HUKAN_SYSTEM_WIN32) #include <Windows.h> namespace hk { class HK_API WindowImplWin32 : public Window { public: WindowImplWin32(WindowCreateInfo* pWindowCreateInfo = nullptr); virtual ~WindowImplWin32(); virtual void Create(); virtual void Update(); virtual void Destroy(); virtual void SetWindowCreateInfo(WindowCreateInfo* pWindowCreateInfo = nullptr); virtual WindowCreateInfo* GetWindowCreateInfo(); virtual HINSTANCE* GetHINSTANCE(); virtual HWND* GetHWND(); private: WindowCreateInfo* mpWindowCreateInfo; HINSTANCE mHinstance; HWND mHwnd; MSG mMessage; }; }; #endif
22.69697
88
0.660881
eUltrabyte
35584232a74fe32e751c0b31c026cbe9e7b28c87
858
cpp
C++
CLL113/Assignments/tut1-1/main.cpp
sak1sham/CLL113-Numerical-Methods-Tutsheets
c6589c39bdf31f9d6e86aec97d2ea155a78d89d4
[ "MIT" ]
2
2020-05-26T02:00:10.000Z
2020-12-09T17:06:37.000Z
CLL113/Assignments/tut1-1/main.cpp
sak1sham/CLL113-Numerical-Methods-Tutsheets
c6589c39bdf31f9d6e86aec97d2ea155a78d89d4
[ "MIT" ]
null
null
null
CLL113/Assignments/tut1-1/main.cpp
sak1sham/CLL113-Numerical-Methods-Tutsheets
c6589c39bdf31f9d6e86aec97d2ea155a78d89d4
[ "MIT" ]
null
null
null
//Saksham Garg 2018CH10927 //Question 1 //Truncation Error //Maclaurin series #include <iostream> #include<math.h> #include<iomanip> using namespace std; long int fac(int n){ long int f = 1; for(int i = 1; i<=n; i++){ f = f*i; } return f; } int main() { int n = 8; double es = 0.5 * pow(10,2-n); const double PI = std::atan(1.0)*4; double x = 0.3 * PI; int i = 0; double res = 0.00000000; //INV: res = res + pow(x,i)/fac(i) ^ pow(x,i)/fac(i)>=es while(pow(x,i)/fac(i)>=es){ res += pow(-1,i/2)*pow(x,i)/fac(i); i+=2; } cout<<"Number of terms required are : "<<i/2<<endl; std::cout << std::fixed; cout<<std::setprecision(8); cout<<"Final answer : "<<res; //assert: res = sum(i = 0 to n){pow(x,i)/fac(i)} ^ pow(x,n)/fac(n)>=es return 0; }
23.189189
75
0.518648
sak1sham
35589f108c3aa4fc3ca6bd4c1f4302315bd01a35
3,090
cpp
C++
Core/Renderer/OpenGL/src/OGLVAO.cpp
SDurand7/AVLIT-Engine
c7a8e361d91e57fb96acfc1c96a88c3b480bb256
[ "MIT" ]
null
null
null
Core/Renderer/OpenGL/src/OGLVAO.cpp
SDurand7/AVLIT-Engine
c7a8e361d91e57fb96acfc1c96a88c3b480bb256
[ "MIT" ]
null
null
null
Core/Renderer/OpenGL/src/OGLVAO.cpp
SDurand7/AVLIT-Engine
c7a8e361d91e57fb96acfc1c96a88c3b480bb256
[ "MIT" ]
null
null
null
#include "OGLVAO.hpp" #include <Core/Base/include/Mesh.hpp> namespace AVLIT { OGLVAO::OGLVAO(const Mesh &mesh) : m_buffers(2) { glGenVertexArrays(1, &m_vaoID); glGenBuffers(2, m_buffers.data()); glBindVertexArray(m_vaoID); const auto &indices = mesh.indices(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffers[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(), indices.data(), GL_STATIC_DRAW); const auto &vertices = mesh.vertices(); glBindBuffer(GL_ARRAY_BUFFER, m_buffers[1]); glBufferData(GL_ARRAY_BUFFER, 3 * sizeof(GLfloat) * vertices.size(), vertices.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(0); if(mesh.hasTexCoords()) { GLuint texCoordsID; glGenBuffers(1, &texCoordsID); const auto &texCoords = mesh.texCoords(); glBindBuffer(GL_ARRAY_BUFFER, texCoordsID); glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(GLfloat) * texCoords.size(), texCoords.data(), GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(1); m_buffers.push_back(texCoordsID); } else { glVertexAttrib2f(1, 0.f, 0.f); } if(mesh.hasNormals()) { GLuint normalsID; glGenBuffers(1, &normalsID); const auto &normals = mesh.normals(); glBindBuffer(GL_ARRAY_BUFFER, normalsID); glBufferData(GL_ARRAY_BUFFER, 3 * sizeof(GLfloat) * normals.size(), normals.data(), GL_STATIC_DRAW); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(2); m_buffers.push_back(normalsID); } else { glVertexAttrib3f(2, 1.f, 0.f, 0.f); } if(mesh.hasTangentSpace()) { GLuint tangentsID; glGenBuffers(1, &tangentsID); const auto &tangents = mesh.tangents(); glBindBuffer(GL_ARRAY_BUFFER, tangentsID); glBufferData(GL_ARRAY_BUFFER, 3 * sizeof(GLfloat) * tangents.size(), tangents.data(), GL_STATIC_DRAW); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(3); m_buffers.push_back(tangentsID); GLuint bitangentsID; glGenBuffers(1, &bitangentsID); const auto &bitangents = mesh.bitangents(); glBindBuffer(GL_ARRAY_BUFFER, bitangentsID); glBufferData(GL_ARRAY_BUFFER, 3 * sizeof(GLfloat) * bitangents.size(), bitangents.data(), GL_STATIC_DRAW); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(4); m_buffers.push_back(bitangentsID); } else { glVertexAttrib3f(3, 1.f, 0.f, 0.f); glVertexAttrib3f(4, 1.f, 0.f, 0.f); } glBindVertexArray(0); GL_CHECK_ERROR(); } OGLVAO::~OGLVAO() { glDeleteBuffers(static_cast<GLsizei>(m_buffers.size()), m_buffers.data()); glDeleteVertexArrays(1, &m_vaoID); } } // namespace AVLIT
35.930233
114
0.668285
SDurand7
355a57dd489e18a5d32107a64bbe1104047f23f2
10,460
cpp
C++
Snake AI Project/src/manager/UI_Manager.cpp
BenjaminViranin/Snake-AI-Project
50f9a8195eed9a298480d24598e221657b06abfa
[ "MIT" ]
null
null
null
Snake AI Project/src/manager/UI_Manager.cpp
BenjaminViranin/Snake-AI-Project
50f9a8195eed9a298480d24598e221657b06abfa
[ "MIT" ]
null
null
null
Snake AI Project/src/manager/UI_Manager.cpp
BenjaminViranin/Snake-AI-Project
50f9a8195eed9a298480d24598e221657b06abfa
[ "MIT" ]
null
null
null
#include "manager/UI_Manager.h" #include <tools/Time.h> #include <manager/Game_Manager.h> UI_Manager::UI_Manager(Snake& p_snake, Map_Manager& p_map_manager, Save_Manager& p_save_manager) : m_windowWidth(0), m_windowHeight(0), m_snake(p_snake), m_map_manager(p_map_manager), m_save_manager(p_save_manager) { } UI_Manager::~UI_Manager() { } void UI_Manager::Init(int p_windowWidth, int p_windowHeight) { m_windowWidth = p_windowWidth; m_windowHeight = p_windowHeight; const sf::Color textColor = sf::Color(135, 206, 250); const float heightTextOffset = 4.0f; // Draw Pause pauseScreen.SetFont(Tools::SfLogger::GetFont("SAO")); pauseScreen.SetSize(50); pauseScreen.SetColor(textColor); pauseScreen.SetOrigin(Tools::ETextEncrage::Middle); pauseScreen.SetText("PAUSE"); pauseScreen.SetPosition(sf::Vector2f(m_windowWidth * 0.5f, m_windowHeight * 0.5f)); pauseScreen.IsDrawable() = false; Tools::SfLogger::Save(pauseScreen); // Draw Game Over GameOver.SetFont(Tools::SfLogger::GetFont("SAO")); GameOver.SetSize(50); GameOver.SetColor(sf::Color::Red); GameOver.SetOrigin(Tools::ETextEncrage::Middle); GameOver.SetText("GAME OVER"); GameOver.SetPosition(sf::Vector2f(m_windowWidth * 0.5f, m_windowHeight * 0.5f)); GameOver.IsDrawable() = false; Tools::SfLogger::Save(GameOver); // Draw Score score.SetFont(Tools::SfLogger::GetFont("SAO")); score.SetSize(50); score.SetColor(textColor); score.SetText("SCORE: ", m_snake.GetScore()); score.SetPosition(sf::Vector2f(10, 10)); Tools::SfLogger::Save(score); // Draw FPS fps.SetFont(Tools::SfLogger::GetFont("SAO")); fps.SetSize(22); fps.SetColor(textColor); fps.SetText("FPS : "); fps.SetPosition(sf::Vector2f(static_cast<float>(m_windowWidth - 450), static_cast<float>(10))); Tools::SfLogger::Save(fps); fpsValue.SetFont(Tools::SfLogger::GetFont("SAO")); fpsValue.SetSize(22); fpsValue.SetColor(sf::Color(253, 106, 2)); fpsValue.SetText(Tools::Time::GetFPS()); fpsValue.SetPositionWithOtherText(fps, Tools::ETextPosition::Right, 2); Tools::SfLogger::Save(fpsValue); // Draw Pause pause.SetFont(Tools::SfLogger::GetFont("SAO")); pause.SetSize(22); pause.SetColor(textColor); pause.SetText("[P] Pause: "); pause.SetPositionWithOtherText(fps, Tools::ETextPosition::Down, heightTextOffset); Tools::SfLogger::Save(pause); pauseValue.SetFont(Tools::SfLogger::GetFont("SAO")); pauseValue.SetSize(22); pauseValue.SetColor(Game_Manager::GameState == EGameState::IsPause ? sf::Color::Green : sf::Color::Red); pauseValue.SetText(Game_Manager::GameState == EGameState::IsPause ? "true" : "false"); pauseValue.SetPositionWithOtherText(pause, Tools::ETextPosition::Right, 2); Tools::SfLogger::Save(pauseValue); // Draw Reset Game resetGame.SetFont(Tools::SfLogger::GetFont("SAO")); resetGame.SetSize(22); resetGame.SetColor(textColor); resetGame.SetText("[R][Return] Reset Game"); resetGame.SetPositionWithOtherText(pause, Tools::ETextPosition::Down, heightTextOffset); Tools::SfLogger::Save(resetGame); // Draw Quit quit.SetFont(Tools::SfLogger::GetFont("SAO")); quit.SetSize(22); quit.SetColor(textColor); quit.SetText("[Escape] Quit Game"); quit.SetPositionWithOtherText(resetGame, Tools::ETextPosition::Down, heightTextOffset); Tools::SfLogger::Save(quit); // Draw Draw Grid drawGrid.SetFont(Tools::SfLogger::GetFont("SAO")); drawGrid.SetSize(22); drawGrid.SetColor(textColor); drawGrid.SetText("[G] Draw Grid: "); drawGrid.SetPositionWithOtherText(fps, Tools::ETextPosition::Right, 200); Tools::SfLogger::Save(drawGrid); drawGridValue.SetFont(Tools::SfLogger::GetFont("SAO")); drawGridValue.SetSize(22); drawGridValue.SetColor(m_map_manager.IsDrawGrid() ? sf::Color::Green : sf::Color::Red); drawGridValue.SetText(m_map_manager.IsDrawGrid() ? "true" : "false"); drawGridValue.SetPositionWithOtherText(drawGrid, Tools::ETextPosition::Right, 2); Tools::SfLogger::Save(drawGridValue); // Draw Snake Speed snakeSpeed.SetFont(Tools::SfLogger::GetFont("SAO")); snakeSpeed.SetSize(22); snakeSpeed.SetColor(textColor); snakeSpeed.SetText("[-][+] Snake Speed: "); snakeSpeed.SetPositionWithOtherText(drawGrid, Tools::ETextPosition::Down, heightTextOffset); Tools::SfLogger::Save(snakeSpeed); snakeSpeedValue.SetFont(Tools::SfLogger::GetFont("SAO")); snakeSpeedValue.SetSize(22); snakeSpeedValue.SetColor(m_snake.GetSpeed() < 50 ? sf::Color::Red : m_snake.GetSpeed() > 85 ? sf::Color::Red : sf::Color::Green); snakeSpeedValue.SetText(m_snake.GetSpeed()); snakeSpeedValue.SetPositionWithOtherText(snakeSpeed, Tools::ETextPosition::Right, 2); Tools::SfLogger::Save(snakeSpeedValue); // Draw Show High Scores showHighScores.SetFont(Tools::SfLogger::GetFont("SAO")); showHighScores.SetSize(22); showHighScores.SetColor(textColor); showHighScores.SetText("[H] Show High Scores "); showHighScores.SetPositionWithOtherText(snakeSpeed, Tools::ETextPosition::Down, heightTextOffset); Tools::SfLogger::Save(showHighScores); // Draw High Scores Title highScoresTitle.SetFont(Tools::SfLogger::GetFont("SAO")); highScoresTitle.SetSize(34); highScoresTitle.SetColor(textColor); highScoresTitle.SetText("HIGH SCORES"); highScoresTitle.SetOrigin(Tools::ETextEncrage::Middle); highScoresTitle.SetPosition(sf::Vector2f(m_windowWidth * 0.5f, 60)); highScoresTitle.IsDrawable() = false; Tools::SfLogger::Save(highScoresTitle); // Draw Player High Scores Tools::SfText playerName; playerName.SetFont(Tools::SfLogger::GetFont("SAO")); playerName.SetSize(28); playerName.SetColor(textColor); playerName.SetText(Game_Manager::PlayerName); playerName.IsDrawable() = false; sf::Vector2f namePos(m_windowWidth * 0.25f - 92, m_windowHeight * 0.25f); Tools::SfText playerScore; playerScore.SetFont(Tools::SfLogger::GetFont("SAO")); playerScore.SetSize(28); playerScore.SetColor(textColor); playerScore.SetText(": ..."); playerScore.IsDrawable() = false; sf::Vector2f scorePos(m_windowWidth * 0.25f + 10, m_windowHeight * 0.25f); for (int i = 0; i < m_save_manager.GetSaveLenght(); ++i) { playerName.SetPosition(namePos); playerScore.SetPosition(scorePos); playerScores.emplace_back(std::pair<Tools::SfText, Tools::SfText>(playerName, playerScore)); Tools::SfLogger::Save(playerScores.back().first); Tools::SfLogger::Save(playerScores.back().second); namePos.y += 30; scorePos.y += 30; } // Draw AI High Scores Tools::SfText AIScore; AIScore.SetFont(Tools::SfLogger::GetFont("SAO")); AIScore.SetSize(28); AIScore.SetColor(textColor); AIScore.SetOrigin(Tools::ETextEncrage::Middle); AIScore.SetText(" AI : ... "); AIScore.IsDrawable() = false; sf::Vector2f AIScorePos(m_windowWidth * 0.75f, m_windowHeight * 0.25f); for (int i = 0; i < m_save_manager.GetSaveLenght(); ++i) { AIScore.SetPosition(AIScorePos); AIScores.push_back(AIScore); Tools::SfLogger::Save(AIScores.back()); AIScorePos.y += 30; } // Draw High Scores Exit highScoresExit.SetFont(Tools::SfLogger::GetFont("SAO")); highScoresExit.SetSize(26); highScoresExit.SetColor(textColor); highScoresExit.SetText("[H] Exit"); highScoresExit.SetOrigin(Tools::ETextEncrage::Middle); highScoresExit.SetPosition(sf::Vector2f(m_windowWidth * 0.5f, AIScores.back().GetPosition().y + 100)); highScoresExit.IsDrawable() = false; Tools::SfLogger::Save(highScoresExit); } void UI_Manager::Update() { // Update Pause if (Game_Manager::GameState == EGameState::IsPause) pauseScreen.IsDrawable() = true; else pauseScreen.IsDrawable() = false; // Update Game Over if (Game_Manager::GameState == EGameState::IsGameOver) GameOver.IsDrawable() = true; else GameOver.IsDrawable() = false; // Update Score score.SetText("SCORE: ", m_snake.GetScore()); // Update FPS fpsValue.SetText(Tools::Time::GetFPS()); // Update Pause pauseValue.SetColor(Game_Manager::GameState == EGameState::IsPause ? sf::Color::Green : sf::Color::Red); pauseValue.SetText(Game_Manager::GameState == EGameState::IsPause ? "true" : "false"); // Update Draw Grid drawGridValue.SetColor(m_map_manager.IsDrawGrid() ? sf::Color::Green : sf::Color::Red); drawGridValue.SetText(m_map_manager.IsDrawGrid() ? "true" : "false"); // Update Snake Speed snakeSpeedValue.SetColor(m_snake.GetSpeed() < 50 ? sf::Color::Red : m_snake.GetSpeed() > 85 ? sf::Color::Red : sf::Color::Green); snakeSpeedValue.SetText(m_snake.GetSpeed()); } void UI_Manager::Draw(sf::RenderWindow* p_window) { Tools::SfLogger::Draw(p_window); } void UI_Manager::ShowMainScreen() { highScoresTitle.IsDrawable() = false; highScoresExit.IsDrawable() = false; for (auto& text : playerScores) text.first.IsDrawable() = text.second.IsDrawable() = false; for (auto& text : AIScores) text.IsDrawable() = false; GameOver.IsDrawable() = true; score.IsDrawable() = true; fps.IsDrawable() = true; fpsValue.IsDrawable() = true; pauseScreen.IsDrawable() = true; pause.IsDrawable() = true; pauseValue.IsDrawable() = true; resetGame.IsDrawable() = true; quit.IsDrawable() = true; drawGrid.IsDrawable() = true; drawGridValue.IsDrawable() = true; snakeSpeed.IsDrawable() = true; snakeSpeedValue.IsDrawable() = true; showHighScores.IsDrawable() = true; } void UI_Manager::ShowScoreScreen() { GameOver.IsDrawable() = false; score.IsDrawable() = false; fps.IsDrawable() = false; fpsValue.IsDrawable() = false; pauseScreen.IsDrawable() = false; pause.IsDrawable() = false; pauseValue.IsDrawable() = false; resetGame.IsDrawable() = false; quit.IsDrawable() = false; drawGrid.IsDrawable() = false; drawGridValue.IsDrawable() = false; snakeSpeed.IsDrawable() = false; snakeSpeedValue.IsDrawable() = false; showHighScores.IsDrawable() = false; const auto& PlayerData = m_save_manager.GetPlayerData(); const auto& AI_Data = m_save_manager.GetAIData(); highScoresTitle.IsDrawable() = true; highScoresExit.IsDrawable() = true; for (int i = 0; i < m_save_manager.GetSaveLenght(); ++i) { playerScores[i].first.IsDrawable() = playerScores[i].second.IsDrawable() = true; if (i < PlayerData.size()) { playerScores[i].first.SetText(PlayerData[i].first); playerScores[i].second.SetText(": ", PlayerData[i].second); } else { playerScores[i].first.SetText("Unknown "); playerScores[i].second.SetText(": ... "); } AIScores[i].IsDrawable() = true; if (i < AI_Data.size()) AIScores[i].SetText(" AI : ", AI_Data[i].second); else AIScores[i].SetText(" AI : ... "); } }
32.996845
130
0.729924
BenjaminViranin
355ffdf1cf9592967332dd5dcdc7b3e6a95c5c74
822
cpp
C++
Dynamic Programming/0-1 Knapsack/(3)EqualSumPartition.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
53
2020-09-26T19:44:33.000Z
2021-09-30T20:38:52.000Z
Dynamic Programming/0-1 Knapsack/(3)EqualSumPartition.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
197
2020-08-25T18:13:56.000Z
2021-06-19T07:26:19.000Z
Dynamic Programming/0-1 Knapsack/(3)EqualSumPartition.cpp
jaydulera/data-structure-and-algorithms
abc2d67871add6f314888a72215ff3a2da2dc6e1
[ "Apache-2.0" ]
204
2020-08-24T09:21:02.000Z
2022-02-13T06:13:42.000Z
#include<bits/stdc++.h> using namespace std; bool t[100][100]; bool SubsetSum(int *wt, int Sum, int n) { for (int i = 0; i <= Sum; i++) t[0][i] = false; for (int i = 0; i <= n; i++) t[i][0] = true; //empty set for (int i = 1; i <= n; i++) { for (int j = 1; j <= Sum; j++) { if (wt[i - 1] <= j) { t[i][j] = (t[i - 1][j - wt[i - 1]] || t[i - 1][j]); } else { t[i][j] = t[i - 1][j]; } } } return t[n][Sum]; } bool EqSumPartition(int *wt, int n) { int s = 0; for (int i = 0; i < n; i++) s += wt[i]; if (s % 2 != 0) return false; else SubsetSum(wt, s / 2, n); } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int wt[] = {2, 6, 4, 10}; int n = sizeof(wt) / sizeof(int); cout << EqSumPartition(wt, n) << endl; }
16.77551
57
0.484185
jaydulera
8316e45167a6f61630e91a88a01c39049abfe830
14,288
cc
C++
kernel/runtime/cxx/runtime/cxxsupport.cc
ManyThreads/mythos
723a4b11e454a0c28e096755140c5e0eecf6a211
[ "MIT" ]
12
2016-10-06T14:02:17.000Z
2021-09-12T06:14:30.000Z
kernel/runtime/cxx/runtime/cxxsupport.cc
ManyThreads/mythos
723a4b11e454a0c28e096755140c5e0eecf6a211
[ "MIT" ]
110
2017-06-22T20:10:17.000Z
2022-01-18T12:58:40.000Z
kernel/runtime/cxx/runtime/cxxsupport.cc
ManyThreads/mythos
723a4b11e454a0c28e096755140c5e0eecf6a211
[ "MIT" ]
6
2016-12-09T08:30:08.000Z
2021-12-10T19:05:04.000Z
/* -*- mode:C++; -*- */ /* MIT License -- MyThOS: The Many-Threads Operating System * * 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. * * Copyright 2014 Randolf Rotta, Maik Krüger, and contributors, BTU Cottbus-Senftenberg */ #include <cstddef> #include <cstdint> #include <stdlib.h> #include <cstdarg> #include <endian.h> #include <pthread.h> #include <atomic> #include <sys/types.h> #include <errno.h> #include <sys/mman.h> #include <sys/time.h> #include <sys/resource.h> #include <bits/alltypes.h> #include "mythos/syscall.hh" #include "runtime/mlog.hh" #include "util/elf64.hh" #include "runtime/ExecutionContext.hh" #include "runtime/Portal.hh" #include "runtime/ExecutionContext.hh" #include "runtime/CapMap.hh" #include "runtime/Example.hh" #include "runtime/PageMap.hh" #include "runtime/KernelMemory.hh" #include "runtime/ProcessorAllocator.hh" #include "runtime/CapAlloc.hh" #include "runtime/tls.hh" #include "runtime/futex.hh" #include "runtime/umem.hh" #include "runtime/thread-extra.hh" #include "mythos/InfoFrame.hh" extern mythos::InfoFrame* info_ptr asm("info_ptr"); extern mythos::Portal portal; extern mythos::CapMap myCS; extern mythos::PageMap myAS; extern mythos::KernelMemory kmem; extern mythos::ProcessorAllocator pa; // synchronization for pthread deletion (exit/join) struct PthreadCleaner{ PthreadCleaner() : flag(FREE) { //MLOG_ERROR(mlog::app, "PthreadCleaner"); } enum state{ UNKNOWN = 0, // invalid FREE = 1, // initial state EXITED = 2 // target pthread has exited and it is now save to free its memory and EC // otherwise it holds the waiters EC pointer }; // marks the target pthread as finished (does not access its memory/stack anymore) // called by the finished pthread after pthread_exit and just before syscall_exit void exit(){ //MLOG_DETAIL(mlog::app, "PthreadCleaner exit", DVARhex(this), DVARhex(pthread_self())); auto ec = flag.exchange(EXITED); if(ec != FREE){ ASSERT(ec!=UNKNOWN); // wake waiter EC mythos::syscall_signal(ec); } } // wait until pthread t has finished (called exit()) // when returning from this function, it is save to free the target pthreads memory and EC void wait(pthread_t t){ auto pcs = reinterpret_cast<PthreadCleaner* >(t - (pthread_self() - reinterpret_cast<uintptr_t>(this))); //MLOG_DETAIL(mlog::app, "PthreadCleaner wait", DVARhex(pcs), DVARhex(this), DVARhex(pthread_self()), DVARhex(t)); while(pcs->flag.load() != EXITED){ mythos::CapPtr exp = FREE; // try to register as waiter if(pcs->flag.compare_exchange_weak(exp, mythos_get_pthread_ec_self())){ //MLOG_DETAIL(mlog::app, "PthreadCleaner going to wait"); mythos_wait(); } } } // lock std::atomic<mythos::CapPtr> flag; }; static thread_local PthreadCleaner pthreadCleaner; extern "C" [[noreturn]] void __assert_fail (const char *expr, const char *file, int line, const char *func) { mlog::Logger<> logassert("assert"); logassert.error("ASSERT",expr,"failed in",file,":",line,func); mythos::syscall_exit(-1); /// @TODO syscall_abort(); to see some stack backtrace etc } void mythosExit(){ MLOG_ERROR(mlog::app, "MYTHOS:PLEASE KILL ME!!!!!!1 elf"); } struct iovec { const char* io_base; size_t iov_len; }; ssize_t writev(int fd, const struct iovec *iov, int iovcnt) { //MLOG_WARN(mlog::app, "syscall writev"); ssize_t ret = 0; for (int i = 0; i < iovcnt; i++) { mlog::sink->write(iov[i].io_base, iov[i].iov_len); ret += iov[i].iov_len; } return ret; } int prlimit( pid_t pid, int resource, const struct rlimit *new_limit, struct rlimit *old_limit) { // dummy implementation return 0; } int sched_setaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask) { //MLOG_DETAIL(mlog::app, "syscall sched_setaffinity", DVAR(pid), DVAR(cpusetsize), DVARhex(mask)); if(cpusetsize == info_ptr->getNumThreads() && mask == NULL) return -EFAULT; return 0; } int sched_getaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask) { //MLOG_DETAIL(mlog::app, "syscall sched_getaffinity", DVAR(pid), DVAR(cpusetsize), DVARhex(mask)); if (mask) { //CPU_ZERO(mask); memset(mask, 0, cpusetsize); for(int i = 0; i < info_ptr->getNumThreads(); i++) CPU_SET(i, mask); } return info_ptr->getNumThreads(); } void clock_gettime(long clk, struct timespec *ts){ unsigned low,high; asm volatile("rdtsc" : "=a" (low), "=d" (high)); unsigned long tsc = low | uint64_t(high) << 32; //MLOG_DETAIL(mlog::app, "syscall clock_gettime", DVAR(clk), DVARhex(ts), DVAR(tsc), DVAR((tsc * PS_PER_TSC)/1000000000000)); ts->tv_nsec = (tsc * info_ptr->getPsPerTSC() / 1000)%1000000000; ts->tv_sec = (tsc * info_ptr->getPsPerTSC())/1000000000000; } extern "C" long mythos_musl_syscall( long num, long a1, long a2, long a3, long a4, long a5, long a6) { //MLOG_DETAIL(mlog::app, "mythos_musl_syscall", DVAR(num), //DVAR(a1), DVAR(a2), DVAR(a3), //DVAR(a4), DVAR(a5), DVAR(a6)); // see http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/ switch (num) { case 9: //mmap MLOG_WARN(mlog::app, "syscall mmap NYI please use stub"); return 0; case 10: //mprotect MLOG_WARN(mlog::app, "syscall mprotect NYI"); return 0; case 11: //munmap MLOG_WARN(mlog::app, "syscall munmap NYI please use stub!"); return 0; case 12: //brk //MLOG_WARN(mlog::app, "syscall brk NYI"); return -1; case 13: // rt_sigaction //MLOG_WARN(mlog::app, "syscall rt_sigaction NYI"); return 0; case 14: // rt_sigprocmask(how, set, oldset, sigsetsize) //MLOG_WARN(mlog::app, "syscall rt_sigprocmask NYI"); return 0; case 16: // ioctl //MLOG_WARN(mlog::app, "syscall ioctl NYI"); return 0; case 20: // writev(fd, *iov, iovcnt) //MLOG_ERROR(mlog::app, "syscall writev NYI"); return writev(a1, reinterpret_cast<const struct iovec *>(a2), a3); case 24: // sched_yield //MLOG_ERROR(mlog::app, "syscall sched_yield NYI"); return 0; case 28: //madvise MLOG_WARN(mlog::app, "syscall madvise NYI"); return 0; case 39: // getpid MLOG_WARN(mlog::app, "syscall getpid NYI"); return 0; case 60: // exit(exit_code) //MLOG_ERROR(mlog::app, "syscall exit", DVAR(a1)); pthreadCleaner.exit(); asm volatile ("syscall" : : "D"(0), "S"(a1) : "memory"); return 0; case 186: // gettid return mythos_get_pthread_tid(pthread_self()); case 200: // tkill(pid, sig) MLOG_WARN(mlog::app, "syscall tkill NYI"); return 0; case 202: // sys_futex //MLOG_DETAIL(mlog::app, "syscall futex"); { //MLOG_ERROR(mlog::app, "Error: syscall futex", DVAR(num), //DVAR(a1), DVAR(a2), DVAR(a3), //DVAR(a4), DVAR(a5), DVAR(a6)); uint32_t val2 = 0; return do_futex(reinterpret_cast<uint32_t*>(a1) /*uaddr*/, a2 /*op*/, a3 /*val*/, reinterpret_cast<uint32_t*>(a4)/* timeout*/, reinterpret_cast<uint32_t*>(a5) /*uaddr2*/, a4/*val2*/, a6/*val3*/); } case 203: // sched_setaffinity return sched_setaffinity(a1, a2, reinterpret_cast<cpu_set_t*>(a3)); case 204: // sched_getaffinity return sched_getaffinity(a1, a2, reinterpret_cast<cpu_set_t*>(a3)); case 228: // clock_gettime //MLOG_ERROR(mlog::app, "Error: mythos_musl_syscall clock_gettime", DVAR(num), //DVARhex(a1), DVARhex(a2), DVARhex(a3), //DVARhex(a4), DVARhex(a5), DVARhex(a6)); clock_gettime(a1, reinterpret_cast<struct timespec *>(a2)); return 0; case 231: // exit_group for all pthreads MLOG_WARN(mlog::app, "syscall exit_group NYI"); mythosExit(); return 0; case 302: // prlimit64 //MLOG_WARN(mlog::app, "syscall prlimit64 NYI", DVAR(a1), DVAR(a2), DVAR(a3), DVAR(a4), DVAR(a5), DVAR(a6)); return 1; default: MLOG_ERROR(mlog::app, "Error: mythos_musl_syscall NYI", DVAR(num), DVAR(a1), DVAR(a2), DVAR(a3), DVAR(a4), DVAR(a5), DVAR(a6)); } return -1; } extern "C" void * mmap(void *start, size_t len, int prot, int flags, int fd, off_t off) { // dummy implementation //MLOG_DETAIL(mlog::app, "mmap", DVAR(start), DVAR(len), DVAR(prot), DVAR(prot), DVAR(flags), DVAR(fd), DVAR(off)); auto tmp = mythos::heap.alloc(len, mythos::align4K); if (!tmp){ errno = ENOMEM; return MAP_FAILED; } if (flags & MAP_ANONYMOUS) { memset(reinterpret_cast<void*>(*tmp), 0, len); } return reinterpret_cast<void*>(*tmp); } extern "C" int munmap(void *start, size_t len) { // dummy implementation //MLOG_DETAIL(mlog::app, "munmap", DVAR(start), DVAR(len)); mythos::heap.free(reinterpret_cast<unsigned long>(start)); return 0; } extern "C" int unmapself(void *start, size_t len) { PANIC_MSG(false, "unmapself: NYI!"); return 0; } extern "C" int mprotect(void *addr, size_t len, int prot) { // dummy implementation //MLOG_DETAIL(mlog::app, "mprotect"); //size_t start, end; //start = (size_t)addr & -PAGE_SIZE; //end = (size_t)((char *)addr + len + PAGE_SIZE-1) & -PAGE_SIZE; return 0; } int myclone( int (*func)(void *), void *stack, int flags, void *arg, int* ptid, void* tls, int* ctid) { //MLOG_DETAIL(mlog::app, "myclone"); ASSERT(tls != nullptr); // The compiler expect a kinda strange alignment coming from clone: // -> rsp % 16 must be 8 // You can see this also in musl/src/thread/x86_64/clone.s (rsi is stack) // We will use the same trick for alignment as musl libc auto rsp = (uintptr_t(stack) & uintptr_t(-16))-8; mythos::PortalLock pl(portal); // future access will fail if the portal is in use already mythos::ExecutionContext ec(capAlloc()); if (ptid && (flags&CLONE_PARENT_SETTID)) *ptid = int(ec.cap()); // @todo store thread-specific ctid pointer, which should set to 0 by the OS on the thread's exit auto sc = pa.alloc(pl).wait(); ASSERT(sc); if(sc->cap == mythos::null_cap){ MLOG_WARN(mlog::app, "Processor allocation failed!"); //todo: set errno = EAGAIN return (-1); } auto res1 = ec.create(kmem) .as(myAS) .cs(myCS) .sched(sc->cap) .rawStack(rsp) .rawFun(func, arg) .suspended(false) .fs(tls) .invokeVia(pl) .wait(); //MLOG_DETAIL(mlog::app, DVAR(ec.cap())); return ec.cap(); } extern "C" int clone(int (*func)(void *), void *stack, int flags, void *arg, ...) { //MLOG_DETAIL(mlog::app, "clone wrapper"); va_list args; va_start(args, arg); int* ptid = va_arg(args, int*); void* tls = va_arg(args, void*); int* ctid = va_arg(args, int*); va_end(args); return myclone(func, stack, flags, arg, ptid, tls, ctid); } // synchronize and cleanup exited pthread extern "C" void mythos_pthread_cleanup(pthread_t t){ MLOG_DETAIL(mlog::app, "mythos_pthread_cleanup", mythos_get_pthread_ec(t)); // wait for target pthread to exit pthreadCleaner.wait(t); // delete EC of target pthread auto cap = mythos_get_pthread_ec(t); mythos::PortalLock pl(portal); capAlloc.free(cap, pl); // memory of target pthread will be free when returning from this function } struct dl_phdr_info { void* dlpi_addr; /* Base address of object */ const char* dlpi_name; /* (Null-terminated) name of object */ const void* dlpi_phdr; /* Pointer to array of ELF program headers for this object */ uint16_t dlpi_phnum; /* # of items in dlpi_phdr */ }; extern char __executable_start; //< provided by the default linker script /** walk through list of shared objects. * http://man7.org/linux/man-pages/man3/dl_iterate_phdr.3.html * https://github.com/ensc/dietlibc/blob/master/libcruft/dl_iterate_phdr.c * * WARNING: use --eh-frame-hdr linker flag to ensure the presence of the EH_FRAME segment! */ extern "C" int dl_iterate_phdr( int (*callback) (dl_phdr_info *info, size_t size, void *data), void *data) { MLOG_ERROR(mlog::app, "dl_iterate_phdr", DVAR((void*)callback), DVAR(&__executable_start)); mythos::elf64::Elf64Image img(&__executable_start); ASSERT(img.isValid()); // HACK this assumes llvm libunwind // the targetAddr contains the instruction pointer where the exception was thrown struct dl_iterate_cb_data { void *addressSpace; void *sects; void *targetAddr; }; auto cbdata = static_cast<dl_iterate_cb_data *>(data); MLOG_ERROR(mlog::app, "dl_iterate_phdr", DVAR(cbdata->addressSpace), DVAR(cbdata->sects), DVAR(cbdata->targetAddr)); dl_phdr_info info; info.dlpi_addr = 0; // callback ignores this header if its target addr is smaller than this. info.dlpi_name = "init.elf"; info.dlpi_phdr = (const void*)img.phdr(0); info.dlpi_phnum = img.phnum(); auto res = (*callback) (&info, sizeof(info), data); return res; }
34.595642
133
0.650756
ManyThreads
8317d2c3a6ced5173b14c4ac268fc250a5faeb3f
13,431
cpp
C++
libot/http/httprequest.cpp
goossens/ObjectTalk
ca1d4f558b5ad2459b376102744d52c6283ec108
[ "MIT" ]
6
2021-11-12T15:03:53.000Z
2022-01-28T18:30:33.000Z
libot/http/httprequest.cpp
goossens/ObjectTalk
ca1d4f558b5ad2459b376102744d52c6283ec108
[ "MIT" ]
null
null
null
libot/http/httprequest.cpp
goossens/ObjectTalk
ca1d4f558b5ad2459b376102744d52c6283ec108
[ "MIT" ]
null
null
null
// ObjectTalk Scripting Language // Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved. // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. // // Include files // #include <filesystem> #include "ot/exception.h" #include "ot/httprequest.h" #include "ot/libuv.h" #include "ot/function.h" #include "ot/dict.h" // // OtHttpRequestClass::OtHttpRequestClass // OtHttpRequestClass::OtHttpRequestClass() { // initialize multipart parser callbacks multipartparser_callbacks_init(&multipartCallbacks); multipartCallbacks.on_part_begin = [](multipartparser* parser) -> int { ((OtHttpRequestClass*)(parser->data))->onMultipartBegin(); return 0; }; multipartCallbacks.on_header_field = [](multipartparser* parser, const char *at, size_t length) -> int { ((OtHttpRequestClass*)(parser->data))->onMultipartHeaderField(at, length); return 0; }; multipartCallbacks.on_header_value = [](multipartparser* parser, const char *at, size_t length) -> int { ((OtHttpRequestClass*)(parser->data))->onMultipartHeaderValue(at, length); return 0; }; multipartCallbacks.on_headers_complete = [](multipartparser* parser) -> int { ((OtHttpRequestClass*)(parser->data))->onMultipartHeadersComplete(); return 0; }; multipartCallbacks.on_data = [](multipartparser* parser, const char *at, size_t length) -> int { ((OtHttpRequestClass*)(parser->data))->onMultipartData(at, length); return 0; }; multipartCallbacks.on_part_end = [](multipartparser* parser) -> int { ((OtHttpRequestClass*)(parser->data))->onMultipartEnd(); return 0; }; } // // OtHttpRequestClass::clear // void OtHttpRequestClass::clear() { method.clear(); url.clear(); path.clear(); version.clear(); headerState = WAITING_FOR_NAME; headerName.clear(); headerValue.clear(); headers.clear(); params.clear(); cookies.clear(); body.clear(); multipartBoundary.clear(); } // // OtHttpRequestClass::onURL // void OtHttpRequestClass::onURL(const char *data, size_t length) { url.append(data, length); } // // OtHttpRequestClass::onHeaderField // void OtHttpRequestClass::onHeaderField(const char *data, size_t length) { // push header if complete if (headerState == WAITING_FOR_VALUE) { setHeader(headerName, headerValue); headerState = WAITING_FOR_NAME; headerName.clear(); headerValue.clear(); } // collect header name headerName.append(data, length); } // // OtHttpRequestClass::onHeaderValue // void OtHttpRequestClass::onHeaderValue(const char *data, size_t length) { // collect header value headerValue.append(data, length); headerState = WAITING_FOR_VALUE; } // // OtHttpRequestClass::onHeadersComplete // void OtHttpRequestClass::onHeadersComplete(const std::string m, const std::string v) { // save method and version method = m; version = v; // save last header if required if (headerState == WAITING_FOR_VALUE) { setHeader(headerName, headerValue); } // parse URL and extract path and query parameter size_t query = url.find('?'); if (query == std::string::npos) { path = OtText::decodeURL(url); } else { path = OtText::decodeURL(url.substr(0, query)); parseParams(url.substr(query + 1, std::string::npos)); } // handle multipart form data if (OtText::contains(getHeader("Content-Type"), "multipart/form-data")) { auto type = getHeader("Content-Type"); auto pos = type.find("boundary="); // find boundary string if (pos != std::string::npos) { multipartBoundary = type.substr(pos + 9); if (multipartBoundary.length() >= 2 && multipartBoundary.front() == '"' && multipartBoundary.back() == '"') { multipartBoundary = multipartBoundary.substr(1, multipartBoundary.size() - 2); } // initialize multipart parser multipartparser_init(&multipartParser, multipartBoundary.c_str()); multipartParser.data = this; } } } // // OtHttpRequestClass::onBody // void OtHttpRequestClass::onBody(const char *data, size_t length) { // handle multipart if required if (multipartBoundary.size()) { auto parsed = multipartparser_execute(&multipartParser, &multipartCallbacks, data, length); if (parsed != length) { OtExcept("Invalid multipart"); } } else { body.append(data, length); } } // // OtHttpRequestClass::onMultipartBegin // void OtHttpRequestClass::onMultipartBegin() { // reset multipart header fields multipartHeaders.clear(); multipartFieldName.clear(); multipartFileName.clear(); multipartFile.clear(); multipartValue.clear(); headerState = WAITING_FOR_NAME; headerName.clear(); headerValue.clear(); } // // OtHttpRequestClass::onMultipartHeaderField // void OtHttpRequestClass::onMultipartHeaderField(const char *data, size_t length) { // push multipart header if complete if (headerState == WAITING_FOR_VALUE) { multipartHeaders.emplace(headerName, headerValue); headerState = WAITING_FOR_NAME; headerName.clear(); headerValue.clear(); } // collect multipart header name headerName.append(data, length); } // // OtHttpRequestClass::onMultipartHeaderValue // void OtHttpRequestClass::onMultipartHeaderValue(const char *data, size_t length) { // collect multipart header value headerValue.append(data, length); headerState = WAITING_FOR_VALUE; } // // OtHttpRequestClass::onMultipartHeaderValue // void OtHttpRequestClass::onMultipartHeadersComplete() { // handle last multipart header (if required) if (headerState == WAITING_FOR_VALUE) { multipartHeaders.emplace(headerName, headerValue); } // parse "Content-Disposition" header if (multipartHeaders.has("Content-Disposition")) { auto d = multipartHeaders.get("Content-Disposition"); OtText::splitTrimIterator(d.data(), d.data() + d.size(), ';', [&](const char *b, const char *e) { auto part = std::string(b, e - b); if (part.find("=") != std::string::npos) { std::string key; std::string val; OtText::splitTrimIterator(b, e, '=', [&](const char *b2, const char *e2) { if (key.empty()) { key.assign(b2, e2); } else { if (*b2 == '"' && b2 < e2) { b2++; } if (*(e2 - 1) == '"' && e2 > b2) { e2--; } val.assign(b2, e2); } }); if (key == "name") { multipartFieldName = val; } else if (key == "filename") { // get client file name multipartFileName = val; // create temporary file std::filesystem::path tmpl = std::filesystem::temp_directory_path() / "ot-XXXXXX"; uv_fs_t req; uv_fs_mkstemp(uv_default_loop(), &req, (const char*) tmpl.c_str(), 0); multipartFile = req.path; multipartFD = req.result; uv_fs_req_cleanup(&req); } } }); } else { OtExcept("Content-Disposition missing in multipart"); } } // // OtHttpRequestClass::onMultipartData // void OtHttpRequestClass::onMultipartData(const char *data, size_t length) { // handle file uploads if (multipartFileName.size()) { uv_fs_t req; uv_buf_t buffer = uv_buf_init((char*) data, length); uv_fs_write(0, &req, multipartFD, &buffer, 1, -1, 0); UV_CHECK_ERROR("uv_fs_write", req.result); uv_fs_req_cleanup(&req); } else { // handle field values multipartValue.append(data, length); } } // // OtHttpRequestClass::onMultipartEnd // void OtHttpRequestClass::onMultipartEnd() { // handle file uploads if (multipartFileName.size()) { uv_fs_t req; uv_fs_close(0, &req, multipartFD, 0); setParam(multipartFieldName, multipartFileName + "|" + multipartFile); } else { // handle field values setParam(multipartFieldName, multipartValue); } } // // OtHttpRequestClass::onMessageComplete // void OtHttpRequestClass::onMessageComplete() { // handle form parameters if (headerIs("Content-Type", "application/x-www-form-urlencoded")) { parseParams(body); } } // // OtHttpRequestClass::setHeader // void OtHttpRequestClass::setHeader(const std::string& name, const std::string& value) { headers.emplace(name, value); if (OtText::caseEqual(name, "cookie")) { OtText::splitIterator(value.data(), value.data() + value.size(), ';', [&](const char *b, const char *e) { std::string key; std::string val; OtText::splitIterator(b, e, '=', [&](const char *b2, const char *e2) { if (key.empty()) { key.assign(b2, e2); } else { val.assign(b2, e2); } }); setCookie(OtText::decodeURL(OtText::trim(key)), OtText::decodeURL(OtText::trim(val))); }); } } // // OtHttpRequestClass::hasHeader // const bool OtHttpRequestClass::hasHeader(const std::string& header) { return headers.find(header) != headers.end(); } // // OtHttpRequestClass::headerIs // const bool OtHttpRequestClass::headerIs(const std::string& header, const std::string& value) { return getHeader(header) == value; } // // std::string OtHttpRequestClass::getHeader // const std::string OtHttpRequestClass::getHeader(const std::string& header) { return headers.get(header); } // // OtHttpRequestClass::getHeaders // const OtObject OtHttpRequestClass::getHeaders() { OtDict dict = OtDictClass::create(); for (auto i = headers.begin(); i != headers.end(); i++) { if (dict->contains(i->first)) { std::string value = dict->getEntry(i->first)->operator std::string(); value += "; " + i->second; dict->setEntry(i->first, OtStringClass::create(value)); } else { dict->setEntry(i->first, OtStringClass::create(i->second)); } } return dict; } // // OtHttpRequestClass::parseParams( // void OtHttpRequestClass::parseParams(const std::string& text) { OtText::splitIterator(text.data(), text.data() + text.size(), '&', [&](const char *b, const char *e) { std::string key; std::string value; OtText::splitIterator(b, e, '=', [&](const char *b2, const char *e2) { if (key.empty()) { key.assign(b2, e2); } else { value.assign(b2, e2); } }); setParam(OtText::decodeURL(key), OtText::decodeURL(value)); }); } // // OtHttpRequestClass::setParam // void OtHttpRequestClass::setParam(const std::string& name, const std::string& value) { params[name] = value; } // // OtHttpRequestClass::hasParam // const bool OtHttpRequestClass::hasParam(const std::string& param) { return params.find(param) != params.end(); } // // OtHttpRequestClass::getParam // const std::string& OtHttpRequestClass::getParam(const std::string& param) { return params[param]; } // // OtHttpRequestClass::setCookie // void OtHttpRequestClass::setCookie(const std::string& name, const std::string& value) { cookies[name] = value; } // // tHttpRequestClass::hasCookie // const bool OtHttpRequestClass::hasCookie(const std::string& cookie) { return cookies.find(cookie) != params.end(); } // // OtHttpRequestClass::getCookie // const std::string& OtHttpRequestClass::getCookie(const std::string& cookie) { return cookies[cookie]; } // // OtHttpRequestClass::getBody // const std::string& OtHttpRequestClass::getBody() { return body; } // // OtHttpRequestClass::debug // const std::string OtHttpRequestClass::debug() { std::stringstream stream; stream << "Method: " << method << std::endl; stream << "URL: " << url << std::endl; stream << "Path: " << path << std::endl; stream << "Version: " << version << std::endl; stream << std::endl << "Headers: " << std::endl << "--------" << std::endl; for (auto i = headers.begin(); i != headers.end(); i++) { stream << i->first << "=" << i->second << std::endl; } stream << std::endl << "Query Parameters: " << std::endl << "-----------------" << std::endl; for (auto i = params.begin(); i != params.end(); i++) { stream << i->first << "=" << i->second << std::endl; } stream << std::endl << "Cookies: " << std::endl << "--------" << std::endl; for (auto i = cookies.begin(); i != cookies.end(); i++) { stream << i->first << "=" << i->second << std::endl; } return stream.str(); } // // OtHttpRequestClass::getMeta // OtType OtHttpRequestClass::getMeta() { static OtType type = nullptr; if (!type) { type = OtTypeClass::create<OtHttpRequestClass>("HttpRequest", OtHttpClass::getMeta()); type->set("getMethod", OtFunctionClass::create(&OtHttpRequestClass::getMethod)); type->set("getURL", OtFunctionClass::create(&OtHttpRequestClass::getURL)); type->set("getPath", OtFunctionClass::create(&OtHttpRequestClass::getPath)); type->set("getVersion", OtFunctionClass::create(&OtHttpRequestClass::getVersion)); type->set("hasHeader", OtFunctionClass::create(&OtHttpRequestClass::hasHeader)); type->set("headerIs", OtFunctionClass::create(&OtHttpRequestClass::hasHeader)); type->set("getHeader", OtFunctionClass::create(&OtHttpRequestClass::getHeader)); type->set("getHeaders", OtFunctionClass::create(&OtHttpRequestClass::getHeaders)); type->set("hasParam", OtFunctionClass::create(&OtHttpRequestClass::hasParam)); type->set("getParam", OtFunctionClass::create(&OtHttpRequestClass::getParam)); type->set("hasCookie", OtFunctionClass::create(&OtHttpRequestClass::hasCookie)); type->set("getCookie", OtFunctionClass::create(&OtHttpRequestClass::getCookie)); type->set("getBody", OtFunctionClass::create(&OtHttpRequestClass::getBody)); type->set("debug", OtFunctionClass::create(&OtHttpRequestClass::debug)); } return type; } // // OtHttpRequestClass::create() // OtHttpRequest OtHttpRequestClass::create() { OtHttpRequest request = std::make_shared<OtHttpRequestClass>(); request->setType(getMeta()); return request; }
22.803056
107
0.680515
goossens
832535cba00d0f1176f861070e58b4b58c4bb575
1,970
cpp
C++
code/Die.cpp
joshuaherrera/CLI-team-fighting-game
a0393ab3e9bf6aec1a7f85863ba18f092a849d43
[ "MIT" ]
null
null
null
code/Die.cpp
joshuaherrera/CLI-team-fighting-game
a0393ab3e9bf6aec1a7f85863ba18f092a849d43
[ "MIT" ]
null
null
null
code/Die.cpp
joshuaherrera/CLI-team-fighting-game
a0393ab3e9bf6aec1a7f85863ba18f092a849d43
[ "MIT" ]
null
null
null
/********************************************************************* ** Program name:Die.cpp ** Author:Joshua Herrera ** Date:04/23/2017 ** Description: The Die.cpp file contains the functions used in the Die ** class that is used to make our die for the game. *********************************************************************/ #include "Die.hpp" /************************************************************* ** Die constructor (default) ** This function neither returns nor takes any arguments. ** it should never be used. and is only here as a safeguard. *************************************************************/ Die::Die() { //should never use this case numSides = -1; } /************************************************************* ** Die constructor ** This function takes in an integer as its argument and does ** not return anything. It uses the function setNumSides to set ** the number of sides for the die. *************************************************************/ Die::Die(int diceSides) { setNumSides(diceSides); } /************************************************************* ** roll ** This function takes no arguments and returns an integer, ** specifically, it returns a random number between 1 and the ** number of sides of the die. *************************************************************/ int Die::roll() { return rand() % numSides + 1; } /************************************************************* **setNumSides ** returns nothing and takes an int which is set to the number ** of sides of the die. *************************************************************/ void Die::setNumSides(int diceSides) { numSides = diceSides; } /************************************************************* ** getNumSides ** takes no arguments and returns the number of sides of the die ** (an int) *************************************************************/ int Die::getNumSides() { return numSides; }
30.78125
71
0.428426
joshuaherrera
8327b1c09c2b89b0f2755a9b33e932a05b077f5f
5,305
cpp
C++
texturing-test/main.cpp
Phyllostachys/graphics-demos
bf1f1f10c95e0c9f752117ad23295ce06acdb17c
[ "MIT" ]
1
2015-09-05T11:15:07.000Z
2015-09-05T11:15:07.000Z
texturing-test/main.cpp
Phyllostachys/graphics-demos
bf1f1f10c95e0c9f752117ad23295ce06acdb17c
[ "MIT" ]
null
null
null
texturing-test/main.cpp
Phyllostachys/graphics-demos
bf1f1f10c95e0c9f752117ad23295ce06acdb17c
[ "MIT" ]
null
null
null
#include <cstdint> #include <ctime> #include <iostream> #include <random> #include <glad/glad.h> #include <GLFW/glfw3.h> #include "lodepng.h" #include "shader.h" void resize_callback(GLFWwindow *window, int width, int height); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); int main(int argc, char** argv) { // Setup GLFW if (!glfwInit()) { std::cout << "Failed to init GLFW.\n"; return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow* window = glfwCreateWindow(256, 256, "Texture Test", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSetWindowSizeCallback(window, resize_callback); glfwSetKeyCallback(window, key_callback); // Load in OGL functions if (!gladLoadGL()) { std::cout << "Failed to initialize OpenGL context\n"; return -1; } // shader Shader s("assets/vert.glsl", "assets/frag.glsl"); if(!s.compile()) { std::cout << "Some error happened while creating shaders\n"; return -1; } float vertices[] = { /* position */ /* texcoords */ -0.75, -0.75, 0.0, 0.0, 0.0, 0.75, -0.75, 0.0, 1.0, 0.0, 0.75, 0.75, 0.0, 1.0, 1.0, -0.75, 0.75, 0.0, 0.0, 1.0, }; GLuint vertex_indices[] = { 0, 1, 2, 2, 3, 0, }; GLuint VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); // load in vertex data GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // TexCoord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertex_indices), vertex_indices, GL_STATIC_DRAW); glBindVertexArray(0); // Unbind VAO // load in texture data GLuint texture; glGenTextures(1, &texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); // Set our texture parameters //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); uint32_t width, height; std::vector<uint8_t> image; //* uint32_t error = lodepng::decode(image, width, height, "assets/asset.png"); if (error) { std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; } //*/ /* create random image data width = 64; height = 64; for (uint32_t y = 0; y < 4*64; y++) { for (uint32_t x = 0; x < 4*64; x++) { image.push_back(rand() % 255); } } //*/ /* spit out image data std::cout << "asset.png data:\n"; std::cout << " width = " << width << std::endl; std::cout << " height = " << height << std::endl; std::cout << std::hex << std::uppercase; for (uint32_t y = 0; y < height; y++) { for (uint32_t x = 0; x < width; x+=3) { std::cout << "0x" << (uint32_t)image[y*width + x] << (uint32_t)image[y*width + x+1] << (uint32_t)image[y*width + x+2] << " "; } std::cout << "\n"; } std::cout << std::dec; //*/ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.data()); //glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); // main loop while (!glfwWindowShouldClose(window)) { /* Render here */ glClear(GL_COLOR_BUFFER_BIT); // Bind Textures using texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glUniform1i(glGetUniformLocation(s.getShaderProgram(), "textureData"), 0); // Activate shader glUseProgram(s.getShaderProgram()); // Draw container glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glfwTerminate(); return 0; } void resize_callback(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); }
29.803371
137
0.626956
Phyllostachys
832edeb22f05b20aab77ebcc1c91f794b98963f3
4,828
cpp
C++
OmnibotGame/src/Player.cpp
neuroprod/omniBotProto
5abf1b5a9846ba093325af7a86ee2d7b8cbe12e6
[ "MIT" ]
46
2017-03-03T20:34:23.000Z
2021-11-07T02:37:44.000Z
OmnibotGame/src/Player.cpp
neuroprod/omniBotProto
5abf1b5a9846ba093325af7a86ee2d7b8cbe12e6
[ "MIT" ]
null
null
null
OmnibotGame/src/Player.cpp
neuroprod/omniBotProto
5abf1b5a9846ba093325af7a86ee2d7b8cbe12e6
[ "MIT" ]
18
2017-04-27T09:40:47.000Z
2021-12-06T05:38:48.000Z
#include "Player.h" #include "cinder/gl/gl.h" #include "GSettings.h" #include "glm\gtc\random.hpp" using namespace std; using namespace ci::app; using namespace ci; Player::Player() { size = GSettings::playerRad; } PlayerRef Player::create() { return make_shared<Player>(); } void Player::update() { if (glm::length2(controlesInput->currentSpeed) == 0) { isMoving = false; } else { isMoving = true; } vec4 currentSpeedRot = rotMatrix *vec4(controlesInput->currentSpeed.x, 0, controlesInput->currentSpeed.z, 1.f); levelPositionVirtual += vec3(currentSpeedRot.x, 0, currentSpeedRot.z); if (levelPositionVirtual.x < 0)levelPositionVirtual.x += worldSize; if (levelPositionVirtual.x > worldSize)levelPositionVirtual.x -= worldSize; if (levelPositionVirtual.z < 0)levelPositionVirtual.z += worldSize; if (levelPositionVirtual.z > worldSize)levelPositionVirtual.z -= worldSize; float centerDistanceNow = glm::length(screenPositionVirtual); float centerDistanceNew = glm::length(screenPositionVirtual + controlesInput->currentSpeed); float moveFactor = 1; if (centerDistanceNew > centerDistanceNow){ if (centerDistanceNow > 200) { moveFactor = max(0.f, 1.f - ((centerDistanceNow - 200.f) / 50.f)); } } screenPositionVirtual += controlesInput->currentSpeed*moveFactor; } void Player::setScreenPosition(vec3 pos) { screenPositionVirtual = pos; screenPosition = pos; screenPosition.x += 0; screenPosition.y +=0; } void Player::setLevelPosition(vec3 pos) { levelPositionVirtual = pos; levelPosition.x = pos.x; levelPosition.y = pos.z; } void Player::resolveScreenMatrix(PlayerRef other) { //if (!isMoving)return; posOther = getClosestLevelPosition(levelPositionVirtual, other->levelPositionVirtual); float screenDistance = glm::distance(screenPositionVirtual, other->screenPositionVirtual); float targetAngle = 0; if (currentDistance <= screenDistance) { float angleLevel = atan2f(levelPositionVirtual.z - posOther.z, levelPositionVirtual.x - posOther.x); float angleScreen = atan2f(screenPositionVirtual.z - other->screenPositionVirtual.z, screenPositionVirtual.x - other->screenPositionVirtual.x); targetAngle = angleLevel - angleScreen; if (targetAngle < 3.1415)targetAngle += 3.1415 * 2; if (targetAngle > 3.1415)targetAngle -= 3.1415 * 2; //console() << targetAngle << " " << id << endl; //TODO: get closest angle //console() << "FOUND HIM" << endl; } angle += ( targetAngle-angle) / 20; glm::mat4 centerMatrix = glm::mat4(); centerMatrix = translate(centerMatrix, vec3(GSettings::windowHeight / 2, GSettings::windowHeight / 2, 0)); screenMatrix = glm::mat4(); // screenMatrix = translate(screenMatrix, vec3(+screenPositionVirtual.x, +screenPositionVirtual.z, 0)); screenMatrix = glm::rotate(screenMatrix, -angle, vec3(0, 0, 1)); screenMatrix = translate(screenMatrix, vec3(-screenPositionVirtual.x, -screenPositionVirtual.z, 0)); screenMatrix = translate(screenMatrix, vec3(-levelPositionVirtual.x + screenPositionVirtual.x, -levelPositionVirtual.z + screenPositionVirtual.z, 0)); screenMatrixInv = glm::inverse(screenMatrix); screenMatrix = centerMatrix*screenMatrix; rotMatrix = glm::mat4(); } ci::vec3 Player::getClosestLevelPosition(ci::vec3 posMe, ci::vec3 posOther) { vec3 posNear = posOther; float distMin = 10000000; for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { vec3 testPos = posOther; testPos.x += x*worldSize; testPos.z += z*worldSize; float dist =glm::distance2(posMe, testPos); if (dist < distMin) { distMin = dist; posNear = testPos; } } } currentDistance =sqrt(distMin); return posNear; } void Player::drawVirtual() { gl::drawLine(vec2(levelPositionVirtual.x, levelPositionVirtual.z), vec2(posOther.x, posOther.z)); gl::drawStrokedCircle(vec2(levelPositionVirtual.x, levelPositionVirtual.z), size); } void Player::draw() { //gl::drawColorCube(levelPosition, vec3(40, 40, 40)); gl::drawStrokedCircle(vec2(levelPosition.x, levelPosition.y), size); } void Player::setTempRealPosition() { //setScreenPosition by camera screenPosition += (screenPositionVirtual - screenPosition) / 5.f; vec4 levelPosition4 = screenMatrixInv*vec4(screenPosition.x, screenPosition.z, 0, 1.0f); levelPosition.x = levelPosition4.x; levelPosition.y = levelPosition4.y; if (levelPosition.x < 0)levelPosition.x += worldSize; if (levelPosition.x > worldSize)levelPosition.x -= worldSize; if (levelPosition.y < 0)levelPosition.y += worldSize; if (levelPosition.y > worldSize)levelPosition.y -= worldSize; int indexX = levelPosition.x / GSettings::tileSize; int indexY = levelPosition.y / GSettings::tileSize; indexX %= GSettings::numTiles; indexY %= GSettings::numTiles; currentTileIndex = indexX + indexY*GSettings::numTiles; }
26.674033
151
0.725559
neuroprod
833a554754b029de70629847deb2d20cb944de8e
1,887
cpp
C++
src/GameUpgradeScreenState.cpp
Xpost2000/Killbot
8cc287758e0c26d0350343f383f5adfe0acac0e9
[ "MIT" ]
null
null
null
src/GameUpgradeScreenState.cpp
Xpost2000/Killbot
8cc287758e0c26d0350343f383f5adfe0acac0e9
[ "MIT" ]
null
null
null
src/GameUpgradeScreenState.cpp
Xpost2000/Killbot
8cc287758e0c26d0350343f383f5adfe0acac0e9
[ "MIT" ]
null
null
null
#include "GameUpgradeScreenState.h" #include "StateMachine.h" #include "GameState.h" #include "constants.h" #include "SoundManager.h" #include "CefManager.h" GameUpgradeScreenState::GameUpgradeScreenState(InputManager* input) : _input(input){ } GameUpgradeScreenState::~GameUpgradeScreenState(){ } void GameUpgradeScreenState::init(){ } bool GameUpgradeScreenState::OnEnter(){ SoundManager::instance()->haltMusic(); SoundManager::instance()->playMusic("audio/music/upgrade_music.ogg", 100, -1); CefManager::instance()->GetCefBrowser()->GetMainFrame()->LoadURL(std::string("file://" + std::string(SDL_GetBasePath()) + "htmlui/upgrade.html")); return true; } bool GameUpgradeScreenState::OnExit(){ SoundManager::instance()->haltMusic(); return true; } void GameUpgradeScreenState::update(float dt){ if (!SoundManager::instance()->isMusicPlaying()) SoundManager::instance()->playMusic("audio/music/upgrade_music.ogg", 100, -1); if(_input->isKeyPressed(SDL_SCANCODE_ESCAPE)){ _parent->setCurrent("mainMenu"); } } bool GameUpgradeScreenState::SetupGame(int whatMode){ switch (whatMode){ case GameModeBossGauntlet: if (canFightBoss){ GameState* ptr = (GameState*)(_parent->getState("game")); ptr->_gameMode = GameModeBossGauntlet; ptr->setUpGameMode(); _parent->setCurrent("game"); return true; } break; case GameModeStandard: GameState* ptr = (GameState*)(_parent->getState("game")); ptr->_gameMode = GameModeStandard; ptr->setUpGameMode(); _parent->setCurrent("game"); return true; break; } return false; } void GameUpgradeScreenState::draw(Renderer2D* renderer){ renderer->RenderRectangle(CefManager::instance()->GetRenderHandler()->getTexture(), Point{ 0, 0 }, Point{ renderer->getWidth(), renderer->getHeight() }, UV{ 0, 0, 1, 1 }, Color{ 255, 255, 255, 255 }); }
29.952381
202
0.703763
Xpost2000
833b4425f4160bcdf1e3594c59cafbc1c0cda8e7
922
cpp
C++
stat_lib/bernulli_stat_model.cpp
ARGO-group/Argo_CUDA
7a15252906860f4a725e37b6add211f625b91869
[ "MIT" ]
null
null
null
stat_lib/bernulli_stat_model.cpp
ARGO-group/Argo_CUDA
7a15252906860f4a725e37b6add211f625b91869
[ "MIT" ]
null
null
null
stat_lib/bernulli_stat_model.cpp
ARGO-group/Argo_CUDA
7a15252906860f4a725e37b6add211f625b91869
[ "MIT" ]
1
2021-07-10T09:59:52.000Z
2021-07-10T09:59:52.000Z
#include "bernulli_stat_model.h" #include "probability.h" using namespace std; BernulliStatModel::BernulliStatModel(const std::vector<std::string> &sequences, bool complementary, bool use_binom_instead_of_chi2, double binom_correction) : StatModel(sequences, complementary, use_binom_instead_of_chi2, binom_correction) { // TODO: определиться как считать вероятность для комплементарных последовательностей. _frequencies_ratio = calc_frequencies_ratio(sequences, false); _probability_x4 = ::calc_probability_x4(_frequencies_ratio); } double BernulliStatModel::motif_probability(uint32_t hash) const { return ::motif_probability(hash, _frequencies_ratio); } double BernulliStatModel::motif_probability_x4(uint32_t hash) const { return ::motif_probability_x4(hash, _probability_x4); }
35.461538
90
0.711497
ARGO-group
833c9a22621b944420d35d1b05e337d7b50120d2
375
cpp
C++
qfb-messenger/src/q_network_reply_helper.cpp
NickCis/harbour-facebook-messenger
b2c2305fdcec27321893c3230bbd9e724773bd7d
[ "MIT" ]
1
2015-05-05T22:45:11.000Z
2015-05-05T22:45:11.000Z
qfb-messenger/src/q_network_reply_helper.cpp
NickCis/harbour-facebook-messenger
b2c2305fdcec27321893c3230bbd9e724773bd7d
[ "MIT" ]
null
null
null
qfb-messenger/src/q_network_reply_helper.cpp
NickCis/harbour-facebook-messenger
b2c2305fdcec27321893c3230bbd9e724773bd7d
[ "MIT" ]
null
null
null
#include "q_network_reply_helper.h" QNetworkReplyHelper::QNetworkReplyHelper(QNetworkReply* r) : QObject(NULL), reply(r) { } QNetworkReplyHelper::~QNetworkReplyHelper(){ this->reply->close(); this->reply->deleteLater(); } QNetworkReply* QNetworkReplyHelper::operator->(){ return this->reply; } QNetworkReply* QNetworkReplyHelper::operator&(){ return this->reply; }
17.857143
60
0.749333
NickCis
8340d59eb889ba9202c9c40d8e482cb6cd124fb6
1,031
cpp
C++
runtime/src/events/ServerScriptEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
runtime/src/events/ServerScriptEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
runtime/src/events/ServerScriptEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
#include "ServerScriptEvent.h" Go::ServerScriptEvent::ServerScriptEvent(ModuleLibrary *module) : IEvent(module) {} void Go::ServerScriptEvent::Call(const alt::CEvent *ev) { static auto call = GET_FUNC(Library, "altServerScriptEvent", bool (*)(const char *name, void *args, unsigned long long size)); if (call == nullptr) { alt::ICore::Instance().LogError("Couldn't not call ServerScriptEvent."); return; } auto event = dynamic_cast<const alt::CServerScriptEvent*>(ev); auto name = event->GetName().CStr(); const auto& args = event->GetArgs(); auto size = args.GetSize(); #ifdef _WIN32 auto constArgs = new MetaData [size]; #else MetaData constArgs[size]; #endif for (unsigned long long i = 0; i < size; ++i) { MetaData data; data.Ptr = args[i].Get(); data.Type = static_cast<unsigned char>(args[i]->GetType()); constArgs[i] = data; } call(name, constArgs, size); #ifdef _WIN32 delete[] constArgs; #endif }
25.775
91
0.632396
Timo972
83458498dc92b20e726f5434eddb46802378aec1
1,208
cpp
C++
src/emitter.cpp
ryonagana/shmup2
e873402dc82dc148340adc2562dd8eb2353f3915
[ "MIT" ]
2
2019-03-26T15:45:22.000Z
2019-03-27T13:18:03.000Z
src/emitter.cpp
ryonagana/shmup2
e873402dc82dc148340adc2562dd8eb2353f3915
[ "MIT" ]
null
null
null
src/emitter.cpp
ryonagana/shmup2
e873402dc82dc148340adc2562dd8eb2353f3915
[ "MIT" ]
1
2019-03-31T02:52:06.000Z
2019-03-31T02:52:06.000Z
#include <iostream> #include <cmath> #include "emitter.h" #include "shared.h" CParticleEmitter::CParticleEmitter(float x, float y, int amount){ this->particles = new CParticle[amount + 1]; for(int i = 0; i < amount + 1; i++){ this->particles[i].alive = false; this->particles[i].x = x; this->particles[i].y = y; this->particles[i].dir_x = 0; this->particles[i].dir_y = 0; } this->count = amount + 1; } void CParticleEmitter::Update(float angle){ for(int i = 0; i < count;i++){ this->particles[i].Update(); if(!this->particles[i].alive){ CParticle *p = FindDeadParticle(); float dx,dy; dx = std::cos(angle); dy = std::sin(angle); p->Set(p->x, p->x, dx,dy, p->life ? p->life : 70, al_map_rgb(255,0,0)); p->alive = true; } } } void CParticleEmitter::Draw(){ for(int i = 0; i < count;i++){ if(!this->particles[i].alive) return; this->particles[i].Draw(); } } CParticle *CParticleEmitter::FindDeadParticle(){ int i = 0; while(!this->particles[i].alive && i < this->count) i++; return &particles[i]; }
21.963636
83
0.540563
ryonagana
834d32549399cce659c9ff2c48eea7e303c42d72
1,633
cpp
C++
Source/Sphere.cpp
PandarinDev/Photon
def2aae59f51c53ea3e75b6daa9572026c338f72
[ "MIT" ]
null
null
null
Source/Sphere.cpp
PandarinDev/Photon
def2aae59f51c53ea3e75b6daa9572026c338f72
[ "MIT" ]
null
null
null
Source/Sphere.cpp
PandarinDev/Photon
def2aae59f51c53ea3e75b6daa9572026c338f72
[ "MIT" ]
null
null
null
#include "Sphere.h" #include <cmath> namespace photon { Sphere::Sphere(const Vec3f& position, double radius, const Material& material) : Geometry(material), position(position), radius(radius) {} std::optional<Intersection> Sphere::intersect(const Ray& ray) const { const auto to_center = ray.origin - position; // Note: a, b, c as per the variable names regularly // used in the quadratic equation. The values here // come from algebraicly simplified ray-sphere intersection // equation, as explained in "Computer Graphics from Scratch" const auto a = ray.direction.dot(ray.direction); const auto b = 2.0f * to_center.dot(ray.direction); const auto c = to_center.dot(to_center) - radius * radius; const auto discriminant = b * b - 4.0f * a * c; if (discriminant < 0.0f) { return std::nullopt; } const auto sqrt_d = std::sqrt(discriminant); const auto two_a = 2.0f * a; const auto t1 = (-b + sqrt_d) / two_a; const auto t2 = (-b - sqrt_d) / two_a; const auto t1_valid = is_valid_intersection(t1); const auto t2_valid = is_valid_intersection(t2); std::optional<double> intersection_t; if (t1_valid && t2_valid) intersection_t = t1 < t2 ? t1 : t2; if (t1_valid) intersection_t = t1; if (t2_valid) intersection_t = t2; if (!intersection_t) { return std::nullopt; } return std::make_optional<Intersection>( *intersection_t, ray.point_at(*intersection_t) - position); } }
37.113636
82
0.614207
PandarinDev
8352a556b860929f4dac4dff2ccfa0defbdfe180
1,383
cpp
C++
anspwm/test/dspmod_test.cpp
mortenjc/fpgacode
28849d243f76fad71e0df720e2afe142fcc06ef9
[ "BSD-2-Clause" ]
null
null
null
anspwm/test/dspmod_test.cpp
mortenjc/fpgacode
28849d243f76fad71e0df720e2afe142fcc06ef9
[ "BSD-2-Clause" ]
null
null
null
anspwm/test/dspmod_test.cpp
mortenjc/fpgacode
28849d243f76fad71e0df720e2afe142fcc06ef9
[ "BSD-2-Clause" ]
null
null
null
// Copyright (C) 2021 Morten Jagd Christensen, see LICENSE file //===----------------------------------------------------------------------===// /// /// \file /// \brief test harness for dspmod //===----------------------------------------------------------------------===// #include <dspmod.h> #include <verilated.h> #include <gtest/gtest.h> #include <string> #include <vector> class DSPModTest: public ::testing::Test { protected: dspmod * dsp; void clock_ticks(int N) { for (int i = 1; i <= N; i++) { dsp->clk = 1; dsp->eval(); dsp->clk = 0; dsp->eval(); } } void reset() { dsp->target = 0; dsp->rst_n = 0; dsp->clk = 1; dsp->eval(); dsp->rst_n = 1; dsp->clk = 0; dsp->eval(); } void SetUp( ) { dsp = new dspmod; reset(); } void TearDown( ) { dsp->final(); delete dsp; } }; TEST_F(DSPModTest, Basic) { dsp->target = 1234554321; dsp->eval(); clock_ticks(1); ASSERT_EQ(dsp->value, 0); clock_ticks(1); ASSERT_EQ(dsp->value, 0); clock_ticks(1); ASSERT_EQ(dsp->value, 18837); clock_ticks(1); printf("%d\n", dsp->value); clock_ticks(1); printf("%d\n", dsp->value); clock_ticks(1); printf("%d\n", dsp->value); } int main(int argc, char **argv) { Verilated::commandArgs(argc, argv); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
17.961039
80
0.509038
mortenjc
835719e800b0cfbd9460bcdc2bb6e437e81e829a
13,139
cpp
C++
tests/parser_tests.cpp
Spaghetti-Software/cxx_plugins
e679ef19079d4b9e3fcf26d1422f690b1cf1ebcb
[ "MIT" ]
null
null
null
tests/parser_tests.cpp
Spaghetti-Software/cxx_plugins
e679ef19079d4b9e3fcf26d1422f690b1cf1ebcb
[ "MIT" ]
null
null
null
tests/parser_tests.cpp
Spaghetti-Software/cxx_plugins
e679ef19079d4b9e3fcf26d1422f690b1cf1ebcb
[ "MIT" ]
null
null
null
///************************************************************************************************* // * Copyright (C) 2020 by Andrey Ponomarev and Timur Kazhimuratov // * This file is part of CXX Plugins project. // * License is available at // * https://github.com/Spaghetti-Software/cxx_plugins/blob/master/LICENSE // *************************************************************************************************/ ///*! // * \file parser_tests.cpp // * \author Andrey Ponomarev // * \date 02 Jul 2020 // * \brief // * $BRIEF$ // */ //#include <cxx_plugins/parser.hpp> //#include <gtest/gtest.h> // //TEST(ParserTests, NumberTests) { // using namespace CxxPlugins; // const char *json_u = "4"; // const char *json_i = "-4"; // const char *json_f = "4.5"; // // rapidjson::Document doc_u_non_const; // doc_u_non_const.Parse(json_u); // rapidjson::Document const &doc_u = doc_u_non_const; // // rapidjson::Document doc_i_non_const; // doc_i_non_const.Parse(json_i); // rapidjson::Document const &doc_i = doc_i_non_const; // // rapidjson::Document doc_f_non_const; // doc_f_non_const.Parse(json_f); // rapidjson::Document const &doc_f = doc_f_non_const; // // unsigned uvar = 0; // parse(doc_u, uvar); // EXPECT_EQ(uvar, 4); // EXPECT_THROW({ parse(doc_i, uvar); }, TypeMismatch); // EXPECT_THROW({ parse(doc_f, uvar); }, TypeMismatch); // // int ivar = 0; // parse(doc_u, ivar); // EXPECT_EQ(ivar, 4); // parse(doc_i, ivar); // EXPECT_EQ(ivar, -4); // EXPECT_THROW({ parse(doc_f, ivar); }, TypeMismatch); // // std::uint64_t u64var = 0; // parse(doc_u, u64var); // EXPECT_EQ(u64var, 4); // EXPECT_THROW({ parse(doc_i, u64var); }, TypeMismatch); // EXPECT_THROW({ parse(doc_f, u64var); }, TypeMismatch); // // std::int64_t i64var = 0; // parse(doc_u, i64var); // EXPECT_EQ(i64var, 4); // parse(doc_i, i64var); // EXPECT_EQ(i64var, -4); // EXPECT_THROW({ parse(doc_f, u64var); }, TypeMismatch); // // float f = 0; // parse(doc_u, f); // EXPECT_EQ(f, 4); // parse(doc_i, f); // EXPECT_EQ(f, -4); // parse(doc_f, f); // EXPECT_EQ(f, 4.5); // // double d = 0; // parse(doc_u, d); // EXPECT_EQ(d, 4); // parse(doc_i, d); // EXPECT_EQ(d, -4); // parse(doc_f, d); // EXPECT_EQ(d, 4.5); //} // //TEST(ParserTests, OptionalNumbers) { // using namespace CxxPlugins; // const char *json_u = "4"; // const char *json_i = "-4"; // const char *json_f = "4.5"; // const char *json_null = "null"; // // rapidjson::Document doc_u_non_const; // doc_u_non_const.Parse(json_u); // rapidjson::Document const &doc_u = doc_u_non_const; // // rapidjson::Document doc_i_non_const; // doc_i_non_const.Parse(json_i); // rapidjson::Document const &doc_i = doc_i_non_const; // // rapidjson::Document doc_f_non_const; // doc_f_non_const.Parse(json_f); // rapidjson::Document const &doc_f = doc_f_non_const; // // rapidjson::Document doc_null_non_const; // doc_null_non_const.Parse(json_null); // rapidjson::Document const &doc_null = doc_null_non_const; // // std::optional<unsigned> uvar = 0; // parse(doc_null, uvar); // EXPECT_EQ(uvar, std::nullopt); // parse(doc_u, uvar); // EXPECT_EQ(uvar, 4); // EXPECT_THROW({ parse(doc_i, uvar); }, TypeMismatch); // EXPECT_THROW({ parse(doc_f, uvar); }, TypeMismatch); // // std::optional<int> ivar = 0; // parse(doc_null, ivar); // EXPECT_EQ(ivar, std::nullopt); // parse(doc_u, ivar); // EXPECT_EQ(ivar, 4); // parse(doc_i, ivar); // EXPECT_EQ(ivar, -4); // EXPECT_THROW({ parse(doc_f, ivar); }, TypeMismatch); // // std::optional<std::uint64_t> u64var = 0; // parse(doc_null, u64var); // EXPECT_EQ(u64var, std::nullopt); // parse(doc_u, u64var); // EXPECT_EQ(u64var, 4); // EXPECT_THROW({ parse(doc_i, u64var); }, TypeMismatch); // EXPECT_THROW({ parse(doc_f, u64var); }, TypeMismatch); // // std::optional<std::int64_t> i64var = 0; // parse(doc_null, i64var); // EXPECT_EQ(i64var, std::nullopt); // parse(doc_u, i64var); // EXPECT_EQ(i64var, 4); // parse(doc_i, i64var); // EXPECT_EQ(i64var, -4); // EXPECT_THROW({ parse(doc_f, u64var); }, TypeMismatch); // // std::optional<float> f = 0; // parse(doc_null, f); // EXPECT_EQ(f, std::nullopt); // parse(doc_u, f); // EXPECT_EQ(f, 4); // parse(doc_i, f); // EXPECT_EQ(f, -4); // parse(doc_f, f); // EXPECT_EQ(f, 4.5); // // std::optional<double> d = 0; // parse(doc_null, d); // EXPECT_EQ(d, std::nullopt); // parse(doc_u, d); // EXPECT_EQ(d, 4); // parse(doc_i, d); // EXPECT_EQ(d, -4); // parse(doc_f, d); // EXPECT_EQ(d, 4.5); //} // //TEST(ParserTests, String) { // using namespace CxxPlugins; // const char *json_str = "\"string\""; // const char *json_null = "null"; // // rapidjson::Document doc_non_const; // doc_non_const.Parse(json_str); // rapidjson::Document const &doc = doc_non_const; // // rapidjson::Document doc_null_non_const; // doc_null_non_const.Parse(json_null); // rapidjson::Document const &doc_null = doc_null_non_const; // // std::string str; // parse(doc, str); // EXPECT_EQ(str, "string"); // // EXPECT_THROW({ parse(doc_null, str); }, TypeMismatch); //} // //TEST(ParserTests, OptionalString) { // using namespace CxxPlugins; // const char *json_str = "\"string\""; // const char *json_null = "null"; // // rapidjson::Document doc_non_const; // doc_non_const.Parse(json_str); // rapidjson::Document const &doc = doc_non_const; // // rapidjson::Document doc_null_non_const; // doc_null_non_const.Parse(json_null); // rapidjson::Document const &doc_null = doc_null_non_const; // // std::optional<std::string> str; // parse(doc, str); // EXPECT_EQ(str, "string"); // // parse(doc_null, str); // EXPECT_EQ(str, std::nullopt); //} // //TEST(ParserTests, Vector) { // using namespace CxxPlugins; // const char *json_null = "null"; // std::vector<unsigned> expected_uint = {1, 2, 3, 4, 5}; // std::vector<int> expected_int = {-1, 2, -3, 4, -5}; // std::vector<double> expected_double = {-1, 2, 0.5, 3.4, -5.6}; // const char *json_array_uint = "[ 1,2,3,4,5]"; // const char *json_array_int = "[-1,2,-3,4,-5]"; // const char *json_array_double = "[-1, 2, 0.5, 3.4, -5.6]"; // // rapidjson::Document doc_null_non_const; // doc_null_non_const.Parse(json_null); // rapidjson::Document const &doc_null = doc_null_non_const; // // rapidjson::Document doc_uint_non_const; // doc_uint_non_const.Parse(json_array_uint); // rapidjson::Document const &doc_uint = doc_uint_non_const; // // rapidjson::Document doc_int_non_const; // doc_int_non_const.Parse(json_array_int); // rapidjson::Document const &doc_int = doc_int_non_const; // // rapidjson::Document doc_double_non_const; // doc_double_non_const.Parse(json_array_double); // rapidjson::Document const &doc_double = doc_double_non_const; // // std::vector<unsigned> uvec; // EXPECT_THROW({ parse(doc_null, uvec); }, TypeMismatch); // std::optional<std::vector<unsigned>> uvec_opt; // parse(doc_null, uvec_opt); // EXPECT_EQ(uvec_opt, std::nullopt); // parse(doc_uint, uvec_opt); // EXPECT_EQ(uvec_opt, expected_uint); // EXPECT_THROW({ parse(doc_int, uvec_opt); }, // TypeMismatch); // EXPECT_THROW({ parse(doc_double, uvec_opt); }, // TypeMismatch); // // std::vector<int> ivec; // EXPECT_THROW({ parse(doc_null, ivec); }, TypeMismatch); // std::optional<std::vector<int>> ivec_opt; // parse(doc_null, ivec_opt); // EXPECT_EQ(ivec_opt, std::nullopt); // // parse(doc_int, ivec_opt); // EXPECT_EQ(ivec_opt.value(), expected_int); // EXPECT_THROW({ parse(doc_double, ivec_opt); }, // TypeMismatch); // // std::vector<double> dvec; // EXPECT_THROW({ parse(doc_null, dvec); }, TypeMismatch); // std::optional<std::vector<double>> dvec_opt; // parse(doc_null, dvec_opt); // EXPECT_EQ(dvec_opt, std::nullopt); // // parse(doc_double, dvec_opt); // EXPECT_EQ(expected_double, dvec_opt); //} // //TEST(ParserTests, Map) { // using namespace CxxPlugins; // // std::map<std::string, int> expected = {{"foo", -4}, {"bar", 3}, {"baz", 2}}; // std::string json = "{"; // for (auto &[name, val] : expected) { // json += '\"' + name + '\"' + " : " + std::to_string(val) + ",\n"; // } // // remove last comma and \n // json.resize(json.size() - 2); // json += "\n}"; // // rapidjson::Document doc_non_const; // doc_non_const.Parse(json.c_str(), json.size()); // rapidjson::Document const &doc = doc_non_const; // // std::map<std::string, int> result; // parse(doc, result); // // EXPECT_EQ(result, expected); //} // //TEST(ParserTests, UnorderedMap) { // using namespace CxxPlugins; // // std::unordered_map<std::string, int> expected = { // {"foo", -4}, {"bar", 3}, {"baz", 2}}; // std::string json = "{"; // for (auto &[name, val] : expected) { // json += '\"' + name + '\"' + " : " + std::to_string(val) + ",\n"; // } // // remove last comma and \n // json.resize(json.size() - 2); // json += "\n}"; // // rapidjson::Document doc; // doc.Parse(json.c_str(), json.size()); // // std::unordered_map<std::string, int> result; // parse(doc, result); // // EXPECT_EQ(result, expected); //} // //TEST(ParserTests, Tuple) { // using namespace CxxPlugins; // // Tuple<int, double, std::string, std::optional<std::string>> expected = { // 4, 0.5, "string", std::nullopt}; // // const char *json = "[4,0.5,\"string\",null]"; // rapidjson::Document doc_non_const; // doc_non_const.Parse(json); // rapidjson::Document const &doc = doc_non_const; // // Tuple<int, double, std::string, std::optional<std::string>> result; // parse(doc, result); // EXPECT_EQ(expected, result); //} // //TEST(ParserTests, StdTuple) { // using namespace CxxPlugins; // // std::tuple<int, double, std::string, std::optional<std::string>> expected = { // 4, 0.5, "string", std::nullopt}; // // const char *json = "[4,0.5,\"string\",null]"; // rapidjson::Document doc_non_const; // doc_non_const.Parse(json); // rapidjson::Document const &doc = doc_non_const; // // std::tuple<int, double, std::string, std::optional<std::string>> result; // parse(doc, result); // EXPECT_EQ(expected, result); //} // //struct my_tag0 {}; //static constexpr my_tag0 my_tag0v = {}; //struct my_tag1 {}; //static constexpr my_tag1 my_tag1v = {}; //struct my_tag2 {}; //static constexpr my_tag2 my_tag2v = {}; // //TEST(ParserTests, SimpleTupleMap) { // using namespace CxxPlugins; // // TupleMap expected{TaggedValue{my_tag0v, 4}, TaggedValue{my_tag1v, 5.0}, // TaggedValue{my_tag2v, std::string{"string"}}}; // // const char *json = "{" // "\"my_tag0\" : 4," // "\"my_tag1\" : 5.0," // "\"my_tag2\" : \"string\"" // "}"; // rapidjson::Document doc_non_const; // doc_non_const.Parse(json); // rapidjson::Document const &doc = doc_non_const; // // TupleMap<TaggedValue<my_tag0, int>, TaggedValue<my_tag1, double>, // TaggedValue<my_tag2, std::string>> // result; // // parse(doc, result); // EXPECT_EQ(result, expected); //} // //TEST(ParserTests, TupleMapSizeMismatch) { // using namespace CxxPlugins; // // const char *json = "{" // "\"my_tag0\" : 4," // "\"my_tag2\" : \"string\"" // "}"; // rapidjson::Document doc_non_const; // doc_non_const.Parse(json); // rapidjson::Document const &doc = doc_non_const; // // TupleMap<TaggedValue<my_tag0, int>, TaggedValue<my_tag1, double>, // TaggedValue<my_tag2, std::string>> // result; // // EXPECT_THROW({ parse(doc, result); }, // ObjectSizeMismatch); //} // //TEST(ParserTests, TupleMapMissingMember) { // using namespace CxxPlugins; // // const char *json = "{" // "\"my_tag0\" : 4," // "\"my_tag1\" : 5.0," // "\"unknown_tag\" : null" // "}"; // rapidjson::Document doc_non_const; // doc_non_const.Parse(json); // rapidjson::Document const &doc = doc_non_const; // // TupleMap<TaggedValue<my_tag0, int>, TaggedValue<my_tag1, double>, // TaggedValue<my_tag2, std::string>> // result; // // EXPECT_THROW({ parse(doc, result); }, // ObjectMemberMissing); //} // //TEST(ParserTests, OptionalTupleMap) { // using namespace CxxPlugins; // // TupleMap<TaggedValue<my_tag0, std::optional<int>>, // TaggedValue<my_tag1, std::optional<double>>, // TaggedValue<my_tag2, std::optional<std::string>>> // expected{std::nullopt, std::nullopt, "string"}; // // const char *json = "{" // // "\"my_tag0\" : 4," // // "\"my_tag1\" : 5.0," // "\"my_tag2\" : \"string\"" // "}"; // rapidjson::Document doc_non_const; // doc_non_const.Parse(json); // rapidjson::Document const &doc = doc_non_const; // // TupleMap<TaggedValue<my_tag0, std::optional<int>>, // TaggedValue<my_tag1, std::optional<double>>, // TaggedValue<my_tag2, std::optional<std::string>>> // result; // // parse(doc, result); // EXPECT_EQ(result, expected); //}
30.915294
101
0.605449
Spaghetti-Software
836000182fc1a7876c2684b660d4a4b575e76123
10,522
cpp
C++
kdiff3/src-QT4/kdiff3_part.cpp
michaelxzhang/kdiff3
471a343af7e2ec3a5f9cd31828b290309959f508
[ "Intel" ]
3
2021-02-25T14:12:14.000Z
2021-10-29T22:44:26.000Z
kdiff3/src-QT4/kdiff3_part.cpp
michaelxzhang/kdiff3
471a343af7e2ec3a5f9cd31828b290309959f508
[ "Intel" ]
3
2020-05-16T05:28:21.000Z
2020-05-26T20:40:25.000Z
kdiff3/src-QT4/kdiff3_part.cpp
michaelxzhang/kdiff3
471a343af7e2ec3a5f9cd31828b290309959f508
[ "Intel" ]
null
null
null
/*************************************************************************** * Copyright (C) 2003-2007 Joachim Eibl <joachim.eibl at gmx.de> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "kdiff3_part.h" #include <kcomponentdata.h> #include <kaction.h> #include <kstandardaction.h> #include <kfiledialog.h> #include <QFile> #include <QTextStream> #include <QProcess> #include "kdiff3.h" #include "fileaccess.h" #include <kmessagebox.h> #include <klocale.h> #include "version.h" KDiff3Part::KDiff3Part( QWidget *parentWidget, const char *widgetName, QObject *parent ) : KParts::ReadWritePart(parent) { // we need an instance setComponentData( *KDiff3PartFactory::instance() ); // this should be your custom internal widget m_widget = new KDiff3App( parentWidget, widgetName, this ); // This hack is necessary to avoid a crash when the program terminates. m_bIsShell = qobject_cast<KParts::MainWindow*>(parentWidget)!=0; // notify the part that this is our internal widget setWidget(m_widget); // create our actions //KStandardAction::open(this, SLOT(fileOpen()), actionCollection()); //KStandardAction::saveAs(this, SLOT(fileSaveAs()), actionCollection()); //KStandardAction::save(this, SLOT(save()), actionCollection()); setXMLFile("kdiff3_part.rc"); // we are read-write by default setReadWrite(true); // we are not modified since we haven't done anything yet setModified(false); } KDiff3Part::~KDiff3Part() { if ( m_widget!=0 && ! m_bIsShell ) { m_widget->saveOptions( m_widget->isPart() ? componentData().config() : KGlobal::config() ); } } void KDiff3Part::setReadWrite(bool /*rw*/) { // ReadWritePart::setReadWrite(rw); } void KDiff3Part::setModified(bool /*modified*/) { /* // get a handle on our Save action and make sure it is valid KAction *save = actionCollection()->action(KStandardAction::stdName(KStandardAction::Save)); if (!save) return; // if so, we either enable or disable it based on the current // state if (modified) save->setEnabled(true); else save->setEnabled(false); // in any event, we want our parent to do it's thing ReadWritePart::setModified(modified); */ } static void getNameAndVersion( const QString& str, const QString& lineStart, QString& fileName, QString& version ) { if ( str.left( lineStart.length() )==lineStart && fileName.isEmpty() ) { int pos = lineStart.length(); while ( pos<str.length() && (str[pos]==' ' || str[pos]=='\t') ) ++pos; int pos2 = str.length()-1; while ( pos2>pos ) { while (pos2>pos && str[pos2]!=' ' && str[pos2]!='\t') --pos2; fileName = str.mid( pos, pos2-pos ); fprintf(stderr, "KDiff3: %s\n", fileName.toLatin1().constData()); if ( FileAccess(fileName).exists() ) break; --pos2; } int vpos = str.lastIndexOf("\t", -1); if ( vpos>0 && vpos>(int)pos2 ) { version = str.mid( vpos+1 ); while( !version.right(1)[0].isLetterOrNumber() ) version.truncate( version.length()-1 ); } } } bool KDiff3Part::openFile() { // m_file is always local so we can use QFile on it fprintf(stderr, "KDiff3: %s\n", localFilePath().toLatin1().constData()); QFile file(localFilePath()); if (file.open(QIODevice::ReadOnly) == false) return false; // our example widget is text-based, so we use QTextStream instead // of a raw QDataStream QTextStream stream(&file); QString str; QString fileName1; QString fileName2; QString version1; QString version2; while (!stream.atEnd() && (fileName1.isEmpty() || fileName2.isEmpty()) ) { str = stream.readLine() + "\n"; getNameAndVersion( str, "---", fileName1, version1 ); getNameAndVersion( str, "+++", fileName2, version2 ); } file.close(); if ( fileName1.isEmpty() && fileName2.isEmpty() ) { KMessageBox::sorry(m_widget, i18n("Couldn't find files for comparison.")); return false; } FileAccess f1(fileName1); FileAccess f2(fileName2); if ( f1.exists() && f2.exists() && fileName1!=fileName2 ) { m_widget->slotFileOpen2( fileName1, fileName2, "", "", "", "", "", 0 ); return true; } else if ( version1.isEmpty() && f1.exists() ) { // Normal patch // patch -f -u --ignore-whitespace -i [inputfile] -o [outfile] [patchfile] QString tempFileName = FileAccess::tempFileName(); QString cmd = "patch -f -u --ignore-whitespace -i \"" + localFilePath() + "\" -o \""+tempFileName + "\" \"" + fileName1+ "\""; QProcess process; process.start( cmd ); process.waitForFinished(-1); m_widget->slotFileOpen2( fileName1, tempFileName, "", "", "", version2.isEmpty() ? fileName2 : "REV:"+version2+":"+fileName2, "", 0 ); // alias names // std::cerr << "KDiff3: f1:" << fileName1.toLatin1() <<"<->"<<tempFileName.toLatin1()<< std::endl; FileAccess::removeTempFile( tempFileName ); } else if ( version2.isEmpty() && f2.exists() ) { // Reverse patch // patch -f -u -R --ignore-whitespace -i [inputfile] -o [outfile] [patchfile] QString tempFileName = FileAccess::tempFileName(); QString cmd = "patch -f -u -R --ignore-whitespace -i \"" + localFilePath() + "\" -o \""+tempFileName + "\" \"" + fileName2+"\""; QProcess process; process.start( cmd ); process.waitForFinished(-1); m_widget->slotFileOpen2( tempFileName, fileName2, "", "", version1.isEmpty() ? fileName1 : "REV:"+version1+":"+fileName1, "", "", 0 ); // alias name // std::cerr << "KDiff3: f2:" << fileName2.toLatin1() <<"<->"<<tempFileName.toLatin1()<< std::endl; FileAccess::removeTempFile( tempFileName ); } else if ( !version1.isEmpty() && !version2.isEmpty() ) { fprintf(stderr, "KDiff3: f1/2:%s<->%s\n", fileName1.toLatin1().constData(), fileName2.toLatin1().constData()); // Assuming that files are on CVS: Try to get them // cvs update -p -r [REV] [FILE] > [OUTPUTFILE] QString tempFileName1 = FileAccess::tempFileName(); QString cmd1 = "cvs update -p -r " + version1 + " \"" + fileName1 + "\" >\""+tempFileName1+"\""; QProcess process1; process1.start( cmd1 ); process1.waitForFinished(-1); QString tempFileName2 = FileAccess::tempFileName(); QString cmd2 = "cvs update -p -r " + version2 + " \"" + fileName2 + "\" >\""+tempFileName2+"\""; QProcess process2; process2.start( cmd2 ); process2.waitForFinished(-1); m_widget->slotFileOpen2( tempFileName1, tempFileName2, "", "", "REV:"+version1+":"+fileName1, "REV:"+version2+":"+fileName2, "", 0 ); // std::cerr << "KDiff3: f1/2:" << tempFileName1.toLatin1() <<"<->"<<tempFileName2.toLatin1()<< std::endl; FileAccess::removeTempFile( tempFileName1 ); FileAccess::removeTempFile( tempFileName2 ); return true; } else { KMessageBox::sorry(m_widget, i18n("Couldn't find files for comparison.")); } return true; } bool KDiff3Part::saveFile() { /* // if we aren't read-write, return immediately if (isReadWrite() == false) return false; // localFilePath() is always local, so we use QFile QFile file(localFilePath()); if (file.open(IO_WriteOnly) == false) return false; // use QTextStream to dump the text to the file QTextStream stream(&file); //stream << m_widget->text(); file.close(); return true; */ return false; // Not implemented } // It's usually safe to leave the factory code alone.. with the // notable exception of the KAboutData data #include <kaboutdata.h> #include <klocale.h> #include <kglobal.h> KComponentData* KDiff3PartFactory::s_instance = 0L; KAboutData* KDiff3PartFactory::s_about = 0L; KDiff3PartFactory::KDiff3PartFactory() : KParts::Factory() { } KDiff3PartFactory::~KDiff3PartFactory() { delete s_instance; delete s_about; s_instance = 0L; } KParts::Part* KDiff3PartFactory::createPartObject( QWidget *parentWidget, QObject *parent, const char *classname, const QStringList&/*args*/ ) { // Create an instance of our Part KDiff3Part* obj = new KDiff3Part( parentWidget, 0, parent ); // See if we are to be read-write or not if (QString(classname) == "KParts::ReadOnlyPart") obj->setReadWrite(false); return obj; } KComponentData* KDiff3PartFactory::instance() { if( !s_instance ) { s_about = new KAboutData(QByteArray("kdiff3part"), QByteArray("kdiff3part"), ki18n("KDiff3Part"), QByteArray(VERSION)); s_about->addAuthor(ki18n("Joachim Eibl"), KLocalizedString(), QByteArray("joachim.eibl at gmx.de")); s_instance = new KComponentData(s_about); } return s_instance; } extern "C" { void* init_libkdiff3part() { return new KDiff3PartFactory; } } // Suppress warning with --enable-final #undef VERSION //#include "kdiff3_part.moc"
32.88125
127
0.587626
michaelxzhang
8361029212864e137d72e5aaa651ed8c8b2dcea3
292
cpp
C++
algorithms/divizori.cpp
MateiSR/CPP
d9c0d2bd1ab48a44e3c2537b513cee0c72dc371b
[ "Unlicense" ]
null
null
null
algorithms/divizori.cpp
MateiSR/CPP
d9c0d2bd1ab48a44e3c2537b513cee0c72dc371b
[ "Unlicense" ]
null
null
null
algorithms/divizori.cpp
MateiSR/CPP
d9c0d2bd1ab48a44e3c2537b513cee0c72dc371b
[ "Unlicense" ]
null
null
null
#include <iostream> int main() { int n; std :: cin >> n; for(int d =1 ; d * d <= n ; d ++ ) if(n % d == 0) { std :: cout << d << " "; if(d * d < n) // dacă d != sqrt(n) std :: cout << n / d << " "; } return 0; }
19.466667
46
0.304795
MateiSR
836253ea122748c9852ff1e946f6a37ca214a3fb
17,059
cpp
C++
src/core/graphics/t2kGCore.cpp
DamakoSoft/t2k
df50be732675cd968aba04296724d5d0acba65cf
[ "MIT" ]
3
2022-01-09T09:02:46.000Z
2022-01-11T01:33:11.000Z
src/core/graphics/t2kGCore.cpp
DamakoSoft/t2k
df50be732675cd968aba04296724d5d0acba65cf
[ "MIT" ]
null
null
null
src/core/graphics/t2kGCore.cpp
DamakoSoft/t2k
df50be732675cd968aba04296724d5d0acba65cf
[ "MIT" ]
null
null
null
// t2k - Tatsuko Driver is a software library designed to drive game development. // Copyright (C) Damako Soft since 2020, all rights reserved. // current version is ver. 0.1. // // Damako Soft staff: // Da: Daizo Sasaki // Ma: yoshiMasa Sugawara // Ko: Koji Saito // // If you are interested in t2k, please follow our Twitter account @DamakoSoft // // These software come with absolutory no warranty and are released under the // MIT License. see https://opensource.org/licenses/MIT // This program is based on M5Stack_LCD_DMA by MHageGH and modified for game // development. You can get the original MHageGH's M5Stack_LCD_DMA here. // https://github.com/MhageGH/M5Stack_LCD_DMA // We would like to thank Mr. MHageGH for making such a wonderful program // available to the public. Thank you very much! #include <M5Core2.h> // #define ENABLE_DEBUG_MESSAGE #include <t2kCommon.h> #include <string.h> #include <esp_task_wdt.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <esp_system.h> #include <driver/spi_master.h> #include <soc/gpio_struct.h> #include <driver/gpio.h> #include <utility/Config.h> #include <utility/In_eSPI.h> #include <t2kGCore.h> const int kLcdWidth =320; const int kLcdHeight=240; static uint8_t *gFrameBuffer[2]={NULL,NULL}; int gCurrentBufferToDraw=0; void t2kLcdReset(bool inState); const int kNumOfDmaTransfer=8; // 8 is max. const int kDmaWidth =320; const int kDmaBufferHeight=240/kNumOfDmaTransfer; const int kGRamGapHeight=120/kNumOfDmaTransfer; static spi_device_handle_t gSpi; static bool lcdInit(spi_device_handle_t inSpi); static bool lcdCmd(spi_device_handle_t inSpi,const uint8_t inCmd); static void lcdData(spi_device_handle_t inSpi,const uint8_t *inData,int inLen); static void sendFramebuffer(spi_device_handle_t inSpi, int inX,int inY,int inWidth,int inHeight, uint16_t *inFrameBuffer); static void sendFrameBufferFinish(spi_device_handle_t inSpi); #define CurrentBuffer (gFrameBuffer[gCurrentBufferToDraw]) static uint16_t *gDmaBuffer=NULL; static volatile uint64_t gToFlipped=0; static volatile uint64_t gFlipped=0; static spi_device_handle_t spiStart(); static void lcdSpiPreTransferCallback(spi_transaction_t *inSpiTransaction); static void flipPump(void *inArgs); static bool createFramebuffer(); static void flip(); bool t2kGCoreInit() { gSpi=spiStart(); if( lcdInit(gSpi) ) { Serial.printf("SUCCESS lcdInit\n"); } else { ERROR("ERROR t2kGCoreInit: lcdInit\n"); } // for M5Stack backlight PWM control. const int BLK_PWM_CHANNEL=7; ledcSetup(7,44100,8); ledcAttachPin(TFT_BL, BLK_PWM_CHANNEL); ledcWrite(BLK_PWM_CHANNEL,255); // max brightness bool ret=createFramebuffer(); if(ret==false) { ERROR("ERROR: t2kGCoreInit() FAILED.\n"); } return ret; } void t2kGCoreStart() { const int kGCoreCpuID=0; xTaskCreatePinnedToCore(flipPump,"t2kGCore",4096,NULL,1,NULL,kGCoreCpuID); } static void flipPump(void *inArgs) { Serial.printf("=== t2kGCore:flipPump Started ===\n"); while(true) { // wait request while(gToFlipped<=gFlipped) { delay(10); //taskYIELD(); //Serial.printf("flipPump WAIT gToFlipped=%d gFlipped=%d\n",gToFlipped,gFlipped); } flip(); gFlipped++; } } void t2kFlip() { gToFlipped++; DEBUG("Request Flip=%d \n",gToFlipped); while(gToFlipped!=gFlipped) { delay(10); // taskYIELD(); } DEBUG("Flip Done=%d \n",gToFlipped); } static bool createFramebuffer() { for(int i=0; i<2; i++) { gFrameBuffer[i]=(uint8_t *)malloc(kGRamWidth*kGRamHeight*sizeof(uint8_t)); if(gFrameBuffer[i]==NULL) { Serial.printf("================NO FrameBuffer MEMORY %d\n",i); return false; } } gDmaBuffer=(uint16_t *)heap_caps_malloc(kDmaWidth*kDmaBufferHeight*sizeof(uint16_t),MALLOC_CAP_DMA); if(gDmaBuffer==NULL) { Serial.println("================NO DMA MEMORY"); return false; } return true; } // @param brightness 0~255 void t2kSetBrightness(uint8_t inBrightness) { t2kLcdBrightness(inBrightness); } uint8_t *t2kGetFramebuffer() { return gFrameBuffer[gCurrentBufferToDraw]; } void t2kFill(uint8_t inColorRGB322) { memset(gFrameBuffer[gCurrentBufferToDraw],inColorRGB322,kGRamWidth*kGRamHeight); } void t2kCopyFromFrontBuffer() { uint8_t *front=gFrameBuffer[(gCurrentBufferToDraw+1)%2]; memcpy(gFrameBuffer[gCurrentBufferToDraw],front,kGRamWidth*kGRamHeight); } void t2kPSet(int inX,int inY,uint8_t inColorRGB332) { if(inX<0 || kGRamWidth<=inX || inY<0 || kGRamHeight<=inY) { return; } CurrentBuffer[FBA(inX,inY)]=inColorRGB332; } // ref https://cdn-shop.adafruit.com/datasheets/ILI9341.pdf // and http://blog.livedoor.jp/prittyparakeet/archives/2016-11-04.html // // kLCD_CMD_... LCD Command // kLCD_PRN_... LCD Parameter const uint8_t kLCD_CMD_PowerControl1=0xC0; const uint8_t kLCD_PRM_PC1_3_80_V=0x23; // 3.80 [volt] const uint8_t kLCD_CMD_PowerControl2=0xC1; const uint8_t kLCD_PRM_PC2_VCIx2=10; const uint8_t kLCD_CMD_VcomControl1 =0xC5; const uint8_t kLCD_PRM_VcomH_4_250V =0x3E; // 4.250 [volt] const uint8_t kLCD_PRM_VcomL_M1_500V=0x28; // -1.500 [volt] const uint8_t kLCD_CMD_VcomControl2=0xC7; const uint8_t kLCD_PRM_VMH_VML_M58 =0x86; const uint8_t kLCD_CMD_MemoryAccessControl=0x36; const uint8_t kLCD_PRM_MAC_RowAddressOrder =0x80; const uint8_t kLCD_PRM_MAC_ColumnAddressOrder =0x40; const uint8_t kLCD_PRM_MAC_RowColumnExchange =0x20; const uint8_t kLCD_PRM_MAC_VerticalRefreshOrder =0x10; const uint8_t kLCD_PRM_MAC_RgbBgrOrder =0x08; const uint8_t kLCD_PRM_MAC_HorizontalRefreshOrder=0x40; const uint8_t kLCD_CMD_PixelFormatSet=0x3A; const uint8_t kLCD_PRM_PFS_RgbInterfaceFormat_16BitsPerPixel=0x50; const uint8_t kLCD_PRM_PFS_McuInterfaceFormat_16BitsPerPixel=0x05; const uint8_t kLCD_CMD_FrameRateControl=0xB1; const uint8_t kLCD_PRM_DivisionRatioStraight=0x00; const uint8_t kLCD_PRM_FrameRate100Hz =0x13; const uint8_t kLCD_CMD_DisplayFunctionControl=0xB6; const uint8_t kLCD_PRM_DFC_IntervalScan =0x08; const uint8_t kLCD_PRM_DFC_V63V0VcomlVcomh=0x00; const uint8_t kLCD_PRM_DFC_LcdNormalyWhite=0x80; const uint8_t kLCD_PRM_DFC_ScanCycle85ms =0x02; const uint8_t kLCD_PRM_DFC_320Lines =0x27; const uint8_t kLCD_CMD_GammaSet=0x26; const uint8_t kLCD_PRM_GS_Gamma2_2=0x01; const uint8_t kLCD_CMD_PositiveGammaCorrection=0xE0; const uint8_t kLCD_CMD_NegativeGammaCorrection=0xE1; const uint8_t kLCD_CMD_SleepOut=0x11; const uint8_t kLCD_PRM_SO_NO_PARAMETER=0x00; const uint8_t kLCD_CMD_DisplayON=0x29; const uint8_t kLCD_PRM_DO_NO_PARAMETER=0x00; const uint8_t kLCD_CMD_DisplayInversionON=0x21; const uint8_t kLCD_PRM_DIO_NO_PARAMETER=0x00; typedef struct { uint8_t cmd; uint8_t data[16]; // No of data in data; bit 7 = delay after set; 0xFF = end of cmds. uint8_t databytes; } LcdInitCmd; const uint8_t kSendDummyData=0x80; const uint8_t kEND=0xFF; DRAM_ATTR const LcdInitCmd kIliInitCmds[] = { // ref to TFT_eSPI::init() In_eSPI.cpp in M5Stack Libarary {0xEF, {0x03, 0x80, 0x02}, 3}, // undocumented magic sequence? {0xCF, {0x00, 0xC1, 0x30}, 3}, // same as above {0xED, {0x64, 0x03, 0x12, 0x81}, 4}, // same as above {0xE8, {0x85, 0x00, 0x78}, 3}, // same as above {0xCB, {0x39, 0x2C, 0x00, 0x34, 0x02}, 5}, // same as above {0xF7, {0x20}, 1}, // same as above {0xEA, {0x00, 0x00}, 2}, // same as above { kLCD_CMD_PowerControl1, { kLCD_PRM_PC1_3_80_V }, 1}, { kLCD_CMD_PowerControl2, { kLCD_PRM_PC2_VCIx2 }, 1}, { kLCD_CMD_VcomControl1, { kLCD_PRM_VcomH_4_250V, kLCD_PRM_VcomL_M1_500V }, 2}, { kLCD_CMD_VcomControl2, { kLCD_PRM_VMH_VML_M58 }, 1}, { kLCD_CMD_MemoryAccessControl, { kLCD_PRM_MAC_RowAddressOrder | kLCD_PRM_MAC_RowColumnExchange | kLCD_PRM_MAC_RgbBgrOrder }, 1}, { kLCD_CMD_PixelFormatSet, { kLCD_PRM_PFS_RgbInterfaceFormat_16BitsPerPixel | kLCD_PRM_PFS_McuInterfaceFormat_16BitsPerPixel }, 1}, { kLCD_CMD_FrameRateControl, { kLCD_PRM_DivisionRatioStraight, kLCD_PRM_FrameRate100Hz }, 2}, { kLCD_CMD_DisplayFunctionControl, { kLCD_PRM_DFC_IntervalScan | kLCD_PRM_DFC_V63V0VcomlVcomh, kLCD_PRM_DFC_LcdNormalyWhite | kLCD_PRM_DFC_ScanCycle85ms, kLCD_PRM_DFC_320Lines}, 3}, {0xF2, {0x00}, 1}, // undocumented magic sequence { kLCD_CMD_GammaSet, { kLCD_PRM_GS_Gamma2_2 }, 1}, { kLCD_CMD_PositiveGammaCorrection, { 0x0F, 0x31, 0x2B, // VP63, VP62, VP61 0x0C, // VP59 0x0E, // VP57 0x08, // VP50 0x4E, // VP43 0xF1, // VP27 and VP36 0x37, // VP20 0x07, // VP13 0x10, // VP6 0x03, // VP4 0x0E, 0x09, 0x00 // VP2, VP1, VP0 }, 15}, { kLCD_CMD_NegativeGammaCorrection, { 0x00, 0x0E, 0x14, // VN63, VN62, VN61 0x03, // VN59 0x11, // VN57 0x07, // VN50 0x31, // VN43 0xC1, // VN36 and VN27 0x48, // VN20 0x08, // VN13 0x0F, // VN6 0x0C, // VN4 0x31, 0x36, 0x0F // VN2, VN1, VN0 }, 15}, { kLCD_CMD_SleepOut, { kLCD_PRM_SO_NO_PARAMETER }, kSendDummyData }, { kLCD_CMD_DisplayON, { kLCD_PRM_DO_NO_PARAMETER }, kSendDummyData }, // ref to setRotation(1) in ILI9341_Rotation.h in M5Stack Library // this command is importand (do not remove!) { kLCD_CMD_MemoryAccessControl, { kLCD_PRM_MAC_RgbBgrOrder }, 1}, // for new M5Stack basic { kLCD_CMD_DisplayInversionON, { kLCD_PRM_DIO_NO_PARAMETER }, kSendDummyData }, { 0, { 0 }, kEND } }; // #define PIN_NUM_MISO GPIO_NUM_19 #ifdef M5StacK_BASIC #define PIN_NUM_MISO GPIO_NUM_19 #define PIN_NUM_MOSI GPIO_NUM_23 #define PIN_NUM_CLK GPIO_NUM_18 #define PIN_NUM_CS GPIO_NUM_14 #define PIN_NUM_DC GPIO_NUM_27 #define PIN_NUM_RST GPIO_NUM_33 #define PIN_NUM_BCKL GPIO_NUM_32 #else #define PIN_NUM_MISO GPIO_NUM_38 #define PIN_NUM_MOSI GPIO_NUM_23 #define PIN_NUM_CLK GPIO_NUM_18 #define PIN_NUM_CS GPIO_NUM_5 #define PIN_NUM_DC GPIO_NUM_15 // #define PIN_NUM_RST GPIO_NUM_33 // #define PIN_NUM_BCKL GPIO_NUM_32 #endif #include <driver/spi_common.h> static spi_device_handle_t spiStart() { Serial.printf("START spiStart()...\n"); spi_bus_config_t buscfg={ .mosi_io_num=PIN_NUM_MOSI, .miso_io_num=PIN_NUM_MISO, .sclk_io_num=PIN_NUM_CLK, .quadwp_io_num=-1, .quadhd_io_num=-1, .max_transfer_sz=240*320*2+8, .flags=SPICOMMON_BUSFLAG_MASTER, .intr_flags=0 }; esp_err_t result=spi_bus_initialize(VSPI_HOST,&buscfg,1); // DMA 1 ch. // ESP_ERROR_CHECK(result); if(result!=ESP_OK) { ERROR("ERROR spiStart: spi_bus_initialize\n"); } else { Serial.printf("spi_bus_initialize() OK.\n"); } spi_device_interface_config_t devcfg={ .command_bits=0, .address_bits=0, .dummy_bits=0, .mode=0, //SPI mode 0 .duty_cycle_pos=0, .cs_ena_pretrans=0, .cs_ena_posttrans=0, // .clock_speed_hz=SPI_MASTER_FREQ_26M, // 40 * 1000 * 1000, .clock_speed_hz=SPI_MASTER_FREQ_40M, .input_delay_ns=0, .spics_io_num=PIN_NUM_CS, // CS pin // .flags=0, .flags=SPI_DEVICE_3WIRE | SPI_DEVICE_HALFDUPLEX, .queue_size=7, // We want to be able to queue 7 transactions at a time .pre_cb=lcdSpiPreTransferCallback, // Specify pre-transfer callback to handle D/C line .post_cb=0 }; spi_device_handle_t hSpi; result=spi_bus_add_device(VSPI_HOST,&devcfg,&hSpi); //ESP_ERROR_CHECK(result); if(result!=ESP_OK) { ERROR("ERROR spiStart: spi_bus_add_device\n"); } else { Serial.printf("spi_bus_add_device() OK.\n"); Serial.printf("SUCCESS spiStart hSpi=%p\n",hSpi); } return hSpi; } static bool lcdCmd(spi_device_handle_t inSpi,const uint8_t inCmd) { spi_transaction_t t; memset(&t,0,sizeof(t)); //Zero out the transaction t.length=8; //Command is 8 bits t.tx_buffer=&inCmd; //The data is the cmd itself t.user=(void *)0; //D/C needs to be set to 0 esp_err_t result=spi_device_polling_transmit(inSpi,&t); //Transmit! // assert(result==ESP_OK); //Should have had no issues. if(result!=ESP_OK) { ERROR("ERROR lcdCmd: spi_device_polling_transmit\n"); } return result==ESP_OK; } static void lcdData(spi_device_handle_t inSpi, const uint8_t *inData, int inLen) { if(inLen==0) { return; } // no need to send anything spi_transaction_t t; memset(&t,0,sizeof(t)); // Zero out the transaction t.length=inLen*8; // Len is in bytes, transaction length is in bits. t.tx_buffer=inData; // Data t.user=(void *)1; // D/C needs to be set to 1 esp_err_t ret=spi_device_polling_transmit(inSpi, &t); // Transmit! assert(ret==ESP_OK); // Should have had no issues. } static void lcdSpiPreTransferCallback(spi_transaction_t *inSpiTransaction) { int dc=(int)inSpiTransaction->user; gpio_set_level(PIN_NUM_DC,dc); } static bool lcdInit(spi_device_handle_t inSpi) { gpio_set_direction(PIN_NUM_DC,GPIO_MODE_OUTPUT); // gpio_set_direction(PIN_NUM_RST, GPIO_MODE_OUTPUT); // for M5 Basic // gpio_set_direction(PIN_NUM_BCKL,GPIO_MODE_OUTPUT); // for M5 Basic // gpio_set_level(PIN_NUM_RST, 0); t2kLcdReset(false); vTaskDelay(100/portTICK_RATE_MS); //gpio_set_level(PIN_NUM_RST, 1); t2kLcdReset(true); vTaskDelay(100/portTICK_RATE_MS); const LcdInitCmd *lcdInitCmds=kIliInitCmds; bool result=true; int cmd=0; while(lcdInitCmds[cmd].databytes!=0xff) { if(lcdCmd(inSpi,lcdInitCmds[cmd].cmd)==false) { result=false; Serial.printf("CMD=%d\n",cmd); break; } lcdData(inSpi,lcdInitCmds[cmd].data, lcdInitCmds[cmd].databytes&0x1F); if(lcdInitCmds[cmd].databytes&0x80) { vTaskDelay(100/portTICK_RATE_MS); } cmd++; } // gpio_set_level(PIN_NUM_BCKL, 1); ///Enable backlight t2kLcdBrightness(255); return result; } static void sendFramebuffer(spi_device_handle_t inSpi, int inX,int inY,int inWidth,int inHeight, uint16_t *inFrameBuffer) { static spi_transaction_t trans[6]; for(int i=0; i<6; i++) { memset(&trans[i],0,sizeof(spi_transaction_t)); if((i&0x1)==0) { trans[i].length=8; trans[i].user=(void *)0; } else { trans[i].length=8*4; trans[i].user=(void *)1; } trans[i].flags=SPI_TRANS_USE_TXDATA; } trans[0].tx_data[0]=0x2A; // column address set trans[1].tx_data[0]=inX>>8; // start col high trans[1].tx_data[1]=inX&0xFF; // start col low const int right=inX+inWidth-1; trans[1].tx_data[2]=right>>8; // end col high trans[1].tx_data[3]=right&0xFF; // end col low trans[2].tx_data[0]=0x2B; // page address set trans[3].tx_data[0]=inY>>8; // start page high trans[3].tx_data[1]=inY&0xFF; // start page low const int bottom=inY+inHeight-1; trans[3].tx_data[2]=bottom>>8; // end page high trans[3].tx_data[3]=bottom&0xFF; // end page low trans[4].tx_data[0]=0x2C; // memory write trans[5].tx_buffer=inFrameBuffer; // finally send the line data trans[5].length=inWidth*2*8*inHeight; // data length, in bits trans[5].flags=0; // undo SPI_TRANS_USE_TXDATA flag esp_err_t result; for(int i=0; i<6; i++) { result=spi_device_queue_trans(inSpi,&trans[i],portMAX_DELAY); //assert(result==ESP_OK); if(result!=ESP_OK) { ERROR("ERROR sendFramebuffer: spi_device_queue_trans\n"); } } } static void sendFrameBufferFinish(spi_device_handle_t inSpi) { spi_transaction_t *rtrans; esp_err_t result; for(int i=0; i<6; i++) { result=spi_device_get_trans_result(inSpi,&rtrans,portMAX_DELAY); // assert(ret == ESP_OK); if(result!=ESP_OK) { ERROR("ERROR sendFrameBufferFinish: spi_device_get_trans_result\n"); } } } static void flip() { DEBUG_LN("**** FLIP IN"); uint8_t *srcP=gFrameBuffer[gCurrentBufferToDraw]; for(int i=0; i<kNumOfDmaTransfer; i++) { const int startY=i*kGRamGapHeight; const int endY=startY+kGRamGapHeight; uint16_t *destP=gDmaBuffer; for(int srcY=startY; srcY<endY; srcY++,destP+=kDmaWidth*2,srcP+=kGRamWidth) { for(int srcX=0,destX=0; srcX<kGRamWidth; srcX++,destX+=2) { uint16_t srcColor=(uint16_t)srcP[srcX]; uint16_t destColor; if(srcColor==0xFF) { destColor=0xFFFF; } else { destColor= ((srcColor & 0xE0)<<8) | ((srcColor & 0x1C)<<6) | ((srcColor & 0x03)<<3); // swap hi-low due to little engian destColor = ((destColor & 0xFF)<<8) | (destColor>>8); } destP[destX]=destP[destX+1] =destP[kDmaWidth+destX]=destP[kDmaWidth+destX+1]=destColor; } } sendFramebuffer(gSpi,0,startY*2,kDmaWidth,kDmaBufferHeight,gDmaBuffer); sendFrameBufferFinish(gSpi); } gCurrentBufferToDraw ^= 0x01; // 0 -> 1 -> 0 -> 1 ... DEBUG_LN("**** FLIP OUT"); }
32.932432
103
0.69582
DamakoSoft
836832beaa041e01e1e4317032e1534e1ebfc469
1,912
hpp
C++
include/pichi/vo/credential.hpp
imuzi/pichi
5ad1372bff4c3bffd201ccfb41df6c839c83c506
[ "BSD-3-Clause" ]
164
2018-09-28T09:41:05.000Z
2021-11-13T09:17:07.000Z
include/pichi/vo/credential.hpp
imuzi/pichi
5ad1372bff4c3bffd201ccfb41df6c839c83c506
[ "BSD-3-Clause" ]
5
2018-12-21T13:40:02.000Z
2021-07-24T04:23:44.000Z
include/pichi/vo/credential.hpp
imuzi/pichi
5ad1372bff4c3bffd201ccfb41df6c839c83c506
[ "BSD-3-Clause" ]
14
2018-12-18T09:35:42.000Z
2021-07-06T12:16:34.000Z
#ifndef PICHI_VO_CREDENTIAL_HPP #define PICHI_VO_CREDENTIAL_HPP #include <pichi/common/enumerations.hpp> #include <rapidjson/document.h> #include <string> #include <unordered_map> #include <unordered_set> namespace pichi::vo { struct UpIngressCredential { std::unordered_map<std::string, std::string> credential_; }; struct UpEgressCredential { std::pair<std::string, std::string> credential_; }; extern rapidjson::Value toJson(UpIngressCredential const&, rapidjson::Document::AllocatorType&); extern rapidjson::Value toJson(UpEgressCredential const&, rapidjson::Document::AllocatorType&); struct TrojanIngressCredential { std::unordered_set<std::string> credential_; }; struct TrojanEgressCredential { std::string credential_; }; extern rapidjson::Value toJson(TrojanIngressCredential const&, rapidjson::Document::AllocatorType&); extern rapidjson::Value toJson(TrojanEgressCredential const&, rapidjson::Document::AllocatorType&); struct VMessIngressCredential { std::unordered_map<std::string, uint16_t> credential_; }; struct VMessEgressCredential { std::string uuid_; uint16_t alter_id_; VMessSecurity security_; }; extern rapidjson::Value toJson(VMessIngressCredential const&, rapidjson::Document::AllocatorType&); extern rapidjson::Value toJson(VMessEgressCredential const&, rapidjson::Document::AllocatorType&); extern bool operator==(UpIngressCredential const&, UpIngressCredential const&); extern bool operator==(UpEgressCredential const&, UpEgressCredential const&); extern bool operator==(TrojanIngressCredential const&, TrojanIngressCredential const&); extern bool operator==(TrojanEgressCredential const&, TrojanEgressCredential const&); extern bool operator==(VMessIngressCredential const&, VMessIngressCredential const&); extern bool operator==(VMessEgressCredential const&, VMessEgressCredential const&); } // namespace pichi::vo #endif // PICHI_VO_CREDENTIAL_HPP
33.54386
100
0.801778
imuzi
836a640bda4b0bf045534138f22a470b38f880d3
1,145
hpp
C++
include/text_screen/entity.hpp
fishjump/osdevc_textscreen
70f2996642c63cbc350869bdcc377057729aa687
[ "MIT" ]
null
null
null
include/text_screen/entity.hpp
fishjump/osdevc_textscreen
70f2996642c63cbc350869bdcc377057729aa687
[ "MIT" ]
null
null
null
include/text_screen/entity.hpp
fishjump/osdevc_textscreen
70f2996642c63cbc350869bdcc377057729aa687
[ "MIT" ]
null
null
null
#pragma once #include <color/color.hpp> #include <font/font.hpp> #include <screen/screen.hpp> #include <std/stdcxx.hpp> namespace system::io::entity { class TextScreen : public Screen { public: TextScreen(system::media::entity::Font defaultFont, system::media::entity::Color defaultColor); static const uint32_t MAX_BUFFER_SIZE = 4096; TextScreen *drawChar(const uint32_t &x, const uint32_t &y, const char &ch); TextScreen *drawChar(const uint32_t &x, const uint32_t &y, const char & ch, const system::media::entity::Font & font, const system::media::entity::Color &color); TextScreen *print(const char *content); TextScreen *print(int64_t content); TextScreen *print(uint64_t content); void fresh(); private: char buffer[MAX_BUFFER_SIZE]; uint32_t bufferCount; uint32_t row; uint32_t column; system::media::entity::Font defaultFont; system::media::entity::Color defaultColor; }; // class TextScreen } // namespace system::io::entity
27.261905
68
0.623581
fishjump
836ec1dce6581a3bd9d6d22998405f7061331ca2
9,431
cpp
C++
looper/firmware/sync.cpp
jessecrossen/hautmidi
7ef969d842c6cd9bc412d08ca422d962547e88e8
[ "Unlicense" ]
4
2017-09-28T02:06:42.000Z
2021-07-15T01:58:58.000Z
looper/firmware/sync.cpp
jessecrossen/hautmidi
7ef969d842c6cd9bc412d08ca422d962547e88e8
[ "Unlicense" ]
null
null
null
looper/firmware/sync.cpp
jessecrossen/hautmidi
7ef969d842c6cd9bc412d08ca422d962547e88e8
[ "Unlicense" ]
null
null
null
#include "sync.h" #define TRACE 0 #include "trace.h" size_t Sync::idealLoopBlocks(Track *track) { SyncPoint *p; uint8_t ti; uint8_t i = track->index; // count sync points to the track for each other track size_t *counts = new size_t[_trackCount]; for (ti = 0; ti < _trackCount; ti++) counts[ti] = 0; for (p = _head; p; p = p->next) { if ((p->target != i) || (p->isProvisional) || (p->source >= _trackCount)) continue; counts[p->source]++; } // for all tracks with more than one reference to this one, // see if we can loop at an even multiple of the source track's length size_t idealBlocks = track->masterBlocks(); size_t bestLength = 0; size_t leastError = 0; size_t unit, count, multiple, target, error, maxError; for (ti = 0; ti < _trackCount; ti++) { count = counts[ti]; if (count < 2) continue; unit = _tracks[ti]->masterBlocks(); maxError = unit / 4; for (multiple = count - 1; multiple <= count + 1; multiple++) { target = unit * multiple; error = (idealBlocks > target) ? (idealBlocks - target) : (target - idealBlocks); if (error > maxError) continue; if ((bestLength == 0) || (error < leastError)) { leastError = error; bestLength = target; } } } // clean up dynamically allocated memory delete[] counts; // if no acceptable match was found, return the track's natural length if (bestLength == 0) return(idealBlocks); // otherwise return our best match return(bestLength); } size_t Sync::blocksUntilNextSyncPoint(Track *track, size_t idealBlocks) { SyncPoint *p; uint8_t i = track->index; // examine all sync points where this track could start its next loop size_t minBlocks = idealBlocks / 4; if (minBlocks < 4) minBlocks = 4; size_t blocksUntil, targetBlock, targetRepeat, time; size_t bestLength = 0; size_t error = 0; size_t leastError = 0; for (p = _head; p; p = p->next) { if ((p->source != i) || (p->isProvisional)) continue; // get the number of blocks until this sync point will arrive targetBlock = _tracks[p->target]->playingBlock(); targetRepeat = _tracks[p->target]->playBlocks(); if (targetRepeat == 0) { WARN1("Sync::blocksUntilNextSyncPoint repeat is zero"); continue; } time = p->time; if (time >= targetRepeat) { // if the target timepoint will not be played in this cycle, // try to sync up with the loop after it's been restarted size_t untilOriginalLoop = _tracks[p->target]->masterBlocks() - time; if (untilOriginalLoop < targetRepeat) { time = targetRepeat - untilOriginalLoop; } } time += targetRepeat; if (targetBlock >= time) { WARN3("Sync::blocksUntilNextSyncPoint time overflow", targetBlock, time); continue; } blocksUntil = (time - targetBlock) % targetRepeat; // find the sync point closest to the natural length of the track while (blocksUntil <= idealBlocks + targetRepeat) { error = (idealBlocks > blocksUntil) ? (idealBlocks - blocksUntil) : (blocksUntil - idealBlocks); if ((bestLength == 0) || (error < leastError)) { leastError = error; bestLength = blocksUntil; } blocksUntil += targetRepeat; } } return(bestLength > minBlocks ? bestLength : idealBlocks); } size_t Sync::trackStarting(Track *track) { SyncPoint *p; uint8_t si = track->index; // if any other track is recording, add a provisional sync point to it for (uint8_t i = 0; i < _trackCount; i++) { if ((i != si) && (_tracks[i]->isRecording())) { p = new SyncPoint; p->source = si; p->target = i; p->time = _tracks[i]->recordingBlock(); p->isProvisional = true; _addPoint(p); } } size_t idealBlocks = idealLoopBlocks(track); size_t bestLength = blocksUntilNextSyncPoint(track, idealBlocks); // if we found no matching sync point, just repeat at the natural length if (bestLength == 0) return(idealBlocks); // otherwise return our best match return(bestLength); } void Sync::trackRecording(Track *track) { SyncPoint *p; uint8_t ri = track->index; // add a sync point onto any other playing tracks for (uint8_t i = 0; i < _trackCount; i++) { if ((i != ri) && (_tracks[i]->isPlaying())) { p = new SyncPoint; p->source = ri; p->target = i; p->time = _tracks[i]->playingBlock(); p->isProvisional = true; _addPoint(p); } } } void Sync::cancelRecording(Track *track) { // remove all provisional sync points SyncPoint *p = _head; while (p) { if (p->isProvisional) p = _removePoint(p); else p = p->next; } } void Sync::commitRecording(Track *track) { uint8_t i = track->index; // remove all old sync points involving the given track and // promote all provisional ones SyncPoint *p = _head; while (p) { // skip sync points not involved with this track if ((p->source != i) && (p->target != i)) { p = p->next; } // promote formerly provisional new sync points else if (p->isProvisional) { p->isProvisional = false; p = p->next; } // remove existing sync points involving this track else { p = _removePoint(p); } } // save the changed sync points save(); } void Sync::trackErased(Track *track) { uint8_t i = track->index; // remove all sync points involving the erased track SyncPoint *p = _head; while (p) { if ((p->source == i) || (p->target == i)) p = _removePoint(p); else p = p->next; } // save the changed sync points save(); } void Sync::setInitialPreroll(Track *track) { track->setPreroll(_prerolls[track->index]); } void Sync::_computePrerolls(size_t startTimes[MAX_TRACKS]) { int i; // get the length of the longest track in blocks size_t maxBlocks = 0; for (i = 0; i < _trackCount; i++) { if (_tracks[i]->masterBlocks() > maxBlocks) maxBlocks = _tracks[i]->masterBlocks(); } // offset start times to get a set of prerolls for (i = 0; i < _trackCount; i++) { if (startTimes[i] > maxBlocks) _prerolls[i] = 0; else _prerolls[i] = maxBlocks - startTimes[i]; } // reduce such that the minimum preroll is zero size_t minBlocks = maxBlocks; for (i = 0; i < _trackCount; i++) { if ((_tracks[i]->masterBlocks() > 0) && (_prerolls[i] < minBlocks)) minBlocks = _prerolls[i]; } for (i = 0; i < _trackCount; i++) { if (_prerolls[i] >= minBlocks) _prerolls[i] -= minBlocks; } } // DOUBLY-LINKED LIST ******************************************************** void Sync::_addPoint(SyncPoint *p) { if (_tail == NULL) { _head = _tail = p; p->next = p->prev = NULL; } else { _tail->next = p; p->prev = _tail; _tail = p; p->next = NULL; } } SyncPoint *Sync::_removePoint(SyncPoint *p) { SyncPoint *next = p->next; if (p->prev) p->prev->next = p->next; else _head = p->next; if (p->next) p->next->prev = p->prev; else _tail = p->prev; delete p; return(next); } void Sync::_removeAllPoints() { SyncPoint *p = _head; SyncPoint *next; while (p) { next = p->next; delete p; p = next; } _head = _tail = NULL; } // PERSISTENCE **************************************************************** void Sync::setPath(char *path) { if (path == NULL) return; if (strncmp(path, _path, sizeof(_path)) == 0) return; strncpy(_path, path, sizeof(_path)); // remove existing sync points _removeAllPoints(); // reset block starts for (int i = 0; i < _trackCount; i++) { _prerolls[i] = 0; } // load sync points from the path if ((_path[0] == '\0') || (! SD.exists(_path))) return; INFO2("Sync::setPath", _path); File f = SD.open(_path, O_READ); if (! f) { WARN2("Sync::setPath unable to open", _path); return; } byte buffer[2 + sizeof(size_t)]; size_t *time = (size_t *)buffer; size_t bytesRead; // read track starting times size_t startTimes[MAX_TRACKS]; for (int i = 0; i < _trackCount; i++) { bytesRead = f.read(buffer, sizeof(size_t)); if (! (bytesRead >= sizeof(size_t))) return; startTimes[i] = *time; } // read sync points time = (size_t *)(buffer + 2); SyncPoint *p; while (true) { bytesRead = f.read(buffer, sizeof(buffer)); if (! (bytesRead >= sizeof(buffer))) return; p = new SyncPoint; p->source = buffer[0] % _trackCount; p->target = buffer[1] % _trackCount; p->time = *time; p->isProvisional = false; DBG4("Sync::setPath point", p->source, p->target, p->time); _addPoint(p); } f.close(); // calculate the preroll for all tracks _computePrerolls(startTimes); } void Sync::save() { // save sync points to the current path if (_path[0] == '\0') return; File f = SD.open(_path, O_WRITE | O_CREAT | O_TRUNC); if (! f) { WARN2("Sync::save unable to open", _path); return; } // write track starting times byte buffer[2 + sizeof(size_t)]; size_t *time = (size_t *)buffer; for (int i = 0; i < _trackCount; i++) { *time = _tracks[i]->playingBlock(); f.write(buffer, sizeof(size_t)); } // write sync points time = (size_t *)(buffer + 2); for (SyncPoint *p = _head; p; p = p->next) { buffer[0] = p->source; buffer[1] = p->target; *time = p->time; DBG4("Sync::save point", p->source, p->target, p->time); f.write(buffer, sizeof(buffer)); } f.close(); }
29.750789
87
0.608207
jessecrossen
837919233197c3444750eb6529a66fdc7331578f
2,620
cpp
C++
test/source/numeric.cpp
nokurn/frequencypp
5280b7a48ca49249c396603aee20cd89785a80b3
[ "0BSD" ]
null
null
null
test/source/numeric.cpp
nokurn/frequencypp
5280b7a48ca49249c396603aee20cd89785a80b3
[ "0BSD" ]
null
null
null
test/source/numeric.cpp
nokurn/frequencypp
5280b7a48ca49249c396603aee20cd89785a80b3
[ "0BSD" ]
null
null
null
// Copyright 2021-2022 Jeremiah Griffin // // 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. #include <frequencypp/frequency.hpp> #include <catch2/catch.hpp> TEST_CASE("floor computes the correct tick count", "[numeric]") { using namespace ::frequencypp; // Positive REQUIRE(floor<kilohertz>(1999_Hz) == 1_KHz); REQUIRE(floor<kilohertz>(2000_Hz) == 2_KHz); REQUIRE(floor<kilohertz>(2001_Hz) == 2_KHz); // Negative REQUIRE(floor<kilohertz>(-1999_Hz) == -2_KHz); REQUIRE(floor<kilohertz>(-2000_Hz) == -2_KHz); REQUIRE(floor<kilohertz>(-2001_Hz) == -3_KHz); } TEST_CASE("ceil computes the correct tick count", "[numeric]") { using namespace ::frequencypp; // Positive REQUIRE(ceil<kilohertz>(1999_Hz) == 2_KHz); REQUIRE(ceil<kilohertz>(2000_Hz) == 2_KHz); REQUIRE(ceil<kilohertz>(2001_Hz) == 3_KHz); // Negative REQUIRE(ceil<kilohertz>(-1999_Hz) == -1_KHz); REQUIRE(ceil<kilohertz>(-2000_Hz) == -2_KHz); REQUIRE(ceil<kilohertz>(-2001_Hz) == -2_KHz); } TEST_CASE("round computes the correct tick count", "[numeric]") { using namespace ::frequencypp; // Positive REQUIRE(round<kilohertz>(1999_Hz) == 2_KHz); REQUIRE(round<kilohertz>(2000_Hz) == 2_KHz); REQUIRE(round<kilohertz>(2001_Hz) == 2_KHz); REQUIRE(round<kilohertz>(3499_Hz) == 3_KHz); REQUIRE(round<kilohertz>(3500_Hz) == 4_KHz); REQUIRE(round<kilohertz>(3501_Hz) == 4_KHz); // Negative REQUIRE(round<kilohertz>(-1999_Hz) == -2_KHz); REQUIRE(round<kilohertz>(-2000_Hz) == -2_KHz); REQUIRE(round<kilohertz>(-2001_Hz) == -2_KHz); REQUIRE(round<kilohertz>(-3499_Hz) == -3_KHz); REQUIRE(round<kilohertz>(-3500_Hz) == -4_KHz); REQUIRE(round<kilohertz>(-3501_Hz) == -4_KHz); } TEST_CASE("abs computes the correct tick count", "[numeric]") { using namespace ::frequencypp; REQUIRE(abs(2_MHz) == 2_MHz); REQUIRE(abs(-2_MHz) == 2_MHz); }
33.164557
75
0.692366
nokurn
8379633dc6cd78efda04fd67747b3d18c4fb5c13
1,586
cpp
C++
sources/InfoWindow.cpp
miqlas/W6
b1940f137e20efee91c0ae060509b7b8507a9159
[ "MIT" ]
1
2017-08-11T17:04:56.000Z
2017-08-11T17:04:56.000Z
sources/InfoWindow.cpp
miqlas/W6
b1940f137e20efee91c0ae060509b7b8507a9159
[ "MIT" ]
4
2017-08-11T17:05:37.000Z
2021-02-01T10:28:53.000Z
sources/InfoWindow.cpp
miqlas/W6
b1940f137e20efee91c0ae060509b7b8507a9159
[ "MIT" ]
1
2020-10-26T07:26:35.000Z
2020-10-26T07:26:35.000Z
#include "InfoWindow.h" #include "ColorWindow.h" #include "day.h" #include "country.h" #include "InfoView.h" #include "GroupWindow.h" #include <TranslationUtils.h> #include <Message.h> InfoWindow::InfoWindow(BRect frame,Country *Country_id[MAX_COUNTRY],Group *Group_id[MAX_GROUP],Politic *Politic_id[MAX_POLITIC], Day *compteur) : BWindow(frame, "Country Infos", B_FLOATING_WINDOW, B_NOT_ZOOMABLE | B_NOT_CLOSABLE | B_NOT_H_RESIZABLE | B_ASYNCHRONOUS_CONTROLS) { _jour=compteur; _country = Country_id; _group = Group_id; _politic = Politic_id; _jour->info_win_exists = ON; i_view = new InfoView(Bounds(), _country,_group,_politic,compteur); AddChild(i_view); //on peut pas le faire à l'intérieur!!! donc après le addchild i_view->ChildAt(0)->SetViewBitmap(BTranslationUtils::GetBitmap('RAWT', 50, NULL)); i_view->grpwin->Hide(); i_view->grporiwin->Hide(); } InfoWindow::~InfoWindow() { _jour->info_win_exists=OFF; //surtout pas faire un Close() ici! On est déjà en train de killer la win } void InfoWindow::MessageReceived(BMessage *message) { // Print the message to see its contents //message->PrintToStream(); switch ( message->what ) { case BUTTON_BUY: _jour->mainWin->PostMessage(BUTTON_BUY); break; case BUTTON_SET: _jour->mainWin->PostMessage(BUTTON_SET); break; case DRAW_INFO: i_view->UpdateCountryInfo(); _jour->mainWin->PostMessage(UPDATE_POWER_BAR); break; default: // Call inherited if we didn't handle the message BWindow::MessageReceived(message); }//end switch }//fin message received
27.344828
143
0.728247
miqlas
837c978c5619ca42c2d34143f49c6a75fd2b61e3
741
hh
C++
src/dbus/audio_device_claim.hh
stanford-stagecast/pancake
e9cfd547edf2dd797f324b159252757190211ff2
[ "Apache-2.0" ]
2
2022-01-05T08:58:11.000Z
2022-01-06T05:33:14.000Z
src/dbus/audio_device_claim.hh
stanford-stagecast/pancake
e9cfd547edf2dd797f324b159252757190211ff2
[ "Apache-2.0" ]
null
null
null
src/dbus/audio_device_claim.hh
stanford-stagecast/pancake
e9cfd547edf2dd797f324b159252757190211ff2
[ "Apache-2.0" ]
null
null
null
#pragma once #include <dbus/dbus.h> #include <memory> #include <optional> #include <string> class AudioDeviceClaim { class DBusConnectionWrapper { struct DBusConnection_deleter { void operator()( DBusConnection* x ) const; }; std::unique_ptr<DBusConnection, DBusConnection_deleter> connection_; public: DBusConnectionWrapper( const DBusBusType type ); operator DBusConnection*(); }; DBusConnectionWrapper connection_; std::optional<std::string> claimed_from_ {}; public: AudioDeviceClaim( const std::string_view name ); const std::optional<std::string>& claimed_from() const { return claimed_from_; } static std::optional<AudioDeviceClaim> try_claim( const std::string_view name ); };
21.794118
82
0.727395
stanford-stagecast
837f9c9108b86a525eb948d2d41d6ccc55ab9ab2
3,680
cpp
C++
Chapter11/blackjack/blackjackold.cpp
Rayyan06/CPP
daeededda19a0d9766115a700dd949d92dfa4963
[ "MIT" ]
1
2021-04-12T17:01:58.000Z
2021-04-12T17:01:58.000Z
Chapter11/blackjack/blackjackold.cpp
Rayyan06/CPP
daeededda19a0d9766115a700dd949d92dfa4963
[ "MIT" ]
null
null
null
Chapter11/blackjack/blackjackold.cpp
Rayyan06/CPP
daeededda19a0d9766115a700dd949d92dfa4963
[ "MIT" ]
null
null
null
#include <iostream> #include.mf struct Card { CardRank rank{}; CardSuit suit{}; }; struct Player { int score{}; }; using deck_type = std::array<Card, 52>; using index_type = deck_type::size_type; // Maximum score before losing. constexpr int maximumScore{ 21 }; // Minium score that the dealer has to have. constexpr int minimumDealerScore{ 17 }; void printCard(const Card& card) { switch (card.rank) { case CardRank::RANK_2: std::cout << '2'; break; case CardRank::RANK_3: std::cout << '3'; break; case CardRank::RANK_4: std::cout << '4'; break; case CardRank::RANK_5: std::cout << '5'; break; case CardRank::RANK_6: std::cout << '6'; break; case CardRank::RANK_7: std::cout << '7'; break; case CardRank::RANK_8: std::cout << '8'; break; case CardRank::RANK_9: std::cout << '9'; break; case CardRank::RANK_10: std::cout << 'T'; break; case CardRank::RANK_JACK: std::cout << 'J'; break; case CardRank::RANK_QUEEN: std::cout << 'Q'; break; case CardRank::RANK_KING: std::cout << 'K'; break; case CardRank::RANK_ACE: std::cout << 'A'; break; default: std::cout << '?'; break; } switch (card.suit) { case CardSuit::SUIT_CLUB: std::cout << 'C'; break; case CardSuit::SUIT_DIAMOND: std::cout << 'D'; break; case CardSuit::SUIT_HEART: std::cout << 'H'; break; case CardSuit::SUIT_SPADE: std::cout << 'S'; break; default: std::cout << '?'; break; } } int getCardValue(const Card& card) { if (card.rank <= CardRank::RANK_10) { return (static_cast<int>(card.rank) + 2); } switch (card.rank) { case CardRank::RANK_JACK: case CardRank::RANK_QUEEN: case CardRank::RANK_KING: return 10; case CardRank::RANK_ACE: return 11; default: assert(false && "should never happen"); return 0; } } void printDeck(const deck_type& deck) { for (const auto& card : deck) { printCard(card); std::cout << ' '; } std::cout << '\n'; } deck_type createDeck() { deck_type deck{}; index_type card{ 0 }; auto suits{ static_cast<index_type>(CardSuit::MAX_SUITS) }; auto ranks{ static_cast<index_type>(CardRank::MAX_RANKS) }; for (index_type suit{ 0 }; suit < suits; ++suit) { for (index_type rank{ 0 }; rank < ranks; ++rank) { deck[card].suit = static_cast<CardSuit>(suit); deck[card].rank = static_cast<CardRank>(rank); ++card; } } return deck; } void shuffleDeck(deck_type& deck) { static std::mt19937 mt{ static_cast<std::mt19937::result_type>(std::time(nullptr)) }; std::shuffle(deck.begin(), deck.end(), mt); } bool playerWantsHit() { while (true) { std::cout << "(h) to hit, or (s) to stand: "; char ch{}; std::cin >> ch; switch (ch) { case 'h': return true; case 's': return false; } } } bool playBlackjack(const deck_type& deck) { index_type nextCardIndex{ 0 }; Player dealer{ getCardValue(deck[nextCardIndex++]) }; std::cout << "The dealer is showing: " << dealer.score << '\n'; Player player{ getCardValue(deck[nextCardIndex]) + getCardValue(deck[nextCardIndex + 1]) }; nextCardIndex += 2; if (playerTurn(deck, nextCardIndex, player)) { return false; } if (dealerTurn(deck, nextCardIndex, dealer)) { return true; } return (player.score > dealer.score); } int main() { auto deck{ createDeck() }; shuffleDeck(deck); if (playBlackjack(deck)) { std::cout << "You win!\n"; } else { std::cout << "You lose!\n"; } return 0; }
17.196262
93
0.589674
Rayyan06
838049378fe0c1c2c357791c878b045183663e12
3,922
cpp
C++
Lab6/Lab6.cpp
DimanStrelok/Labs_Programming
7b87bc7d1c3f446afd86adbb8b8b3ab4d751fd3a
[ "MIT" ]
null
null
null
Lab6/Lab6.cpp
DimanStrelok/Labs_Programming
7b87bc7d1c3f446afd86adbb8b8b3ab4d751fd3a
[ "MIT" ]
null
null
null
Lab6/Lab6.cpp
DimanStrelok/Labs_Programming
7b87bc7d1c3f446afd86adbb8b8b3ab4d751fd3a
[ "MIT" ]
null
null
null
#include <string> #include <locale> #include <iostream> #include <vector> enum class Gender { Man = 0, Women }; struct Employee { int t_num; std::string name; int salary; std::string post; Gender gender; friend std::ostream& operator<<(std::ostream& os, const Employee& employee) { os << "Номер: " << employee.t_num << "; " << "ФИО: " << employee.name << "; " << "Оклад: " << employee.salary << "; " << "Должность: " << employee.post << "; "; if (employee.gender == Gender::Man) { os << "Пол: Мужчина" << "."; } else { os << "Пол: Женщина" << "."; } return os; } friend std::istream& operator>>(std::istream& is, Employee& employee) { is >> employee.t_num; is >> employee.name; // std::getline(is >> std::ws, employee.name); is >> employee.salary; is >> employee.post; std::string str; is >> str; if (str == "Мужчина") { employee.gender = Gender::Man; } else { employee.gender = Gender::Women; } return is; } }; int sum_salary(const std::vector<Employee>& employees) { int res = 0; for (const Employee& employee : employees) { res += employee.salary; } return res; } int sum_m(const std::vector<Employee>& employees) { int res = 0; for (const Employee& employee : employees) { if (employee.gender == Gender::Man) { res++; } } return res; } int sum_f(const std::vector<Employee>& employees) { int res = 0; for (const Employee& employee : employees) { if (employee.gender == Gender::Women) { res++; } } return res; } int sum_salary_m(const std::vector<Employee>& employees) { int res = 0; for (const Employee& employee : employees) { if (employee.gender == Gender::Man) { res += employee.salary; } } return res; } int sum_salary_f(const std::vector<Employee>& employees) { int res = 0; for (const Employee& employee : employees) { if (employee.gender == Gender::Women) { res += employee.salary; } } return res; } std::vector<Employee> enterEmployees() { std::vector<Employee> res; std::cout << "Введите кол-во работников" << std::endl; int n = 0; std::cin >> n; for (int i = 0; i < n; i++) { Employee temp; std::cin >> temp; res.push_back(temp); } return res; } void printEmployees(const std::vector<Employee>& employees) { std::cout << "Список" << std::endl; for (const Employee& employee : employees) { std::cout << employee << std::endl; } } // Type 1 /* 4 1 Вася 15500 Грузчик Мужчина 2 Катя 25000 Менеджер Женщина 3 Саня 35000 Программист Мужчина 4 Даша 15000 Кассир Женщина */ // Type 2 /* 4 1 Вася Пупкин 15500 Грузчик Мужчина 2 Катя Печкина 25000 Менеджер Женщина 3 Саня Петров 35000 Программист Мужчина 4 Даша Ельцина 15000 Кассир Женщина */ int main() { std::locale::global(std::locale("")); // Test std::vector<Employee> employees1 = { {1, "Вася", 5500, "Грузчик", Gender::Man}, {2, "Петя", 7500, "Строитель", Gender::Women}, {3, "Катя", 13000, "Менеджер", Gender::Man}, {4, "Даша", 25000, "Руководитель", Gender::Women} }; std::vector<Employee> employees = enterEmployees(); printEmployees(employees); std::cout << "Сумма окладов: " << sum_salary(employees) << std::endl; std::cout << "Кол-во мужчин: " << sum_m(employees) << std::endl; std::cout << "Кол-во женщин: " << sum_f(employees) << std::endl; std::cout << "Сумма окладов мужчин: " << sum_salary_m(employees) << std::endl; std::cout << "Сумма окладов женщин: " << sum_salary_f(employees) << std::endl; return 0; }
25.467532
82
0.556604
DimanStrelok
8b52227fe6e5a7028a3778fa31853daa6e2d4f87
2,968
hpp
C++
Engine/Src/Runtime/Core/Public/Core/Utility/MemoryUtil.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Utility/MemoryUtil.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Utility/MemoryUtil.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
#pragma once #include <Core/CoreApi.hpp> #include <xmemory> namespace Fade { template <typename ValueType> struct TDefaultAllocator : public std::allocator<ValueType> { }; // Default deleter for TUniquePtr template <typename ValueType> struct TDefaultDelete { /* * Default constructor */ constexpr TDefaultDelete() noexcept = default; /* * Copy constructor */ constexpr TDefaultDelete(const TDefaultDelete&) noexcept = default; /* * Destructor */ ~TDefaultDelete() = default; /* * Copy assignment */ TDefaultDelete& operator=(const TDefaultDelete&) noexcept = default; /* * Copy constructor for default deleter with other value type * Note this constructor is only available if our value type pointer and the other value type pointer are convertible */ template < typename OtherType, typename = typename TEnableIf<TIsConvertible<ValueType*, OtherType*>::sm_Value>::TType > TDefaultDelete(const TDefaultDelete<OtherType>&) noexcept {} /* * Parenthesis operator, takes pointer as parameter that will be deleted */ void operator()(ValueType* a_Ptr) const noexcept { static_assert(0 < sizeof(ValueType), "Size of ValueType is 0, \ Unable to delete an incomplete type"); delete a_Ptr; } }; // Default array deleter for TUniquePtr template <typename ValueType> struct TDefaultDelete<ValueType[]> { /* * Default constructor */ constexpr TDefaultDelete() noexcept = default; /* * Copy constructor */ constexpr TDefaultDelete(const TDefaultDelete&) noexcept = default; /* * Destructor */ ~TDefaultDelete() = default; /* * Copy assignment */ TDefaultDelete& operator=(const TDefaultDelete&) noexcept = default; /* * Copy constructor for default deleter with other value type * Note this constructor is only available if our value type and the other value type are convertible */ template < typename OtherType, typename = typename TEnableIf<TIsConvertible<OtherType(*)[], ValueType(*)[]>::sm_Value>::TType > TDefaultDelete(const TDefaultDelete<OtherType[]>&) noexcept {} /* * Parenthesis operator * Note this function is only available if the pointers to arrays of our value type and the other value type are convertible */ template < typename OtherType, // OtherType(*)[] and ValueType(*)[] are pointers-to-an-array typename = typename TEnableIf<TIsConvertible<OtherType(*)[], ValueType(*)[]>::sm_Value>::TType > void operator()(OtherType* a_Ptr) const noexcept { static_assert(0 < sizeof(OtherType), "Size of OtherType is 0, \ Unable to delete an incomplete type"); delete[] a_Ptr; } }; template <class First, class Last> void DestroyRange(First a_First, Last a_Last) noexcept; template <class Type> void DestroyInPlace(Type& a_Object) noexcept { if constexpr (TIsArray<Type>::sm_Value) { } else { a_Object.~Type(); } } template <class First, class Last> void DestroyRange(First a_First, Last a_Last) noexcept { } }
21.823529
125
0.718666
Septus10
8b5310ad5681d532f18b6ad821bcc9ee5a15820d
1,100
cpp
C++
p_euler_78.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
p_euler_78.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
p_euler_78.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define f first #define s second #define ll long long #define pb push_back #define mp make_pair #define inp(x) cin>>x #define print(x) cout<<x #define pii pair<int,int> #define pll pair<ll,ll> #define gcd(a,b) __gcd(a,b) #define reset(d,val) memset(d,val,sizeof(d)) #define sort(v) sort(v.begin(),v.end()) #define sort_arr(arr,i,f) sort(arr+i,arr+f) #define pq priority_queue<int,vector<int>,greater<int> > #define pq1 priority_queue<pll,vector<pll>,greater<pll> > const int mod = 1e9+7; ll x = 1e6; int n,m; ll dp[10000][10000]; //int arr[] = {1,2,3,4,5}; ll f(int i,int j){ if(j>m) return i==n; if(i==n) return 1; if(dp[i][j]!=-1) return dp[i][j]; ll ans = 0; if(i+j<=n) { ans = f(i+j,j); //ans += f(i+arr[j],j+1); } ans += f(i,j+1); ans = (ans+x)%x; return dp[i][j]=ans%x; } int main(int argc, char const *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); for (int i = 1; i <10000 ; ++i) { memset(dp,-1,sizeof(dp)); n=i,m=i; cout<<f(0,1)%x<<endl; } return 0; }
20.754717
58
0.590909
Krshivam
8b5565050574954ea78c8f6dd31e9784dba7eb4d
6,840
cpp
C++
TongueQT/TongueQT/src/Vega/libraries/corotationalLinearFEM/corotationalLinearFEMMT.cpp
lrkk1234/TongueSimulation
347cf38452aa62d1173da1c4935f691456255e46
[ "MIT" ]
2
2020-03-28T03:15:49.000Z
2020-09-09T02:54:33.000Z
TongueQT/TongueQT/src/Vega/libraries/corotationalLinearFEM/corotationalLinearFEMMT.cpp
lrkk1234/TongueSimulation
347cf38452aa62d1173da1c4935f691456255e46
[ "MIT" ]
null
null
null
TongueQT/TongueQT/src/Vega/libraries/corotationalLinearFEM/corotationalLinearFEMMT.cpp
lrkk1234/TongueSimulation
347cf38452aa62d1173da1c4935f691456255e46
[ "MIT" ]
2
2020-09-08T19:28:19.000Z
2021-07-25T00:35:26.000Z
/************************************************************************* * * * Vega FEM Simulation Library Version 2.2 * * * * "corotational linear FEM" library , Copyright (C) 2015 USC * * All rights reserved. * * * * Code author: Jernej Barbic * * http://www.jernejbarbic.com/code * * * * Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * * LICENSE.TXT for more details. * * * *************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <pthread.h> #include <vector> #include <set> #include "macros.h" #include "corotationalLinearFEMMT.h" using namespace std; CorotationalLinearFEMMT::CorotationalLinearFEMMT(TetMesh * tetMesh, int numThreads_) : CorotationalLinearFEM(tetMesh), numThreads(numThreads_) { if(numThreads < 1) numThreads = 1; Initialize(); } CorotationalLinearFEMMT::~CorotationalLinearFEMMT() { free(startElement); free(endElement); free(internalForceBuffer); for(int i=0; i<numThreads; i++) delete(stiffnessMatrixBuffer[i]); free(stiffnessMatrixBuffer); } struct CorotationalLinearFEMMT_threadArg { CorotationalLinearFEMMT * corotationalLinearFEMMT; double * u; double * f; SparseMatrix * stiffnessMatrix; int warp; int rank; }; void * CorotationalLinearFEMMT_WorkerThread(void * arg) { struct CorotationalLinearFEMMT_threadArg * threadArgp = (struct CorotationalLinearFEMMT_threadArg*) arg; CorotationalLinearFEMMT * corotationalLinearFEMMT = threadArgp->corotationalLinearFEMMT; double * u = threadArgp->u; double * f = threadArgp->f; SparseMatrix * stiffnessMatrix = threadArgp->stiffnessMatrix; int warp = threadArgp->warp; int rank = threadArgp->rank; int startElement = corotationalLinearFEMMT->GetStartElement(rank); int endElement = corotationalLinearFEMMT->GetEndElement(rank); //printf("%d %d\n", startElement, endElement); corotationalLinearFEMMT->ComputeForceAndStiffnessMatrixOfSubmesh(u, f, stiffnessMatrix, warp, startElement, endElement); return NULL; } void CorotationalLinearFEMMT::Initialize() { internalForceBuffer = (double*) malloc (sizeof(double) * numThreads * 3 * tetMesh->getNumVertices()); // generate skeleton matrices stiffnessMatrixBuffer = (SparseMatrix**) malloc (sizeof(SparseMatrix*) * numThreads); SparseMatrix * sparseMatrix; GetStiffnessMatrixTopology(&sparseMatrix); stiffnessMatrixBuffer[0] = sparseMatrix; for(int i=1; i<numThreads; i++) stiffnessMatrixBuffer[i] = new SparseMatrix(*sparseMatrix); // split the workload int numElements = tetMesh->getNumElements(); startElement = (int*) malloc (sizeof(int) * numThreads); endElement = (int*) malloc (sizeof(int) * numThreads); int remainder = numElements % numThreads; // the first 'remainder' nodes will process one edge more int jobSize = numElements / numThreads; for(int rank=0; rank < numThreads; rank++) { if (rank < remainder) { startElement[rank] = rank * (jobSize+1); endElement[rank] = (rank+1) * (jobSize+1); } else { startElement[rank] = remainder * (jobSize+1) + (rank-remainder) * jobSize; endElement[rank] = remainder * (jobSize+1) + ((rank-remainder)+1) * jobSize; } } //printf("Total elements: %d \n", numElements); //printf("Num threads: %d \n", numThreads); //printf("Canonical job size: %d \n", jobSize); //printf("Num threads with job size augmented by one edge: %d \n", remainder); } void CorotationalLinearFEMMT::ComputeForceAndStiffnessMatrix(double * u, double * f, SparseMatrix * stiffnessMatrix, int warp) { // launch threads struct CorotationalLinearFEMMT_threadArg * threadArgv = (struct CorotationalLinearFEMMT_threadArg*) malloc (sizeof(struct CorotationalLinearFEMMT_threadArg) * numThreads); pthread_t * tid = (pthread_t*) malloc (sizeof(pthread_t) * numThreads); int numVertices3 = 3 * tetMesh->getNumVertices(); for(int i=0; i<numThreads; i++) { threadArgv[i].corotationalLinearFEMMT = this; threadArgv[i].u = u; threadArgv[i].f = &internalForceBuffer[i * numVertices3]; threadArgv[i].stiffnessMatrix = stiffnessMatrixBuffer[i]; threadArgv[i].warp = warp; threadArgv[i].rank = i; } for(int i=0; i<numThreads; i++) { if (pthread_create(&tid[i], NULL, CorotationalLinearFEMMT_WorkerThread, &threadArgv[i]) != 0) { printf("Error: unable to launch thread %d.\n", i); exit(1); } } for(int i=0; i<numThreads; i++) { if (pthread_join(tid[i], NULL) != 0) { printf("Error: unable to join thread %d.\n", i); exit(1); } } free(threadArgv); free(tid); if (f != NULL) memset(f, 0, sizeof(double) * numVertices3); if (stiffnessMatrix != NULL) { stiffnessMatrix->ResetToZero(); for(int i=0; i<numThreads; i++) { double * source = &internalForceBuffer[i * numVertices3]; if (f != NULL) { for(int j=0; j<numVertices3; j++) f[j] += source[j]; } *stiffnessMatrix += *(stiffnessMatrixBuffer[i]); } } } int CorotationalLinearFEMMT::GetStartElement(int rank) { return startElement[rank]; } int CorotationalLinearFEMMT::GetEndElement(int rank) { return endElement[rank]; }
34.545455
173
0.580848
lrkk1234
8b5a7f74dfe34b65674f2451b8947016be1935da
7,664
cpp
C++
test/src/trajectory_generator_test.cpp
kohonda/state_lattice_planner
3368f222d0296c6325673027f9c59989b8783733
[ "BSD-3-Clause" ]
79
2019-05-31T14:57:32.000Z
2022-03-26T13:49:33.000Z
test/src/trajectory_generator_test.cpp
lucianzhong/state_lattice_planner
21da9743ad56f58e68dd7bb651c16c2dde57294c
[ "BSD-3-Clause" ]
17
2019-04-18T06:48:16.000Z
2022-02-01T02:09:11.000Z
test/src/trajectory_generator_test.cpp
lucianzhong/state_lattice_planner
21da9743ad56f58e68dd7bb651c16c2dde57294c
[ "BSD-3-Clause" ]
33
2019-10-29T07:17:03.000Z
2022-02-18T06:12:58.000Z
#include <gtest/gtest.h> #include "trajectory_generator/motion_model_diff_drive.h" #include "trajectory_generator/trajectory_generator_diff_drive.h" TEST(MotionModelTest, Interpolation) { MotionModelDiffDrive::AngularVelocityParams omega(0, 0.5, 1.0, 5); omega.calculate_spline(); MotionModelDiffDrive mm; double cf = mm.calculate_cubic_function(0, omega.coefficients[0]); EXPECT_NEAR(0, cf, 0.01); cf = mm.calculate_cubic_function(2.5, omega.coefficients[0]); EXPECT_NEAR(0.5, cf, 0.01); cf = mm.calculate_cubic_function(2.5, omega.coefficients[1]); EXPECT_NEAR(0.5, cf, 0.01); cf = mm.calculate_cubic_function(5, omega.coefficients[1]); EXPECT_NEAR(1.0, cf, 0.01); } TEST(MotionModelTest, Interpolation2) { MotionModelDiffDrive::AngularVelocityParams omega(0, -0.5, -1.0, 10); omega.calculate_spline(); MotionModelDiffDrive mm; double cf = mm.calculate_cubic_function(0, omega.coefficients[0]); EXPECT_NEAR(0, cf, 0.01); cf = mm.calculate_cubic_function(5, omega.coefficients[0]); EXPECT_NEAR(-0.5, cf, 0.01); cf = mm.calculate_cubic_function(5, omega.coefficients[1]); EXPECT_NEAR(-0.5, cf, 0.01); cf = mm.calculate_cubic_function(10, omega.coefficients[1]); EXPECT_NEAR(-1.0, cf, 0.01); } TEST(MotionModelTest, GenerateTrajectory) { MotionModelDiffDrive mm; MotionModelDiffDrive::VelocityParams vel(0.5, 0.5, 1.0, 0.5, 0.5); MotionModelDiffDrive::AngularVelocityParams omega(0.0, 0.0, 0.0, 5); MotionModelDiffDrive::Trajectory trajectory; mm.generate_trajectory(0.01, MotionModelDiffDrive::ControlParams(vel, omega), trajectory); EXPECT_NEAR(5, trajectory.trajectory.back()(0), 0.05); EXPECT_NEAR(0, trajectory.trajectory.back()(1), 0.05); EXPECT_NEAR(0, trajectory.trajectory.back()(2), 0.05); } TEST(TrajectoryGeneratorFunctionTest, GenerateOptimizedTrajectory) { TrajectoryGeneratorDiffDrive tg; MotionModelDiffDrive::ControlParams output; MotionModelDiffDrive::VelocityParams init_v(0.0, 0.5, 1.0, 0.5, 0.5); MotionModelDiffDrive::ControlParams init_params(init_v, MotionModelDiffDrive::AngularVelocityParams(0, 0, 0.5, 5)); Eigen::Vector3d goal(5, 1, 1); MotionModelDiffDrive::Trajectory trajectory; std::cout << "generate optimized trajectory" << std::endl; double cost = tg.generate_optimized_trajectory(goal, init_params, 0.05, 1e-1, 5, output, trajectory); std::cout << "trajecotry.back():" << std::endl; std::cout << trajectory.trajectory.back() << std::endl; std::cout << "cost: " << cost << std::endl; for(auto vel : trajectory.velocities){ std::cout << vel << "[m/s]" << std::endl; } EXPECT_NEAR(5, trajectory.trajectory.back()(0), 0.1); EXPECT_NEAR(1, trajectory.trajectory.back()(1), 0.1); EXPECT_NEAR(1, trajectory.trajectory.back()(2), 0.05); EXPECT_GT(cost, 0);// cost > 0 } TEST(TrajectoryGeneratorFunctionTest, GenerateNotOptimizedTrajectory) { Eigen::Vector3d goal(1, 2, -1.0472); TrajectoryGeneratorDiffDrive tg; tg.set_motion_param(1.0, 2.0, 1.0, 11.6, 0.125, 0.5); MotionModelDiffDrive::ControlParams output; MotionModelDiffDrive::VelocityParams init_v(0.0, 1.0, 0.8, 0.8, 1.0); MotionModelDiffDrive::ControlParams init_params(init_v, MotionModelDiffDrive::AngularVelocityParams(-0.8, 0, 0, goal.segment(0, 2).norm())); MotionModelDiffDrive::Trajectory trajectory; std::cout << "generate optimized trajectory" << std::endl; double cost = tg.generate_optimized_trajectory(goal, init_params, 1e-1, 1e-1, 100, output, trajectory); std::cout << "trajecotry.back():" << std::endl; std::cout << trajectory.trajectory.back() << std::endl; std::cout << "cost: " << cost << std::endl; // expect failure EXPECT_LT(cost, 0);// cost > 0 } // negative value test TEST(MotionModelTest, InterpolationBack) { MotionModelDiffDrive::AngularVelocityParams omega(0, 0.5, 1.0, -5); omega.calculate_spline(); MotionModelDiffDrive mm; double cf = mm.calculate_cubic_function(0, omega.coefficients[0]); EXPECT_NEAR(0, cf, 0.01); cf = mm.calculate_cubic_function(-2.5, omega.coefficients[0]); EXPECT_NEAR(0.5, cf, 0.01); cf = mm.calculate_cubic_function(-2.5, omega.coefficients[1]); EXPECT_NEAR(0.5, cf, 0.01); cf = mm.calculate_cubic_function(-5, omega.coefficients[1]); EXPECT_NEAR(1.0, cf, 0.01); } TEST(MotionModelTest, GeenrateTrajectoryToBack) { MotionModelDiffDrive mm; MotionModelDiffDrive::VelocityParams vel(0.0, 0.5, -0.5, 0.0, 0.5); MotionModelDiffDrive::AngularVelocityParams omega(0.0, 0.0, 0.0, -5); MotionModelDiffDrive::Trajectory trajectory; mm.generate_trajectory(0.1, MotionModelDiffDrive::ControlParams(vel, omega), trajectory); EXPECT_NEAR(-5, trajectory.trajectory.back()(0), 0.05); EXPECT_NEAR(0, trajectory.trajectory.back()(1), 0.05); EXPECT_NEAR(0, trajectory.trajectory.back()(2), 0.05); } TEST(TrajectoryGeneratorFunctionTest, GenerateOptimizedTrajectoryToBack) { TrajectoryGeneratorDiffDrive tg; MotionModelDiffDrive::ControlParams output; MotionModelDiffDrive::VelocityParams init_v(0.0, 0.5, -1.0, 0.0, 0.5); Eigen::Vector3d goal(-5, 1, -0.5); MotionModelDiffDrive::ControlParams init_params(init_v, MotionModelDiffDrive::AngularVelocityParams(0, 0, 0, goal.segment(0, 2).norm())); MotionModelDiffDrive::Trajectory trajectory; std::cout << "generate optimized trajectory" << std::endl; double cost = tg.generate_optimized_trajectory(goal, init_params, 0.05, 1e-1, 5, output, trajectory); std::cout << "trajecotry.back():" << std::endl; std::cout << trajectory.trajectory.back() << std::endl; std::cout << "cost: " << cost << std::endl; for(auto vel : trajectory.velocities){ std::cout << vel << "[m/s]" << std::endl; } EXPECT_NEAR(goal(0), trajectory.trajectory.back()(0), 0.1); EXPECT_NEAR(goal(1), trajectory.trajectory.back()(1), 0.1); EXPECT_NEAR(goal(2), trajectory.trajectory.back()(2), 0.05); EXPECT_GT(cost, 0);// cost > 0 } // sharp curve test TEST(TrajectoryGeneratorFunctionTest, GenerateOptimizedTrajectoryWithSharpCurve) { TrajectoryGeneratorDiffDrive tg; tg.set_motion_param(1.0, 2.0, 1.0, 11.6, 0.125, 0.5); MotionModelDiffDrive::ControlParams output; MotionModelDiffDrive::VelocityParams init_v(0.0, 1.0, 1.0, 0.0, 1.0); Eigen::Vector3d goal(0.5, 5, M_PI/2.0); std::cout << "goal: " << goal.transpose() << std::endl; MotionModelDiffDrive::ControlParams init_params(init_v, MotionModelDiffDrive::AngularVelocityParams(0.0, 0.5, 0.0, goal.segment(0, 2).norm())); MotionModelDiffDrive::Trajectory trajectory; std::cout << "generate optimized trajectory" << std::endl; double cost = tg.generate_optimized_trajectory(goal, init_params, 0.1, 1e-1, 100, output, trajectory); std::cout << "trajecotry.back():" << std::endl; std::cout << trajectory.trajectory.back() << std::endl; std::cout << "cost: " << cost << std::endl; int size = trajectory.trajectory.size(); for(int i=0;i<size;i++){ std::cout << i << ": " << trajectory.trajectory[i].transpose() << ", " << trajectory.velocities[i] << "[m/s], " << trajectory.angular_velocities[i] << "[rad/s]" << std::endl; } EXPECT_NEAR(goal(0), trajectory.trajectory.back()(0), 0.10); EXPECT_NEAR(goal(1), trajectory.trajectory.back()(1), 0.10); EXPECT_NEAR(goal(2), trajectory.trajectory.back()(2), 0.10); EXPECT_GT(cost, 0);// cost > 0 } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); int r_e_t = RUN_ALL_TESTS(); return r_e_t; }
43.794286
182
0.691284
kohonda
8b5d6f77b8af926c1d591243e707353a221beaa1
921
cpp
C++
MFC/MFCDemo/Curve.cpp
Johnny-Martin/Win32UI
570feb103bfda72063f13871b06326c6884cebd1
[ "MIT" ]
1
2021-02-13T18:10:51.000Z
2021-02-13T18:10:51.000Z
MFC/MFCDemo/Curve.cpp
Johnny-Martin/Win32UI
570feb103bfda72063f13871b06326c6884cebd1
[ "MIT" ]
null
null
null
MFC/MFCDemo/Curve.cpp
Johnny-Martin/Win32UI
570feb103bfda72063f13871b06326c6884cebd1
[ "MIT" ]
3
2018-01-28T05:55:00.000Z
2021-08-18T07:47:20.000Z
#include"stdafx.h" #include"Curve.h" using namespace BaseElement; Curve::Curve(CDC* pDC, int iMaxPointCount, int iLineWidth): m_vecPoints(), m_cursor(), m_iCursor(0), m_pen(PS_SOLID, 1, RGB(255, 0, 255)) { m_pDC = pDC; m_iMaxPointCount = iMaxPointCount; m_iLineWidth = iLineWidth; m_pDC->SelectObject(m_pen); } void Curve::AddNewPoint(int x, int y) { if (m_vecPoints.size() > 10240) return; m_vecPoints.push_back(std::pair<int, int>(x, y)); Draw(); } void Curve::Draw() { if (m_vecPoints.empty() || m_vecPoints.size() == 1) { return; } while (m_iCursor + 1 != m_vecPoints.size()) { std::pair<int, int> pointA = m_vecPoints[m_iCursor]; std::pair<int, int> pointB = m_vecPoints[++m_iCursor]; Draw(pointA, pointB); } } void Curve::Draw(std::pair<int, int> pointA, std::pair<int, int> pointB) { m_pDC->MoveTo(pointA.first, pointA.second); m_pDC->LineTo(pointB.first, pointB.second); }
18.795918
72
0.677524
Johnny-Martin
8b69b564a035f4d92a4cacd7c83d528a87d2396a
2,138
cc
C++
test/log/raw_logging_test.cc
Conun/abel
485ef38c917c0df3750242cc38966a2bcb163588
[ "BSD-3-Clause" ]
null
null
null
test/log/raw_logging_test.cc
Conun/abel
485ef38c917c0df3750242cc38966a2bcb163588
[ "BSD-3-Clause" ]
null
null
null
test/log/raw_logging_test.cc
Conun/abel
485ef38c917c0df3750242cc38966a2bcb163588
[ "BSD-3-Clause" ]
null
null
null
// // This test serves primarily as a compilation test for base/raw_logging.h. // Raw logging testing is covered by logging_unittest.cc, which is not as // portable as this test. #include <abel/log/raw_logging.h> #include <tuple> #include <gtest/gtest.h> #include <abel/strings/str_cat.h> namespace { TEST(RawLoggingCompilationTest, Log) { ABEL_RAW_LOG(INFO, "RAW INFO: %d", 1); ABEL_RAW_LOG(INFO, "RAW INFO: %d %d", 1, 2); ABEL_RAW_LOG(INFO, "RAW INFO: %d %d %d", 1, 2, 3); ABEL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d", 1, 2, 3, 4); ABEL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d %d", 1, 2, 3, 4, 5); ABEL_RAW_LOG(WARNING, "RAW WARNING: %d", 1); ABEL_RAW_LOG(ERROR, "RAW ERROR: %d", 1); } TEST(RawLoggingCompilationTest, PassingCheck) { ABEL_RAW_CHECK(true, "RAW CHECK"); } // Not all platforms support output from raw log, so we don't verify any // particular output for RAW check failures (expecting the empty string // accomplishes this). This test is primarily a compilation test, but we // are verifying process death when EXPECT_DEATH works for a platform. const char kExpectedDeathOutput[] = ""; TEST(RawLoggingDeathTest, FailingCheck) { EXPECT_DEATH_IF_SUPPORTED(ABEL_RAW_CHECK(1 == 0, "explanation"), kExpectedDeathOutput); } TEST(RawLoggingDeathTest, LogFatal) { EXPECT_DEATH_IF_SUPPORTED(ABEL_RAW_LOG(FATAL, "my dog has fleas"), kExpectedDeathOutput); } TEST(InternalLog, CompilationTest) { ABEL_INTERNAL_LOG(INFO, "Internal Log"); std::string log_msg = "Internal Log"; ABEL_INTERNAL_LOG(INFO, log_msg); ABEL_INTERNAL_LOG(INFO, log_msg + " 2"); float d = 1.1f; ABEL_INTERNAL_LOG(INFO, abel::string_cat("Internal log ", 3, " + ", d)); } TEST(InternalLogDeathTest, FailingCheck) { EXPECT_DEATH_IF_SUPPORTED(ABEL_INTERNAL_CHECK(1 == 0, "explanation"), kExpectedDeathOutput); } TEST(InternalLogDeathTest, LogFatal) { EXPECT_DEATH_IF_SUPPORTED(ABEL_INTERNAL_LOG(FATAL, "my dog has fleas"), kExpectedDeathOutput); } } // namespace
32.393939
76
0.67072
Conun
8b6b26c97a0681365b3c4da805626a38a5827daf
106
hpp
C++
include/netp/core/platform/osx_x86_.hpp
cainiaoDJ/netplus
03350d507830b3a39620374225d16c0b57623ef1
[ "MIT" ]
48
2021-02-22T03:10:40.000Z
2022-03-29T03:26:33.000Z
include/netp/core/platform/osx_x86_.hpp
cainiaoDJ/netplus
03350d507830b3a39620374225d16c0b57623ef1
[ "MIT" ]
7
2021-03-20T09:25:11.000Z
2022-03-07T03:26:56.000Z
include/netp/core/platform/osx_x86_.hpp
cainiaoDJ/netplus
03350d507830b3a39620374225d16c0b57623ef1
[ "MIT" ]
13
2021-02-25T01:49:58.000Z
2022-03-21T00:30:34.000Z
#ifndef _CORE_PLATFORM_NETP_PLATFORM_OSX_X86_HPP_ #define _CORE_PLATFORM_NETP_PLATFORM_OSX_X86_HPP_ #endif
35.333333
49
0.933962
cainiaoDJ
8b6c8271568be513899ec162dd37302bd78e1609
2,450
cpp
C++
operators (overload, week 4).cpp
snow482/cpp_white_belt
5218c122d69c081d0b00711f0223e6309689061e
[ "MIT" ]
1
2020-11-03T15:16:45.000Z
2020-11-03T15:16:45.000Z
operators (overload, week 4).cpp
snow482/cpp_white_belt
5218c122d69c081d0b00711f0223e6309689061e
[ "MIT" ]
null
null
null
operators (overload, week 4).cpp
snow482/cpp_white_belt
5218c122d69c081d0b00711f0223e6309689061e
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <string> #include <vector> using namespace std; /*using std::vector; using std::string; using std::cin; using std::cout; using std::endl; using std::istream; using std::ostream;*/ struct Duration{ int hour; int min; Duration(int h = 0, int m = 0){ int total_time = h * 60 + m; hour = total_time / 60; min = total_time % 60 ; } }; // ---------------------------------------------------------------------------------- // function for cin without overloading operators (with the same function body) /*Duration ReadDuration (istream& stream){ int h = 0; int m = 0; stream >> h; stream.ignore(1); stream >> m; return Duration {h, m}; }*/ // ---------------------------------------------------------------------------------- // creating overload operator ">>" // by scheme " istream& operator >> (istream& stream, Obj& obj) istream& operator >> (istream& stream, Duration& duration){ stream >> duration.hour; stream.ignore(1); stream >> duration.min; return stream; // returning the stream reference - is very important!!!! } // ---------------------------------------------------------------------------------- // function for cout without overloading operators (with the same function body) /*void PrintDuration(ostream& stream, const Duration& duration){ stream << setfill('0'); // stream << setw(2) << duration.hour << ':'; stream << setw(2) << duration.min; }*/ // ---------------------------------------------------------------------------------- ostream& operator << (ostream& stream, const Duration& duration){ stream << setfill('0'); // stream << setw(2) << duration.hour << ':'; stream << setw(2) << duration.min; return stream; // returning the stream reference - is very important!!!! } Duration operator + (const Duration& lhs, const Duration& rhs){ return Duration(lhs.hour + rhs.hour, lhs.min + rhs.min); } int main(){ stringstream dur_ss("13:14"); /*Duration dur1 = ReadDuration(dur_ss);*/ Duration dur1; // constructor for default time adding // dur_ss >> dur1; Duration dur2 = {0, 47}; /*PrintDuration(cout, dur1);*/ // without overloading operators cout << dur1 + dur2 << endl; cout << dur1 << endl; cout << dur1 << endl; //operator<<(operator<<(cout, "hello "), "world"); }
26.344086
85
0.538776
snow482
8b6f5316881822682e8f1dc4fc12d338b44e852a
3,204
hpp
C++
sketch/dense_transform_Mixed.hpp
xdata-skylark/libskylark
89c3736136a24d519c14fc0738c21f37f1e10360
[ "Apache-2.0" ]
86
2015-01-20T03:12:46.000Z
2022-01-10T04:05:21.000Z
sketch/dense_transform_Mixed.hpp
xdata-skylark/libskylark
89c3736136a24d519c14fc0738c21f37f1e10360
[ "Apache-2.0" ]
48
2015-05-12T09:31:23.000Z
2018-12-05T14:45:46.000Z
sketch/dense_transform_Mixed.hpp
xdata-skylark/libskylark
89c3736136a24d519c14fc0738c21f37f1e10360
[ "Apache-2.0" ]
25
2015-01-18T23:02:11.000Z
2021-06-12T07:30:35.000Z
#ifndef SKYLARK_DENSE_TRANSFORM_MIXED_HPP #define SKYLARK_DENSE_TRANSFORM_MIXED_HPP #include "../base/base.hpp" #include "transforms.hpp" #include "dense_transform_data.hpp" #include "../utility/get_communicator.hpp" #include "../base/sparse_vc_star_matrix.hpp" #include "sketch_params.hpp" namespace skylark { namespace sketch { /** * Specialization distributed input sparse_vc_star_matrix_t and output in [VC, *] */ template <typename ValueType, typename ValuesAccessor> struct dense_transform_t < base::sparse_vc_star_matrix_t<ValueType>, El::DistMatrix<ValueType, El::VC, El::STAR>, ValuesAccessor> : public dense_transform_data_t<ValuesAccessor> { // Typedef matrix and distribution types so that we can use them regularly typedef ValueType value_type; typedef base::sparse_vc_star_matrix_t<value_type> matrix_type; typedef El::DistMatrix<value_type, El::VC, El::STAR> output_matrix_type; typedef dense_transform_data_t<ValuesAccessor> data_type; /** * Regular constructor */ dense_transform_t (int N, int S, double scale, base::context_t& context) : data_type (N, S, scale, context), _local(*this) { } /** * Copy constructor */ dense_transform_t (dense_transform_t<matrix_type, output_matrix_type, ValuesAccessor>& other) : data_type(other), _local(other) {} /** * Constructor from data */ dense_transform_t(const data_type& other_data) : data_type(other_data), _local(other_data) {} /** * Apply the sketching transform that is described in by the sketch_of_A. */ template <typename Dimension> void apply (const matrix_type& A, output_matrix_type& sketch_of_A, Dimension dimension) const { try { apply_impl(A, sketch_of_A, dimension); } catch (std::logic_error e) { SKYLARK_THROW_EXCEPTION ( base::elemental_exception() << base::error_msg(e.what()) ); } catch(boost::mpi::exception e) { SKYLARK_THROW_EXCEPTION ( base::mpi_exception() << base::error_msg(e.what()) ); } } int get_N() const { return this->_N; } /**< Get input dimension. */ int get_S() const { return this->_S; } /**< Get output dimension. */ const sketch_transform_data_t* get_data() const { return this; } private: void apply_impl(const matrix_type& A, output_matrix_type& sketch_of_A, skylark::sketch::rowwise_tag tag) const { _local.apply(A.locked_matrix(), sketch_of_A.Matrix(), tag); } void apply_impl(const matrix_type& A, output_matrix_type& sketch_of_A, skylark::sketch::columnwise_tag) const { SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation()); } const dense_transform_t<base::sparse_matrix_t<ValueType>, El::Matrix<ValueType>, ValuesAccessor> _local; }; } } /** namespace skylark::sketch */ #endif // SKYLARK_DENSE_TRANSFORM_MIXED_HPP
30.226415
81
0.634831
xdata-skylark
8b8607ba08f78e6ced9c0c632589327bfd73706d
330
cpp
C++
CPP/CWE-477/3/bad.cpp
squinky86/FUBER
ee1382d01d589dd88d12ac1186c5e908acff240f
[ "ISC" ]
1
2021-06-17T23:05:37.000Z
2021-06-17T23:05:37.000Z
CPP/CWE-477/3/bad.cpp
squinky86/FUBER
ee1382d01d589dd88d12ac1186c5e908acff240f
[ "ISC" ]
null
null
null
CPP/CWE-477/3/bad.cpp
squinky86/FUBER
ee1382d01d589dd88d12ac1186c5e908acff240f
[ "ISC" ]
null
null
null
/* * Copyright © 2018, Jon Hood www.hoodsecurity.com * License: ISC */ #include <cstdlib> #include <iostream> #include <memory> using namespace std; int main(int argc, char *argv[]) { auto_ptr<int> p(new int); //auto_ptr deprecated by C++11 and removed in C++17 *p.get() = 1; cout << *p << endl; return EXIT_SUCCESS; }
16.5
78
0.657576
squinky86
8b88977a872c289ee6fce09a65fcf940f4291244
17,738
hpp
C++
include/utils/te.hpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
29
2021-11-19T11:28:22.000Z
2022-03-29T00:26:51.000Z
include/utils/te.hpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
null
null
null
include/utils/te.hpp
SakuraEngine/Sakura.Runtime
5a397fb2b1285326c4216f522fe10e347bd566f7
[ "MIT" ]
1
2022-03-05T08:14:40.000Z
2022-03-05T08:14:40.000Z
// // Copyright (c) 2018-2019 Kris Jusiak (kris at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #pragma once #if not defined(__cpp_variadic_templates) or \ not defined(__cpp_rvalue_references) or not defined(__cpp_decltype) or \ not defined(__cpp_alias_templates) or \ not defined(__cpp_generic_lambdas) or not defined(__cpp_constexpr) or \ not defined(__cpp_return_type_deduction) or \ not defined(__cpp_fold_expressions) or not defined(__cpp_static_assert) or \ not defined(__cpp_delegating_constructors) #error "[Boost].TE requires C++17 support" #else #include "platform/memory.h" #include <type_traits> #include <utility> #include <stdexcept> #include <memory> namespace boost { inline namespace ext { namespace te { inline namespace v1 { namespace detail { template <class...> struct type_list { }; template <class, std::size_t> struct mappings final { friend auto get(mappings); template <class T> struct set { friend auto get(mappings) { return T{}; } }; }; template <std::size_t, class...> constexpr std::size_t mappings_size_impl(...) { return {}; } template <std::size_t N, class T, class... Ts> constexpr auto mappings_size_impl(bool dummy) -> decltype(get(mappings<T, N>{}), std::size_t{}) { return 1 + mappings_size_impl<N + 1, T, Ts...>(dummy); } template <class... Ts> constexpr auto mappings_size() { return mappings_size_impl<1, Ts...>(bool{}); } template <class T, class = decltype(sizeof(T))> std::true_type is_complete_impl(bool); template <class> std::false_type is_complete_impl(...); template <class T> struct is_complete : decltype(is_complete_impl<T>(bool{})) { }; template <class T> constexpr auto requires__(bool) -> decltype(std::declval<T>().template requires__<T>()); template <class> constexpr auto requires__(...) -> void; template <class TExpr> class expr_wrapper final { static_assert(std::is_empty<TExpr>{}); public: template <class... Ts> decltype(auto) operator()(Ts&&... args) const { return reinterpret_cast<const TExpr&>(*this)(std::forward<Ts>(args)...); } }; /*! Same as std::exchange() but is guaranteed constexpr !*/ template <class T, class U> constexpr inline T exchange(T& obj, U&& new_value) noexcept( std::is_nothrow_move_constructible<T>::value&& std::is_nothrow_assignable<T&, U>::value) { T old_value = std::move(obj); obj = std::forward<U>(new_value); return old_value; } } // namespace detail struct non_owning_storage { template < class T, class T_ = std::decay_t<T>, std::enable_if_t<!std::is_same_v<T_, non_owning_storage>, bool> = true> constexpr explicit non_owning_storage(T&& t) noexcept : ptr{ &t } { } void* ptr = nullptr; }; struct shared_storage { template < class T, class T_ = std::decay_t<T>, std::enable_if_t<!std::is_same_v<T_, shared_storage>, bool> = true> constexpr explicit shared_storage(T&& t) noexcept(noexcept(std::make_shared<T_>(std::forward<T>(t)))) : ptr{ std::make_shared<T_>(std::forward<T>(t)) } { } std::shared_ptr<void> ptr; }; struct dynamic_storage { template < class T, class T_ = std::decay_t<T>, std::enable_if_t<!std::is_same_v<T_, dynamic_storage>, bool> = true> constexpr explicit dynamic_storage(T&& t) noexcept(noexcept(SkrNew<T_>(std::forward<T>(t)))) : ptr{ SkrNew<T_>(std::forward<T>(t)) } , del{ [](void* self) { delete reinterpret_cast<T_*>(self); } } , copy{ [](const void* self) -> void* { if constexpr (std::is_copy_constructible_v<T_>) return SkrNew<T_>(*reinterpret_cast<const T_*>(self)); else throw std::runtime_error("dynamic_storage : erased type is not copy constructible"); } } { } constexpr dynamic_storage(const dynamic_storage& other) : ptr{ other.ptr ? other.copy(other.ptr) : nullptr } , del{ other.del } , copy{ other.copy } { } constexpr dynamic_storage& operator=(const dynamic_storage& other) { if (other.ptr != ptr) { reset(); ptr = other.ptr ? other.copy(other.ptr) : nullptr; del = other.del; copy = other.copy; } return *this; } constexpr dynamic_storage(dynamic_storage&& other) noexcept : ptr{ detail::exchange(other.ptr, nullptr) } , del{ detail::exchange(other.del, nullptr) } , copy{ detail::exchange(other.copy, nullptr) } { } constexpr dynamic_storage& operator=(dynamic_storage&& other) noexcept { if (other.ptr != ptr) { reset(); ptr = detail::exchange(other.ptr, nullptr); del = detail::exchange(other.del, nullptr); copy = detail::exchange(other.copy, nullptr); } return *this; } ~dynamic_storage() { reset(); } constexpr void reset() noexcept { if (ptr) del(ptr); ptr = nullptr; } void* ptr = nullptr; void (*del)(void*) = nullptr; void* (*copy)(const void*) = nullptr; }; template <std::size_t Size, std::size_t Alignment = 8> struct local_storage { template < class T, class T_ = std::decay_t<T>, std::enable_if_t<!std::is_same_v<T_, local_storage>, bool> = true> constexpr explicit local_storage(T&& t) noexcept(noexcept(new (&data) T_{ std::forward<T>(t) })) : ptr{ new (&data) T_{ std::forward<T>(t) } } , del{ [](void* mem) { reinterpret_cast<T_*>(mem)->~T_(); } } , copy{ [](const void* self, void* mem) -> void* { if constexpr (std::is_copy_constructible_v<T_>) return new (mem) T_{ *reinterpret_cast<const T_*>(self) }; else throw std::runtime_error("local_storage : erased type is not copy constructible"); } } , move{ [](void* self, void* mem) -> void* { if constexpr (std::is_move_constructible_v<T_>) return new (mem) T_{ std::move(*reinterpret_cast<T_*>(self)) }; else throw std::runtime_error("local_storage : erased type is not move constructible"); } } { static_assert(sizeof(T_) <= Size, "insufficient size"); static_assert(Alignment % alignof(T_) == 0, "bad alignment"); } constexpr local_storage(const local_storage& other) : ptr{ other.ptr ? other.copy(other.ptr, &data) : nullptr } , del{ other.del } , copy{ other.copy } , move{ other.move } { } constexpr local_storage& operator=(const local_storage& other) { if (other.ptr != ptr) { reset(); ptr = other.ptr ? other.copy(other.ptr, &data) : nullptr; del = other.del; copy = other.copy; move = other.move; } return *this; } constexpr local_storage(local_storage&& other) : ptr{ other.ptr ? other.move(other.ptr, &data) : nullptr } , del{ other.del } , copy{ other.copy } , move{ other.move } { } constexpr local_storage& operator=(local_storage&& other) { if (other.ptr != ptr) { reset(); ptr = other.ptr ? other.move(other.ptr, &data) : nullptr; del = other.del; copy = other.copy; move = other.move; } return *this; } ~local_storage() { reset(); } constexpr void reset() noexcept { if (ptr) del(&data); ptr = nullptr; } std::aligned_storage_t<Size, Alignment> data; void* ptr = nullptr; void (*del)(void*) = nullptr; void* (*copy)(const void*, void* mem) = nullptr; void* (*move)(void*, void* mem) = nullptr; }; template <std::size_t Size, std::size_t Alignment = 8> struct sbo_storage { template <typename T_> struct type_fits : std::integral_constant<bool, sizeof(T_) <= Size && Alignment % alignof(T_) == 0> { }; template < class T, class T_ = std::decay_t<T>, std::enable_if_t<!std::is_same_v<T_, sbo_storage>, bool> = true, std::enable_if_t<type_fits<T_>::value, bool> = true> constexpr explicit sbo_storage(T&& t) noexcept(noexcept(new (&data) T_{ std::forward<T>(t) })) : ptr{ new (&data) T_{ std::forward<T>(t) } } , del{ [](void*, void* mem) { reinterpret_cast<T_*>(mem)->~T_(); } } , copy{ [](const void* self, void* mem) -> void* { if constexpr (std::is_copy_constructible_v<T_>) return new (mem) T_{ *reinterpret_cast<const T_*>(self) }; else throw std::runtime_error("sbo_storage : erased type is not copy constructible"); } } , move{ [](void*& self, void* mem) -> void* { if constexpr (std::is_move_constructible_v<T_>) return new (mem) T_{ std::move(*reinterpret_cast<T_*>(self)) }; else throw std::runtime_error("sbo_storage : erased type is not move constructible"); } } { } template < class T, class T_ = std::decay_t<T>, std::enable_if_t<!std::is_same_v<T_, sbo_storage>, bool> = true, std::enable_if_t<!type_fits<T_>::value, bool> = true> constexpr explicit sbo_storage(T&& t) noexcept(noexcept(SkrNew<T_>(std::forward<T>(t)))) : ptr{ SkrNew<T_>(std::forward<T>(t)) } , del{ [](void* self, void*) { delete reinterpret_cast<T_*>(self); } } , copy{ [](const void* self, void*) -> void* { if constexpr (std::is_copy_constructible_v<T_>) return SkrNew<T_>(*reinterpret_cast<const T_*>(self)); else throw std::runtime_error("dynamic_storage : erased type is not copy constructible"); } } , move{ [](void*& self, void*) { return detail::exchange(self, nullptr); } } { } constexpr sbo_storage(const sbo_storage& other) : ptr{ other.ptr ? other.copy(other.ptr, &data) : nullptr } , del{ other.del } , copy{ other.copy } , move{ other.move } { } constexpr sbo_storage& operator=(const sbo_storage& other) { if (other.ptr != ptr) { reset(); ptr = other.ptr ? other.copy(other.ptr, &data) : nullptr; del = other.del; copy = other.copy; move = other.move; } return *this; } constexpr sbo_storage(sbo_storage&& other) : ptr{ other.ptr ? other.move(other.ptr, &data) : nullptr } , del{ other.del } , copy{ other.copy } , move{ other.move } { } constexpr sbo_storage& operator=(sbo_storage&& other) { if (other.ptr != ptr) { reset(); ptr = other.ptr ? other.move(other.ptr, &data) : nullptr; del = other.del; copy = other.copy; move = other.move; } return *this; } ~sbo_storage() { reset(); } constexpr void reset() noexcept { if (ptr) del(ptr, &data); ptr = nullptr; } std::aligned_storage_t<Size, Alignment> data; void* ptr = nullptr; void (*del)(void*, void*) = nullptr; void* (*copy)(const void*, void*) = nullptr; void* (*move)(void*&, void*) = nullptr; }; class static_vtable { using ptr_t = void*; public: template <class T, std::size_t Size> static_vtable(T&&, ptr_t*& vtable, std::integral_constant<std::size_t, Size>) noexcept { static ptr_t vt[Size]{}; vtable = vt; } }; namespace detail { struct poly_base { void** vptr = nullptr; virtual void* ptr() const noexcept = 0; }; } // namespace detail template < class I, class TStorage = dynamic_storage, class TVtable = static_vtable> class poly : detail::poly_base, public std::conditional_t<detail::is_complete<I>{}, I, detail::type_list<I>> { public: template < class T, class T_ = std::decay_t<T>, class = std::enable_if_t<not std::is_convertible<T_, poly>::value>> constexpr poly(T&& t) noexcept(std::is_nothrow_constructible_v<T_, T&&>) : poly{ std::forward<T>(t), detail::type_list<decltype(detail::requires__<I>(bool{}))>{} } { } constexpr poly(poly const&) noexcept(std::is_nothrow_copy_constructible_v<TStorage>) = default; constexpr poly& operator=(poly const&) noexcept(std::is_nothrow_copy_constructible_v<TStorage>) = default; constexpr poly(poly&&) noexcept(std::is_nothrow_move_constructible_v<TStorage>) = default; constexpr poly& operator=(poly&&) noexcept(std::is_nothrow_move_constructible_v<TStorage>) = default; private: template < class T, class T_ = std::decay_t<T>, class TRequires> constexpr poly(T&& t, const TRequires) noexcept(std::is_nothrow_constructible_v<T_, T&&>) : poly{ std::forward<T>(t), std::make_index_sequence<detail::mappings_size<I>()>{} } { } template < class T, class T_ = std::decay_t<T>, std::size_t... Ns> constexpr poly(T&& t, std::index_sequence<Ns...>) noexcept(std::is_nothrow_constructible_v<T_, T&&>) : detail::poly_base{} , vtable{ std::forward<T>(t), vptr, std::integral_constant<std::size_t, sizeof...(Ns)>{} } , storage{ std::forward<T>(t) } { static_assert(sizeof...(Ns) > 0); static_assert(std::is_destructible<T_>{}); static_assert(std::is_copy_constructible<T>{} or std::is_move_constructible<T>{}); (init<Ns + 1, std::decay_t<T>>( decltype(get(detail::mappings<I, Ns + 1>{})){}), ...); } template <std::size_t N, class T, class TExpr, class... TArgs> constexpr void init(detail::type_list<TExpr, TArgs...>) noexcept { vptr[N - 1] = reinterpret_cast<void*>(+[](void* self, TArgs... args) { return detail::expr_wrapper<TExpr>{}(*static_cast<T*>(self), args...); }); } void* ptr() const noexcept { if constexpr (std::is_same_v<TStorage, shared_storage>) return storage.ptr.get(); else return storage.ptr; } TStorage storage; TVtable vtable; }; namespace detail { template < class I, std::size_t N, class R, class TExpr, class... Ts> constexpr auto call_impl( const poly_base& self, std::integral_constant<std::size_t, N>, type_list<R>, const TExpr, Ts&&... args) { void(typename mappings<I, N>::template set<type_list<TExpr, Ts...>>{}); return reinterpret_cast<R (*)(void*, Ts...)>(self.vptr[N - 1])( self.ptr(), std::forward<Ts>(args)...); } template <class I, class T, std::size_t... Ns> constexpr auto extends_impl(std::index_sequence<Ns...>) noexcept { (void(typename mappings<T, Ns + 1>::template set<decltype(get(mappings<I, Ns + 1>{}))>{}), ...); } template <class T, class TExpr, class... Ts> constexpr auto requires_impl(type_list<TExpr, Ts...>) -> decltype(&TExpr::template operator()<T, Ts...>); template <class I, class T, std::size_t... Ns> constexpr auto requires_impl(std::index_sequence<Ns...>) -> type_list< decltype(requires_impl<I>(decltype(get(mappings<T, Ns + 1>{})){}))...>; } // namespace detail template < class R = void, std::size_t N = 0, class TExpr, class I, class... Ts> constexpr auto call( const TExpr expr, const I& itf, Ts&&... args) { static_assert(std::is_empty<TExpr>{}); return detail::call_impl<I>( reinterpret_cast<const detail::poly_base&>(itf), std::integral_constant<std::size_t, detail::mappings_size<I, class call>() + 1>{}, detail::type_list<R>{}, expr, std::forward<Ts>(args)...); } template <class I, class T> constexpr auto extends(const T&) noexcept { detail::extends_impl<I, T>( std::make_index_sequence<detail::mappings_size<I, T>()>{}); } #if defined(__cpp_concepts) template <class I, class T> concept bool var = requires { detail::requires_impl<I, T>( std::make_index_sequence<detail::mappings_size<T, I>()>{}); }; template <class I, class T> concept bool conceptify = requires { detail::requires_impl<I, T>( std::make_index_sequence<detail::mappings_size<T, I>()>{}); }; #endif } // namespace v1 } // namespace te } // namespace ext } // namespace boost #if not defined(REQUIRES) #define REQUIRES(R, name, ...) \ R \ { \ return ::te::call<R>( \ [](auto&& self, auto&&... args) -> decltype(self.name(std::forward<decltype(args)>(args)...)) { \ return self.name(std::forward<decltype(args)>(args)...); \ }, \ *this, ##__VA_ARGS__); \ } #endif #endif
29.563333
113
0.566242
SakuraEngine
8b90cbc75d2671e687e4f050a6fc61a6171237c2
3,017
cpp
C++
src/lexer/lexer.cpp
shrimpster00/mark-sideways
16eeebb514d3e3fe1425cda5326bf3ac74f60235
[ "MIT" ]
1
2021-09-23T22:38:24.000Z
2021-09-23T22:38:24.000Z
src/lexer/lexer.cpp
shrimpster00/mark-sideways
16eeebb514d3e3fe1425cda5326bf3ac74f60235
[ "MIT" ]
null
null
null
src/lexer/lexer.cpp
shrimpster00/mark-sideways
16eeebb514d3e3fe1425cda5326bf3ac74f60235
[ "MIT" ]
null
null
null
// //lexer // v. 0.4.0 // // Author: Cayden Lund // Date: 10/30/2021 // // This file is part of sparkdown, a new markup/markdown language // for quickly writing and formatting notes. // // This file contains the implementation of the lex() method. // This method is used to lex a line for parsing. // // Copyright (C) 2021 Cayden Lund <https://github.com/shrimpster00> // License: MIT <https://opensource.org/licenses/MIT> // System imports. #include <string> #include <vector> // We use the Token class to build a vector of tokens. #include "token/token.hpp" // The header for the lex() method. #include "lexer.hpp" // The sparkdown namespace contains all the classes and methods of the sparkdown library. namespace sparkdown { // The lex() method is used to lex a line for parsing. // // * const std::string &line - The line to lex. // * return std::vector<Token> - A vector of tokens. std::vector<Token> lex(const std::string &line) { // The vector of tokens to return. std::vector<Token> tokens; // Iterate over the characters in the line. for (const char c : line) { switch (c) { case ' ': case '\t': tokens.push_back(Token(token_type::SPACE, c)); break; case '$': tokens.push_back(Token(token_type::DOLLAR)); break; case ':': tokens.push_back(Token(token_type::COLON)); break; case '[': tokens.push_back(Token(token_type::LBRAC)); break; case ']': tokens.push_back(Token(token_type::RBRAC)); break; case '#': tokens.push_back(Token(token_type::HASH)); break; case '*': tokens.push_back(Token(token_type::STAR)); break; case '-': tokens.push_back(Token(token_type::DASH)); break; case '=': tokens.push_back(Token(token_type::EQUALS)); break; case '<': tokens.push_back(Token(token_type::LT)); break; case '>': tokens.push_back(Token(token_type::GT)); break; case '\\': tokens.push_back(Token(token_type::ESCAPE)); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tokens.push_back(Token(token_type::NUMBER, c)); break; case '\n': // Ignore newlines. break; default: tokens.push_back(Token(token_type::TERMINAL, c)); break; } } return tokens; } }
29.009615
89
0.48757
shrimpster00
8b91c42ed431ba8adc12f1ad407bb28526b10573
6,773
cpp
C++
src/feature_detector.cpp
ChristophPacher/MassKerade
064b3e6055032a45a917129d6134e9b70f12fb85
[ "BSD-2-Clause" ]
1
2018-08-14T06:39:55.000Z
2018-08-14T06:39:55.000Z
src/feature_detector.cpp
ChristophPacher/MassKerade
064b3e6055032a45a917129d6134e9b70f12fb85
[ "BSD-2-Clause" ]
null
null
null
src/feature_detector.cpp
ChristophPacher/MassKerade
064b3e6055032a45a917129d6134e9b70f12fb85
[ "BSD-2-Clause" ]
null
null
null
/*! * @file feature_detector.cpp * @author Christoph Pacher <chris@christophpacher.com> * @version 1.0 * * @section LICENSE * * Copyright (c) 2014 Christoph Pacher http://www.christophpacher.com * * 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. */ #include "feature_detector.h" #include <opencv2/highgui/highgui.hpp> #include <ppl.h> #include <concurrent_vector.h> #include <string> #include <limits> //#define FD_SHOW_DEBUG_IMG using namespace cv; using namespace std; #ifdef PC_PERF_MARK using namespace concurrency; using namespace concurrency::diagnostic; #endif // PC_PERF_MARK feature_detector::feature_detector(const feature_detector::settings &s) : settings_(s), cv_detector_( FastFeatureDetector::create( settings_.detector_threshold ) ) { #ifdef PC_PERF_MARK marker_series_ = make_shared<marker_series>( L"Feature Processing" ); #endif #ifdef FD_SHOW_DEBUG_IMG //namedWindow( "FeatureDetector", WINDOW_AUTOSIZE ); namedWindow( "FeatureDetector2", WINDOW_AUTOSIZE ); #endif // FD_SHOW_DEBUG_IMG } std::vector<cv::KeyPoint> feature_detector::detect( const cv::Mat &rgb_in, const cv::Mat &mask /*= cv::Mat()*/ ) { #ifdef PC_PERF_MARK span span( *marker_series_, L"detect Key Points" ); #endif //equalizeHist( gray, gray ); Mat mask_erode; if ( settings_.mask_erode_interations > 0 ) { mask_erode = mask.clone(); dilate( mask_erode, mask_erode, erode_kernel_, Point( -1, -1 ), settings_.mask_erode_interations ); } else mask_erode = mask; vector<cv::KeyPoint> kps; #ifdef PC_PERF_MARK marker_series_->write_message( L"Detect" ); #endif cv_detector_->detect( rgb_in, kps, mask_erode ); #ifdef FD_SHOW_DEBUG_IMG Mat outImg2; drawKeypoints( rgb_in, kps, outImg2, Scalar::all( -1 ), DrawMatchesFlags::DEFAULT ); imshow( "FeatureDetector2", outImg2 ); #endif return kps; } cv::Mat feature_detector::describe( const cv::Mat &rgb_in, std::vector<cv::KeyPoint> &kp ) { #ifdef PC_PERF_MARK span span( *marker_series_, L"describe Key Points" ); #endif Mat descriptor; cv_extractor_->compute( rgb_in, kp, descriptor ); return descriptor; } std::vector<cv::DMatch> feature_detector::match( const cv::Mat &descr_old, const cv::Mat &descr_new, const std::vector<cv::KeyPoint> &kp_old, const std::vector<cv::KeyPoint> &kp_new ) { #ifdef PC_PERF_MARK span span( *marker_series_, L"match Key Points" ); #endif vector<vector<cv::DMatch>> matches; double max_dist = 0; double min_dist = 100; if ( descr_new.rows > 0 && descr_old.rows > 0 ) { // match only if there is something to match cv_matcher_.knnMatch( descr_new, descr_old, matches, 2 ); } /* for_each( matches.begin(), matches.end(), [ &]( vector<DMatch> &e ) { double dist = e[ 0 ].distance; if ( dist < min_dist ) min_dist = dist; if ( dist > max_dist ) max_dist = dist; } ); const float max_descr_distance = min_dist = max( min_dist * settings_.max_descriptor_distance_multi, 0.02 ); */ //concurrent_vector<cv::DMatch> good_matches; vector<cv::DMatch> good_matches; good_matches.reserve( matches.size() ); // Filter matches according to descriptor distance and euclidean distance in image space //parallel_for_each( matches.begin(), matches.end(), [ &]( vector<DMatch> &e ) for_each( matches.begin(), matches.end(), [ &]( vector<DMatch> &e ) { using namespace cv; if ( e.size() > 1 && e[ 0 ].distance < e[ 1 ].distance * settings_.match_1_2_ratio && e[ 0 ].distance < settings_.max_descriptor_distance_multi ) { const Point2f delta = kp_new[ e[ 0 ].queryIdx ].pt - kp_old[ e[ 0 ].trainIdx ].pt; const float img_distance = delta.x * delta.x + delta.y * delta.y; if ( img_distance < settings_.max_keypoint_distance ) { good_matches.push_back( e[ 0 ] ); } } } ); //return{ good_matches.begin(), good_matches.end() }; return good_matches; // Mat outImg; // vector<DMatch> gm; // // if ( good_matches_.size() > 0 ) // { // gm.insert( gm.begin(), good_matches_.begin(), good_matches_.end() ); // drawMatches( rgb_in, kp_new_, img_old_, kp_old_, gm, outImg, Scalar::all( -1 ), Scalar::all( -1 ), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); // imshow( "FeatureDetector", outImg ); // } // // // if ( kps_max_ < kp_new_.size() ) kps_max_ = kp_new_.size(); // if ( kps_min_ > kp_new_.size() && kp_new_.size() > 0 ) kps_min_ = kp_new_.size(); // if ( matched_max_ < good_matches_.size() ) matched_max_ = good_matches_.size(); // if ( matched_min_ > good_matches_.size() && good_matches_.size() > 0 ) matched_min_ = good_matches_.size(); // // float speed = 0.999; // average_kps_ = average_kps_ * speed + kp_new_.size() * ( 1 - speed ); // average_matched_ = average_matched_ * speed + good_matches_.size() * ( 1 - speed ); // putText( outImg2, "Kpts avg: " + to_string( average_kps_ ) + // " min: " + to_string( kps_min_ ) + " max: " + to_string( kps_max_ ), // Point( 10, 20 ), FONT_HERSHEY_SIMPLEX, 0.5, Scalar( 255, 255, 255 ) ); // putText( outImg2, "Matched avg: " + to_string( average_matched_ ) + // " min: " + to_string( matched_min_ ) + " max: " + to_string( matched_max_ ), // Point( 10, 40 ), FONT_HERSHEY_SIMPLEX, 0.5, Scalar( 255, 255, 255 ) ); // putText( outImg2, "Min Descr Dist: " + to_string( min_dist ) + // " Max Descr Dist: " + to_string( max_dist ), // Point( 10, 60 ), FONT_HERSHEY_SIMPLEX, 0.5, Scalar( 255, 255, 255 ) ); // // img_old_ = rgb_in.clone(); //#endif } void feature_detector::detector_threshold( int threshold ) { cv_detector_->setThreshold( threshold ); }
33.20098
162
0.704119
ChristophPacher
8bab0d9c5705dc539ab5061f1edffed8f02f73e2
656
cpp
C++
src/QtCryptography/nPKCS7encryptor.cpp
Vladimir-Lin/QtCryptography
b200e70b38564b274e2d53ab21cfa459e00ed449
[ "MIT" ]
null
null
null
src/QtCryptography/nPKCS7encryptor.cpp
Vladimir-Lin/QtCryptography
b200e70b38564b274e2d53ab21cfa459e00ed449
[ "MIT" ]
null
null
null
src/QtCryptography/nPKCS7encryptor.cpp
Vladimir-Lin/QtCryptography
b200e70b38564b274e2d53ab21cfa459e00ed449
[ "MIT" ]
null
null
null
#include <qtcryptography> #include <openssl/pkcs7.h> N::Encrypt::Pkcs7:: Pkcs7 (void) : Encryptor ( ) { } N::Encrypt::Pkcs7::~Pkcs7 (void) { } bool N::Encrypt::Pkcs7::supports (int algorithm) { return ( Cryptography::PKI == algorithm ) ; } int N::Encrypt::Pkcs7::type(void) const { return 100022 ; } QString N::Encrypt::Pkcs7::name(void) { return QString("PKCS7") ; } QStringList N::Encrypt::Pkcs7::Methods(void) { QStringList E ; return E ; } CUIDs N::Encrypt::Pkcs7::Bits(void) { CUIDs IDs ; return IDs ; } bool N::Encrypt::Pkcs7::encrypt(QByteArray & input,QByteArray & output) { return true ; }
14.909091
71
0.625
Vladimir-Lin
8baef9f62a3036660afa755725e8efc46e74a77b
150
cpp
C++
Disassembler.cpp
Pyxxil/LC3
7a2b201745846cd0f188648bfcc93f35d7ac711b
[ "MIT" ]
2
2020-08-18T01:04:58.000Z
2022-02-21T19:46:59.000Z
Disassembler.cpp
Pyxxil/LC3
7a2b201745846cd0f188648bfcc93f35d7ac711b
[ "MIT" ]
null
null
null
Disassembler.cpp
Pyxxil/LC3
7a2b201745846cd0f188648bfcc93f35d7ac711b
[ "MIT" ]
null
null
null
#include "Disassembler.hpp" auto main(int argc, char **argv) -> int { Disassembler disassembler(argc, argv); return disassembler.disassemble(); }
25
41
0.726667
Pyxxil
8bb3e4a4a1765909d48b9df682b6952f6fbd35fd
3,482
hpp
C++
inc/tetra/gl/Buffer.hpp
projectTetra/tetra-gl
318b0b4184ac3064b2bb5de6f82dc38c35aff956
[ "MIT" ]
null
null
null
inc/tetra/gl/Buffer.hpp
projectTetra/tetra-gl
318b0b4184ac3064b2bb5de6f82dc38c35aff956
[ "MIT" ]
null
null
null
inc/tetra/gl/Buffer.hpp
projectTetra/tetra-gl
318b0b4184ac3064b2bb5de6f82dc38c35aff956
[ "MIT" ]
null
null
null
#pragma once #ifndef TETRA_GL_BUFFER_HPP #define TETRA_GL_BUFFER_HPP #include <array> #include <vector> #include <tetra/gl/VertexArrayObject.hpp> #include <tetra/gl/GLException.hpp> namespace tetra { namespace gl { /** * A safe, RAII OpenGL array buffer object. * Templated on the type of the data that the buffer should * contain. The buffer also keeps an internal VertexArrayObject * which OpenGL uses to keep track of the enabled vertex attributes * and how to get the attribute data. **/ template <class VertexType> class Buffer { public: /** * Creates a new buffer using glGenBuffers. * @throws GLException if glGenBuffers fails. **/ Buffer(); /** * Automatically deletes underlying OpenGL buffer. **/ ~Buffer(); /** * Move constructor. **/ Buffer( Buffer<VertexType>&& b ) NOEXCEPT; /** * Move assignment, deletes the current buffer and steals * the input's buffer. * @throws GLException if glDeleteBuffers fails during the copy **/ Buffer<VertexType>& operator=( Buffer<VertexType>&& b ); /** * Sets the buffer's data and the vertex count. * @param data A vector of vertex data * @param BufferUsage GLenum used to provide a hint to OpenGL abuot * how the buffer will be used. * @throws GLException if there are any gl errors **/ void setData( const std::vector<VertexType>& data, GLenum BufferUsage = GL_STATIC_DRAW ); /** * Sets the index data when drawing indexed geometry. * Creates an element array buffer if it did not already * exist. VertexCount will now store the number of * indicies, rather than the size of the ArrayBuffer. * @param data A vector of vertex indicies * @param BufferUsage GLenum used to provide a hint to OpenGL about * how the buffer will be used. * @throws GLException if there are any gl errors **/ void setElementData( const std::vector<unsigned short>& data, GLenum BufferUsage = GL_STATIC_DRAW ); /** * Enables the vertex attribute with the index specified. * @param Index The index of the attribute to enable * @param Attrib Pointer to a std::array of float data * which represents the attribute in the * VertexType structure. * @throws GLException if there are any OpenGL errors **/ template <std::array<float, 1>::size_type length> Buffer<VertexType>& enableVertexAttrib( GLuint Index, std::array<float, length> VertexType::*Attrib ); /** * Draws the vertex data using the topology specified. * If there is an element buffer then this will call glDrawElements, * otherwise it will call glDrawArrays. * @throws GLException if there are any OpenGL errors **/ void draw( GLenum Topology = GL_TRIANGLES ) const; /** * Returns the handle to the buffer. * Note: do not delete the buffer handle! **/ GLuint expose() const NOEXCEPT; /** * Binds the VertexArrayObject. **/ void bind() const NOEXCEPT; /** * Returns the number of verticies in this buffer. (the * size of the vector in the last SetData call) **/ unsigned int size() const NOEXCEPT; private: Buffer( Buffer& ) = delete; Buffer& operator=( Buffer& ) = delete; private: GLuint bufferHandle{0}; GLuint elementBufferHandle{0}; unsigned int vertexCount{0}; VertexArrayObject vao; }; #include <tetra/gl/buffer/BufferImpl.hpp> } /* namespace gl */ } /* namespace tetra */ #endif
27.203125
70
0.68093
projectTetra
8bbf5b061cc224c341e47f9b3d9573633ed73eb9
773
cpp
C++
PETCS/Intermediate/ccc07j2.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
PETCS/Intermediate/ccc07j2.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
PETCS/Intermediate/ccc07j2.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; map<string, string> mp; string shrt[12] = {"CU", ":-)", ":-(", ";-)", ":-P", "(~.~)", "TA", "CCC", "CUZ", "TY", "YW", "TTYL"}; string tran[12] = {"see you", "I'm happy", "I'm unhappy", "wink", "stick out my tongue", "sleepy", "totally awesome", "Canadian Computing Competition", "because", "thank-you", "you're welcome", "talk to you later"}; int main() { cin.sync_with_stdio(0); cin.tie(0); cout.tie(0); for(int i = 0; i < 12; i++) { mp[shrt[i]] = tran[i]; } string s; while(1) { cin >> s; if(mp.count(s)) { cout << mp[s] << "\n"; } else { cout << s << "\n"; } if(s == "TTYL") { break; } } return 0; }
29.730769
215
0.456662
dl4us
8bc52998b312a1a94b2f8ce8a4016799d24e8d1f
967
cpp
C++
src/Heteroclinic.cpp
tmkwan/Cpp-Runge-Kutta-Fehlberg
4e1aeb1d0231acbb12c94617fb79a33b3f542726
[ "MIT" ]
null
null
null
src/Heteroclinic.cpp
tmkwan/Cpp-Runge-Kutta-Fehlberg
4e1aeb1d0231acbb12c94617fb79a33b3f542726
[ "MIT" ]
null
null
null
src/Heteroclinic.cpp
tmkwan/Cpp-Runge-Kutta-Fehlberg
4e1aeb1d0231acbb12c94617fb79a33b3f542726
[ "MIT" ]
null
null
null
/* * Heteroclinic.cpp * * Implements a heteroclinic cycle. * * Created on: Aug 6, 2016 * Author: Ted Kwan. */ #include <cmath> #include "Heteroclinic.h" using namespace std; using namespace arma; /** * Default constructor with default parameters. */ Heteroclinic::Heteroclinic() { dim=2; epsilon=0.0; mu1=0.1; mu2=0.1; } /** * Constructor with parameters provided. * * @param params - vector containing the parameters to set. */ Heteroclinic::Heteroclinic(vector<double> params){ dim=2; epsilon=params[0]; mu1=params[1]; mu2=params[2]; } /** * Overloaded method from parent class for use in calculating * the value at the current time and state. * * @param t - current time. * @param x - current space state. * @return - output of the function. */ vec Heteroclinic::evalF(double t,vec x){ vec u=zeros<vec>(2); u(0)=x(1)+epsilon*(mu1*x(0)+mu2*x(1)); u(1)=-x(0)+pow(x(0),3.0); return u; } Heteroclinic::~Heteroclinic() { }
16.964912
61
0.659772
tmkwan
8bc8385b2ca50499fab71d9e0683370c1b8e5901
291
hpp
C++
matlab/src/util.hpp
nfagan/mtype
a745271d366df64e1b4692cc90f0685ea4084ba6
[ "MIT" ]
null
null
null
matlab/src/util.hpp
nfagan/mtype
a745271d366df64e1b4692cc90f0685ea4084ba6
[ "MIT" ]
null
null
null
matlab/src/util.hpp
nfagan/mtype
a745271d366df64e1b4692cc90f0685ea4084ba6
[ "MIT" ]
null
null
null
#pragma once #include "mex.h" #include <string> namespace mt { std::string get_string_with_trap(const mxArray* in_str, const char* id); bool bool_or_default(const mxArray* in_array, bool default_value); bool bool_convertible_or_default(const mxArray* in_array, bool default_value); }
29.1
80
0.780069
nfagan
8bcb9d5c7d216d58f7f08d73f21a1f174a681131
2,279
cpp
C++
src/transactiondb.cpp
jon34560/Safire
49bf7ec7d9f2b7536af9bd4a03789694078dfe77
[ "MIT" ]
null
null
null
src/transactiondb.cpp
jon34560/Safire
49bf7ec7d9f2b7536af9bd4a03789694078dfe77
[ "MIT" ]
null
null
null
src/transactiondb.cpp
jon34560/Safire
49bf7ec7d9f2b7536af9bd4a03789694078dfe77
[ "MIT" ]
null
null
null
#include "transactiondb.h" #include <sstream> #include <unistd.h> // open and close #include "leveldb/db.h" using namespace std; /** * * * Description: Generate a random sha256 hash to be used as a private key. * Generates 128 random ascii characters to feed into a sha256 hash. * * @param: std::string output private key. * @return int returns 1 is successfull. */ int CTransactionDB::AddTransaction(std::string id, std::string message) { user u; u.publicKey = publicKey; u.ipAddress = ipAddress; return AddUser(u); } int CTransactionDB::AddTransaction(CTransactionDB::transaction transaction){ leveldb::DB* db; leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, "./transactiondb", &db); if (false == status.ok()) { cerr << "Unable to open/create test database './transactiondb'" << endl; cerr << status.ToString() << endl; return -1; } leveldb::WriteOptions writeOptions; // Insert ostringstream keyStream; keyStream << "Key" << transaction.; ostringstream valueStream; valueStream << "Test data value: " << user.publicKey << user.ipAddress; db->Put(writeOptions, keyStream.str(), valueStream.str()); // Close the database delete db; return 1; } void CTransactionDB::GetTransactions() { leveldb::DB* db; leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, "./transactiondb", &db); if (false == status.ok()) { cerr << "Unable to open/create test database './transactiondb'" << endl; cerr << status.ToString() << endl; return; } // Iterate over each item in the database and print them leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions()); for (it->SeekToFirst(); it->Valid(); it->Next()) { cout << it->key().ToString() << " : " << it->value().ToString() << endl; } if (false == it->status().ok()) { cerr << "An error was found during the scan" << endl; cerr << it->status().ToString() << endl; } // Close the database delete db; } int CTransactionDB::GetTransactionCount(){ return 0; }
25.322222
80
0.627029
jon34560
8bd0326a084c3291b46d74188bf46538d853b1bf
10,975
cpp
C++
Framework/Source/Windows/LWPlatform/LWInputDevice_Windows.cpp
slicer4ever/Lightwaver
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
3
2017-10-24T08:04:49.000Z
2018-08-28T10:08:08.000Z
Framework/Source/Windows/LWPlatform/LWInputDevice_Windows.cpp
slicer4ever/Lightwave
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
null
null
null
Framework/Source/Windows/LWPlatform/LWInputDevice_Windows.cpp
slicer4ever/Lightwave
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
null
null
null
#include "LWPlatform/LWInputDevice.h" #include "LWPlatform/LWPlatform.h" #include "LWPlatform/LWWindow.h" #include <Xinput.h> #include <algorithm> #include <iostream> #pragma region LWMouse bool LWMouse::ProcessSystemMessage(uint32_t MessageID, void *MessageData, uint64_t , LWWindow *Window){ MSG *M = (MSG*)MessageData; LWVector2i WndSize = Window->GetSize(); if(MessageID==WM_MOUSEMOVE || MessageID==WM_LBUTTONUP || MessageID==WM_LBUTTONDOWN || MessageID==WM_RBUTTONDOWN || MessageID==WM_RBUTTONUP || MessageID==WM_MBUTTONDOWN || MessageID==WM_MBUTTONUP || MessageID==WM_MOUSEWHEEL || MessageID==WM_XBUTTONDOWN || MessageID==WM_XBUTTONUP){ m_CurrState = (((M->wParam & 0x1) != 0) ? (uint32_t)LWMouseKey::Left : 0) | (((M->wParam & 0x2) != 0) ? (uint32_t)LWMouseKey::Right : 0) | (((M->wParam & 0x10) != 0) ? (uint32_t)LWMouseKey::Middle : 0) | (((M->wParam & 0x20) != 0) ? (uint32_t)LWMouseKey::X1 : 0) | (((M->wParam & 0x40) != 0) ? (uint32_t)LWMouseKey::X2 : 0); if (MessageID == WM_MOUSEWHEEL) m_Scroll = GET_WHEEL_DELTA_WPARAM(M->wParam); else m_Position = LWVector2i(M->lParam & 0xFFFF, WndSize.y - ((M->lParam & 0xFFFF0000) >> 16)); return true; } return false; } #pragma endregion #pragma region LWKeyboard bool LWKeyboard::ProcessSystemMessage(uint32_t MessageID, void *MessageData, uint64_t , LWWindow *){ auto Translate = [](uint32_t Key) -> LWKey{ switch (Key) { case 'A': return LWKey::A; case 'B': return LWKey::B; case 'C': return LWKey::C; case 'D': return LWKey::D; case 'E': return LWKey::E; case 'F': return LWKey::F; case 'G': return LWKey::G; case 'H': return LWKey::H; case 'I': return LWKey::I; case 'J': return LWKey::J; case 'K': return LWKey::K; case 'L': return LWKey::L; case 'M': return LWKey::M; case 'N': return LWKey::N; case 'O': return LWKey::O; case 'P': return LWKey::P; case 'Q': return LWKey::Q; case 'R': return LWKey::R; case 'S': return LWKey::S; case 'T': return LWKey::T; case 'U': return LWKey::U; case 'V': return LWKey::V; case 'W': return LWKey::W; case 'X': return LWKey::X; case 'Y': return LWKey::Y; case 'Z': return LWKey::Z; case '0': return LWKey::Key0; case '1': return LWKey::Key1; case '2': return LWKey::Key2; case '3': return LWKey::Key3; case '4': return LWKey::Key4; case '5': return LWKey::Key5; case '6': return LWKey::Key6; case '7': return LWKey::Key7; case '8': return LWKey::Key8; case '9': return LWKey::Key9; case VK_TAB: return LWKey::Tab; case VK_CAPITAL: return LWKey::CapLock; case VK_SHIFT: return LWKey::LShift; case VK_MENU: return LWKey::LAlt; case VK_CONTROL: return LWKey::LCtrl; case VK_LSHIFT: return LWKey::LShift; case VK_LCONTROL: return LWKey::LCtrl; case VK_LWIN: return LWKey::LMenu; case VK_LMENU: return LWKey::LAlt; case VK_SPACE: return LWKey::Space; case VK_RMENU: return LWKey::RAlt; case VK_APPS: return LWKey::RMenu; case VK_RCONTROL: return LWKey::RCtrl; case VK_RSHIFT: return LWKey::RShift; case VK_RETURN: return LWKey::Return; case VK_BACK: return LWKey::Back; case VK_OEM_COMMA: return LWKey::OEM_COMMA; case VK_OEM_MINUS: return LWKey::OEM_MINUS; case VK_OEM_PLUS: return LWKey::OEM_PLUS; case VK_OEM_PERIOD: return LWKey::OEM_PERIOD; case VK_OEM_3: return LWKey::OEM_0; case VK_OEM_2: return LWKey::OEM_1; case VK_OEM_1: return LWKey::OEM_2; case VK_OEM_7: return LWKey::OEM_3; case VK_OEM_4: return LWKey::OEM_4; case VK_OEM_6: return LWKey::OEM_5; case VK_OEM_5: return LWKey::OEM_6; case VK_LEFT: return LWKey::Left; case VK_RIGHT: return LWKey::Right; case VK_UP: return LWKey::Up; case VK_DOWN: return LWKey::Down; case VK_INSERT: return LWKey::Insert; case VK_DELETE: return LWKey::Delete; case VK_HOME: return LWKey::Home; case VK_END: return LWKey::End; case VK_PRIOR: return LWKey::PageUp; case VK_NEXT: return LWKey::PageDown; case VK_SNAPSHOT: return LWKey::PrintScreen; case VK_SCROLL: return LWKey::ScrollLock; case VK_PAUSE: return LWKey::Pause; case VK_NUMLOCK: return LWKey::NumLock; case VK_NUMPAD0: return LWKey::Num0; case VK_NUMPAD1: return LWKey::Num1; case VK_NUMPAD2: return LWKey::Num2; case VK_NUMPAD3: return LWKey::Num3; case VK_NUMPAD4: return LWKey::Num4; case VK_NUMPAD5: return LWKey::Num5; case VK_NUMPAD6: return LWKey::Num6; case VK_NUMPAD7: return LWKey::Num7; case VK_NUMPAD8: return LWKey::Num8; case VK_NUMPAD9: return LWKey::Num9; case VK_DECIMAL: return LWKey::NumDecimal; case VK_ADD: return LWKey::NumAdd; case VK_SUBTRACT: return LWKey::NumMinus; case VK_MULTIPLY: return LWKey::NumMultiply; case VK_DIVIDE: return LWKey::NumDivide; case VK_ESCAPE: return LWKey::Esc; case VK_F1: return LWKey::F1; case VK_F2: return LWKey::F2; case VK_F3: return LWKey::F3; case VK_F4: return LWKey::F4; case VK_F5: return LWKey::F5; case VK_F6: return LWKey::F6; case VK_F7: return LWKey::F7; case VK_F8: return LWKey::F8; case VK_F9: return LWKey::F9; case VK_F10: return LWKey::F10; case VK_F11: return LWKey::F11; case VK_F12: return LWKey::F12; case VK_F13: return LWKey::F13; case VK_F14: return LWKey::F14; case VK_F15: return LWKey::F15; case VK_F16: return LWKey::F16; case VK_F17: return LWKey::F17; case VK_F18: return LWKey::F18; case VK_F19: return LWKey::F19; case VK_MEDIA_PLAY_PAUSE: return LWKey::MediaPlayPause; case VK_MEDIA_NEXT_TRACK: return LWKey::MediaNext; case VK_MEDIA_PREV_TRACK: return LWKey::MediaPrev; case VK_VOLUME_MUTE: return LWKey::VolumeMute; case VK_VOLUME_DOWN: return LWKey::VolumeDown; case VK_VOLUME_UP: return LWKey::VolumeUp; case VK_LAUNCH_MAIL: return LWKey::Mail; } return LWKey::Unknown; }; MSG *M = (MSG*)MessageData; LWKey Key = LWKey::Unknown; bool Up = MessageID == WM_KEYUP || MessageID==WM_SYSKEYUP; auto SetKeyState = [this](uint32_t Key, bool Up) { uint32_t Word = Key / (sizeof(uint32_t) * 8); if (Word >= (sizeof(m_CurrState) / sizeof(uint32_t))) return 0; uint32_t Bit = 1 << (Key % (sizeof(uint32_t) * 8)); if (Up) m_CurrState[Word] &= ~Bit; else { if ((m_PrevState[Word] & Bit) != 0) m_PrevState[Word] &= ~Bit; m_CurrState[Word] |= Bit; } if (m_KeyChangeCount < MaxKeyChanges) { m_KeyChanges[m_KeyChangeCount] = Key; m_KeyStates[m_KeyChangeCount] = !Up; m_KeyChangeCount++; } return 1; }; if (MessageID==WM_CHAR || MessageID==WM_SYSCHAR) { if (m_CharPressed >= MaxKeyChanges) return false; m_CharInputs[m_CharPressed++] = (uint32_t)M->wParam; return true; } if (MessageID == WM_KEYUP || MessageID == WM_KEYDOWN || MessageID == WM_SYSKEYUP || MessageID == WM_SYSKEYDOWN) { Key = Translate((uint32_t)M->wParam); if (Key == LWKey::Unknown) std::cout << "Keycode: " << (uint32_t)M->wParam << std::endl; } if (Key == LWKey::Unknown) return false; SetKeyState((uint32_t)Key, Up); TranslateMessage(M); return true; } #pragma endregion #pragma region LWTouch bool LWTouch::ProcessSystemMessage(uint32_t MessageID, void *MessageData, uint64_t lCurrentTime, LWWindow *Window) { MSG *M = (MSG*)MessageData; LWVector2i WndSize = Window->GetSize(); if (MessageID == WM_MOUSEMOVE || MessageID == WM_LBUTTONUP || MessageID == WM_LBUTTONDOWN) { //m_CurrState = ((M->wParam & 0x1) != 0) ? (uint32_t)LWMouseKey::Left : 0 | ((M->wParam & 0x2) != 0) ? (uint32_t)LWMouseKey::Right : 0 | ((M->wParam & 0x10) != 0) ? (uint32_t)LWMouseKey::Middle : 0 | ((M->wParam & 0x20) != 0) ? (uint32_t)LWMouseKey::X1 : 0 | ((M->wParam & 0x40) != 0) ? (uint32_t)LWMouseKey::X2 : 0; LWVector2i Pos = LWVector2i(M->lParam & 0xFFFF, WndSize.y - ((M->lParam & 0xFFFF0000) >> 16)); if (m_PointCount == 1) { if (m_Points[0].m_State != LWTouchPoint::UP) { m_Points[0].m_State = (MessageID == WM_MOUSEMOVE ? LWTouchPoint::MOVED : (MessageID == WM_LBUTTONUP ? LWTouchPoint::UP : m_Points[0].m_State)); } } if (MessageID == WM_LBUTTONDOWN) { m_Points[0].m_State = LWTouchPoint::DOWN; m_Points[0].m_DownTime = lCurrentTime; m_Points[0].m_InitPosition = Pos; m_Points[0].m_PrevPosition = Pos; m_Points[0].m_Size = 1.0f; m_PointCount = 1; } m_Points[0].m_Position = Pos; return true; } return false; } #pragma endregion #pragma region LWGamePad LWInputDevice &LWGamePad::Update(LWWindow *, uint64_t ) { m_PrevButtons = m_Buttons; XINPUT_STATE s; memset(&s, 0, sizeof(XINPUT_STATE)); if (XInputGetState(0, &s) != ERROR_SUCCESS) return *this; uint32_t B = 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_A ? LWGamePad::A : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_B ? LWGamePad::B : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_X ? LWGamePad::X : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_Y ? LWGamePad::Y : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_LEFT ? LWGamePad::Left : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_RIGHT ? LWGamePad::Right : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_UP ? LWGamePad::Up : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_DOWN ? LWGamePad::Down : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_LEFT_SHOULDER ? LWGamePad::L1 : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_RIGHT_SHOULDER ? LWGamePad::R1 : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_LEFT_THUMB ? LWGamePad::L3 : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_RIGHT_THUMB ? LWGamePad::R3 : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_BACK ? LWGamePad::Select : 0; B |= s.Gamepad.wButtons&XINPUT_GAMEPAD_START ? LWGamePad::Start : 0; B |= s.Gamepad.bLeftTrigger > 200 ? LWGamePad::L2 : 0; B |= s.Gamepad.bRightTrigger > 200 ? LWGamePad::R2 : 0; m_Buttons = B; float normLX = std::max<float>(-1.0f, (float)s.Gamepad.sThumbLX / 32767.0f); float normLY = std::max<float>(-1.0f, (float)s.Gamepad.sThumbLY / 32767.0f); float normRX = std::max<float>(-1.0f, (float)s.Gamepad.sThumbRX / 32767.0f); float normRY = std::max<float>(-1.0f, (float)s.Gamepad.sThumbRY / 32767.0f); m_LeftAxis = LWVector2f(normLX, normLY); m_RightAxis = LWVector2f(normRX, normRY); m_BumperStrength = LWVector2f((float)s.Gamepad.bLeftTrigger / 255.0f, (float)s.Gamepad.bRightTrigger / 255.0f); return *this; } bool LWGamePad::ProcessSystemMessage(uint32_t , void *, uint64_t , LWWindow *) { return false; } #pragma endregion #pragma region LWAccelerometer bool LWAccelerometer::ProcessSystemMessage(uint32_t, void *, uint64_t , LWWindow *) { return false; } LWInputDevice &LWAccelerometer::Update(LWWindow *, uint64_t) { return *this; } #pragma endregion #pragma region LWGyroscope bool LWGyroscope::ProcessSystemMessage(uint32_t , void *, uint64_t, LWWindow *) { return false; } LWInputDevice &LWGyroscope::Update(LWWindow *, uint64_t) { return *this; } #pragma endregion
38.780919
327
0.682825
slicer4ever
8bd0b2534fde342bff692e97d9fa027e5d755a26
880
cpp
C++
src/qad.cpp
mkujalowicz/trismers-qtadservice
c0315ebe7268fca9ac53504dda11af74a92689c7
[ "Apache-2.0" ]
null
null
null
src/qad.cpp
mkujalowicz/trismers-qtadservice
c0315ebe7268fca9ac53504dda11af74a92689c7
[ "Apache-2.0" ]
null
null
null
src/qad.cpp
mkujalowicz/trismers-qtadservice
c0315ebe7268fca9ac53504dda11af74a92689c7
[ "Apache-2.0" ]
null
null
null
#include "qad.h" QAd::QAd(QObject *parent) : QObject(parent), m_format(Null) { } void QAd::setUrl(const QUrl &arg) { if (m_url != arg) { m_url = arg; emit urlChanged(arg); } } void QAd::setImageUrl(QUrl arg) { if (m_imageUrl != arg) { m_imageUrl = arg; emit imageUrlChanged(arg); } } void QAd::setFormat(QAd::Format arg) { if (m_format != arg) { m_format = arg; emit formatChanged(arg); } } void QAd::setText(QString arg) { if (m_text != arg) { m_text = arg; emit textChanged(arg); } } void QAd::setTrackingId(QString arg) { if (m_trackingId != arg) { m_trackingId = arg; emit trackingIdChanged(arg); } } void QAd::setTrackingUrl(QUrl arg) { if (m_trackingUrl != arg) { m_trackingUrl = arg; emit trackingUrlChanged(arg); } }
16
37
0.564773
mkujalowicz
8bd60b3aba0e576d3d204e9177cfaa5d5bbc8032
5,929
cpp
C++
SCNN/seg_label_generate/src/lane/util.cpp
IAmNotMahd/LaneDetector
07198cc8e8981020f7375b8fb9acbdf8bd72b71e
[ "MIT" ]
2
2019-07-28T18:20:53.000Z
2020-02-19T08:08:59.000Z
SCNN/seg_label_generate/src/lane/util.cpp
IAmNotMahd/LaneDetector
07198cc8e8981020f7375b8fb9acbdf8bd72b71e
[ "MIT" ]
null
null
null
SCNN/seg_label_generate/src/lane/util.cpp
IAmNotMahd/LaneDetector
07198cc8e8981020f7375b8fb9acbdf8bd72b71e
[ "MIT" ]
null
null
null
/************************************************************************* > File Name: util.cpp > Author: Jun Li, Xingang Pan > Mail: xingangpan1994@gmail.com > Created Time: 2016年07月20日 星期三 16时20分51秒 ************************************************************************/ #include "lane/util.hpp" #include "lane/spline.hpp" namespace lane { void sortLanes(vector<vector<Point2f> > &lanes) { for(size_t n=0; n<lanes.size(); n++) { vector<Point2f> &p_seq = lanes[n]; sort(p_seq.begin(), p_seq.end(), [](const Point2f& p1, const Point2f &p2){ return p1.y>p2.y; }); remove_dumplicate_points(p_seq); } sort(lanes.begin(), lanes.end(), less_by_line_order); } void nameLineByK(vector<vector<Point2f> > &lanes, vector<int> &lanes_label) { if(lanes.empty()) { lanes_label.clear(); return; } if(lanes.size()==1) { if(get_k(lanes[0])<=0) lanes_label.push_back(1); else lanes_label.push_back(2); } if(lanes.size()==2) { lanes_label.push_back(1); lanes_label.push_back(2); return; } const int max_lines = 4; size_t split_idx = lanes.size(); // lane labels that is less than max_lines are valid lanes_label.resize(lanes.size(), max_lines); bool find_k_flag = false; for(size_t n=1; n<lanes.size(); n++) { if(get_k(lanes[n-1]) <= 0 && get_k(lanes[n]) > 0) { split_idx = n; find_k_flag = true; break; } } if(!find_k_flag) { // find from the end_pos double center_x = im_width * 0.5; for(size_t n=0; n<lanes.size(); n++) { double interact_x = get_intersection_x(lanes[n]); if(interact_x > center_x) { split_idx = n; break; } } } for(int i=0; i<max_lines; i++) { int idx = i + split_idx - 2; if(idx<0 || idx>=lanes.size()) continue; else lanes_label[idx] = i; } } void sortLanesCen(vector<vector<Point2f> > &lanes) { sort(lanes.begin(), lanes.end(), less_by_central_dist); if(lanes.size()<5) { sort(lanes.begin(), lanes.end(), less_by_line_order); return; } for(size_t m=lanes.size()-1; m>3; m--) { lanes.erase(lanes.begin()+m); } sort(lanes.begin(), lanes.end(), less_by_line_order); } void remove_dumplicate_points(vector<Point2f> &p_seq) { int s=0, e=1; while(e<p_seq.size()) { if(std::sqrt((p_seq[s].x-p_seq[e].x)*(p_seq[s].x-p_seq[e].x) + (p_seq[s].y-p_seq[e].y)*(p_seq[s].y-p_seq[e].y))<2 || std::fabs(p_seq[s].y-p_seq[e].y) < 1) { p_seq.erase(p_seq.begin()+e); } else { s++; e++; } } } double get_intersection_x(const vector<Point2f> &line) { vector<double> x_seq, y_seq; for(int i=0; i<line.size(); i++) { x_seq.push_back(line[i].x); y_seq.push_back(line[i].y); } const int nDegree = 1; vector<double> p_seq = polyfit(y_seq, x_seq, nDegree); vector<double> y_out(1, im_height); vector<double> x_out = polyval(p_seq, y_out); return x_out[0]; } double get_k(const vector<Point2f> &line) { if(line.size()<2) { cerr<<"Error: line size must be greater or equal to 2"<<endl; return 0; } return ((line[1].x-line[0].x)/(line[1].y-line[0].y)); } bool less_by_line_order(const vector<Point2f> &line1, const vector<Point2f> &line2) { double x1 = get_intersection_x(line1); double x2 = get_intersection_x(line2); return x1<x2; } bool less_by_central_dist(const vector<Point2f> &line1, const vector<Point2f> &line2) { double mid = 960; double x1 = get_intersection_x(line1); double x2 = get_intersection_x(line2); return std::abs(x1-mid)<std::abs(x2-mid); } void changeToFixPoint(vector<Point2f> &curr_lane, size_t fix_pts) { Spline splineSolver; if(curr_lane.size()<2) return; // change to 30 pts vector<Point2f> p_interp = splineSolver.splineInterpStep(curr_lane, 1); if(p_interp.size() < fix_pts) return; size_t pts_per_line = curr_lane.size(); double step = (p_interp.size() - 1.0)/(pts_per_line - 1.0); curr_lane.clear(); for(size_t i=0; i<pts_per_line; i++) { size_t idx = i*step; curr_lane.push_back(p_interp[idx]); } } // suppose line has been sorted with y from big to small bool extend_line(vector<Point2f> &line) { double eps = 1; if(line.size()<=2) return false; if(fabs(line[0].x - 0)<eps || fabs(line[0].x - im_width + 1)<eps || fabs(line[0].y - im_height + 1 )<eps) { return true; } // roll back first int idx = 0; while(line[idx].x < 0 || line[idx].x > im_width - 1 || line[idx].y < 0 || line[idx].y > im_height - 1) { idx++; if(idx==line.size()) break; } if(idx>line.size()-2) { cerr<<"error in extending line"<<endl; for(auto p:line) cerr<<p<<" "; cerr<<endl; return false; } Point2f p0 = line[idx]; Point2f p1 = line[idx+1]; // check double x0 = p0.x; double y0 = p0.y; double x1 = p1.x; double y1 = p1.y; vector<Point2f> new_line; if(fabs(x0 - 0)>eps && fabs(x0 - im_width + 1) > eps && fabs(y0 - im_height + 1)>eps) { double x, y; if(fabs(y0 - y1) < 0.001) { // use x if(x0 < x1) { x = 0; } else { x = im_width - 1; } y = y0 + (x - x0)*(y1-y0)/(x1-x0); } else { // first calc y y = im_height - 1; x = x0 + (y - y0)*(x1 - x0)/(y1-y0); if( x < 0 - eps || x > im_width - 1 + eps) { // use x if(x0 < x1) { x = 0; } else { x = im_width - 1; } y = y0 + (x - x0)*(y1-y0)/(x1-x0); } } // insert a sequence of point Point2f p = Point2f(x,y); int insert_num = (std::max(fabs(x - x0), fabs(y - y0)))/eps; for(int i=0; i<insert_num; i++) { double alpha = 1 - i/double(insert_num); Point2f tmp_p = alpha*p + (1-alpha)*p0; new_line.push_back(tmp_p); } } for(size_t i = idx; i<line.size(); i++) { new_line.push_back(line[i]); } std::swap(new_line, line); return true; } };
21.404332
157
0.572609
IAmNotMahd
8bdafaff33eb3d52dbfbb163085fcad0bac3631d
440
hpp
C++
src/face/eye/lenet/lenet.hpp
bububa/openvision
0864e48ec8e69ac13d6889d41f7e1171f53236dd
[ "Apache-2.0" ]
1
2022-02-08T06:42:05.000Z
2022-02-08T06:42:05.000Z
src/face/eye/lenet/lenet.hpp
bububa/openvision
0864e48ec8e69ac13d6889d41f7e1171f53236dd
[ "Apache-2.0" ]
null
null
null
src/face/eye/lenet/lenet.hpp
bububa/openvision
0864e48ec8e69ac13d6889d41f7e1171f53236dd
[ "Apache-2.0" ]
null
null
null
#ifndef _FACE_EYE_LENET_H_ #define _FACE_EYE_LENET_H_ #include "../eye.hpp" namespace ovface { class LenetEye : public Eye { public: int Status(const unsigned char *rgbdata, int img_width, int img_height, const ov::Rect rect, std::vector<float> &cls_scores); private: const int target_width = 36; const int target_height = 28; const float mean_vals[1] = {60.f}; }; } // namespace ovface #endif // !_FACE_EYE_LENET_H_
24.444444
73
0.713636
bububa
8be4028bd038fc25b930e28f93b6d628d7bb125e
1,232
hpp
C++
boost/network/protocol/http/client/macros.hpp
JimmyHwang/cpp-netlib
86d08de44145be6d1f7f80d07f69585842b8d325
[ "BSL-1.0" ]
null
null
null
boost/network/protocol/http/client/macros.hpp
JimmyHwang/cpp-netlib
86d08de44145be6d1f7f80d07f69585842b8d325
[ "BSL-1.0" ]
null
null
null
boost/network/protocol/http/client/macros.hpp
JimmyHwang/cpp-netlib
86d08de44145be6d1f7f80d07f69585842b8d325
[ "BSL-1.0" ]
null
null
null
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_MACROS_HPP_20110430 #define BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_MACROS_HPP_20110430 // Copyright 2011 Dean Michael Berris <mikhailberis@gmail.com>. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/range/iterator_range.hpp> #include <array> #include <system_error> #ifndef BOOST_NETWORK_HTTP_CLIENT_CONNECTION_BUFFER_SIZE /** * We define the buffer size for each connection that we will use on the client * side. */ #define BOOST_NETWORK_HTTP_CLIENT_CONNECTION_BUFFER_SIZE 4096uL #endif #ifndef BOOST_NETWORK_HTTP_BODY_CALLBACK #define BOOST_NETWORK_HTTP_BODY_CALLBACK(function_name, range_name, error_name)\ void function_name( \ boost::iterator_range< \ std::array<char, BOOST_NETWORK_HTTP_CLIENT_CONNECTION_BUFFER_SIZE>:: \ const_iterator>(range_name), \ boost::system::error_code const&(error_name)) #endif #endif /* BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_MACROS_HPP_20110430 */
39.741935
80
0.703734
JimmyHwang
8bea6947d86cd97ebcc460df5b81adad098724b5
1,086
cpp
C++
src/engine/graphics/vulkan.cpp
dmfedorin/ubiquitility
f3a1062d2489ffd48889bff5fc8062c05706a946
[ "MIT" ]
null
null
null
src/engine/graphics/vulkan.cpp
dmfedorin/ubiquitility
f3a1062d2489ffd48889bff5fc8062c05706a946
[ "MIT" ]
null
null
null
src/engine/graphics/vulkan.cpp
dmfedorin/ubiquitility
f3a1062d2489ffd48889bff5fc8062c05706a946
[ "MIT" ]
null
null
null
#include "vulkan.hpp" Vulkan::Vulkan(Window &wnd) { layers = std::make_unique<ValidationLayers>(true); inst = std::make_unique<Instance>(*layers); surface = std::make_unique<Surface>(inst.get(), wnd); phys_dev = std::make_unique<PhysicalDevice>(*inst, *surface); dev = std::make_unique<Device>(*layers, *phys_dev); allocator = std::make_unique<Allocator>(*inst, *phys_dev, *dev); swap_chain = std::make_unique<SwapChain>( *phys_dev, dev.get(), *surface, wnd); rend = std::make_unique<Renderer>(dev.get(), *swap_chain, *phys_dev); pipeline = std::make_unique<Pipeline>(dev.get(), *swap_chain, *rend); } Vulkan::~Vulkan(void) { vkDeviceWaitIdle(dev->get_dev()); } auto Vulkan::draw(void) -> void { rend->begin(*swap_chain); pipeline->bind(*rend); for (const auto &cmd_buf : rend->get_cmd_bufs()) { vkCmdDraw(cmd_buf, 3, 1, 0, 0); } rend->end(); rend->render(*swap_chain); }
28.578947
77
0.567219
dmfedorin
8bee177fd878b1c3f6be5c14901f01dc35f8a04c
655
cpp
C++
Leetcode/SumRoottoLeafNumbers.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
Leetcode/SumRoottoLeafNumbers.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
Leetcode/SumRoottoLeafNumbers.cpp
zhanghuanzj/C-
b271de02885466e97d6a2072f4f93f87625834e4
[ "Apache-2.0" ]
null
null
null
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sumNumbers(TreeNode *root) { int result = 0; getValue(root,0,result); return result; } private: void getValue(TreeNode *root,int pre,int &result) { if (root==nullptr) { return; } pre = pre*10+root->val; if (root->left) { getValue(root->left,pre,result); } if (root->right) { getValue(root->right,pre,result); } if (root->left==nullptr && root->right==nullptr) { result += pre; } } };
17.236842
59
0.580153
zhanghuanzj
8bee661d1e371865219495f1dab75fc535a5a71f
397
cpp
C++
SumaParesImpares.cpp
Wjavier15/cpp
cf7d1f541828a616520aea95faaac0f3a27c7d44
[ "MIT" ]
null
null
null
SumaParesImpares.cpp
Wjavier15/cpp
cf7d1f541828a616520aea95faaac0f3a27c7d44
[ "MIT" ]
null
null
null
SumaParesImpares.cpp
Wjavier15/cpp
cf7d1f541828a616520aea95faaac0f3a27c7d44
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int a=0,b=0,p=0,i=0; cout<<"ingrese un numero: ";cin>>a; cout<<"ingrese otro numero: ";cin>>b; while(a<=b) { if(a%2==0) {p=p+a; a=a+1;} else {i=i+a; a=a+1;} } cout<<"suma de pares: "<<p<<endl; cout<<"suma de impares: "<<i<<endl; cin.ignore(); return 0; }
19.85
42
0.463476
Wjavier15
8bf2a1105b6570e6613afc0c936a4c7bc2cb0a5c
8,302
cpp
C++
BarCode39.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
BarCode39.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
BarCode39.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////// // Copyright 2003 by David Hillard // // This information must remain in file // // // // Please provide credit for this code in your // // finished application in the Help/About box // ///////////////////////////////////////////////////// #include "stdafx.h" #include "BarCode39.h" int BC39_Decode(char letter) { int code; switch(letter) { case '*':code = 0x0094;break; case '1':code = 0x0121;break; case '2':code = 0x0061;break; case '3':code = 0x0160;break; case '4':code = 0x0031;break; case '5':code = 0x0130;break; case '6':code = 0x0070;break; case '7':code = 0x0025;break; case '8':code = 0x0124;break; case '9':code = 0x0064;break; case '0':code = 0x0034;break; case 'A':code = 0x0109;break; case 'B':code = 0x0049;break; case 'C':code = 0x0148;break; case 'D':code = 0x0019;break; case 'E':code = 0x0118;break; case 'F':code = 0x0058;break; case 'G':code = 0x000D;break; case 'H':code = 0x010C;break; case 'I':code = 0x004C;break; case 'J':code = 0x001C;break; case 'K':code = 0x0103;break; case 'L':code = 0x0043;break; case 'M':code = 0x0142;break; case 'N':code = 0x0013;break; case 'O':code = 0x0112;break; case 'P':code = 0x0052;break; case 'Q':code = 0x0007;break; case 'R':code = 0x0106;break; case 'S':code = 0x0046;break; case 'T':code = 0x0016;break; case 'U':code = 0x0181;break; case 'V':code = 0x00C1;break; case 'W':code = 0x01C0;break; case 'X':code = 0x0091;break; case 'Y':code = 0x0190;break; case 'Z':code = 0x00D0;break; case '-':code = 0x0085;break; case '.':code = 0x0184;break; case ' ':code = 0x00C4;break; case '$':code = 0x00A8;break; case '/':code = 0x00A2;break; case '+':code = 0x008A;break; case '%':code = 0x002A;break; default: code = 0x0000;//don't barcode invalid characters }//end switch return code; } void BC39_Expand(int code,char* wn) { { if(code & 0x0100){wn[0]='W';}else{wn[0]='N';} if(code & 0x0080){wn[1]='W';}else{wn[1]='N';} if(code & 0x0040){wn[2]='W';}else{wn[2]='N';} if(code & 0x0020){wn[3]='W';}else{wn[3]='N';} if(code & 0x0010){wn[4]='W';}else{wn[4]='N';} if(code & 0x0008){wn[5]='W';}else{wn[5]='N';} if(code & 0x0004){wn[6]='W';}else{wn[6]='N';} if(code & 0x0002){wn[7]='W';}else{wn[7]='N';} if(code & 0x0001){wn[8]='W';}else{wn[8]='N';} wn[9]='N'; wn[10]=0x00; } } int BC39_Draw(HDC hdc,RECT* rect,char* text,double cpi,BOOL HORIZ) { char bcarray[400]; char wn[11]; char tbuffer[100]; char textcopy[100]; int j,code,sl,barwidth,barcodelength,rv; int ppi,numchars,lengthinxwidths; double xdim,offset; HPEN holdpen; HBRUSH holdbrush; //copy text to textcopy for modification to uppercase strcpy(textcopy,text); if(strlen(textcopy)>30) { return 1; } strcpy(bcarray,""); strupr(textcopy); code=BC39_Decode('*'); BC39_Expand(code,wn); strcpy(bcarray,wn); for(j=0;j<(int)(strlen(textcopy));j++) { code=BC39_Decode(textcopy[j]); if(code) { BC39_Expand(code,wn); strcat(bcarray,wn); } } code=BC39_Decode('*'); BC39_Expand(code,wn); strcat(bcarray,wn); //now bcarray holds bar width string; 10 bytes per character numchars=(int)(strlen(bcarray)/10); lengthinxwidths=numchars*16; //calculate the x dimension if(HORIZ) { ppi=GetDeviceCaps(hdc,LOGPIXELSX); } else { ppi=GetDeviceCaps(hdc,LOGPIXELSY); } wsprintf(tbuffer,"ppi = %d",ppi); if(cpi<1){cpi=1;} xdim=(ppi/(16*cpi)); if(xdim<1){xdim=1;} barcodelength=(int)(xdim*lengthinxwidths + xdim*20); //adjust rect width if necessary rv=0; if(HORIZ) { int diff; diff=barcodelength-(rect->right - rect->left); if(diff > 0) { rect->right += diff; rv=1; } } else { int diff; diff=barcodelength-(rect->bottom - rect->top); if(diff > 0) { rect->bottom += diff; rv=1; } } holdbrush=(HBRUSH)SelectObject(hdc,GetStockObject(BLACK_BRUSH)); holdpen=(HPEN)SelectObject(hdc,GetStockObject(BLACK_PEN)); sl=strlen(bcarray); if(HORIZ) { offset=((rect->right - rect->left)/2) - (barcodelength/2); } else { offset=((rect->bottom - rect->top)/2) - (barcodelength/2); } offset+=xdim*10; if(HORIZ) { for(j=0;j<sl;j++) { if(((j/2)*2)==j) { //even is bar if(bcarray[j]=='W') { //draw wide bar barwidth=(int)(xdim*3); Rectangle(hdc,rect->left+(int)offset,rect->top,rect->left+(int)offset+barwidth,rect->bottom); offset+=barwidth; } else { //draw narrow bar barwidth=(int)xdim; Rectangle(hdc,rect->left+(int)offset,rect->top,rect->left+(int)offset+barwidth,rect->bottom); offset+=barwidth; } } else { //odd is space if(bcarray[j]=='W') { offset+=(xdim*3); } else { offset+=(xdim); } } } } else //not HORIZ { for(j=0;j<sl;j++) { if(((j/2)*2)==j) { //even is bar if(bcarray[j]=='W') { //draw wide bar barwidth=(int)(xdim*3); Rectangle(hdc,rect->left,rect->top+(int)offset,rect->right,rect->top+(int)offset+barwidth); offset+=barwidth; } else { //draw narrow bar barwidth=(int)xdim; Rectangle(hdc,rect->left,rect->top+(int)offset,rect->right,rect->top+(int)offset+barwidth); offset+=barwidth; } } else { //odd is space if(bcarray[j]=='W') { offset+=(xdim*3); } else { offset+=(xdim); } } } } SelectObject(hdc,holdpen); SelectObject(hdc,holdbrush); return rv; }
31.328302
122
0.39364
matthias-christen
8bf43e304ab090e242ed61cb7b22bfe2dbc944a3
9,450
cpp
C++
examples/testbed/framework/view_model.cpp
irlanrobson/bounce
1cf7f40fff528bff8514a50e786ea58e86d53a54
[ "Zlib" ]
368
2016-12-18T21:19:18.000Z
2022-03-10T19:13:04.000Z
examples/testbed/framework/view_model.cpp
irlanrobson/bounce
1cf7f40fff528bff8514a50e786ea58e86d53a54
[ "Zlib" ]
104
2016-12-19T20:44:53.000Z
2022-03-12T21:31:14.000Z
examples/testbed/framework/view_model.cpp
irlanrobson/bounce
1cf7f40fff528bff8514a50e786ea58e86d53a54
[ "Zlib" ]
34
2017-02-12T23:50:56.000Z
2021-12-17T04:33:41.000Z
/* * Copyright (c) 2016-2019 Irlan Robson * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "view_model.h" #include "model.h" #include "GLFW/glfw3.h" #include "test.h" #include "tests/convex_hull.h" #include "tests/cluster.h" #include "tests/distance_test.h" #include "tests/linear_time_of_impact.h" #include "tests/time_of_impact.h" #include "tests/aabb_time_of_impact.h" #include "tests/capsule_collision.h" #include "tests/hull_collision.h" #include "tests/deep_capsule.h" #include "tests/box_face_contact.h" #include "tests/box_edge_contact.h" #include "tests/linear_motion.h" #include "tests/angular_motion.h" #include "tests/gyro_motion.h" #include "tests/initial_overlap.h" #include "tests/capsule_spin.h" #include "tests/quadric_shapes.h" #include "tests/compound_body.h" #include "tests/spring_test.h" #include "tests/motor_test.h" #include "tests/weld_test.h" #include "tests/cone_test.h" #include "tests/revolute_test.h" #include "tests/prismatic_test.h" #include "tests/wheel_test.h" #include "tests/hinge_chain.h" #include "tests/newton_cradle.h" #include "tests/ragdoll.h" #include "tests/mesh_contact_test.h" #include "tests/triangle_contact_test.h" #include "tests/hull_contact_test.h" #include "tests/sphere_stack.h" #include "tests/capsule_stack.h" #include "tests/box_stack.h" #include "tests/sheet_stack.h" #include "tests/shape_stack.h" #include "tests/jenga.h" #include "tests/pyramid.h" #include "tests/pyramids.h" #include "tests/ray_cast.h" #include "tests/shape_cast.h" #include "tests/sensor_test.h" #include "tests/body_types.h" #include "tests/varying_friction.h" #include "tests/varying_restitution.h" #include "tests/tumbler.h" #include "tests/multiple_pendulum.h" #include "tests/conveyor_belt.h" #include "tests/rope_test.h" TestSettings* g_testSettings = nullptr; Settings* g_settings = nullptr; Settings::Settings() { testID = 0; testCount = 0; drawPoints = true; drawLines = true; drawTriangles = true; drawGrid = true; drawStats = false; drawProfiler = false; } void Settings::RegisterTest(const char* name, TestCreate createFn) { TestEntry* test = tests + testCount++; test->name = name; test->create = createFn; } ViewModel::ViewModel(Model* model, GLFWwindow* window) { m_model = model; m_window = window; m_ps0.SetZero(); m_settings.RegisterTest("Convex Hull", &ConvexHull::Create ); m_settings.RegisterTest("Cluster", &Cluster::Create ); m_settings.RegisterTest("Distance", &Distance::Create ); m_settings.RegisterTest("Linear Time of Impact", &LinearTimeOfImpact::Create ); m_settings.RegisterTest("Time of Impact", &TimeOfImpact::Create ); m_settings.RegisterTest("AABB Time of Impact", &AABBTimeOfImpact::Create ); m_settings.RegisterTest("Capsule Collision", &CapsuleCollision::Create ); m_settings.RegisterTest("Hull Collision", &HullCollision::Create ); m_settings.RegisterTest("Deep Capsule", &DeepCapsule::Create ); m_settings.RegisterTest("Box Face Contact", &BoxFaceContact::Create ); m_settings.RegisterTest("Box Edge Contact", &BoxEdgeContact::Create ); m_settings.RegisterTest("Capsule Spin", &CapsuleSpin::Create ); m_settings.RegisterTest("Hull Contact Test", &HullContactTest::Create ); m_settings.RegisterTest("Triangle Contact Test", &TriangleContactTest::Create ); m_settings.RegisterTest("Mesh Contact Test", &MeshContactTest::Create ); m_settings.RegisterTest("Linear Motion", &LinearMotion::Create ); m_settings.RegisterTest("Angular Motion", &AngularMotion::Create ); m_settings.RegisterTest("Gyroscopic Motion", &GyroMotion::Create ); m_settings.RegisterTest("Compound Body", &CompoundBody::Create ); m_settings.RegisterTest("Quadric Shapes", &QuadricShapes::Create ); m_settings.RegisterTest("Spring Test", &SpringTest::Create ); m_settings.RegisterTest("Prismatic Test", &PrismaticTest::Create ); m_settings.RegisterTest("Wheel Test", &WheelTest::Create ); m_settings.RegisterTest("Weld Test", &WeldTest::Create ); m_settings.RegisterTest("Cone Test", &ConeTest::Create ); m_settings.RegisterTest("Motor Test", &MotorTest::Create ); m_settings.RegisterTest("Revolute Test", &RevoluteTest::Create ); m_settings.RegisterTest("Hinge Chain", &HingeChain::Create ); m_settings.RegisterTest("Ragdoll", &Ragdoll::Create ); m_settings.RegisterTest("Newton's Cradle", &NewtonCradle::Create ); m_settings.RegisterTest("Sphere Stack", &SphereStack::Create ); m_settings.RegisterTest("Capsule Stack", &CapsuleStack::Create ); m_settings.RegisterTest("Box Stack", &BoxStack::Create ); m_settings.RegisterTest("Sheet Stack", &SheetStack::Create ); m_settings.RegisterTest("Shape Stack", &ShapeStack::Create ); m_settings.RegisterTest("Jenga", &Jenga::Create ); m_settings.RegisterTest("Box Pyramid", &Pyramid::Create ); m_settings.RegisterTest("Box Pyramid Rows", &Pyramids::Create ); m_settings.RegisterTest("Ray Cast", &RayCast::Create ); m_settings.RegisterTest("Shape Cast", &ShapeCast::Create ); m_settings.RegisterTest("Sensor Test", &SensorTest::Create ); m_settings.RegisterTest("Body Types", &BodyTypes::Create ); m_settings.RegisterTest("Varying Friction", &VaryingFriction::Create ); m_settings.RegisterTest("Varying Restitution", &VaryingRestitution::Create ); m_settings.RegisterTest("Tumbler", &Tumbler::Create ); m_settings.RegisterTest("Initial Overlap", &InitialOverlap::Create ); m_settings.RegisterTest("Multiple Pendulum", &MultiplePendulum::Create ); m_settings.RegisterTest("Conveyor Belt", &ConveyorBelt::Create ); m_settings.RegisterTest("Rope", &Rope::Create); g_settings = &m_settings; g_testSettings = &m_testSettings; } ViewModel::~ViewModel() { g_settings = nullptr; g_testSettings = nullptr; } b3Vec2 ViewModel::GetCursorPosition() const { double x, y; glfwGetCursorPos(m_window, &x, &y); return b3Vec2(scalar(x), scalar(y)); } void ViewModel::Action_SetTest() { m_model->Action_SetTest(); } void ViewModel::Action_PreviousTest() { m_settings.testID = b3Clamp(m_settings.testID - 1, 0, int(m_settings.testCount) - 1); m_model->Action_SetTest(); } void ViewModel::Action_NextTest() { m_settings.testID = b3Clamp(m_settings.testID + 1, 0, int(m_settings.testCount) - 1); m_model->Action_SetTest(); } void ViewModel::Action_PlayPause() { m_testSettings.pause = !m_testSettings.pause; } void ViewModel::Action_SinglePlay() { m_testSettings.pause = true; m_testSettings.singlePlay = true; } void ViewModel::Action_ResetCamera() { m_model->Action_ResetCamera(); } void ViewModel::Event_SetWindowSize(int w, int h) { m_model->Command_ResizeCamera(scalar(w), scalar(h)); } void ViewModel::Event_Press_Key(int button) { bool shiftDown = glfwGetKey(m_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS; if (shiftDown) { if (button == GLFW_KEY_DOWN) { m_model->Command_ZoomCamera(1.0f); } if (button == GLFW_KEY_UP) { m_model->Command_ZoomCamera(-1.0f); } } else { m_model->Command_Press_Key(button); } } void ViewModel::Event_Release_Key(int button) { bool shiftDown = glfwGetKey(m_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS; if (!shiftDown) { m_model->Command_Release_Key(button); } } void ViewModel::Event_Press_Mouse(int button) { if (button == GLFW_MOUSE_BUTTON_LEFT) { bool shiftDown = glfwGetKey(m_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS; if (!shiftDown) { m_model->Command_Press_Mouse_Left(GetCursorPosition()); } } } void ViewModel::Event_Release_Mouse(int button) { if (button == GLFW_MOUSE_BUTTON_LEFT) { bool shiftDown = glfwGetKey(m_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS; if (!shiftDown) { m_model->Command_Release_Mouse_Left(GetCursorPosition()); } } } void ViewModel::Event_Move_Cursor(float x, float y) { b3Vec2 ps; ps.Set(x, y); b3Vec2 dp = ps - m_ps0; m_ps0 = ps; b3Vec2 n = b3Normalize(dp); bool shiftDown = glfwGetKey(m_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS; bool leftDown = glfwGetMouseButton(m_window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; bool rightDown = glfwGetMouseButton(m_window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS; if (shiftDown) { if (leftDown) { scalar ax = -0.005f * B3_PI * n.x; scalar ay = -0.005f * B3_PI * n.y; m_model->Command_RotateCameraY(ax); m_model->Command_RotateCameraX(ay); } if (rightDown) { scalar tx = 0.2f * n.x; scalar ty = -0.2f * n.y; m_model->Command_TranslateCameraX(tx); m_model->Command_TranslateCameraY(ty); } } else { m_model->Command_Move_Cursor(ps); } } void ViewModel::Event_Scroll(float dx, float dy) { b3Vec2 n(dx, dy); n.Normalize(); bool shiftDown = glfwGetKey(m_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS; if (shiftDown) { m_model->Command_ZoomCamera(1.0f * n.y); } }
30.095541
86
0.750053
irlanrobson
8bf55ffa6d4fc0c15dda133810e874c97d06dc38
22,546
cpp
C++
lib/AFE-APIs/AFE-API-MQTT-Domoticz.cpp
lukasz-pekala/AFE-Firmware
59e10dd2f9665ba816c22905e63eaa60ec8fda09
[ "MIT" ]
null
null
null
lib/AFE-APIs/AFE-API-MQTT-Domoticz.cpp
lukasz-pekala/AFE-Firmware
59e10dd2f9665ba816c22905e63eaa60ec8fda09
[ "MIT" ]
null
null
null
lib/AFE-APIs/AFE-API-MQTT-Domoticz.cpp
lukasz-pekala/AFE-Firmware
59e10dd2f9665ba816c22905e63eaa60ec8fda09
[ "MIT" ]
null
null
null
/* AFE Firmware for smart home devices, Website: https://afe.smartnydom.pl/ */ #include "AFE-API-MQTT-Domoticz.h" #ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED AFEAPIMQTTDomoticz::AFEAPIMQTTDomoticz() : AFEAPI(){}; #ifdef AFE_CONFIG_HARDWARE_LED void AFEAPIMQTTDomoticz::begin(AFEDataAccess *Data, AFEDevice *Device, AFELED *Led) { AFEAPI::begin(Data, Device, Led); #ifdef DEBUG Serial << endl << F("INFO: Domoticz version: ") << (Device->configuration.api.domoticzVersion == AFE_DOMOTICZ_VERSION_0 ? L_DOMOTICZ_VERSION_410 : L_DOMOTICZ_VERSION_2020); #endif } #else void AFEAPIMQTTDomoticz::begin(AFEDataAccess *Data, AFEDevice *Device) { AFEAPI::begin(Data, Device); } #endif // AFE_CONFIG_HARDWARE_LED void AFEAPIMQTTDomoticz::listener() { if (Mqtt.listener()) { #ifdef AFE_CONFIG_API_PROCESS_REQUESTS processRequest(); #endif } } void AFEAPIMQTTDomoticz::synchronize() { #ifdef DEBUG Serial << endl << F("INFO: Sending current device state to MQTT Broker ..."); #endif /* Synchronize: Relay */ #ifdef AFE_CONFIG_HARDWARE_RELAY for (uint8_t i = 0; i < _Device->configuration.noOfRelays; i++) { #ifdef DEBUG Serial << endl << F("INFO: Synchronizing RELAY: ") << i; #endif publishRelayState(i); } #endif /* Synchronize: Switch */ #ifdef AFE_CONFIG_HARDWARE_SWITCH for (uint8_t i = 0; i < _Device->configuration.noOfSwitches; i++) { #ifdef DEBUG Serial << endl << F("INFO: Synchronizing SWITCH: ") << i; #endif publishSwitchState(i); } #endif /* Synchronize: Contactron */ #ifdef AFE_CONFIG_HARDWARE_CONTACTRON for (uint8_t i = 0; i < _Device->configuration.noOfContactrons; i++) { #ifdef DEBUG Serial << endl << F("INFO: Synchronizing CONTACTRON: ") << i; #endif publishContactronState(i); } #endif /* Synchronize: Gate */ #ifdef AFE_CONFIG_HARDWARE_GATE for (uint8_t i = 0; i < _Device->configuration.noOfGates; i++) { #ifdef DEBUG Serial << endl << F("INFO: Synchronizing GATE: ") << i; #endif publishGateState(i); } #endif #ifdef DEBUG Serial << endl << F("INFO: Sending message: device is connected ..."); #endif if (Mqtt.configuration.lwt.idx > 0) { char lwtMessage[100]; sprintf( lwtMessage, "{\"command\":\"udevice\",\"idx\":%d,\"nvalue\":1,\"svalue\":\"%s\"," "\"Battery\":100,\"RSSI\":%d}", Mqtt.configuration.lwt.idx, L_CONNECTED, getRSSI()); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, lwtMessage); } } void AFEAPIMQTTDomoticz::subscribe() { #ifdef DEBUG Serial << endl << F("INFO: Subsribing to MQTT Topics ..."); #endif Mqtt.subscribe(AFE_CONFIG_API_DOMOTICZ_TOPIC_OUT); } #ifdef AFE_CONFIG_API_PROCESS_REQUESTS DOMOTICZ_MQTT_COMMAND AFEAPIMQTTDomoticz::getCommand() { DOMOTICZ_MQTT_COMMAND command; char json[Mqtt.message.length]; for (uint16_t i = 0; i < Mqtt.message.length; i++) { json[i] = Mqtt.message.content[i]; } StaticJsonBuffer<AFE_CONFIG_API_JSON_BUFFER_SIZE> jsonBuffer; JsonObject &root = jsonBuffer.parseObject(json); if (root.success()) { command.domoticz.idx = root["idx"]; command.nvalue = root["nvalue"]; #ifdef DEBUG Serial << endl << F("INFO: Domoticz: Got command: ") << command.nvalue << F(", IDX: ") << command.domoticz.idx; #endif } #ifdef DEBUG else { Serial << endl << F("ERROR: Domoticz: Problem with JSON pharsing"); } #endif return command; } #endif #ifdef AFE_CONFIG_API_PROCESS_REQUESTS void AFEAPIMQTTDomoticz::processRequest() { DOMOTICZ_MQTT_COMMAND command = getCommand(); if (command.domoticz.idx > 0 && idxForProcessing(command.domoticz.idx)) { #ifdef DEBUG uint8_t _found = false; #endif for (uint8_t i = 0; i < lastIDXChacheIndex; i++) { if (idxCache[i].domoticz.idx == command.domoticz.idx) { switch (idxCache[i].type) { /* Processing Relay command*/ case AFE_DOMOTICZ_DEVICE_RELAY: #ifdef DEBUG Serial << endl << F("INFO: Domoticz: Found Relay ID: ") << idxCache[i].id; _found = true; #endif if (_Relay[idxCache[i].id]->get() != (byte)command.nvalue) { if (command.nvalue == AFE_SWITCH_OFF) { _Relay[idxCache[i].id]->off(); } else { _Relay[idxCache[i].id]->on(); } publishRelayState(idxCache[i].id); } #ifdef DEBUG else { Serial << endl << F("WARN: Domoticz: Same state. No change needed"); } #endif break; #ifdef AFE_CONFIG_HARDWARE_GATE /* Processing Gate command*/ case AFE_DOMOTICZ_DEVICE_GATE: #ifdef DEBUG Serial << endl << F("INFO: Domoticz: Found Gate ID: ") << idxCache[i].id; _found = true; #endif if (command.nvalue == AFE_SWITCH_ON) { _Gate[idxCache[i].id]->toggle(); } #ifdef DEBUG else { Serial << endl << F("INFO: OFF Command, skipping"; } #endif #endif // AFE_CONFIG_HARDWARE_GATE break; /* Processing Unknown command*/ default: #ifdef DEBUG Serial << endl << F("ERROR: Domoticz: Device type not handled. Type: ") << idxCache[i].type; #endif break; } } } #ifdef DEBUG if (!_found) { Serial << endl << F("WARN: Domoticz: No item found with IDX: ") << command.domoticz.idx; } #endif } #ifdef DEBUG else { Serial << endl << (command.domoticz.idx > 0 ? "INFO: Domoticz: Bypassing IDX: " : " - no IDX: ") << command.domoticz.idx; } #endif } #endif // AFE_CONFIG_API_PROCESS_REQUESTS #ifdef AFE_CONFIG_API_PROCESS_REQUESTS boolean AFEAPIMQTTDomoticz::idxForProcessing(uint32_t idx) { boolean _ret = true; // Returns true if Domoticz is in version 2020.x. All requests are processed if (idx == bypassProcessing.idx && _Device->configuration.api.domoticzVersion == AFE_DOMOTICZ_VERSION_0) { bypassProcessing.idx = 0; _ret = false; } return _ret; } #endif // AFE_CONFIG_API_PROCESS_REQUESTS #ifdef AFE_CONFIG_HARDWARE_RELAY void AFEAPIMQTTDomoticz::addClass(AFERelay *Relay) { AFEAPI::addClass(Relay); #ifdef DEBUG Serial << endl << F("INFO: Caching IDXs for Relays"); #endif for (uint8_t i = 0; i < _Device->configuration.noOfRelays; i++) { if (_Relay[i]->configuration.domoticz.idx > 0) { idxCache[lastIDXChacheIndex].domoticz.idx = _Relay[i]->configuration.domoticz.idx; idxCache[lastIDXChacheIndex].id = i; idxCache[lastIDXChacheIndex].type = AFE_DOMOTICZ_DEVICE_RELAY; #ifdef DEBUG Serial << endl << F(" - added IDX: ") << idxCache[lastIDXChacheIndex].domoticz.idx; #endif lastIDXChacheIndex++; } #ifdef DEBUG else { Serial << endl << F(" - IDX not set"); } #endif } } #endif // AFE_CONFIG_HARDWARE_RELAY #ifdef AFE_CONFIG_API_PROCESS_REQUESTS boolean AFEAPIMQTTDomoticz::publishRelayState(uint8_t id) { #ifdef DEBUG Serial << endl << F("INFO: Publishing relay: ") << id << F(", IDX: ") << idxCache[id].domoticz.idx << F(" state"); #endif boolean publishStatus = false; if (enabled && _Relay[id]->configuration.domoticz.idx > 0) { char json[AFE_CONFIG_API_JSON_SWITCH_COMMAND_LENGTH]; generateSwitchMessage(json, _Relay[id]->configuration.domoticz.idx, _Relay[id]->get()); publishStatus = Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); bypassProcessing.idx = _Relay[id]->configuration.domoticz.idx; } #ifdef DEBUG else { Serial << endl << F("INFO: Not published"); } #endif return publishStatus; } #endif // AFE_CONFIG_API_PROCESS_REQUESTS #ifdef AFE_CONFIG_HARDWARE_SWITCH void AFEAPIMQTTDomoticz::addClass(AFESwitch *Switch) { AFEAPI::addClass(Switch); } #endif // AFE_CONFIG_HARDWARE_SWITCH #ifdef AFE_CONFIG_HARDWARE_SWITCH boolean AFEAPIMQTTDomoticz::publishSwitchState(uint8_t id) { boolean publishStatus = false; if (enabled && _Switch[id]->configuration.domoticz.idx) { char json[AFE_CONFIG_API_JSON_SWITCH_COMMAND_LENGTH]; generateSwitchMessage(json, _Switch[id]->configuration.domoticz.idx, _Switch[id]->getPhisicalState() == 1 ? AFE_SWITCH_OFF : AFE_SWITCH_ON); publishStatus = Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } return publishStatus; } #endif // AFE_CONFIG_HARDWARE_SWITCH #ifdef AFE_CONFIG_HARDWARE_ADC_VCC void AFEAPIMQTTDomoticz::addClass(AFEAnalogInput *Analog) { AFEAPI::addClass(Analog); } #endif #ifdef AFE_CONFIG_HARDWARE_ADC_VCC void AFEAPIMQTTDomoticz::publishADCValues() { if (enabled) { char json[AFE_CONFIG_API_JSON_DEVICE_COMMAND_LENGTH]; char value[20]; if (_AnalogInput->configuration.domoticz.percent > 0) { sprintf(value, "%-.2f", _AnalogInput->data.percent); generateDeviceValue(json, _AnalogInput->configuration.domoticz.percent, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_AnalogInput->configuration.domoticz.voltage > 0) { sprintf(value, "%-.4f", _AnalogInput->data.voltage); generateDeviceValue(json, _AnalogInput->configuration.domoticz.voltage, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_AnalogInput->configuration.domoticz.voltageCalculated > 0) { sprintf(value, "%-.4f", _AnalogInput->data.voltageCalculated); generateDeviceValue( json, _AnalogInput->configuration.domoticz.voltageCalculated, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_AnalogInput->configuration.domoticz.raw > 0) { sprintf(value, "%-d", _AnalogInput->data.raw); generateDeviceValue(json, _AnalogInput->configuration.domoticz.raw, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } } #endif #ifdef AFE_CONFIG_FUNCTIONALITY_BATTERYMETER void AFEAPIMQTTDomoticz::publishBatteryMeterValues() { if (enabled) { char json[AFE_CONFIG_API_JSON_BATTERYMETER_COMMAND_LENGTH]; char value[8]; if (_AnalogInput->configuration.battery.domoticz.idx > 0) { sprintf(value, "%-.3f", _AnalogInput->batteryPercentage); generateDeviceValue(json, _AnalogInput->configuration.battery.domoticz.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } } #endif // AFE_CONFIG_FUNCTIONALITY_BATTERYMETER void AFEAPIMQTTDomoticz::generateSwitchMessage(char *json, uint32_t idx, boolean state) { sprintf(json, "{\"command\":\"switchlight\",\"idx\":%d,\"switchcmd\":\"%s\"}", idx, state ? "On" : "Off"); } void AFEAPIMQTTDomoticz::generateDeviceValue(char *json, uint32_t idx, char *svalue, uint8_t nvalue) { sprintf( json, "{\"command\":\"udevice\",\"idx\":%d,\"nvalue\":%d,\"svalue\":\"%s\"}", idx, nvalue, svalue); } uint8_t AFEAPIMQTTDomoticz::getRSSI() { uint8_t _ret; long current = WiFi.RSSI(); if (current > -50) { _ret = 10; } else if (current < -98) { _ret = 0; } else { _ret = ((current + 97) / 5) + 1; } return _ret; } #ifdef AFE_CONFIG_HARDWARE_BMEX80 void AFEAPIMQTTDomoticz::addClass(AFESensorBMEX80 *Sensor) { AFEAPI::addClass(Sensor); } boolean AFEAPIMQTTDomoticz::publishBMx80SensorData(uint8_t id) { if (enabled) { char json[AFE_CONFIG_API_JSON_DEVICE_COMMAND_LENGTH]; char value[50]; if (_BMx80Sensor[id]->configuration.domoticz.temperature.idx > 0) { sprintf(value, "%-.2f", _BMx80Sensor[id]->data.temperature.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.temperature.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.pressure.idx > 0) { sprintf(value, "%-.2f;0", _BMx80Sensor[id]->data.pressure.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.pressure.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.relativePressure.idx > 0) { sprintf(value, "%-.2f;0", _BMx80Sensor[id]->data.relativePressure.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.relativePressure.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.type != AFE_BMP180_SENSOR) { if (_BMx80Sensor[id]->configuration.domoticz.temperatureHumidity.idx > 0) { sprintf(value, "%-.2f;%-.2f;%-d", _BMx80Sensor[id]->data.temperature.value, _BMx80Sensor[id]->data.humidity.value, _BMx80Sensor[id]->getDomoticzHumidityState( _BMx80Sensor[id]->data.humidity.value)); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.temperatureHumidity.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id] ->configuration.domoticz.temperatureHumidityPressure.idx > 0) { sprintf(value, "%-.2f;%-.2f;%-d;%-.2f;0", _BMx80Sensor[id]->data.temperature.value, _BMx80Sensor[id]->data.humidity.value, _BMx80Sensor[id]->getDomoticzHumidityState( _BMx80Sensor[id]->data.humidity.value), _BMx80Sensor[id]->data.pressure.value); generateDeviceValue( json, _BMx80Sensor[id] ->configuration.domoticz.temperatureHumidityPressure.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.humidity.idx > 0) { sprintf(value, "%d", _BMx80Sensor[id]->getDomoticzHumidityState( _BMx80Sensor[id]->data.humidity.value)); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.humidity.idx, value, (uint8_t)_BMx80Sensor[id]->data.humidity.value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.dewPoint.idx > 0) { sprintf(value, "%-.2f", _BMx80Sensor[id]->data.dewPoint.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.dewPoint.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.heatIndex.idx > 0) { sprintf(value, "%-.2f", _BMx80Sensor[id]->data.heatIndex.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.heatIndex.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } if (_BMx80Sensor[id]->configuration.type == AFE_BME680_SENSOR) { if (_BMx80Sensor[id]->configuration.domoticz.gasResistance.idx > 0) { sprintf(value, "%-.2f", _BMx80Sensor[id]->data.gasResistance.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.gasResistance.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.iaq.idx > 0) { sprintf(value, "%-.0f", _BMx80Sensor[id]->data.iaq.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.iaq.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.staticIaq.idx > 0) { sprintf(value, "%-.0f", _BMx80Sensor[id]->data.staticIaq.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.staticIaq.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.co2Equivalent.idx > 0) { sprintf(value, "%-.0f", _BMx80Sensor[id]->data.co2Equivalent.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.co2Equivalent.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_BMx80Sensor[id]->configuration.domoticz.breathVocEquivalent.idx > 0) { sprintf(value, "%-.1f", _BMx80Sensor[id]->data.breathVocEquivalent.value); generateDeviceValue( json, _BMx80Sensor[id]->configuration.domoticz.breathVocEquivalent.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } } return true; } #endif // AFE_CONFIG_HARDWARE_BMEX80 #ifdef AFE_CONFIG_HARDWARE_HPMA115S0 void AFEAPIMQTTDomoticz::addClass(AFESensorHPMA115S0 *Sensor) { AFEAPI::addClass(Sensor); } boolean AFEAPIMQTTDomoticz::publishHPMA115S0SensorData(uint8_t id) { if (enabled) { char json[AFE_CONFIG_API_JSON_DEVICE_COMMAND_LENGTH]; char value[5]; if (_HPMA115S0Sensor[id]->configuration.domoticz.pm25.idx > 0) { sprintf(value, "%-d", _HPMA115S0Sensor[id]->data.pm25); generateDeviceValue( json, _HPMA115S0Sensor[id]->configuration.domoticz.pm25.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } if (_HPMA115S0Sensor[id]->configuration.domoticz.pm10.idx > 0) { sprintf(value, "%-d", _HPMA115S0Sensor[id]->data.pm10); generateDeviceValue( json, _HPMA115S0Sensor[id]->configuration.domoticz.pm10.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } return true; } #endif // AFE_CONFIG_HARDWARE_HPMA115S0 #ifdef AFE_CONFIG_HARDWARE_BH1750 void AFEAPIMQTTDomoticz::addClass(AFESensorBH1750 *Sensor) { AFEAPI::addClass(Sensor); } boolean AFEAPIMQTTDomoticz::publishBH1750SensorData(uint8_t id) { if (enabled) { if (_BH1750Sensor[id]->configuration.domoticz.idx > 0) { char json[AFE_CONFIG_API_JSON_DEVICE_COMMAND_LENGTH]; char value[6]; sprintf(value, "%-.0f", _BH1750Sensor[id]->data); generateDeviceValue(json, _BH1750Sensor[id]->configuration.domoticz.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } return true; } #endif // AFE_CONFIG_HARDWARE_BH1750 #ifdef AFE_CONFIG_HARDWARE_AS3935 void AFEAPIMQTTDomoticz::addClass(AFESensorAS3935 *Sensor) { AFEAPI::addClass(Sensor); } boolean AFEAPIMQTTDomoticz::publishAS3935SensorData(uint8_t id) { if (enabled) { if (_AS3935Sensor[id]->configuration.domoticz.idx > 0) { char json[AFE_CONFIG_API_JSON_DEVICE_COMMAND_LENGTH]; char value[4]; sprintf(value, "%-d", _AS3935Sensor[id]->distance); generateDeviceValue(json, _AS3935Sensor[id]->configuration.domoticz.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } return true; } #endif // AFE_CONFIG_HARDWARE_AS3935 #ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR void AFEAPIMQTTDomoticz::addClass(AFESensorAnemometer *Sensor) { AFEAPI::addClass(Sensor); } void AFEAPIMQTTDomoticz::publishAnemometerSensorData() { if (enabled) { char json[AFE_CONFIG_API_JSON_ANEMOMETER_COMMAND_LENGTH]; char value[20]; if (_AnemometerSensor->configuration.domoticz.idx > 0) { sprintf(value, "0;N;%-.2f;0;?;?", 10 * _AnemometerSensor->lastSpeedMS); generateDeviceValue(json, _AnemometerSensor->configuration.domoticz.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } } #endif // AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR #ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR void AFEAPIMQTTDomoticz::addClass(AFESensorRainmeter *Sensor) { AFEAPI::addClass(Sensor); } void AFEAPIMQTTDomoticz::publishRainSensorData() { if (enabled) { char json[AFE_CONFIG_API_JSON_RAINMETER_COMMAND_LENGTH]; char value[20]; if (_RainmeterSensor->configuration.domoticz.idx > 0) { sprintf(value, "%-.2f;%-.2f", _RainmeterSensor->rainLevelLastHour * 100, _RainmeterSensor->current.counter); generateDeviceValue(json, _RainmeterSensor->configuration.domoticz.idx, value); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } } } #endif // AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR #ifdef AFE_CONFIG_HARDWARE_GATE void AFEAPIMQTTDomoticz::addClass(AFEGate *Item) { AFEAPI::addClass(Item); #ifdef DEBUG Serial << endl << F("INFO: Caching IDXs for Gates"; #endif for (uint8_t i = 0; i < _Device->configuration.noOfGates; i++) { if (_Gate[i]->configuration.domoticzControl.idx > 0) { idxCache[lastIDXChacheIndex].domoticz.idx = _Gate[i]->configuration.domoticzControl.idx; idxCache[lastIDXChacheIndex].id = i; idxCache[lastIDXChacheIndex].type = AFE_DOMOTICZ_DEVICE_GATE; #ifdef DEBUG Serial << endl << F(" - added IDX: ") << idxCache[lastIDXChacheIndex].domoticz.idx; #endif lastIDXChacheIndex++; } #ifdef DEBUG else { Serial << endl << F(" - IDX not set"; } #endif } } boolean AFEAPIMQTTDomoticz::publishGateState(uint8_t id) { if (enabled && _Gate[id]->configuration.domoticz.idx > 0) { char json[AFE_CONFIG_API_JSON_GATE_COMMAND_LENGTH]; generateSwitchMessage(json, _Gate[id]->configuration.domoticz.idx, _Gate[id]->get() == AFE_GATE_CLOSED ? false : true); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } return true; } #endif #ifdef AFE_CONFIG_HARDWARE_CONTACTRON void AFEAPIMQTTDomoticz::addClass(AFEContactron *Item) { AFEAPI::addClass(Item); } boolean AFEAPIMQTTDomoticz::publishContactronState(uint8_t id) { if (enabled && _Contactron[id]->configuration.domoticz.idx > 0) { char json[AFE_CONFIG_API_JSON_CONTACTRON_COMMAND_LENGTH]; generateSwitchMessage( json, _Contactron[id]->configuration.domoticz.idx, _Contactron[id]->get() == AFE_CONTACTRON_OPEN ? true : false); Mqtt.publish(AFE_CONFIG_API_DOMOTICZ_TOPIC_IN, json); } return true; } #endif #endif // AFE_CONFIG_API_DOMOTICZ_ENABLED
33.204713
81
0.659762
lukasz-pekala
8bf64bb65d47dd57613615571f2a57962186f992
2,938
cpp
C++
Array/Subarray or Subsequence Related Problems/Find all unique pairs of max & second max elements over all sub arrays.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Array/Subarray or Subsequence Related Problems/Find all unique pairs of max & second max elements over all sub arrays.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Array/Subarray or Subsequence Related Problems/Find all unique pairs of max & second max elements over all sub arrays.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// Ref: https://www.geeksforgeeks.org/find-all-unique-pairs-of-maximum-and-second-maximum-elements-over-all-sub-arrays-in-onlogn/ // Similar ques based on this: https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/little-shino-and-pairs/ /**************************************************************************************************************************************************************/ // Problem: Sed Max // Contest: CodeChef - February Lunchtime 2021 Division 2 // URL: https://www.codechef.com/LTIME93B/problems/SEDMAX // Memory Limit: 256 MB // Time Limit: 1000 ms // Parsed on: 05-03-2021 21:57:52 IST (UTC+05:30) // Author: Kapil Choudhary // ******************************************************************** // कर्मण्येवाधिकारस्ते मा फलेषु कदाचन | // मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि || १.४७ || // ******************************************************************** #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; set<pii> find_pairs(vi &v, int n) { set<pii> s; stack<int> stk; // Push first element into stack stk.push(v[0]); // For each element 'x' in v[], pop the stack while top element // is smaller than 'x' and form a pair. // If the stack is not empty after the previous operation, create // a pair. // Push 'x' into the stack. for(int i = 1; i < n; i++) { while(!stk.empty() and v[i] > stk.top()) { s.insert({stk.top(), v[i]}); stk.pop(); } if(!stk.empty()) s.insert({v[i], stk.top()}); stk.push(v[i]); } return s; } void solve() { int n; cin >> n; vi v(n); for(auto &x: v) cin >> x; set<pii> s = find_pairs(v, n); set<int> res; for(auto p: s) { res.insert(p.S - p.F); } cout << res.size() << "\n"; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; cin >> t; while(t--) { solve(); } return 0; }
27.716981
160
0.561266
Edith-3000
8bf8b20421748bf925d7480b4ed48c4d030305a0
728
hpp
C++
include/rcmp/detail/exception.hpp
Smertig/rcmp
72cef849f9de81f483347ae045ac02b3401f9aa2
[ "MIT" ]
41
2020-10-03T20:44:52.000Z
2022-03-09T07:07:16.000Z
include/rcmp/detail/exception.hpp
Smertig/rcmp
72cef849f9de81f483347ae045ac02b3401f9aa2
[ "MIT" ]
1
2020-11-09T13:11:47.000Z
2020-11-09T14:08:27.000Z
include/rcmp/detail/exception.hpp
Smertig/rcmp
72cef849f9de81f483347ae045ac02b3401f9aa2
[ "MIT" ]
3
2020-10-04T15:10:11.000Z
2021-01-18T05:16:07.000Z
#pragma once #include <stdexcept> #include <cstdio> #include <cinttypes> #include <string> namespace rcmp { class error : public std::exception { std::string m_message; public: template <class... Args> explicit error(const char* fmt, const Args& ...args) { if constexpr (sizeof...(Args) > 0) { const auto len = std::snprintf(nullptr, 0, fmt, args...); m_message.resize(len + 1); snprintf(m_message.data(), m_message.size(), fmt, args...); m_message.pop_back(); // drop '\0' } else { m_message = fmt; } } const char* what() const noexcept final { return m_message.c_str(); } }; } // namespace rcmp
21.411765
71
0.563187
Smertig
8bf9390fb8c55c557f93e7620557e5806642a8a2
736
cpp
C++
Leetcode/String/consecutive-characters.cpp
susantabiswas/competitive_coding
49163ecdc81b68f5c1bd90988cc0dfac34ad5a31
[ "MIT" ]
2
2021-04-29T14:44:17.000Z
2021-10-01T17:33:22.000Z
Leetcode/String/consecutive-characters.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
null
null
null
Leetcode/String/consecutive-characters.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
1
2021-10-01T17:33:29.000Z
2021-10-01T17:33:29.000Z
/* https://leetcode.com/problems/consecutive-characters/ Idea is to traverse the array and look at the previous char each time to decide if are still part of the window with only 1 unique char. TC: O(N) */ class Solution { public: int maxPower(string s) { int curr_len = s.empty() ? 0 : 1; int max_len = curr_len; for(int i = 1; i < s.size(); i++) { // same char as before means we can continue with same window if(s[i] == s[i-1]) { ++curr_len; max_len = max(max_len, curr_len); } // reset window else curr_len = 1; } return max_len; } };
26.285714
73
0.504076
susantabiswas
8bffd41371efc8e0baead592cd97eaa3717c7f8c
888
hpp
C++
include/lab4.hpp
shockkolate/gameai-gecode
703849d96d1faf652c3931f1204dfa347216ea72
[ "Unlicense" ]
null
null
null
include/lab4.hpp
shockkolate/gameai-gecode
703849d96d1faf652c3931f1204dfa347216ea72
[ "Unlicense" ]
null
null
null
include/lab4.hpp
shockkolate/gameai-gecode
703849d96d1faf652c3931f1204dfa347216ea72
[ "Unlicense" ]
null
null
null
#pragma once #include <iostream> #include <gecode/minimodel.hh> namespace gameai { namespace gecode { class lab4 : public Gecode::Space { private: const int count = 2; Gecode::IntVarArray xy; public: lab4() : xy(*this, count, -30, 30) { Gecode::IntVar x(xy[0]), y(xy[1]); Gecode::rel(*this, x * x + y * y == 5 * 5); Gecode::branch(*this, xy, Gecode::INT_VAR_SIZE_MIN(), Gecode::INT_VAL_MIN()); } lab4(const bool share, lab4 &s) : Gecode::Space(share, s) { xy.update(*this, share, s.xy); } Gecode::Space * copy (const bool share) { return new lab4(share, *this); } std::ostream & print(std::ostream &os) { return os << "lab4 { xy = {" << std::setw(3) << xy[0] << ", " << std::setw(3) << xy[1] << "} }" << std::endl; } }; } }
25.371429
66
0.503378
shockkolate
e300c3835723adc2ac8f96631835f79585fc5519
825
cpp
C++
libcaf_core/src/ipv4_endpoint.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
2,517
2015-01-04T22:19:43.000Z
2022-03-31T12:20:48.000Z
libcaf_core/src/ipv4_endpoint.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
894
2015-01-07T14:21:21.000Z
2022-03-30T06:37:18.000Z
libcaf_core/src/ipv4_endpoint.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
570
2015-01-21T18:59:33.000Z
2022-03-31T19:00:02.000Z
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #include "caf/ipv4_endpoint.hpp" #include "caf/hash/fnv.hpp" namespace caf { ipv4_endpoint::ipv4_endpoint(ipv4_address address, uint16_t port) : address_(address), port_(port) { // nop } size_t ipv4_endpoint::hash_code() const noexcept { return hash::fnv<size_t>::compute(address_, port_); } long ipv4_endpoint::compare(ipv4_endpoint x) const noexcept { auto res = address_.compare(x.address()); return res == 0 ? port_ - x.port() : res; } std::string to_string(const ipv4_endpoint& ep) { return to_string(ep.address()) + ":" + std::to_string(ep.port()); } } // namespace caf
27.5
77
0.721212
seewpx
bdd8e30a5ef9045038801d08182d9596122c0479
1,364
cpp
C++
src/CodeGen/TypeLowering.cpp
artagnon/rhine
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
[ "MIT" ]
234
2015-01-02T18:32:50.000Z
2022-02-03T19:41:33.000Z
src/CodeGen/TypeLowering.cpp
artagnon/rhine
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
[ "MIT" ]
7
2015-02-16T15:02:54.000Z
2016-05-26T07:46:02.000Z
src/CodeGen/TypeLowering.cpp
artagnon/rhine
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
[ "MIT" ]
13
2015-02-16T13:37:12.000Z
2020-12-12T04:18:43.000Z
#include "rhine/IR/Context.hpp" #include "rhine/IR/Type.hpp" #include "rhine/IR/Value.hpp" namespace rhine { llvm::Type *UnType::generate(llvm::Module *M) { assert(0 && "Cannot generate() without inferring type"); return nullptr; } llvm::Type *VoidType::generate(llvm::Module *M) { return context()->Builder->getVoidTy(); } llvm::Type *IntegerType::generate(llvm::Module *M) { switch (Bitwidth) { case 32: return context()->Builder->getInt32Ty(); case 64: return context()->Builder->getInt64Ty(); default: assert (0 && "int bitwidths other than 32 and 64 are unimplemented"); } return nullptr; } llvm::Type *BoolType::generate(llvm::Module *M) { return context()->Builder->getInt1Ty(); } llvm::Type *FloatType::generate(llvm::Module *M) { return context()->Builder->getFloatTy(); } llvm::Type *StringType::generate(llvm::Module *M) { return context()->Builder->getInt8PtrTy(); } llvm::Type *FunctionType::generate(llvm::Module *M) { auto ATys = getATys(); std::vector<llvm::Type *> ATyAr; if (ATys.size() != 1 || !isa<VoidType>(ATys[0])) for (auto Ty: getATys()) ATyAr.push_back(Ty->generate(M)); return llvm::FunctionType::get(returnType()->generate(M), ATyAr, isVariadic()); } llvm::Type *PointerType::generate(llvm::Module *M) { return llvm::PointerType::get(containedType()->generate(M), 0); } }
26.230769
81
0.670088
artagnon
bddb4c0ea0036bc0feca9882d2bd11ed4a072ac5
2,073
cpp
C++
code_snippets/Chapter26/chapter.26.3.3.2.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
170
2015-05-02T18:08:38.000Z
2018-07-31T11:35:17.000Z
code_snippets/Chapter26/chapter.26.3.3.2.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
7
2018-08-29T15:43:14.000Z
2021-09-23T21:56:49.000Z
code_snippets/Chapter26/chapter.26.3.3.2.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
105
2015-05-28T11:52:19.000Z
2018-07-17T14:11:25.000Z
// // This is example code from Chapter 26.3.3.2 "Resource management" of // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // #include <iostream> #include <fstream> #include <string> #include <vector> #include <stdio.h> using namespace std; //------------------------------------------------------------------------------ struct Bad_arg {}; //------------------------------------------------------------------------------ void do_resources1(int a, int b, const string& s) // messy function // undisciplined resource use { FILE* f = fopen(s.c_str(),"r"); // open file (C style) int* p = new int[a]; // allocate some memory if (b<=0) throw Bad_arg(); // maybe throw an exception int* q = new int[b]; // allocate some more memory delete[] p; // deallocate the memory pointed to by p } //------------------------------------------------------------------------------ void do_resources2(int a, int b, const string& s) // less messy function { ifstream is(s.c_str(),ios_base::in); // open file vector<int>v1(a); // create vector (owning memory) if (b<=0) throw Bad_arg(); // maybe throw an exception vector<int> v2(b); // create another vector (owning memory) } //------------------------------------------------------------------------------ int* var = 0; //------------------------------------------------------------------------------ FILE* do_resources3(int a, int* p, const string& s) // messy function // undisciplined resource passing { FILE* f = fopen(s.c_str(),"r"); delete p; delete var; var = new int[27]; return f; } //------------------------------------------------------------------------------ int main() try { } catch (exception& e) { cerr << "error: " << e.what() << '\n'; return 1; } catch (...) { cerr << "Oops: unknown exception!\n"; return 2; } //------------------------------------------------------------------------------
28.39726
80
0.421129
TingeOGinge
bddd26f2252a0cc0517610afee861fa518897760
1,088
cpp
C++
adapters/FCGI/src/FCGIContext.cpp
rfernandes/answer
aeb69e72308072c445a011a86ce4c6838af42a46
[ "MIT" ]
1
2015-06-26T02:31:43.000Z
2015-06-26T02:31:43.000Z
adapters/FCGI/src/FCGIContext.cpp
rfernandes/answer
aeb69e72308072c445a011a86ce4c6838af42a46
[ "MIT" ]
null
null
null
adapters/FCGI/src/FCGIContext.cpp
rfernandes/answer
aeb69e72308072c445a011a86ce4c6838af42a46
[ "MIT" ]
null
null
null
#include "FCGIContext.hh" #include <boost/algorithm/string.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> namespace answer { namespace adapter { namespace fcgi { using namespace std; using namespace Fastcgipp; FCGIContext::FCGIContext(const Fastcgipp::Http::Environment &env): _operation(env.requestUri) { _query = env.gets; _environment.insert(env.environment.begin(), env.environment.end()); // Accepts accepts(env.acceptContentTypes); boost::property_tree::ptree pt; if (!env.posts.empty()) { for (const auto & envPost : env.posts) { if (envPost.second.type == Http::Post::form) { pt.put(_operation.operation() + "." + envPost.first, envPost.second.value); } } } stringstream ss; boost::property_tree::write_xml(ss, pt); // Remove the xml header, header is always present Request req; req.body(ss.str().substr(ss.str().find_first_of("\n") + 1)); request(req); } OperationInfo &FCGIContext::operationInfo() { return _operation; } } //fcgi } //adapter } //answer
20.923077
83
0.6875
rfernandes
bddd47821e698aceca13eb46b78c0ae80edd1dc8
374
cpp
C++
src/utils/htmlutils.cpp
lizhyumzi/vnote
7c4d89b0272cf817902272e8733d56c2cddb797a
[ "MIT" ]
1
2021-09-13T04:38:27.000Z
2021-09-13T04:38:27.000Z
src/utils/htmlutils.cpp
micalstanley/vnote-1
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
null
null
null
src/utils/htmlutils.cpp
micalstanley/vnote-1
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
null
null
null
#include "htmlutils.h" #include <QRegExp> using namespace vnotex; bool HtmlUtils::hasOnlyImgTag(const QString &p_html) { // Tricky. QRegExp reg(QStringLiteral("<(?:p|span|div) ")); return !p_html.contains(reg); } QString HtmlUtils::escapeHtml(QString p_text) { p_text.replace(">", "&gt;").replace("<", "&lt;").replace("&", "&amp;"); return p_text; }
19.684211
75
0.644385
lizhyumzi
bde3fd581d1b4b58ee5617ac76b3af7cadd45c69
1,046
hpp
C++
include/utility/trait/type/categories/is_pointer.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
2
2017-12-10T10:59:48.000Z
2017-12-13T04:11:14.000Z
include/utility/trait/type/categories/is_pointer.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
include/utility/trait/type/categories/is_pointer.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
#ifndef __UTILITY_TRAIT_TYPE_CATEGORIES_IS_POINTER__ #define __UTILITY_TRAIT_TYPE_CATEGORIES_IS_POINTER__ #include<utility/trait/trait_helper.hpp> #include<utility/trait/type/transform/remove_cv.hpp> namespace utility { namespace trait { namespace type { namespace categories { // is_pointer namespace __is_pointer_impl { template<typename _T> struct __is_pointer_test : public trait::false_type { }; template<typename _T> struct __is_pointer_test<_T*> : public trait::true_type { }; } template<typename _T> struct is_pointer : public __is_pointer_impl::__is_pointer_test< typename trait::type::transform::remove_cv<_T>::type> { }; #if !defined(__UTILITY_NO_CPP14__) template<typename _T> constexpr bool is_pointer_v = is_pointer<_T>::value; #endif } } } } #endif // __UTILITY_TRAIT_TYPE_CATEGORIES_IS_POINTER__
22.73913
60
0.630019
SakuraLife
bde64c400c3bcff2576a84864e561b5cfabdf431
566
cpp
C++
OOP/Exercises/Semester2/23.1/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
OOP/Exercises/Semester2/23.1/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
OOP/Exercises/Semester2/23.1/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<myHeader.h> using namespace std; Point::Point(double x, double y) { this->_x = x; this->_y = y; } Point::Point(const Point &P) { this->_x = P._x; this->_y = P._y; } void Point::setPoint(double x, double y) { this->_x = x; this->_y = y; } void Point::showPoint() { cout << "X: " << this->_x << " - Y: " << this->_y << endl; } double Point::getX() const { return this->_x; } double Point::getY() const { return this->_y; } void Point::shiftAxis(double value) { this->_x -= value; this->_y -= value; }
12.304348
59
0.597173
Solaflex
bdeb7e69cc153950f4a428ed0437ddc6fa12c80c
4,373
cpp
C++
Engine/Renderer/Renderer.cpp
MadLadSquad/UntitledVulkanGameEngine
e7d41ab7fe6e104ad4aed6363cb384032ff6c184
[ "MIT" ]
16
2020-12-13T09:38:04.000Z
2022-03-20T14:33:55.000Z
Engine/Renderer/Renderer.cpp
MadLadSquad/UntitledVulkanGameEngine
e7d41ab7fe6e104ad4aed6363cb384032ff6c184
[ "MIT" ]
8
2020-12-25T14:49:41.000Z
2021-08-25T01:21:53.000Z
Engine/Renderer/Renderer.cpp
MadLadSquad/UntitledVulkanGameEngine
e7d41ab7fe6e104ad4aed6363cb384032ff6c184
[ "MIT" ]
4
2021-04-05T13:19:53.000Z
2022-03-18T10:56:35.000Z
// Renderer.cpp // Last update 22/9/2021 by Madman10K #include "Renderer.hpp" #include <Engine/Core/Core/Global.hpp> #include <GameFramework/GameplayClasses/Level/Level.hpp> #include <Renderer/EditorUI/Editor.hpp> UVK::Renderer::Renderer(UVK::Level* lvl, bool bUsesEditor) { startRenderer(lvl, bUsesEditor); } void UVK::Renderer::switchRenderer() { if (global.bUsesVulkan) global.bUsesVulkan = false; else global.bUsesVulkan = true; global.rendererSettings.saveSettings(); GameInstance::exit(); } void UVK::RendererSettings::saveSettings() const { YAML::Emitter out; out << YAML::BeginMap; out << YAML::Key << "vulkan" << YAML::Value << global.bUsesVulkan; out << YAML::Key << "theme" << YAML::Value << themeLoc; out << YAML::Key << "v-sync" << YAML::Value << bVsync; out << YAML::Key << "v-sync-immediate" << YAML::Value << bVsyncImmediate; out << YAML::Key << "max-saved-transactions" << YAML::Value << maxSavedTransactions; out << YAML::Key << "filesystem-file-padding" << YAML::Value << global.instance->editor->filesystemWidgetData.padding; out << YAML::Key << "filesystem-file-thumbnail-size" << YAML::Value << global.instance->editor->filesystemWidgetData.imageSize; out << YAML::Key << "filesystem-using-previews" << YAML::Value << global.instance->editor->filesystemWidgetData.bUsePreviews; out << YAML::Key << "filesystem-max-preview-files" << YAML::Value << global.instance->editor->filesystemWidgetData.maxFileNum; out << YAML::EndMap; std::ofstream fileout("../Config/Settings/Renderer.yaml"); fileout << out.c_str(); } void UVK::Renderer::startRenderer(UVK::Level* lvl, bool bUsesEditor) { loadSettings(); if (global.bUsesVulkan) { VulkanRenderer renderer{}; renderer.run(); } else { GLRenderer renderer(lvl, bUsesEditor, rs->themeLoc.c_str()); } } void UVK::Renderer::loadSettings() { YAML::Node a; bool bUsesConf = true; rs = &global.rendererSettings; try { a = YAML::LoadFile("../Config/Settings/Renderer.yaml"); } catch (YAML::BadFile&) { bUsesConf = false; logger.consoleLog("Invalid renderer file defaulting to OpenGL with default theme if the editor is in use!", UVK_LOG_TYPE_ERROR); } if (bUsesConf) { if (a["vulkan"]) global.bUsesVulkan = a["vulkan"].as<bool>(); if (a["theme"]) rs->themeLoc = a["theme"].as<std::string>(); if (a["v-sync"]) rs->bVsync = a["v-sync"].as<bool>(); if (a["v-sync-immediate"]) rs->bVsyncImmediate = a["v-sync-immediate"].as<bool>(); if (a["max-saved-transactions"]) { auto i = a["max-saved-transactions"].as<uint32_t>(); if (i <= 5) rs->maxSavedTransactions = 100; else rs->maxSavedTransactions = i; } } else { global.bUsesVulkan = false; } global.instance->stateTracker.init(); } bool& UVK::Renderer::getVSync() { return global.rendererSettings.bVsync; } void UVK::Renderer::saveSettings() { global.rendererSettings.saveSettings(); } bool& UVK::Renderer::getImmediateRender() { return global.rendererSettings.bVsyncImmediate; } void UVK::Renderer::loadFilesystemSettings() { YAML::Node a; bool bUsesConf = true; try { a = YAML::LoadFile("../Config/Settings/Renderer.yaml"); } catch (YAML::BadFile&) { bUsesConf = false; logger.consoleLog("Invalid renderer file defaulting to OpenGL with default theme if the editor is in use!", UVK_LOG_TYPE_ERROR); } if (bUsesConf) { if (a["filesystem-file-padding"]) global.instance->editor->filesystemWidgetData.padding = a["filesystem-file-padding"].as<float>(); if (a["filesystem-file-thumbnail-size"]) global.instance->editor->filesystemWidgetData.imageSize = a["filesystem-file-thumbnail-size"].as<float>(); if (a["filesystem-using-previews"]) global.instance->editor->filesystemWidgetData.bUsePreviews = a["filesystem-using-previews"].as<bool>(); if (a["filesystem-max-preview-files"]) global.instance->editor->filesystemWidgetData.maxFileNum = a["filesystem-max-preview-files"].as<uint32_t>(); } }
29.348993
136
0.62863
MadLadSquad