blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
72979cbe9e5ace50d5939d23c585fdff430b1379
61deafb2dcf4820d46f2500d12497a89ff66e445
/1775.cpp
43fdd114d4f83d409a0170326114c9c13ec000e1
[]
no_license
Otrebus/timus
3495f314587beade3de67890e65b6f72d53b3954
3a1dca43dc61b27c8f903a522743afeb69d38df2
refs/heads/master
2023-04-08T16:54:07.973863
2023-04-06T19:59:07
2023-04-06T19:59:07
38,758,841
72
40
null
null
null
null
UTF-8
C++
false
false
1,819
cpp
1775.cpp
/* 1775. Space Bowling - http://acm.timus.ru/problem.aspx?num=1775 * * Strategy: * For each pair of points, sort the other points by distance from the line spanning the pair and * use the kth such distance to update the global minimum. * * Performance: * O(N^3 log N), runs the tests in 0.764s using 404KB memory. */ #include <vector> #include <algorithm> #include <iostream> #include <iomanip> struct point { long long x, y; point operator-(const point& b) { return { x-b.x, y-b.y }; } long long dist2() { return x*x + y*y; } } points[200]; int main() { double ans = std::numeric_limits<double>::infinity(); int n, k; std::cin >> n >> k; for(int i = 0; i < n; i++) std::cin >> points[i].x >> points[i].y; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { std::vector<double> v = { 0, 0 }; for(int k = 0; k < n; k++) { if(k == i || k == j) continue; point p1 = points[i], p2 = points[j], p0 = points[k]; point u = p2 - p1; point w = p0 - p1; if(u.x*w.y - u.y*w.x > 0) // On the wrong side continue; // Calculate the distance from the point to the line double n = (p2.y - p1.y)*p0.x - (p2.x - p1.x)*p0.y + p2.x*p1.y - p2.y*p1.x; v.push_back(std::sqrt(n*n/double(u.dist2()))); } std::sort(v.begin(), v.end() ); if(v.size() > k-1 && ans > v[k-1]) ans = v[k-1]; } } if(ans == std::numeric_limits<double>::infinity() || std::abs(ans-0) < 1e-9) std::cout << "0.000000"; else std::cout << std::fixed << std::setprecision(10) << std::max(0.0, ans - 1.0); }
7b1838317102e9c74a3e8cc18d9a3d406eaf4f45
9b727ccbf91d12bbe10adb050784c04b4753758c
/ZOJ/ZOJ Monthly, June 2013/ZOJ3717.cpp
d5c6e7a070871f25eb658035c2deb51145401220
[]
no_license
codeAligned/acm-icpc-1
b57ab179228f2acebaef01082fe6b67b0cae6403
090acaeb3705b6cf48790b977514965b22f6d43f
refs/heads/master
2020-09-19T19:39:30.929711
2015-10-06T15:13:12
2015-10-06T15:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,867
cpp
ZOJ3717.cpp
#include <cmath> #include <vector> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; const int MAXN = 400 + 10; vector<int> G[MAXN]; int low[MAXN], dfn[MAXN], stk[MAXN], belong[MAXN]; int vis[MAXN], cnt, top, tid; void dfs(int x) { low[x] = dfn[x] = ++ tid; stk[top ++] = x; vis[x] = true; for (int i = 0, y; i < (int)G[x].size(); ++ i) { if (!dfn[y = G[x][i]]) { dfs(y); low[x] = min(low[x], low[y]); } else if (vis[y]) low[x] = min(low[x], dfn[y]); } if (dfn[x] == low[x]) { int y; do { y = stk[-- top]; vis[y] = false; belong[y] = cnt; } while (y != x); cnt ++; } } bool check(int n) { for (int i = 0; i < 2 * n; ++ i) { vis[i] = 0; dfn[i] = 0; } cnt = top = tid = 0; for (int i = 0; i < 2 * n; ++ i) if (!dfn[i]) dfs(i); for (int i = 0; i < 2 * n; ++ i) if (belong[i] == belong[i ^ 1]) return false; return true; } int x[MAXN], y[MAXN], z[MAXN]; inline double sqr(double x) {return x * x;} inline double dis(int i, int j) { return sqrt(sqr(x[i] - x[j]) + sqr(y[i] - y[j]) + sqr(z[i] - z[j])); } void build(int n, double lim) { for (int i = 0; i < 2 * n; ++ i) G[i].clear(); for (int i = 0; i < 2 * n; ++ i) { for (int j = i + 1; j < 2 * n; ++ j) { if ((i ^ 1) == j) continue; double d = dis(i, j); if (d < 2 * lim) { G[i].push_back(j ^ 1); G[j].push_back(i ^ 1); } } } } int main() { int n; while (scanf("%d", &n) == 1) { for (int i = 0; i < n; ++ i) { scanf("%d%d%d", &x[2 * i], &y[2 *i], &z[2 * i]); scanf("%d%d%d", &x[2 * i + 1], &y[2 *i + 1], &z[2 * i + 1]); } double left = 0, right = 20000; for (int times = 0; times < 100; ++ times) { double mid = (left + right) * 0.5; build(n, mid); if (check(n)) left = mid; else right = mid; } printf("%.3f\n", (int)(left * 1000)/1000.0); } return 0; }
4d213c43e8d8a523a4612805d8ac408cc3357515
7912617cf87b9104a6bd38231508535d959e998d
/gameengine/src/generic/TwoWayUnorderedMap.cpp
ac88899890c23c45b37d100f992c68fbcc4d24bf
[]
no_license
seckujdivad/gameengine
47ebb1ee98e09dcac38728f63d22f5aa99cc9303
50a676d4faeeeb68587133048444a153b8539186
refs/heads/master
2021-10-16T20:49:57.050929
2021-10-10T03:58:23
2021-10-10T03:58:23
222,322,461
5
0
null
2021-03-16T21:04:33
2019-11-17T22:43:54
C++
UTF-8
C++
false
false
31
cpp
TwoWayUnorderedMap.cpp
#include "TwoWayUnorderedMap.h"
79769ccbea8e5031f41b410b9a936bbdbff2f854
75cd69287a6063726be4496d2a3b2a100e69f12e
/chapter_15/funcmacro.cpp
c08722af08d561ace07a5f02f0a4a8f11a1950e5
[]
no_license
kou164nkn/tutorial-cpp
e63ee8bcedf4996c29da8080ec2fd4b0b95c9bb9
c93ee44f3ef63ec2ab63840378378a3c2148d3b1
refs/heads/master
2023-03-02T06:35:33.746880
2021-01-30T14:53:09
2021-01-30T14:53:09
275,815,304
0
0
null
2021-01-30T14:53:10
2020-06-29T12:56:20
C++
UTF-8
C++
false
false
485
cpp
funcmacro.cpp
#include <iostream> #define sqr(x) ((x) * (x)) #define sss(x) (#x) // # で受け取ったパラメータを文字列化する // デバッグ用マクロ // ... で可変数個のパラメータを受け取り __VA_ARGS__ でパラメータを使用する #define dbg(...) std::cout << #__VA_ARGS__ << " = " << [&]{ return __VA_ARGS__; }() <<std::endl; int main() { std::cout << sqr(4) << std::endl; // => 16 std::cout << sss(abcd) << std::endl; // => "abcd" dbg(3 * 4); }
a93b332660e66aa2133e808eeb69dbcc134fb506
6bf03623fbe8c90c32ba101f9d6f110f3c654ce3
/BOJ/알고리즘 분류/그리디/11047.cpp
31d677cd66d909d301787c33d63d9b5402376c6b
[]
no_license
yoogle96/algorithm
6d6a6360c0b2aae2b5a0735f7e0200b6fc37544e
bcc3232c705adc53a563681eeefd89e5b706566f
refs/heads/master
2022-12-27T05:15:04.388117
2020-10-09T14:48:58
2020-10-09T14:48:58
177,144,251
0
0
null
null
null
null
UTF-8
C++
false
false
660
cpp
11047.cpp
#include <cstdio> using namespace std; int main(void) { int n; int money; int count = 0; scanf("%d", &n); scanf("%d", &money); int * arr = new int(n); for(int i = 0 ; i < n; i++){ scanf("%d", &arr[i]); } for(int i = n-1; i >= 0; i--){ if(arr[i] > money){ continue; } else if(money <= 0){ break; } else{ while(1){ money -= arr[i]; count++; if(money < arr[i]){ break; } } } } printf("%d\n", count); return 0; }
0466ca435fcbd80725fe1888e20a5f825d5a218f
de81e62eb730b3ff0e8cfafbdfc5bdebf5083e7f
/src/LinearAlgebra.h
57388a88601f7142344271fe39e7513ab3e18118
[]
no_license
Siim-Alas/AeroOptimizer
d0069ee7032d202f8d014f52124f9720c1857fb0
06b971cad4d4ed9736ef9d6e677a104fa457cfac
refs/heads/main
2023-04-06T09:47:45.980952
2021-03-25T09:25:29
2021-03-25T09:25:29
327,970,866
0
0
null
null
null
null
UTF-8
C++
false
false
2,409
h
LinearAlgebra.h
#pragma once namespace AeroOptimizer { namespace LinearAlgebra { /* * result = left + right, adds the left and right vectors. * * @param left, the array representing one vector to be added. * @param right, the array representing the other vector to be added. * @param result, the array where the resulting vector gets saved. * @param n, the amount of elements in each vector (their dimension). */ void AddVectors(const double* left, const double* right, double* result, int n); /* * result = left x right, computes cartesian 3D the cross product of the left and right vector. * * @param left, the array of length 3 representing the left vector. * @param right, the array of length 3 representing the right vector. * @param result, the array of length 3 where the results will get written. */ void CrossProduct(const double* left, const double* right, double* result); /* * v1 dot v2, calculates the dot product (in cartesian coordinates) of two vectors. * * @param v1, a pointer to the first array representing a vector. * @param v2, a pointer to the second array representing a vector. * @param n, the number of components in each vector. * * @return The dot product of the two vectors. */ double DotProduct(const double* v1, const double* v2, int n); /* * Mv, multiplies a square matrix and a vector together. This assumes that both the matrix * and vector have the specified number of dimensions. * * @param M, a pointer to the 2-dimensional array representing the matrix. * @param v, a pointer to the 1-dimensional array representing the vector. * @param result, the resulting vector (with n components). * @param n, the number of elements the vector has and the "side length" of the matrix. * * @return A pointer to the resulting vector. */ void MatrixVectorMult(const double* M, const double* v, double* result, int n); /* * result = left - right, subtracts the right vector from the left one. * * @param left, the array representing the vector from which to subtract the other vector. * @param right, the array representing the vector to subtract from the other vector. * @param result, the array where the resulting vector gets stored. * @param n, the amount of elements in each vector (their dimension). */ void SubtractVectors(const double* left, const double* right, double* result, int n); }; }
f1f952e0eb791e71c43e9fc5c1b74f5390bf2eec
93d68c3c498cc9be902ea7894231e3e9bc40c1c5
/User.h
a31b7de5665afe5b20a610bf81d62e9aed22b80d
[]
no_license
rares04/Lab-6
0bebe6d1d40899ac7d9fb575ad1421e410ecebf9
4dce20d1df256fa14fe69120937be5988ced8be1
refs/heads/master
2022-08-02T07:30:39.718079
2020-06-05T06:55:14
2020-06-05T06:55:14
262,234,463
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
h
User.h
#pragma once #include<iostream> #include <vector> #include "Film.h" #include "FilmRepository.h" using namespace std; class User { private: vector <Film> watchList; FilmRepository filmRepo; public: // Default constructor, nothing will be initialized, made to pass User as attribute in UI User(); User(FilmRepository FilmRepo); // Return the watchList std::vector <Film>& getWatchList(); // Sets the watchList void setWatchList(vector <Film> list) ; // Adds a film to the watchList void addFilmToWatchList(Film _film); // Removes a film from the watchList void removeFilmFromWatchList(Film _film); // Prints the watchList void showWatchList() const; // Adds 1 like to the film void like(Film _film); // Searches for the film in the watchlist bool search_film(Film _film) const; // Returns the adress of the FilmRepository attribute FilmRepository& getFilmRepo(); // Saves the data into the file void write_movies_to_file(string filename); // Reads the movies from the file void read_movies_from_file(string filename); };
745cf3cfc832fd71491ecf04f3467cce3f099903
00387cb8474ca01052a189b6a9370a6577384919
/src/plugins/bittorrent/pieceswidget.cpp
7d3c65057000487cdce3b38db88412956e755c5d
[ "BSL-1.0" ]
permissive
WildeGeist/leechcraft
bcfd646b407c6ae6654eb9c17d095cf070f7c943
719c9635a2f8e7bb7540d2a11301d61bbfeead7a
refs/heads/master
2023-01-24T03:41:58.670559
2020-10-04T15:06:19
2020-10-04T15:06:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,520
cpp
pieceswidget.cpp
/********************************************************************** * 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 "pieceswidget.h" #include <QPainter> #include <QPaintEvent> #include <QVector> #include <QtDebug> #include <QApplication> #include <QPalette> namespace LC { namespace BitTorrent { PiecesWidget::PiecesWidget (QWidget *parent) : QLabel (parent) { } void PiecesWidget::setPieceMap (const libtorrent::bitfield& pieces) { Pieces_ = pieces; update (); } QList<QPair<int, int>> FindTrues (const libtorrent::bitfield& pieces) { QList<QPair<int, int>> result; bool prevVal = pieces [0]; int prevPos = 0; int size = static_cast<int> (pieces.size ()); for (int i = 1; i < size; ++i) if (pieces [i] != prevVal) { if (prevVal) result << qMakePair (prevPos, i); prevPos = i; prevVal = 1 - prevVal; } if (!prevPos && prevVal) result << qMakePair<int, int> (0, pieces.size ()); else if (prevVal && result.size () && result.last ().second != size - 1) result << qMakePair<int, int> (prevPos, size); else if (prevVal && !result.size ()) result << qMakePair<int, int> (0, size); return result; } void PiecesWidget::paintEvent (QPaintEvent *e) { int s = Pieces_.size (); QPainter painter (this); painter.setRenderHints (QPainter::Antialiasing | QPainter::SmoothPixmapTransform); if (!s) { painter.setBackgroundMode (Qt::OpaqueMode); painter.setBackground (Qt::white); painter.end (); return; } const QPalette& palette = QApplication::palette (); const QColor& backgroundColor = palette.color (QPalette::Base); const QColor& downloadedPieceColor = palette.color (QPalette::Highlight); QPixmap tempPicture (s, 1); QPainter tempPainter (&tempPicture); tempPainter.setPen (backgroundColor); tempPainter.drawLine (0, 0, s, 0); QList<QPair<int, int>> trues = FindTrues (Pieces_); for (int i = 0; i < trues.size (); ++i) { QPair<int, int> pair = trues.at (i); tempPainter.setPen (downloadedPieceColor); tempPainter.drawLine (pair.first, 0, pair.second, 0); } tempPainter.end (); painter.drawPixmap (QRect (0, 0, width (), height ()), tempPicture); painter.end (); e->accept (); } } }
20e650aa13e97a4c187cefa5ab9044c3d9e4e9c7
1634d4f09e2db354cf9befa24e5340ff092fd9db
/Wonderland/Wonderland/Editor/Foundation/UI/Components/Frame/UIFrameToken.cpp
792e1984d14181bb6b7be2ef00e53cbe50771de4
[ "MIT" ]
permissive
RodrigoHolztrattner/Wonderland
cd5a977bec96fda1851119a8de47b40b74bd85b7
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
refs/heads/master
2021-01-10T15:29:21.940124
2017-10-01T17:12:57
2017-10-01T17:12:57
84,469,251
4
1
null
null
null
null
UTF-8
C++
false
false
836
cpp
UIFrameToken.cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: UIFrameToken.cpp //////////////////////////////////////////////////////////////////////////////// #include "UIFrameToken.h" ////////////////// // CONSTRUCTORS // ////////////////// UIFrameToken::UIFrameToken() { // Set the initial data m_TokenId = 0; } UIFrameToken::UIFrameToken(const UIFrameToken& other) { m_TokenId = other.m_TokenId; } UIFrameToken::~UIFrameToken() { } bool UIFrameToken::IsEqual(UIFrameToken& _otherToken) { // Compare both tokens if (m_TokenId == _otherToken.m_TokenId) { return true; } // Update the token id _otherToken.m_TokenId = m_TokenId; return false; } /* void UIFrameToken::Update(UIFrameToken& _other) { _other.m_TokenId = m_TokenId; } */ void UIFrameToken::Increment() { m_TokenId++; }
1baefb845df2805e6628288e50873f17b8b1a799
267d1ecc53f7896c02e144bdf0248882633deb30
/d01/ex00/Pony.hpp
fba0a15a337aa539be4f5dc22dc41971be7da9f0
[]
no_license
fabienblin/piscineCPP
c015a7c1996f43b03d6573f32a5831defa5f9499
85ad4ea72afc022050e3cb20fa955907ad9ddf8b
refs/heads/master
2022-04-04T03:22:44.378943
2020-01-29T16:57:10
2020-01-29T16:57:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
hpp
Pony.hpp
/* ************************************************************************** */ /* LE - / */ /* / */ /* Pony.hpp .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: fablin <fablin@student.le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2020/01/14 12:36:34 by fablin #+# ## ## #+# */ /* Updated: 2020/01/14 13:18:42 by fablin ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #ifndef PONY_HPP # define PONY_HPP #include <string> #include <iostream> class Pony { private: std::string name; int age; public: Pony(); Pony(std::string name, int age); ~Pony(); }; #endif
d9b723042b72b53e4b29e7f4504fd5025c00a98c
0e27a85d6825cfdd277e7fe9e232d55785d7303f
/calculator.cpp
67a59d98a4c876fe4e58971b3fd2f7f75cb215d8
[]
no_license
IvanAnanchikov/calculator
c6ac756c1df3cf06792a5bf0cedd07b95650f6e7
7f81f5f6e23313f0ded3cdc2922012101f272157
refs/heads/master
2020-03-26T15:20:48.137812
2018-08-16T20:53:06
2018-08-16T20:53:17
145,037,704
0
0
null
null
null
null
UTF-8
C++
false
false
4,608
cpp
calculator.cpp
#include "calculator.h" Calculator::Calculator (QWidget *parent) : QWidget(parent) { lcd = new QLCDNumber(this); lcd->setMinimumSize(150, 50); lcd->setSegmentStyle(QLCDNumber::Flat); lcd->setDigitCount(11); lcd->setSmallDecimalPoint(true); label = new QLabel(""); label->setMinimumSize (150, 50); label->setAlignment(Qt::AlignRight); display_str = new QLabel(""); QChar keys[4][4] = { {'7', '8', '9', '/'}, {'4', '5', '6', '*'}, {'1', '2', '3', '-'}, {'0', '.', '=', '+'} }; QGridLayout *gLay = new QGridLayout; gLay->addWidget(lcd, 0, 0, 1, 4); gLay->addWidget(label, 1, 0, 1, 4); gLay->addWidget(addButton("<-"), 2, 0); gLay->addWidget(addButton("sqrt"), 2, 1); gLay->addWidget(addButton("1/x"), 2, 2); gLay->addWidget(addButton("C"), 2, 3); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { gLay->addWidget(addButton(keys[i][j]), i + 3, j); } } setLayout(gLay); } QPushButton* Calculator::addButton (const QString& str) { QPushButton* pcmd = new QPushButton(str); pcmd->setMinimumSize(40, 33); connect(pcmd, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); return pcmd; } void Calculator::ButtonHandling(QString str) { QString text = display_str->text(); QString text_lcd = QString::number(lcd->value()); int len = text.length(); QString last = ""; if (len>0) last = text.right(1); if (((len==0 && stack.count()==0) ||//если еще ничего не вводили ((stack.count()==2 && len>1 && //если уже есть операнд и операция (last=="+"||last=="-"||last=="*"||last=="/")))) && (str.contains(QRegExp("[0-9]")) || str=="-")) {//если первый операнд отрицательное число label->setText(text); text=str; //отобразить нажатый символ text_lcd=str; } else if ((text+str).contains(QRegExp("^-?[0-9]+\\.?[0-9]*$"))) { text+=str; //продолжаем вводить число text_lcd+=str; } else if (text.contains(QRegExp("^-?[0-9]+\\.?[0-9]*$"))) { if (str=="*"||str=="/"||str=="+"||str=="-"||str=="=") { if (stack.count()==2) { //если есть операнд и оператор stack.push(text); label->setText(label->text()+text+"="); calculate(); text=display_str->text(); text_lcd=lcd->value(); } if (str!="=") { stack.push(text);//первый операнд в стек text+=str;//отобразить операцию text_lcd+=str;//операцию в стек stack.push(str); label->setText(text); } } } display_str->setText(text); lcd->display(text); //унарные операции if (str == "sqrt") { stack.push(text); label->setText(label->text()+text+"="); sqrt(); text=display_str->text(); text_lcd=lcd->value(); } else if (str == "1/x") { stack.push(text); label->setText(label->text()+text+"="); X_1(); text=display_str->text(); text_lcd=lcd->value(); } else if (str == "<-") { QString temp = QString::number(lcd->value()); temp.chop(1); text = temp; text_lcd = temp; display_str->setText(text); lcd->display(text_lcd); } } void Calculator::calculate() { double nmb_2 = stack.pop().toDouble(); QString Op = stack.pop(); double nmb_1 = stack.pop().toDouble(); double res = 0; if (Op == "+") { res = nmb_1 + nmb_2; } else if (Op == "-") { res = nmb_1 - nmb_2; } else if (Op == "/") { res = nmb_1 / nmb_2; } else if (Op == "*") { res = nmb_1 * nmb_2; } display_str->setText(QString("%1").arg(res, 0, 'f', 3)); lcd->display(res); } void Calculator::sqrt() { double nmb = stack.pop().toDouble(); double res = 0; res = nmb * nmb; display_str->setText(QString("%1").arg(res, 0, 'f', 3)); lcd->display(res); } void Calculator::X_1() { double nmb = stack.pop().toDouble(); double res = 0; if (nmb == 0){ lcd->display("D BY 0"); } else { res = 1 / nmb; display_str->setText(QString("%1").arg(res, 0, 'f', 3)); lcd->display(res); } } void Calculator::clearAll() { stack.clear(); display_str->setText(""); label->setText(""); lcd->display(0); } void Calculator::slotButtonClicked() { QString str = ((QPushButton*)sender())->text(); if (str == "C") clearAll(); else ButtonHandling(str); } void Calculator::keyPressEvent(QKeyEvent *event) { int key=event->key(); QString str = QString(QChar(key)); if (key==Qt::Key_Delete) clearAll(); else if (key==Qt::Key_C) clearAll(); else ButtonHandling(str); }
013e407a2c5b837bee7e80bd058fe5067069e49a
a0dce37339bf2e60d7ddff5b1b9346e364a04bc8
/rational.cpp
bfb82b48142792642690baa43034ee1ce19caa71
[]
no_license
archiver/spoj
c0dfdc2bfea0c4d811ee0b95dce83c720bea3eae
ac78437594b4ff062db886d03db2a7192478b603
refs/heads/master
2020-05-18T00:58:53.697941
2013-01-18T22:00:38
2013-01-18T22:00:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
cpp
rational.cpp
#include <stdio.h> #include <math.h> #define N 1001 #define M 1000001 #define P 200 typedef unsigned long long ull; int primes[P]; int phi[M]; ull phi_sum[M]; void init() { bool pmask[N]; int i,j; int limit=sqrt(N)+1; //sieve of erasthosenes for(i=0;i<N;++i) pmask[i]=true; primes[0]=2; for(i=3;i<limit;++i) { if(pmask[i]) { for(j=i*i;j<N;j+=(i+i)) pmask[j]=false; } } j=1; for(i=3;i<N;i+=2) { if(pmask[i]) { primes[j]=i; j+=1; } } //euler totient function phi[1]=1; phi_sum[1]=0L; int pnum,num,val,t; for(i=2;i<M;++i) { pnum=-1; for(t=0;t<j;++t) if(i%primes[t] == 0) { pnum=primes[t];break;} if(pnum==-1) //it is a prime number > N phi[i]=(i-1); else { num=i; val=1; while(num%pnum==0) { num/=pnum; val*=pnum; } val/=pnum; val*=(pnum-1); phi[i]=val*phi[num]; } phi_sum[i]=phi_sum[i-1]+phi[i]; } } int main() { init(); for(int i=1;i<=1000000;++i) printf("%d %d\n",i,phi[i]); } /* int main() { init(); int t,val; scanf("%d",&t); while(t--) { scanf("%d",&val); printf("%llu\n",phi_sum[val]); } return 0; } */
29ebf4f85a352c2136fb5288c9e37c8d0fa32e78
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
/chromium/chrome/browser/page_load_metrics/observers/page_anchors_metrics_observer.h
607510b6c418e04d72a8734e133290529165bda5
[ "BSD-3-Clause" ]
permissive
ric2b/Vivaldi-browser
388a328b4cb838a4c3822357a5529642f86316a5
87244f4ee50062e59667bf8b9ca4d5291b6818d7
refs/heads/master
2022-12-21T04:44:13.804535
2022-12-17T16:30:35
2022-12-17T16:30:35
86,637,416
166
41
BSD-3-Clause
2021-03-31T18:49:30
2017-03-29T23:09:05
null
UTF-8
C++
false
false
3,051
h
page_anchors_metrics_observer.h
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_PAGE_ANCHORS_METRICS_OBSERVER_H_ #define CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_PAGE_ANCHORS_METRICS_OBSERVER_H_ #include "base/memory/raw_ptr.h" #include "components/page_load_metrics/browser/page_load_metrics_observer.h" #include "content/public/browser/web_contents_user_data.h" // Tracks anchor information in content::NavigationPredictor to report gathered // data on navigating out the page. Ideally this should be managed by // per outermost page manner. However we ensure that this structure is not // created and accessed during prerendering as we have a DCHECK in // content::NavigationPredictor::ReportNewAnchorElements. So, we can manage it // as per WebContents without polluting gathered data. class PageAnchorsMetricsObserver : public page_load_metrics::PageLoadMetricsObserver { public: class AnchorsData : public content::WebContentsUserData<AnchorsData> { public: AnchorsData(const AnchorsData&) = delete; ~AnchorsData() override; AnchorsData& operator=(const AnchorsData&) = delete; int MedianLinkLocation(); void Clear(); size_t number_of_anchors_same_host_ = 0; size_t number_of_anchors_contains_image_ = 0; size_t number_of_anchors_in_iframe_ = 0; size_t number_of_anchors_url_incremented_ = 0; size_t number_of_anchors_ = 0; int total_clickable_space_ = 0; int viewport_height_ = 0; int viewport_width_ = 0; std::vector<int> link_locations_; private: friend class content::WebContentsUserData<AnchorsData>; explicit AnchorsData(content::WebContents* contents); WEB_CONTENTS_USER_DATA_KEY_DECL(); }; PageAnchorsMetricsObserver(const PageAnchorsMetricsObserver&) = delete; explicit PageAnchorsMetricsObserver(content::WebContents* web_contents) : web_contents_(web_contents) {} PageAnchorsMetricsObserver& operator=(const PageAnchorsMetricsObserver&) = delete; // page_load_metrics::PageLoadMetricsObserver: ObservePolicy OnPrerenderStart(content::NavigationHandle* navigation_handle, const GURL& currently_committed_url) override; page_load_metrics::PageLoadMetricsObserver::ObservePolicy OnFencedFramesStart( content::NavigationHandle* navigation_handle, const GURL& currently_committed_url) override; void OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing) override; page_load_metrics::PageLoadMetricsObserver::ObservePolicy FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing) override; void DidActivatePrerenderedPage( content::NavigationHandle* navigation_handle) override; private: void RecordUkm(); bool is_in_prerendered_page_ = false; raw_ptr<content::WebContents> web_contents_; }; #endif // CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_PAGE_ANCHORS_METRICS_OBSERVER_H_
78f01b532b5614484c40dd3de1bb23a5c354882c
179ffb8f2137307583a23cb6826d720974fc9784
/Unit04/TotalArea/TotalaArea.cpp
e107a29baede0741ad1111301e1a7188f79d4444
[]
no_license
Sheepypy/MOOC
e59f85732e225cc0f6059e46b0620dd34869faa8
258b178481419dcea1dc32f07aab4536f606205c
refs/heads/master
2023-08-13T23:14:52.245101
2021-09-14T09:57:46
2021-09-14T09:57:46
392,976,556
2
0
null
null
null
null
GB18030
C++
false
false
1,091
cpp
TotalaArea.cpp
#include <iostream> #include "Circle2.h" using std::cout; using std::cin; using std::endl; int main() { //1 Circle ca1[]{ Circle{1.0}, Circle{2.0}, Circle{3.0} };//原生数组不能用auto Circle ca2[]{ 1.0, 2.0, 3.0 }; ca1[2].setRadius(4.0); ca2[1].setRadius(100.0); auto area1{ 0.0 }; auto area2{ 0.0 }; for (int i = 0; i < sizeof(ca1) / sizeof(ca1[0]); i++) {//sizeof:以字节为单位 cout << ca1[i].getRadius() << endl; area1 += ca1[i].getArea(); } for (auto x : ca2) { cout << x.getRadius() << endl; area2 += x.getArea(); } cout << "area1=" << area1 << endl; cout << "area2=" << area2 << endl; //2 //Circle* pca1=new Circle[3]{ Circle{1.0}, Circle{2.0}, Circle{3.0} }; auto pca1 = new Circle[3]{ 1.0, 2.0, 3.0 };//等效写法 pca1[2].setRadius(4.0); auto area11{ 0.0 }; for (int i = 0; i < sizeof(ca1) / sizeof(ca1[0]); i++) {//sizeof:以字节为单位 cout << pca1[i].getRadius() << endl; cout << (pca1+i)->getRadius()<<endl; area11 += pca1[i].getArea(); } cout << "area1=" << area11 << endl; delete[] pca1; pca1 = nullptr; return 0; }
177e15ce8f7c049e8a690bd925c3e74f170cc197
2fa31ae8d02cd92bf24bd8cf0f2a611a02a28519
/since2018/integrated_algorithm/16561.cpp
d119c85cf7b2b0987f325b62bb2e0d72dc378ac6
[]
no_license
dlftls38/algorithms
3619186d8d832cda695dfbf985e5d86ef6f2f06e
18ab96bbb3c8512a2da180477e4cc36a25edd30d
refs/heads/master
2021-07-10T06:09:53.211350
2020-10-17T00:04:43
2020-10-17T00:04:43
206,953,967
0
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
16561.cpp
#include <stdio.h> #include <iostream> #include <string.h> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <map> #include <set> #include <limits.h> #include <functional> #include <math.h> #include <fstream> #define INF 987654321 #define MAX_VALUE 1000000000 #define MOD 1000000009 #define pi 3.141592 using namespace std; typedef pair<int,int> pii; int dp[3001][4]; int solve(int n,int cnt){ if(cnt==0){ if(n==0){ return 1; } else{ return 0; } } int &res = dp[n][cnt]; if(res!=0){ return res; } int cur=3; for(int i=1;i<=1000;i++){ if(n-cur*i>=0 && cnt-1>=0){ res += solve(n-cur*i,cnt-1); } else{ break; } } return res; } int main(){ int n; scanf("%d",&n); printf("%d",solve(n,3)); }
c8ab5a8291713e8ea5aa3fc824a1faf05bf02cc8
1c9ad827c00830e9fc3723612645e509b9e698d8
/TheGame/Background.h
bc471926f298b0582d60009d87b25689247ed604
[]
no_license
JoBri93/Astrosolver
2f499b864236e0f07456b41ec7b632afd7766897
b621cdf5fee32871c591643c09e0faeb92712cdd
refs/heads/master
2020-05-05T11:15:51.647480
2019-04-07T15:29:31
2019-04-07T15:29:31
179,982,034
0
0
null
null
null
null
UTF-8
C++
false
false
167
h
Background.h
#pragma once class Background : public SceneObject { public: std::string textureName; void Render(); void Update(); Background(std::string); ~Background(); };
5e435d8ea2f190bd384fe23e2c60519aae7a639b
ef35552267ac45345c60135845470260afbd6687
/Applications/sprout_alcc/alfalfa/src/examples/sproutbt2.cc
3e9d5b7905c6e8ab6f3f2227d5ac355a04f4a289
[ "MIT" ]
permissive
xianliangjiang/ALCC
2bbe7e48aaf7ab273cfea4622855be12e261730f
fc9c627de8c381987fc775ce0872339fceb43ddf
refs/heads/main
2023-05-16T21:11:06.738812
2021-06-10T11:43:23
2021-06-10T11:43:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,673
cc
sproutbt2.cc
#include <unistd.h> #include <string> #include <assert.h> #include <list> #include <sys/time.h> #include <iostream> #include <fstream> #include "sproutconn.h" #include "select.h" using namespace std; using namespace Network; int main( int argc, char *argv[] ) { struct timeval time2; char *ip; int port; ofstream WNDLog; char command[512]; Network::SproutConnection *net; bool server = true; if ( argc > 2 ) { /* client */ server = false; ip = argv[ 1 ]; port = atoi( argv[ 2 ] ); net = new Network::SproutConnection( "4h/Td1v//4jkYhqhLGgegw", ip, port ); } else { net = new Network::SproutConnection( NULL, NULL ); } fprintf( stderr, "Port bound is %d\n", net->port() ); Select &sel = Select::get_instance(); sel.add_fd( net->fd() ); const int fallback_interval = 50; /* wait to get attached */ if ( server ) { sprintf (command, "%s", argv[1]); WNDLog.open(command); while ( 1 ) { int active_fds = sel.select( -1 ); if ( active_fds < 0 ) { perror( "select" ); exit( 1 ); } if ( sel.read( net->fd() ) ) { net->recv(); } if ( net->get_has_remote_addr() ) { break; } } } uint64_t time_of_next_transmission = timestamp() + fallback_interval; fprintf( stderr, "Looping...\n" ); /* loop */ while ( 1 ) { int CWND = -1; int bytes_to_send = net->window_size(&CWND); /* actually send, maybe */ if ( ( bytes_to_send > 0 ) || ( time_of_next_transmission <= timestamp() ) ) { if (argc <= 2) { gettimeofday(&time2,NULL); WNDLog << time2.tv_sec << "." << time2.tv_usec << "," << CWND << "\n"; WNDLog.flush(); //printf("---- %ld.%06ld, %d \n", time2.tv_sec, time2.tv_usec, CWND); } do { int this_packet_size = std::min( 1440, bytes_to_send ); bytes_to_send -= this_packet_size; assert( bytes_to_send >= 0 ); string garbage( this_packet_size, 'x' ); int time_to_next = 0; if ( bytes_to_send == 0 ) { time_to_next = fallback_interval; } net->send( garbage, time_to_next ); } while ( bytes_to_send > 0 ); time_of_next_transmission = std::max( timestamp() + fallback_interval, time_of_next_transmission ); } /* wait */ int wait_time = time_of_next_transmission - timestamp(); if ( wait_time < 0 ) { wait_time = 0; } else if ( wait_time > 10 ) { wait_time = 10; } int active_fds = sel.select( wait_time ); if ( active_fds < 0 ) { perror( "select" ); exit( 1 ); } /* receive */ if ( sel.read( net->fd() ) ) { string packet( net->recv() ); } } WNDLog.close(); }
52549f1da85024ce35646cc8dd2ec164d34ba256
d310f6d99f5c966f0a7b1ebf7e5312ac6317976e
/RCCar.ino
4ec574090274ac88f7841f65d9225b109a088b90
[]
no_license
Sryther/RCCar
b53417caa9cf6043fa917233e4ea8c0d6887bfe8
c2fc61f238f0437ed989e81fe74fa345b637c0e6
refs/heads/master
2021-01-23T00:15:52.945087
2014-01-14T15:36:09
2014-01-14T15:36:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
181
ino
RCCar.ino
#include <nmea.h> void setup() //fonction d'initialisation de la carte { } void loop() //fonction principale, elle se répète (s’exécute) à l'infini { }
6e6de8ea270e805f0da739b721c466d540930fec
707d78afbff89aa8a7ab6c3b1253e1f032be8073
/Heap Sort/Heap.h
0ab80120413ad8f28692520c188534ec15480054
[]
no_license
KDunc11/Heap_Sort
8589a963a6b71dffb18ed2787534bfd5c8fa0790
2de24ea6b019d3a04408c1aa2bec05e9e7a21327
refs/heads/master
2022-12-26T17:12:12.297056
2020-10-05T17:29:22
2020-10-05T17:29:22
301,487,463
0
0
null
null
null
null
UTF-8
C++
false
false
889
h
Heap.h
#ifndef HEAP_H #define HEAP_H #include <iostream> using namespace std; template<typename T> class Heap { public: //Default Constructor Heap<T>(); //Constructor Heap<T>(T dataArr[], const int& dataSize, const char& type); //Destructor ~Heap(); void sort(); //Used to sort the heap either as a min or max heap based off the heapType variable template<typename T2> friend ostream& operator<<(ostream& ostrm, const Heap<T2>& heap); //Used to output the heap private: T* data; int size = 0; char heapType = '\0'; void heapifyMax(T arr[], const int& n, int i); //Heapifies the heap according to the heap property for a max heap void maxHeapSort(T arr[], int n); //Used to sort a max heap void heapifyMin(T arr[], const int& n, int i); //Heapifies the heap according to the heap property for a min heap void minHeapSort(T arr[], int n); //Used to sort a min heap }; #endif
1b9ec1f7f77458eb47564850265cdbf87d21861e
ea2ef79d13c8c8c70f96ba6683bf0f321e9942c1
/src/input/XWindowManager.cpp
f172967f64b70f7366858277abacaecd847ea46e
[ "MIT" ]
permissive
stnma7e/scim
32145a3d51aadb2013f2ab452fb1c83af563ca13
a82f0e97018a4a2abf0a225f75ebc7e8ef6f1e0d
refs/heads/master
2021-01-10T20:17:34.222501
2014-02-01T19:08:54
2014-02-01T19:08:54
7,210,907
1
2
null
null
null
null
UTF-8
C++
false
false
2,898
cpp
XWindowManager.cpp
#include "input/XWindowManager.h" #include "input/InputTools.h" #include "event/EventManager.h" #include "event/events/ShutdownGameEvent.h" #include <stdio.h> #include <stdlib.h> namespace scim { extern EventManager* g_eventManager; XWindowManager::XWindowManager(const char* windowName, I32 width, I32 height, bool fullscreen) { GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; dpy = XOpenDisplay(NULL); if(dpy == NULL) { printf("\n\tcannot connect to X server\n\n"); return; } root = DefaultRootWindow(dpy); vi = glXChooseVisual(dpy, 0, att); if(vi == NULL) { printf("\n\tno appropriate visual found\n\n"); exit(0); } else { printf("\n\tvisual %p selected\n", (void *)vi->visualid); /* %p creates hexadecimal output like in glxinfo */ } cmap = XCreateColormap(dpy, root, vi->visual, AllocNone); swa.colormap = cmap; swa.event_mask = ExposureMask | KeyPressMask; win = XCreateWindow(dpy, root, 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa); XMapWindow(dpy, win); XStoreName(dpy, win, windowName); XSelectInput(dpy, win, m_inputMask); glc = glXCreateContext(dpy, vi, NULL, GL_TRUE); glXMakeCurrent(dpy, win, glc); } XWindowManager::~XWindowManager() { glXMakeCurrent(dpy, None, NULL); glXDestroyContext(dpy, glc); XDestroyWindow(dpy, win); XCloseDisplay(dpy); } void XWindowManager::CollectInputs() { XEvent xev; Input inpt = { 0x00000000, 0x00000000, 0.0f, 0.0f, 0, 0 }; while (XCheckWindowEvent(dpy, win, m_inputMask, &xev)) { switch(xev.type) { case Expose: { glXSwapBuffers(dpy, win); } break; case ConfigureNotify: { XConfigureEvent xce = xev.xconfigure; inpt.window_w = xce.width; inpt.window_h = xce.height; } break; case KeyPress: case KeyRelease: { char string[25]; KeySym keysym; I32 len = XLookupString(&xev.xkey, string, 25, &keysym, NULL); if (len > 0) { GetKeypressAndUpdate(string[0], &inpt); } else { switch (keysym) { case 0xff51: { inpt.specialKeys = inpt.specialKeys | SCIM_KEY_LEFT; } break; case 0xff53: { inpt.specialKeys = inpt.specialKeys | SCIM_KEY_RIGHT; } break; case 0xff52: { inpt.specialKeys = inpt.specialKeys | SCIM_KEY_UP; } break; case 0xff54: { inpt.specialKeys = inpt.specialKeys | SCIM_KEY_DOWN; } break; } } } break; case MotionNotify: { XMotionEvent xme = xev.xmotion; inpt.mousePosX = xme.x_root; inpt.mousePosY = xme.y_root; } break; } memset(&xev, 0, sizeof(xev)); } m_collectedInputs = inpt; } void XWindowManager::PreRender() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void XWindowManager::PostRender() { glXSwapBuffers(dpy, win); } }
ed5cbe2295c3fe05d2c1c908ab2d66506f5f0299
e92af86f33f4bdd457578733074d3c7f6aa7c7fb
/source/GameCommon/MissionConfig.pb.h
2e085780876c9d4cb90730900688b2f4de0a44d4
[]
no_license
crazysnail/XServer
aac7e0aaa9da29c74144241e1cc926b8c76d0514
da9f9ae3842e253dcacb2b83b25c5fa56927bdd3
refs/heads/master
2022-03-25T15:52:57.238609
2019-12-04T09:25:33
2019-12-04T09:25:33
224,835,205
0
0
null
null
null
null
UTF-8
C++
false
true
63,028
h
MissionConfig.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: MissionConfig.proto #ifndef PROTOBUF_MissionConfig_2eproto__INCLUDED #define PROTOBUF_MissionConfig_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 2005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/generated_message_util.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> #include "AllConfigEnum.pb.h" #include "ProtoBufOption.pb.h" // @@protoc_insertion_point(includes) namespace Config { // Internal implementation detail -- do not call these. void protobuf_AddDesc_MissionConfig_2eproto(); void protobuf_AssignDesc_MissionConfig_2eproto(); void protobuf_ShutdownFile_MissionConfig_2eproto(); class MissionConfig; class MissionExConfig; class TargetConfig; class StoryStageConfig; // =================================================================== class MissionConfig : public ::google::protobuf::Message { public: MissionConfig(); virtual ~MissionConfig(); MissionConfig(const MissionConfig& from); inline MissionConfig& operator=(const MissionConfig& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const MissionConfig& default_instance(); void Swap(MissionConfig* other); // implements Message ---------------------------------------------- MissionConfig* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const MissionConfig& from); void MergeFrom(const MissionConfig& from); void Clear(); bool IsInitialized() const; void SetInitialized(); int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required int32 id = 1; inline bool has_id() const; inline void clear_id(); static const int kIdFieldNumber = 1; inline ::google::protobuf::int32 id() const; inline void set_id(::google::protobuf::int32 value); // repeated int32 pre_id = 2; inline int pre_id_size() const; inline void clear_pre_id(); static const int kPreIdFieldNumber = 2; inline ::google::protobuf::int32 pre_id(int index) const; inline void set_pre_id(int index, ::google::protobuf::int32 value); inline void add_pre_id(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& pre_id() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_pre_id(); // required .Config.FinishType finish_type = 3; inline bool has_finish_type() const; inline void clear_finish_type(); static const int kFinishTypeFieldNumber = 3; inline ::Config::FinishType finish_type() const; inline void set_finish_type(::Config::FinishType value); // required .Config.MissionType type = 4; inline bool has_type() const; inline void clear_type(); static const int kTypeFieldNumber = 4; inline ::Config::MissionType type() const; inline void set_type(::Config::MissionType value); // required int32 group = 5; inline bool has_group() const; inline void clear_group(); static const int kGroupFieldNumber = 5; inline ::google::protobuf::int32 group() const; inline void set_group(::google::protobuf::int32 value); // required int32 open_level = 6; inline bool has_open_level() const; inline void clear_open_level(); static const int kOpenLevelFieldNumber = 6; inline ::google::protobuf::int32 open_level() const; inline void set_open_level(::google::protobuf::int32 value); // required int32 count_limit = 7; inline bool has_count_limit() const; inline void clear_count_limit(); static const int kCountLimitFieldNumber = 7; inline ::google::protobuf::int32 count_limit() const; inline void set_count_limit(::google::protobuf::int32 value); // required int32 adapt_level = 8; inline bool has_adapt_level() const; inline void clear_adapt_level(); static const int kAdaptLevelFieldNumber = 8; inline ::google::protobuf::int32 adapt_level() const; inline void set_adapt_level(::google::protobuf::int32 value); // required int32 circle = 9; inline bool has_circle() const; inline void clear_circle(); static const int kCircleFieldNumber = 9; inline ::google::protobuf::int32 circle() const; inline void set_circle(::google::protobuf::int32 value); // required int32 rate = 10; inline bool has_rate() const; inline void clear_rate(); static const int kRateFieldNumber = 10; inline ::google::protobuf::int32 rate() const; inline void set_rate(::google::protobuf::int32 value); // required int32 can_drop = 11; inline bool has_can_drop() const; inline void clear_can_drop(); static const int kCanDropFieldNumber = 11; inline ::google::protobuf::int32 can_drop() const; inline void set_can_drop(::google::protobuf::int32 value); // repeated int32 param = 12; inline int param_size() const; inline void clear_param(); static const int kParamFieldNumber = 12; inline ::google::protobuf::int32 param(int index) const; inline void set_param(int index, ::google::protobuf::int32 value); inline void add_param(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& param() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_param(); // required int32 exp = 13; inline bool has_exp() const; inline void clear_exp(); static const int kExpFieldNumber = 13; inline ::google::protobuf::int32 exp() const; inline void set_exp(::google::protobuf::int32 value); // required float exp_rate = 14; inline bool has_exp_rate() const; inline void clear_exp_rate(); static const int kExpRateFieldNumber = 14; inline float exp_rate() const; inline void set_exp_rate(float value); // required int32 gold = 15; inline bool has_gold() const; inline void clear_gold(); static const int kGoldFieldNumber = 15; inline ::google::protobuf::int32 gold() const; inline void set_gold(::google::protobuf::int32 value); // required float gold_rate = 16; inline bool has_gold_rate() const; inline void clear_gold_rate(); static const int kGoldRateFieldNumber = 16; inline float gold_rate() const; inline void set_gold_rate(float value); // required int32 package_id = 17; inline bool has_package_id() const; inline void clear_package_id(); static const int kPackageIdFieldNumber = 17; inline ::google::protobuf::int32 package_id() const; inline void set_package_id(::google::protobuf::int32 value); // required int32 publish_npc_id = 18; inline bool has_publish_npc_id() const; inline void clear_publish_npc_id(); static const int kPublishNpcIdFieldNumber = 18; inline ::google::protobuf::int32 publish_npc_id() const; inline void set_publish_npc_id(::google::protobuf::int32 value); // required int32 commit_npc_id = 19; inline bool has_commit_npc_id() const; inline void clear_commit_npc_id(); static const int kCommitNpcIdFieldNumber = 19; inline ::google::protobuf::int32 commit_npc_id() const; inline void set_commit_npc_id(::google::protobuf::int32 value); // required int32 other_npc_group = 20; inline bool has_other_npc_group() const; inline void clear_other_npc_group(); static const int kOtherNpcGroupFieldNumber = 20; inline ::google::protobuf::int32 other_npc_group() const; inline void set_other_npc_group(::google::protobuf::int32 value); // required int32 roll_drop = 21; inline bool has_roll_drop() const; inline void clear_roll_drop(); static const int kRollDropFieldNumber = 21; inline ::google::protobuf::int32 roll_drop() const; inline void set_roll_drop(::google::protobuf::int32 value); // required int32 is_open = 22; inline bool has_is_open() const; inline void clear_is_open(); static const int kIsOpenFieldNumber = 22; inline ::google::protobuf::int32 is_open() const; inline void set_is_open(::google::protobuf::int32 value); // @@protoc_insertion_point(class_scope:Config.MissionConfig) private: inline void set_has_id(); inline void clear_has_id(); inline void set_has_finish_type(); inline void clear_has_finish_type(); inline void set_has_type(); inline void clear_has_type(); inline void set_has_group(); inline void clear_has_group(); inline void set_has_open_level(); inline void clear_has_open_level(); inline void set_has_count_limit(); inline void clear_has_count_limit(); inline void set_has_adapt_level(); inline void clear_has_adapt_level(); inline void set_has_circle(); inline void clear_has_circle(); inline void set_has_rate(); inline void clear_has_rate(); inline void set_has_can_drop(); inline void clear_has_can_drop(); inline void set_has_exp(); inline void clear_has_exp(); inline void set_has_exp_rate(); inline void clear_has_exp_rate(); inline void set_has_gold(); inline void clear_has_gold(); inline void set_has_gold_rate(); inline void clear_has_gold_rate(); inline void set_has_package_id(); inline void clear_has_package_id(); inline void set_has_publish_npc_id(); inline void clear_has_publish_npc_id(); inline void set_has_commit_npc_id(); inline void clear_has_commit_npc_id(); inline void set_has_other_npc_group(); inline void clear_has_other_npc_group(); inline void set_has_roll_drop(); inline void clear_has_roll_drop(); inline void set_has_is_open(); inline void clear_has_is_open(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > pre_id_; ::google::protobuf::int32 id_; int finish_type_; int type_; ::google::protobuf::int32 group_; ::google::protobuf::int32 open_level_; ::google::protobuf::int32 count_limit_; ::google::protobuf::int32 adapt_level_; ::google::protobuf::int32 circle_; ::google::protobuf::int32 rate_; ::google::protobuf::int32 can_drop_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > param_; ::google::protobuf::int32 exp_; float exp_rate_; ::google::protobuf::int32 gold_; float gold_rate_; ::google::protobuf::int32 package_id_; ::google::protobuf::int32 publish_npc_id_; ::google::protobuf::int32 commit_npc_id_; ::google::protobuf::int32 other_npc_group_; ::google::protobuf::int32 roll_drop_; ::google::protobuf::int32 is_open_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(22 + 31) / 32]; friend void protobuf_AddDesc_MissionConfig_2eproto(); friend void protobuf_AssignDesc_MissionConfig_2eproto(); friend void protobuf_ShutdownFile_MissionConfig_2eproto(); void InitAsDefaultInstance(); static MissionConfig* default_instance_; }; // ------------------------------------------------------------------- class MissionExConfig : public ::google::protobuf::Message { public: MissionExConfig(); virtual ~MissionExConfig(); MissionExConfig(const MissionExConfig& from); inline MissionExConfig& operator=(const MissionExConfig& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const MissionExConfig& default_instance(); void Swap(MissionExConfig* other); // implements Message ---------------------------------------------- MissionExConfig* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const MissionExConfig& from); void MergeFrom(const MissionExConfig& from); void Clear(); bool IsInitialized() const; void SetInitialized(); int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required int32 index = 1; inline bool has_index() const; inline void clear_index(); static const int kIndexFieldNumber = 1; inline ::google::protobuf::int32 index() const; inline void set_index(::google::protobuf::int32 value); // required .Config.SubFinishType sub_type = 2; inline bool has_sub_type() const; inline void clear_sub_type(); static const int kSubTypeFieldNumber = 2; inline ::Config::SubFinishType sub_type() const; inline void set_sub_type(::Config::SubFinishType value); // repeated int32 monster = 3; inline int monster_size() const; inline void clear_monster(); static const int kMonsterFieldNumber = 3; inline ::google::protobuf::int32 monster(int index) const; inline void set_monster(int index, ::google::protobuf::int32 value); inline void add_monster(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& monster() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_monster(); // repeated int32 item = 4; inline int item_size() const; inline void clear_item(); static const int kItemFieldNumber = 4; inline ::google::protobuf::int32 item(int index) const; inline void set_item(int index, ::google::protobuf::int32 value); inline void add_item(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& item() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_item(); // repeated int32 rate = 5; inline int rate_size() const; inline void clear_rate(); static const int kRateFieldNumber = 5; inline ::google::protobuf::int32 rate(int index) const; inline void set_rate(int index, ::google::protobuf::int32 value); inline void add_rate(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& rate() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_rate(); // repeated int32 count = 6; inline int count_size() const; inline void clear_count(); static const int kCountFieldNumber = 6; inline ::google::protobuf::int32 count(int index) const; inline void set_count(int index, ::google::protobuf::int32 value); inline void add_count(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& count() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_count(); // required int32 pos_param = 7; inline bool has_pos_param() const; inline void clear_pos_param(); static const int kPosParamFieldNumber = 7; inline ::google::protobuf::int32 pos_param() const; inline void set_pos_param(::google::protobuf::int32 value); // @@protoc_insertion_point(class_scope:Config.MissionExConfig) private: inline void set_has_index(); inline void clear_has_index(); inline void set_has_sub_type(); inline void clear_has_sub_type(); inline void set_has_pos_param(); inline void clear_has_pos_param(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::int32 index_; int sub_type_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > monster_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > item_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > rate_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > count_; ::google::protobuf::int32 pos_param_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(7 + 31) / 32]; friend void protobuf_AddDesc_MissionConfig_2eproto(); friend void protobuf_AssignDesc_MissionConfig_2eproto(); friend void protobuf_ShutdownFile_MissionConfig_2eproto(); void InitAsDefaultInstance(); static MissionExConfig* default_instance_; }; // ------------------------------------------------------------------- class TargetConfig : public ::google::protobuf::Message { public: TargetConfig(); virtual ~TargetConfig(); TargetConfig(const TargetConfig& from); inline TargetConfig& operator=(const TargetConfig& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const TargetConfig& default_instance(); void Swap(TargetConfig* other); // implements Message ---------------------------------------------- TargetConfig* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const TargetConfig& from); void MergeFrom(const TargetConfig& from); void Clear(); bool IsInitialized() const; void SetInitialized(); int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required int32 index = 1; inline bool has_index() const; inline void clear_index(); static const int kIndexFieldNumber = 1; inline ::google::protobuf::int32 index() const; inline void set_index(::google::protobuf::int32 value); // required int32 min_level = 2; inline bool has_min_level() const; inline void clear_min_level(); static const int kMinLevelFieldNumber = 2; inline ::google::protobuf::int32 min_level() const; inline void set_min_level(::google::protobuf::int32 value); // required int32 max_level = 3; inline bool has_max_level() const; inline void clear_max_level(); static const int kMaxLevelFieldNumber = 3; inline ::google::protobuf::int32 max_level() const; inline void set_max_level(::google::protobuf::int32 value); // required int32 switch_open = 4; inline bool has_switch_open() const; inline void clear_switch_open(); static const int kSwitchOpenFieldNumber = 4; inline ::google::protobuf::int32 switch_open() const; inline void set_switch_open(::google::protobuf::int32 value); // required .Config.TargetFinishType finish_type = 5; inline bool has_finish_type() const; inline void clear_finish_type(); static const int kFinishTypeFieldNumber = 5; inline ::Config::TargetFinishType finish_type() const; inline void set_finish_type(::Config::TargetFinishType value); // required int32 camp = 6; inline bool has_camp() const; inline void clear_camp(); static const int kCampFieldNumber = 6; inline ::google::protobuf::int32 camp() const; inline void set_camp(::google::protobuf::int32 value); // repeated int32 param = 7; inline int param_size() const; inline void clear_param(); static const int kParamFieldNumber = 7; inline ::google::protobuf::int32 param(int index) const; inline void set_param(int index, ::google::protobuf::int32 value); inline void add_param(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& param() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_param(); // repeated int32 reward_item = 8; inline int reward_item_size() const; inline void clear_reward_item(); static const int kRewardItemFieldNumber = 8; inline ::google::protobuf::int32 reward_item(int index) const; inline void set_reward_item(int index, ::google::protobuf::int32 value); inline void add_reward_item(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& reward_item() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_reward_item(); // repeated int32 count = 9; inline int count_size() const; inline void clear_count(); static const int kCountFieldNumber = 9; inline ::google::protobuf::int32 count(int index) const; inline void set_count(int index, ::google::protobuf::int32 value); inline void add_count(::google::protobuf::int32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& count() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* mutable_count(); // optional int32 group = 10; inline bool has_group() const; inline void clear_group(); static const int kGroupFieldNumber = 10; inline ::google::protobuf::int32 group() const; inline void set_group(::google::protobuf::int32 value); // @@protoc_insertion_point(class_scope:Config.TargetConfig) private: inline void set_has_index(); inline void clear_has_index(); inline void set_has_min_level(); inline void clear_has_min_level(); inline void set_has_max_level(); inline void clear_has_max_level(); inline void set_has_switch_open(); inline void clear_has_switch_open(); inline void set_has_finish_type(); inline void clear_has_finish_type(); inline void set_has_camp(); inline void clear_has_camp(); inline void set_has_group(); inline void clear_has_group(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::int32 index_; ::google::protobuf::int32 min_level_; ::google::protobuf::int32 max_level_; ::google::protobuf::int32 switch_open_; int finish_type_; ::google::protobuf::int32 camp_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > param_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > reward_item_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > count_; ::google::protobuf::int32 group_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(10 + 31) / 32]; friend void protobuf_AddDesc_MissionConfig_2eproto(); friend void protobuf_AssignDesc_MissionConfig_2eproto(); friend void protobuf_ShutdownFile_MissionConfig_2eproto(); void InitAsDefaultInstance(); static TargetConfig* default_instance_; }; // ------------------------------------------------------------------- class StoryStageConfig : public ::google::protobuf::Message { public: StoryStageConfig(); virtual ~StoryStageConfig(); StoryStageConfig(const StoryStageConfig& from); inline StoryStageConfig& operator=(const StoryStageConfig& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const StoryStageConfig& default_instance(); void Swap(StoryStageConfig* other); // implements Message ---------------------------------------------- StoryStageConfig* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const StoryStageConfig& from); void MergeFrom(const StoryStageConfig& from); void Clear(); bool IsInitialized() const; void SetInitialized(); int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required int32 mission_id = 1; inline bool has_mission_id() const; inline void clear_mission_id(); static const int kMissionIdFieldNumber = 1; inline ::google::protobuf::int32 mission_id() const; inline void set_mission_id(::google::protobuf::int32 value); // required int32 stage_index = 2; inline bool has_stage_index() const; inline void clear_stage_index(); static const int kStageIndexFieldNumber = 2; inline ::google::protobuf::int32 stage_index() const; inline void set_stage_index(::google::protobuf::int32 value); // required int32 event_type_1 = 3; inline bool has_event_type_1() const; inline void clear_event_type_1(); static const int kEventType1FieldNumber = 3; inline ::google::protobuf::int32 event_type_1() const; inline void set_event_type_1(::google::protobuf::int32 value); // required int32 npc_id_1 = 4; inline bool has_npc_id_1() const; inline void clear_npc_id_1(); static const int kNpcId1FieldNumber = 4; inline ::google::protobuf::int32 npc_id_1() const; inline void set_npc_id_1(::google::protobuf::int32 value); // required int32 npc_side_1 = 5; inline bool has_npc_side_1() const; inline void clear_npc_side_1(); static const int kNpcSide1FieldNumber = 5; inline ::google::protobuf::int32 npc_side_1() const; inline void set_npc_side_1(::google::protobuf::int32 value); // required int32 npc_pos_1 = 6; inline bool has_npc_pos_1() const; inline void clear_npc_pos_1(); static const int kNpcPos1FieldNumber = 6; inline ::google::protobuf::int32 npc_pos_1() const; inline void set_npc_pos_1(::google::protobuf::int32 value); // required int32 npc_id_2 = 7; inline bool has_npc_id_2() const; inline void clear_npc_id_2(); static const int kNpcId2FieldNumber = 7; inline ::google::protobuf::int32 npc_id_2() const; inline void set_npc_id_2(::google::protobuf::int32 value); // required int32 npc_side_2 = 8; inline bool has_npc_side_2() const; inline void clear_npc_side_2(); static const int kNpcSide2FieldNumber = 8; inline ::google::protobuf::int32 npc_side_2() const; inline void set_npc_side_2(::google::protobuf::int32 value); // required int32 npc_pos_2 = 9; inline bool has_npc_pos_2() const; inline void clear_npc_pos_2(); static const int kNpcPos2FieldNumber = 9; inline ::google::protobuf::int32 npc_pos_2() const; inline void set_npc_pos_2(::google::protobuf::int32 value); // @@protoc_insertion_point(class_scope:Config.StoryStageConfig) private: inline void set_has_mission_id(); inline void clear_has_mission_id(); inline void set_has_stage_index(); inline void clear_has_stage_index(); inline void set_has_event_type_1(); inline void clear_has_event_type_1(); inline void set_has_npc_id_1(); inline void clear_has_npc_id_1(); inline void set_has_npc_side_1(); inline void clear_has_npc_side_1(); inline void set_has_npc_pos_1(); inline void clear_has_npc_pos_1(); inline void set_has_npc_id_2(); inline void clear_has_npc_id_2(); inline void set_has_npc_side_2(); inline void clear_has_npc_side_2(); inline void set_has_npc_pos_2(); inline void clear_has_npc_pos_2(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::int32 mission_id_; ::google::protobuf::int32 stage_index_; ::google::protobuf::int32 event_type_1_; ::google::protobuf::int32 npc_id_1_; ::google::protobuf::int32 npc_side_1_; ::google::protobuf::int32 npc_pos_1_; ::google::protobuf::int32 npc_id_2_; ::google::protobuf::int32 npc_side_2_; ::google::protobuf::int32 npc_pos_2_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(9 + 31) / 32]; friend void protobuf_AddDesc_MissionConfig_2eproto(); friend void protobuf_AssignDesc_MissionConfig_2eproto(); friend void protobuf_ShutdownFile_MissionConfig_2eproto(); void InitAsDefaultInstance(); static StoryStageConfig* default_instance_; }; // =================================================================== // =================================================================== // MissionConfig // required int32 id = 1; inline bool MissionConfig::has_id() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void MissionConfig::set_has_id() { _has_bits_[0] |= 0x00000001u; } inline void MissionConfig::clear_has_id() { _has_bits_[0] &= ~0x00000001u; } inline void MissionConfig::clear_id() { id_ = 0; clear_has_id(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::id() const { return id_; } inline void MissionConfig::set_id(::google::protobuf::int32 value) { SetDirty(); set_has_id(); id_ = value; } // repeated int32 pre_id = 2; inline int MissionConfig::pre_id_size() const { return pre_id_.size(); } inline void MissionConfig::clear_pre_id() { pre_id_.Clear(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::pre_id(int index) const { return pre_id_.Get(index); } inline void MissionConfig::set_pre_id(int index, ::google::protobuf::int32 value) { SetDirty(); pre_id_.Set(index, value); } inline void MissionConfig::add_pre_id(::google::protobuf::int32 value) { SetDirty(); pre_id_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& MissionConfig::pre_id() const { return pre_id_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* MissionConfig::mutable_pre_id() { SetDirty(); return &pre_id_; } // required .Config.FinishType finish_type = 3; inline bool MissionConfig::has_finish_type() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void MissionConfig::set_has_finish_type() { _has_bits_[0] |= 0x00000004u; } inline void MissionConfig::clear_has_finish_type() { _has_bits_[0] &= ~0x00000004u; } inline void MissionConfig::clear_finish_type() { finish_type_ = -1; clear_has_finish_type(); SetDirty(); } inline ::Config::FinishType MissionConfig::finish_type() const { return static_cast< ::Config::FinishType >(finish_type_); } inline void MissionConfig::set_finish_type(::Config::FinishType value) { assert(::Config::FinishType_IsValid(value)); SetDirty(); set_has_finish_type(); finish_type_ = value; } // required .Config.MissionType type = 4; inline bool MissionConfig::has_type() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void MissionConfig::set_has_type() { _has_bits_[0] |= 0x00000008u; } inline void MissionConfig::clear_has_type() { _has_bits_[0] &= ~0x00000008u; } inline void MissionConfig::clear_type() { type_ = -1; clear_has_type(); SetDirty(); } inline ::Config::MissionType MissionConfig::type() const { return static_cast< ::Config::MissionType >(type_); } inline void MissionConfig::set_type(::Config::MissionType value) { assert(::Config::MissionType_IsValid(value)); SetDirty(); set_has_type(); type_ = value; } // required int32 group = 5; inline bool MissionConfig::has_group() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void MissionConfig::set_has_group() { _has_bits_[0] |= 0x00000010u; } inline void MissionConfig::clear_has_group() { _has_bits_[0] &= ~0x00000010u; } inline void MissionConfig::clear_group() { group_ = 0; clear_has_group(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::group() const { return group_; } inline void MissionConfig::set_group(::google::protobuf::int32 value) { SetDirty(); set_has_group(); group_ = value; } // required int32 open_level = 6; inline bool MissionConfig::has_open_level() const { return (_has_bits_[0] & 0x00000020u) != 0; } inline void MissionConfig::set_has_open_level() { _has_bits_[0] |= 0x00000020u; } inline void MissionConfig::clear_has_open_level() { _has_bits_[0] &= ~0x00000020u; } inline void MissionConfig::clear_open_level() { open_level_ = 0; clear_has_open_level(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::open_level() const { return open_level_; } inline void MissionConfig::set_open_level(::google::protobuf::int32 value) { SetDirty(); set_has_open_level(); open_level_ = value; } // required int32 count_limit = 7; inline bool MissionConfig::has_count_limit() const { return (_has_bits_[0] & 0x00000040u) != 0; } inline void MissionConfig::set_has_count_limit() { _has_bits_[0] |= 0x00000040u; } inline void MissionConfig::clear_has_count_limit() { _has_bits_[0] &= ~0x00000040u; } inline void MissionConfig::clear_count_limit() { count_limit_ = 0; clear_has_count_limit(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::count_limit() const { return count_limit_; } inline void MissionConfig::set_count_limit(::google::protobuf::int32 value) { SetDirty(); set_has_count_limit(); count_limit_ = value; } // required int32 adapt_level = 8; inline bool MissionConfig::has_adapt_level() const { return (_has_bits_[0] & 0x00000080u) != 0; } inline void MissionConfig::set_has_adapt_level() { _has_bits_[0] |= 0x00000080u; } inline void MissionConfig::clear_has_adapt_level() { _has_bits_[0] &= ~0x00000080u; } inline void MissionConfig::clear_adapt_level() { adapt_level_ = 0; clear_has_adapt_level(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::adapt_level() const { return adapt_level_; } inline void MissionConfig::set_adapt_level(::google::protobuf::int32 value) { SetDirty(); set_has_adapt_level(); adapt_level_ = value; } // required int32 circle = 9; inline bool MissionConfig::has_circle() const { return (_has_bits_[0] & 0x00000100u) != 0; } inline void MissionConfig::set_has_circle() { _has_bits_[0] |= 0x00000100u; } inline void MissionConfig::clear_has_circle() { _has_bits_[0] &= ~0x00000100u; } inline void MissionConfig::clear_circle() { circle_ = 0; clear_has_circle(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::circle() const { return circle_; } inline void MissionConfig::set_circle(::google::protobuf::int32 value) { SetDirty(); set_has_circle(); circle_ = value; } // required int32 rate = 10; inline bool MissionConfig::has_rate() const { return (_has_bits_[0] & 0x00000200u) != 0; } inline void MissionConfig::set_has_rate() { _has_bits_[0] |= 0x00000200u; } inline void MissionConfig::clear_has_rate() { _has_bits_[0] &= ~0x00000200u; } inline void MissionConfig::clear_rate() { rate_ = 0; clear_has_rate(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::rate() const { return rate_; } inline void MissionConfig::set_rate(::google::protobuf::int32 value) { SetDirty(); set_has_rate(); rate_ = value; } // required int32 can_drop = 11; inline bool MissionConfig::has_can_drop() const { return (_has_bits_[0] & 0x00000400u) != 0; } inline void MissionConfig::set_has_can_drop() { _has_bits_[0] |= 0x00000400u; } inline void MissionConfig::clear_has_can_drop() { _has_bits_[0] &= ~0x00000400u; } inline void MissionConfig::clear_can_drop() { can_drop_ = 0; clear_has_can_drop(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::can_drop() const { return can_drop_; } inline void MissionConfig::set_can_drop(::google::protobuf::int32 value) { SetDirty(); set_has_can_drop(); can_drop_ = value; } // repeated int32 param = 12; inline int MissionConfig::param_size() const { return param_.size(); } inline void MissionConfig::clear_param() { param_.Clear(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::param(int index) const { return param_.Get(index); } inline void MissionConfig::set_param(int index, ::google::protobuf::int32 value) { SetDirty(); param_.Set(index, value); } inline void MissionConfig::add_param(::google::protobuf::int32 value) { SetDirty(); param_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& MissionConfig::param() const { return param_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* MissionConfig::mutable_param() { SetDirty(); return &param_; } // required int32 exp = 13; inline bool MissionConfig::has_exp() const { return (_has_bits_[0] & 0x00001000u) != 0; } inline void MissionConfig::set_has_exp() { _has_bits_[0] |= 0x00001000u; } inline void MissionConfig::clear_has_exp() { _has_bits_[0] &= ~0x00001000u; } inline void MissionConfig::clear_exp() { exp_ = 0; clear_has_exp(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::exp() const { return exp_; } inline void MissionConfig::set_exp(::google::protobuf::int32 value) { SetDirty(); set_has_exp(); exp_ = value; } // required float exp_rate = 14; inline bool MissionConfig::has_exp_rate() const { return (_has_bits_[0] & 0x00002000u) != 0; } inline void MissionConfig::set_has_exp_rate() { _has_bits_[0] |= 0x00002000u; } inline void MissionConfig::clear_has_exp_rate() { _has_bits_[0] &= ~0x00002000u; } inline void MissionConfig::clear_exp_rate() { exp_rate_ = 0; clear_has_exp_rate(); SetDirty(); } inline float MissionConfig::exp_rate() const { return exp_rate_; } inline void MissionConfig::set_exp_rate(float value) { SetDirty(); set_has_exp_rate(); exp_rate_ = value; } // required int32 gold = 15; inline bool MissionConfig::has_gold() const { return (_has_bits_[0] & 0x00004000u) != 0; } inline void MissionConfig::set_has_gold() { _has_bits_[0] |= 0x00004000u; } inline void MissionConfig::clear_has_gold() { _has_bits_[0] &= ~0x00004000u; } inline void MissionConfig::clear_gold() { gold_ = 0; clear_has_gold(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::gold() const { return gold_; } inline void MissionConfig::set_gold(::google::protobuf::int32 value) { SetDirty(); set_has_gold(); gold_ = value; } // required float gold_rate = 16; inline bool MissionConfig::has_gold_rate() const { return (_has_bits_[0] & 0x00008000u) != 0; } inline void MissionConfig::set_has_gold_rate() { _has_bits_[0] |= 0x00008000u; } inline void MissionConfig::clear_has_gold_rate() { _has_bits_[0] &= ~0x00008000u; } inline void MissionConfig::clear_gold_rate() { gold_rate_ = 0; clear_has_gold_rate(); SetDirty(); } inline float MissionConfig::gold_rate() const { return gold_rate_; } inline void MissionConfig::set_gold_rate(float value) { SetDirty(); set_has_gold_rate(); gold_rate_ = value; } // required int32 package_id = 17; inline bool MissionConfig::has_package_id() const { return (_has_bits_[0] & 0x00010000u) != 0; } inline void MissionConfig::set_has_package_id() { _has_bits_[0] |= 0x00010000u; } inline void MissionConfig::clear_has_package_id() { _has_bits_[0] &= ~0x00010000u; } inline void MissionConfig::clear_package_id() { package_id_ = 0; clear_has_package_id(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::package_id() const { return package_id_; } inline void MissionConfig::set_package_id(::google::protobuf::int32 value) { SetDirty(); set_has_package_id(); package_id_ = value; } // required int32 publish_npc_id = 18; inline bool MissionConfig::has_publish_npc_id() const { return (_has_bits_[0] & 0x00020000u) != 0; } inline void MissionConfig::set_has_publish_npc_id() { _has_bits_[0] |= 0x00020000u; } inline void MissionConfig::clear_has_publish_npc_id() { _has_bits_[0] &= ~0x00020000u; } inline void MissionConfig::clear_publish_npc_id() { publish_npc_id_ = 0; clear_has_publish_npc_id(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::publish_npc_id() const { return publish_npc_id_; } inline void MissionConfig::set_publish_npc_id(::google::protobuf::int32 value) { SetDirty(); set_has_publish_npc_id(); publish_npc_id_ = value; } // required int32 commit_npc_id = 19; inline bool MissionConfig::has_commit_npc_id() const { return (_has_bits_[0] & 0x00040000u) != 0; } inline void MissionConfig::set_has_commit_npc_id() { _has_bits_[0] |= 0x00040000u; } inline void MissionConfig::clear_has_commit_npc_id() { _has_bits_[0] &= ~0x00040000u; } inline void MissionConfig::clear_commit_npc_id() { commit_npc_id_ = 0; clear_has_commit_npc_id(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::commit_npc_id() const { return commit_npc_id_; } inline void MissionConfig::set_commit_npc_id(::google::protobuf::int32 value) { SetDirty(); set_has_commit_npc_id(); commit_npc_id_ = value; } // required int32 other_npc_group = 20; inline bool MissionConfig::has_other_npc_group() const { return (_has_bits_[0] & 0x00080000u) != 0; } inline void MissionConfig::set_has_other_npc_group() { _has_bits_[0] |= 0x00080000u; } inline void MissionConfig::clear_has_other_npc_group() { _has_bits_[0] &= ~0x00080000u; } inline void MissionConfig::clear_other_npc_group() { other_npc_group_ = 0; clear_has_other_npc_group(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::other_npc_group() const { return other_npc_group_; } inline void MissionConfig::set_other_npc_group(::google::protobuf::int32 value) { SetDirty(); set_has_other_npc_group(); other_npc_group_ = value; } // required int32 roll_drop = 21; inline bool MissionConfig::has_roll_drop() const { return (_has_bits_[0] & 0x00100000u) != 0; } inline void MissionConfig::set_has_roll_drop() { _has_bits_[0] |= 0x00100000u; } inline void MissionConfig::clear_has_roll_drop() { _has_bits_[0] &= ~0x00100000u; } inline void MissionConfig::clear_roll_drop() { roll_drop_ = 0; clear_has_roll_drop(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::roll_drop() const { return roll_drop_; } inline void MissionConfig::set_roll_drop(::google::protobuf::int32 value) { SetDirty(); set_has_roll_drop(); roll_drop_ = value; } // required int32 is_open = 22; inline bool MissionConfig::has_is_open() const { return (_has_bits_[0] & 0x00200000u) != 0; } inline void MissionConfig::set_has_is_open() { _has_bits_[0] |= 0x00200000u; } inline void MissionConfig::clear_has_is_open() { _has_bits_[0] &= ~0x00200000u; } inline void MissionConfig::clear_is_open() { is_open_ = 0; clear_has_is_open(); SetDirty(); } inline ::google::protobuf::int32 MissionConfig::is_open() const { return is_open_; } inline void MissionConfig::set_is_open(::google::protobuf::int32 value) { SetDirty(); set_has_is_open(); is_open_ = value; } // ------------------------------------------------------------------- // MissionExConfig // required int32 index = 1; inline bool MissionExConfig::has_index() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void MissionExConfig::set_has_index() { _has_bits_[0] |= 0x00000001u; } inline void MissionExConfig::clear_has_index() { _has_bits_[0] &= ~0x00000001u; } inline void MissionExConfig::clear_index() { index_ = 0; clear_has_index(); SetDirty(); } inline ::google::protobuf::int32 MissionExConfig::index() const { return index_; } inline void MissionExConfig::set_index(::google::protobuf::int32 value) { SetDirty(); set_has_index(); index_ = value; } // required .Config.SubFinishType sub_type = 2; inline bool MissionExConfig::has_sub_type() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void MissionExConfig::set_has_sub_type() { _has_bits_[0] |= 0x00000002u; } inline void MissionExConfig::clear_has_sub_type() { _has_bits_[0] &= ~0x00000002u; } inline void MissionExConfig::clear_sub_type() { sub_type_ = -1; clear_has_sub_type(); SetDirty(); } inline ::Config::SubFinishType MissionExConfig::sub_type() const { return static_cast< ::Config::SubFinishType >(sub_type_); } inline void MissionExConfig::set_sub_type(::Config::SubFinishType value) { assert(::Config::SubFinishType_IsValid(value)); SetDirty(); set_has_sub_type(); sub_type_ = value; } // repeated int32 monster = 3; inline int MissionExConfig::monster_size() const { return monster_.size(); } inline void MissionExConfig::clear_monster() { monster_.Clear(); SetDirty(); } inline ::google::protobuf::int32 MissionExConfig::monster(int index) const { return monster_.Get(index); } inline void MissionExConfig::set_monster(int index, ::google::protobuf::int32 value) { SetDirty(); monster_.Set(index, value); } inline void MissionExConfig::add_monster(::google::protobuf::int32 value) { SetDirty(); monster_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& MissionExConfig::monster() const { return monster_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* MissionExConfig::mutable_monster() { SetDirty(); return &monster_; } // repeated int32 item = 4; inline int MissionExConfig::item_size() const { return item_.size(); } inline void MissionExConfig::clear_item() { item_.Clear(); SetDirty(); } inline ::google::protobuf::int32 MissionExConfig::item(int index) const { return item_.Get(index); } inline void MissionExConfig::set_item(int index, ::google::protobuf::int32 value) { SetDirty(); item_.Set(index, value); } inline void MissionExConfig::add_item(::google::protobuf::int32 value) { SetDirty(); item_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& MissionExConfig::item() const { return item_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* MissionExConfig::mutable_item() { SetDirty(); return &item_; } // repeated int32 rate = 5; inline int MissionExConfig::rate_size() const { return rate_.size(); } inline void MissionExConfig::clear_rate() { rate_.Clear(); SetDirty(); } inline ::google::protobuf::int32 MissionExConfig::rate(int index) const { return rate_.Get(index); } inline void MissionExConfig::set_rate(int index, ::google::protobuf::int32 value) { SetDirty(); rate_.Set(index, value); } inline void MissionExConfig::add_rate(::google::protobuf::int32 value) { SetDirty(); rate_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& MissionExConfig::rate() const { return rate_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* MissionExConfig::mutable_rate() { SetDirty(); return &rate_; } // repeated int32 count = 6; inline int MissionExConfig::count_size() const { return count_.size(); } inline void MissionExConfig::clear_count() { count_.Clear(); SetDirty(); } inline ::google::protobuf::int32 MissionExConfig::count(int index) const { return count_.Get(index); } inline void MissionExConfig::set_count(int index, ::google::protobuf::int32 value) { SetDirty(); count_.Set(index, value); } inline void MissionExConfig::add_count(::google::protobuf::int32 value) { SetDirty(); count_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& MissionExConfig::count() const { return count_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* MissionExConfig::mutable_count() { SetDirty(); return &count_; } // required int32 pos_param = 7; inline bool MissionExConfig::has_pos_param() const { return (_has_bits_[0] & 0x00000040u) != 0; } inline void MissionExConfig::set_has_pos_param() { _has_bits_[0] |= 0x00000040u; } inline void MissionExConfig::clear_has_pos_param() { _has_bits_[0] &= ~0x00000040u; } inline void MissionExConfig::clear_pos_param() { pos_param_ = 0; clear_has_pos_param(); SetDirty(); } inline ::google::protobuf::int32 MissionExConfig::pos_param() const { return pos_param_; } inline void MissionExConfig::set_pos_param(::google::protobuf::int32 value) { SetDirty(); set_has_pos_param(); pos_param_ = value; } // ------------------------------------------------------------------- // TargetConfig // required int32 index = 1; inline bool TargetConfig::has_index() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void TargetConfig::set_has_index() { _has_bits_[0] |= 0x00000001u; } inline void TargetConfig::clear_has_index() { _has_bits_[0] &= ~0x00000001u; } inline void TargetConfig::clear_index() { index_ = 0; clear_has_index(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::index() const { return index_; } inline void TargetConfig::set_index(::google::protobuf::int32 value) { SetDirty(); set_has_index(); index_ = value; } // required int32 min_level = 2; inline bool TargetConfig::has_min_level() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void TargetConfig::set_has_min_level() { _has_bits_[0] |= 0x00000002u; } inline void TargetConfig::clear_has_min_level() { _has_bits_[0] &= ~0x00000002u; } inline void TargetConfig::clear_min_level() { min_level_ = 0; clear_has_min_level(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::min_level() const { return min_level_; } inline void TargetConfig::set_min_level(::google::protobuf::int32 value) { SetDirty(); set_has_min_level(); min_level_ = value; } // required int32 max_level = 3; inline bool TargetConfig::has_max_level() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void TargetConfig::set_has_max_level() { _has_bits_[0] |= 0x00000004u; } inline void TargetConfig::clear_has_max_level() { _has_bits_[0] &= ~0x00000004u; } inline void TargetConfig::clear_max_level() { max_level_ = 0; clear_has_max_level(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::max_level() const { return max_level_; } inline void TargetConfig::set_max_level(::google::protobuf::int32 value) { SetDirty(); set_has_max_level(); max_level_ = value; } // required int32 switch_open = 4; inline bool TargetConfig::has_switch_open() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void TargetConfig::set_has_switch_open() { _has_bits_[0] |= 0x00000008u; } inline void TargetConfig::clear_has_switch_open() { _has_bits_[0] &= ~0x00000008u; } inline void TargetConfig::clear_switch_open() { switch_open_ = 0; clear_has_switch_open(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::switch_open() const { return switch_open_; } inline void TargetConfig::set_switch_open(::google::protobuf::int32 value) { SetDirty(); set_has_switch_open(); switch_open_ = value; } // required .Config.TargetFinishType finish_type = 5; inline bool TargetConfig::has_finish_type() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void TargetConfig::set_has_finish_type() { _has_bits_[0] |= 0x00000010u; } inline void TargetConfig::clear_has_finish_type() { _has_bits_[0] &= ~0x00000010u; } inline void TargetConfig::clear_finish_type() { finish_type_ = -1; clear_has_finish_type(); SetDirty(); } inline ::Config::TargetFinishType TargetConfig::finish_type() const { return static_cast< ::Config::TargetFinishType >(finish_type_); } inline void TargetConfig::set_finish_type(::Config::TargetFinishType value) { assert(::Config::TargetFinishType_IsValid(value)); SetDirty(); set_has_finish_type(); finish_type_ = value; } // required int32 camp = 6; inline bool TargetConfig::has_camp() const { return (_has_bits_[0] & 0x00000020u) != 0; } inline void TargetConfig::set_has_camp() { _has_bits_[0] |= 0x00000020u; } inline void TargetConfig::clear_has_camp() { _has_bits_[0] &= ~0x00000020u; } inline void TargetConfig::clear_camp() { camp_ = 0; clear_has_camp(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::camp() const { return camp_; } inline void TargetConfig::set_camp(::google::protobuf::int32 value) { SetDirty(); set_has_camp(); camp_ = value; } // repeated int32 param = 7; inline int TargetConfig::param_size() const { return param_.size(); } inline void TargetConfig::clear_param() { param_.Clear(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::param(int index) const { return param_.Get(index); } inline void TargetConfig::set_param(int index, ::google::protobuf::int32 value) { SetDirty(); param_.Set(index, value); } inline void TargetConfig::add_param(::google::protobuf::int32 value) { SetDirty(); param_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& TargetConfig::param() const { return param_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* TargetConfig::mutable_param() { SetDirty(); return &param_; } // repeated int32 reward_item = 8; inline int TargetConfig::reward_item_size() const { return reward_item_.size(); } inline void TargetConfig::clear_reward_item() { reward_item_.Clear(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::reward_item(int index) const { return reward_item_.Get(index); } inline void TargetConfig::set_reward_item(int index, ::google::protobuf::int32 value) { SetDirty(); reward_item_.Set(index, value); } inline void TargetConfig::add_reward_item(::google::protobuf::int32 value) { SetDirty(); reward_item_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& TargetConfig::reward_item() const { return reward_item_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* TargetConfig::mutable_reward_item() { SetDirty(); return &reward_item_; } // repeated int32 count = 9; inline int TargetConfig::count_size() const { return count_.size(); } inline void TargetConfig::clear_count() { count_.Clear(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::count(int index) const { return count_.Get(index); } inline void TargetConfig::set_count(int index, ::google::protobuf::int32 value) { SetDirty(); count_.Set(index, value); } inline void TargetConfig::add_count(::google::protobuf::int32 value) { SetDirty(); count_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& TargetConfig::count() const { return count_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* TargetConfig::mutable_count() { SetDirty(); return &count_; } // optional int32 group = 10; inline bool TargetConfig::has_group() const { return (_has_bits_[0] & 0x00000200u) != 0; } inline void TargetConfig::set_has_group() { _has_bits_[0] |= 0x00000200u; } inline void TargetConfig::clear_has_group() { _has_bits_[0] &= ~0x00000200u; } inline void TargetConfig::clear_group() { group_ = 0; clear_has_group(); SetDirty(); } inline ::google::protobuf::int32 TargetConfig::group() const { return group_; } inline void TargetConfig::set_group(::google::protobuf::int32 value) { SetDirty(); set_has_group(); group_ = value; } // ------------------------------------------------------------------- // StoryStageConfig // required int32 mission_id = 1; inline bool StoryStageConfig::has_mission_id() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void StoryStageConfig::set_has_mission_id() { _has_bits_[0] |= 0x00000001u; } inline void StoryStageConfig::clear_has_mission_id() { _has_bits_[0] &= ~0x00000001u; } inline void StoryStageConfig::clear_mission_id() { mission_id_ = 0; clear_has_mission_id(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::mission_id() const { return mission_id_; } inline void StoryStageConfig::set_mission_id(::google::protobuf::int32 value) { SetDirty(); set_has_mission_id(); mission_id_ = value; } // required int32 stage_index = 2; inline bool StoryStageConfig::has_stage_index() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void StoryStageConfig::set_has_stage_index() { _has_bits_[0] |= 0x00000002u; } inline void StoryStageConfig::clear_has_stage_index() { _has_bits_[0] &= ~0x00000002u; } inline void StoryStageConfig::clear_stage_index() { stage_index_ = 0; clear_has_stage_index(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::stage_index() const { return stage_index_; } inline void StoryStageConfig::set_stage_index(::google::protobuf::int32 value) { SetDirty(); set_has_stage_index(); stage_index_ = value; } // required int32 event_type_1 = 3; inline bool StoryStageConfig::has_event_type_1() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void StoryStageConfig::set_has_event_type_1() { _has_bits_[0] |= 0x00000004u; } inline void StoryStageConfig::clear_has_event_type_1() { _has_bits_[0] &= ~0x00000004u; } inline void StoryStageConfig::clear_event_type_1() { event_type_1_ = 0; clear_has_event_type_1(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::event_type_1() const { return event_type_1_; } inline void StoryStageConfig::set_event_type_1(::google::protobuf::int32 value) { SetDirty(); set_has_event_type_1(); event_type_1_ = value; } // required int32 npc_id_1 = 4; inline bool StoryStageConfig::has_npc_id_1() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void StoryStageConfig::set_has_npc_id_1() { _has_bits_[0] |= 0x00000008u; } inline void StoryStageConfig::clear_has_npc_id_1() { _has_bits_[0] &= ~0x00000008u; } inline void StoryStageConfig::clear_npc_id_1() { npc_id_1_ = 0; clear_has_npc_id_1(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::npc_id_1() const { return npc_id_1_; } inline void StoryStageConfig::set_npc_id_1(::google::protobuf::int32 value) { SetDirty(); set_has_npc_id_1(); npc_id_1_ = value; } // required int32 npc_side_1 = 5; inline bool StoryStageConfig::has_npc_side_1() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void StoryStageConfig::set_has_npc_side_1() { _has_bits_[0] |= 0x00000010u; } inline void StoryStageConfig::clear_has_npc_side_1() { _has_bits_[0] &= ~0x00000010u; } inline void StoryStageConfig::clear_npc_side_1() { npc_side_1_ = 0; clear_has_npc_side_1(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::npc_side_1() const { return npc_side_1_; } inline void StoryStageConfig::set_npc_side_1(::google::protobuf::int32 value) { SetDirty(); set_has_npc_side_1(); npc_side_1_ = value; } // required int32 npc_pos_1 = 6; inline bool StoryStageConfig::has_npc_pos_1() const { return (_has_bits_[0] & 0x00000020u) != 0; } inline void StoryStageConfig::set_has_npc_pos_1() { _has_bits_[0] |= 0x00000020u; } inline void StoryStageConfig::clear_has_npc_pos_1() { _has_bits_[0] &= ~0x00000020u; } inline void StoryStageConfig::clear_npc_pos_1() { npc_pos_1_ = 0; clear_has_npc_pos_1(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::npc_pos_1() const { return npc_pos_1_; } inline void StoryStageConfig::set_npc_pos_1(::google::protobuf::int32 value) { SetDirty(); set_has_npc_pos_1(); npc_pos_1_ = value; } // required int32 npc_id_2 = 7; inline bool StoryStageConfig::has_npc_id_2() const { return (_has_bits_[0] & 0x00000040u) != 0; } inline void StoryStageConfig::set_has_npc_id_2() { _has_bits_[0] |= 0x00000040u; } inline void StoryStageConfig::clear_has_npc_id_2() { _has_bits_[0] &= ~0x00000040u; } inline void StoryStageConfig::clear_npc_id_2() { npc_id_2_ = 0; clear_has_npc_id_2(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::npc_id_2() const { return npc_id_2_; } inline void StoryStageConfig::set_npc_id_2(::google::protobuf::int32 value) { SetDirty(); set_has_npc_id_2(); npc_id_2_ = value; } // required int32 npc_side_2 = 8; inline bool StoryStageConfig::has_npc_side_2() const { return (_has_bits_[0] & 0x00000080u) != 0; } inline void StoryStageConfig::set_has_npc_side_2() { _has_bits_[0] |= 0x00000080u; } inline void StoryStageConfig::clear_has_npc_side_2() { _has_bits_[0] &= ~0x00000080u; } inline void StoryStageConfig::clear_npc_side_2() { npc_side_2_ = 0; clear_has_npc_side_2(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::npc_side_2() const { return npc_side_2_; } inline void StoryStageConfig::set_npc_side_2(::google::protobuf::int32 value) { SetDirty(); set_has_npc_side_2(); npc_side_2_ = value; } // required int32 npc_pos_2 = 9; inline bool StoryStageConfig::has_npc_pos_2() const { return (_has_bits_[0] & 0x00000100u) != 0; } inline void StoryStageConfig::set_has_npc_pos_2() { _has_bits_[0] |= 0x00000100u; } inline void StoryStageConfig::clear_has_npc_pos_2() { _has_bits_[0] &= ~0x00000100u; } inline void StoryStageConfig::clear_npc_pos_2() { npc_pos_2_ = 0; clear_has_npc_pos_2(); SetDirty(); } inline ::google::protobuf::int32 StoryStageConfig::npc_pos_2() const { return npc_pos_2_; } inline void StoryStageConfig::set_npc_pos_2(::google::protobuf::int32 value) { SetDirty(); set_has_npc_pos_2(); npc_pos_2_ = value; } // @@protoc_insertion_point(namespace_scope) } // namespace Config #ifndef SWIG namespace google { namespace protobuf { } // namespace google } // namespace protobuf #endif // SWIG // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_MissionConfig_2eproto__INCLUDED
71e817fd74a8343b2c8abdd1b260450f0a1e3b6a
d73a472a633a88ca54560e0761557266f3a5ff61
/src/GatewayServer/main.cpp
67a6d2fb8e90cc534e8e7bdc1fe76d54e24a61ba
[]
no_license
lcbkeith/MServer
b412ec73cdf4820722edc01a1f9f9e1a49e209be
ef5a0e3752492ccdca21f6e1cdc25881bdf9495f
refs/heads/master
2021-01-18T03:40:01.783948
2017-10-26T08:49:35
2017-10-26T08:49:35
85,799,393
0
0
null
null
null
null
UTF-8
C++
false
false
381
cpp
main.cpp
#include "GatewayApp.h" #include "../ServerBase/Tools/JsonConfig.h" int main() { JsonConfig config; if (!config.Parse("GatewayServer.setting")) { return 0; } int port = config.GetInt("port"); GatewayApp* gateway = new GatewayApp; gateway->Start(port); while (true) { gateway->Tick(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } return 0; }
9fcee69dd6689cd78d92e226ba0281b441e54c78
872095f6ca1d7f252a1a3cb90ad73e84f01345a2
/mediatek/proprietary/hardware/ril/rilproxy/mtk-rilproxy/telephony/ir/RpIrNwRatSwitchCallback.cpp
50248e39c922154522dee530df24bc103ad960e4
[ "Apache-2.0" ]
permissive
colinovski/mt8163-vendor
724c49a47e1fa64540efe210d26e72c883ee591d
2006b5183be2fac6a82eff7d9ed09c2633acafcc
refs/heads/master
2020-07-04T12:39:09.679221
2018-01-20T09:11:52
2018-01-20T09:11:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,835
cpp
RpIrNwRatSwitchCallback.cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /***************************************************************************** * Include *****************************************************************************/ #include "RfxLog.h" #include "RpIrStrategyOP095M.h" #include "RpNwRatController.h" #include "RpIrNwRatSwitchCallback.h" #define RFX_LOG_TAG "[IRC][RpIrNwRatSwitchCallback]" /***************************************************************************** * Class RpIrNwRatSwitchCallback *****************************************************************************/ RFX_IMPLEMENT_CLASS("RpIrNwRatSwitchCallback", RpIrNwRatSwitchCallback, RfxController); RpIrNwRatSwitchCallback::RpIrNwRatSwitchCallback() : mRpIrController(NULL), mRpIrCdmaHandler(NULL), mRpIrLwgHandler(NULL), mRpIrStrategy(NULL), mRpNwRatController(NULL) { } RpIrNwRatSwitchCallback::RpIrNwRatSwitchCallback( RpIrController *rpIrController, RpIrCdmaHandler *rpIrCdmaHandler, RpIrLwgHandler *rpIrLwgHandler, RpIrStrategy *rpIrStrategy) : mRpIrController(rpIrController), mRpIrCdmaHandler(rpIrCdmaHandler), mRpIrLwgHandler(rpIrLwgHandler), mRpIrStrategy(rpIrStrategy), mRpNwRatController(NULL) { } RpIrNwRatSwitchCallback::~RpIrNwRatSwitchCallback() { } void RpIrNwRatSwitchCallback::onInit() { RfxController::onInit(); mRpNwRatController = (RpNwRatController *)findController(RFX_OBJ_CLASS_INFO(RpNwRatController)); RFX_ASSERT(mRpNwRatController != NULL); } void RpIrNwRatSwitchCallback::onRatSwitchStart(const int curPrefNwType, const int newPrefNwType, const NwsMode curNwsMode, const NwsMode newNwsMode) { logD(RFX_LOG_TAG, "onRatSwitchStart, curPrefNwType=%s, newPrefNwType=%s, curNwsMode=%s, newNwsMode=%s", prefNwType2Str(curPrefNwType), prefNwType2Str(newPrefNwType), Nws2Str(curNwsMode), Nws2Str(newNwsMode)); if (!mRpIrController->isCdmaDualModeSimCard()) { logD(RFX_LOG_TAG, "onRatSwitchStart() not CT 4G or 3G dual mode return"); mRpIrController->setIrEnableState(false); return; } const bool curPrefNwTypeIs3G = is3GPrefNwType(curPrefNwType); const bool newPrefNwTypeIs3G = is3GPrefNwType(newPrefNwType); if ((!curPrefNwTypeIs3G && newPrefNwTypeIs3G) || (curPrefNwTypeIs3G && !newPrefNwTypeIs3G)) { logD(RFX_LOG_TAG, "onRatSwitchStart, disable IR Controller and Gmss handle while switching"); // disable IR controll while switching between AP-iRAT IR and MD-iRAT IR if (!mRpIrCdmaHandler->isCT3GCardType()) { mRpIrController->setIrControllerEnableState(false); } mRpIrController->setGmssEnableState(false); } if (newPrefNwTypeIs3G) { mRpIrLwgHandler->setIfEnabled(true); mRpIrCdmaHandler->setIfEnabled(true); } else { mRpIrLwgHandler->setIfEnabled(false); mRpIrCdmaHandler->setIfEnabled(false); } if (!curPrefNwTypeIs3G && newPrefNwTypeIs3G) { mRpIrController->setIsSwitchingTo3GMode(true); } mRpIrController->onNwsModeChange(newNwsMode); } void RpIrNwRatSwitchCallback::onRatSwitchDone(const int curPrefNwType, const int newPrefNwType) { logD(RFX_LOG_TAG, "onRatSwitchDone, curPrefNwType=%s, newPrefNwType=%s", prefNwType2Str(curPrefNwType), prefNwType2Str(newPrefNwType)); if (!mRpIrController->isCdmaDualModeSimCard()) { logD(RFX_LOG_TAG, "onRatSwitchDone() not CT 4G or 3G dual mode return"); return; } mRpIrController->setIsSwitchingTo3GMode(false); if (is3GPrefNwType(newPrefNwType)) { mRpIrController->setIrControllerEnableState(true); mRpIrLwgHandler->setIfEnabled(true); mRpIrCdmaHandler->setIfEnabled(true); } else { mRpIrController->setGmssEnableState(true); mRpIrLwgHandler->setIfEnabled(false); mRpIrCdmaHandler->setIfEnabled(false); } // For RpIrStrategyOP095M mRpIrStrategy->onRatSwitchDone(curPrefNwType, newPrefNwType); } void RpIrNwRatSwitchCallback::onEctModeChangeDone(const int curPrefNwType, const int newPrefNwType) { logD(RFX_LOG_TAG, "onEctModeChangeDone, curPrefNwType=%s, newPrefNwType=%s", prefNwType2Str(curPrefNwType), prefNwType2Str(newPrefNwType)); if (!mRpIrController->isCdmaDualModeSimCard()) { logD(RFX_LOG_TAG, "onEctModeChangeDone() not CT 4G or 3G dual mode return"); return; } if (is3GPrefNwType(newPrefNwType)) { mRpIrController->setIrControllerEnableState(true); } } bool RpIrNwRatSwitchCallback::is3GPrefNwType(int prefNwType) { switch (prefNwType) { case PREF_NET_TYPE_LTE_CDMA_EVDO: case PREF_NET_TYPE_LTE_GSM_WCDMA: case PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA: case PREF_NET_TYPE_LTE_ONLY: case PREF_NET_TYPE_LTE_WCDMA: case PREF_NET_TYPE_LTE_GSM: case PREF_NET_TYPE_LTE_TDD_ONLY: return false; default: return true; } } const char* RpIrNwRatSwitchCallback::prefNwType2Str(int prefNwType) { switch (prefNwType) { case PREF_NET_TYPE_GSM_WCDMA: return "PREF_NET_TYPE_GSM_WCDMA"; break; case PREF_NET_TYPE_GSM_ONLY: return "PREF_NET_TYPE_GSM_ONLY"; break; case PREF_NET_TYPE_WCDMA: return "PREF_NET_TYPE_WCDMA"; break; case PREF_NET_TYPE_GSM_WCDMA_AUTO: return "PREF_NET_TYPE_GSM_WCDMA_AUTO"; break; case PREF_NET_TYPE_CDMA_EVDO_AUTO: return "PREF_NET_TYPE_CDMA_EVDO_AUTO"; break; case PREF_NET_TYPE_CDMA_ONLY: return "PREF_NET_TYPE_CDMA_ONLY"; break; case PREF_NET_TYPE_EVDO_ONLY: return "PREF_NET_TYPE_EVDO_ONLY"; break; case PREF_NET_TYPE_GSM_WCDMA_CDMA_EVDO_AUTO: return "PREF_NET_TYPE_GSM_WCDMA_CDMA_EVDO_AUTO"; break; case PREF_NET_TYPE_LTE_CDMA_EVDO: return "PREF_NET_TYPE_LTE_CDMA_EVDO"; break; case PREF_NET_TYPE_LTE_GSM_WCDMA: return "PREF_NET_TYPE_LTE_GSM_WCDMA"; break; case PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA: return "PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA"; break; case PREF_NET_TYPE_LTE_ONLY: return "PREF_NET_TYPE_LTE_ONLY"; break; case PREF_NET_TYPE_LTE_WCDMA: return "PREF_NET_TYPE_LTE_WCDMA"; break; case PREF_NET_TYPE_LTE_GSM: return "PREF_NET_TYPE_LTE_GSM"; break; case PREF_NET_TYPE_LTE_TDD_ONLY: return "PREF_NET_TYPE_LTE_TDD_ONLY"; break; default: break; } return "unknown"; }
cc2f20e2591fde9b67fd270e912c56b7f57d1bf0
92a9f837503a591161330d39d061ce290c996f0e
/SiNDY-u/CheckSplitShape/RWN.cpp
b905c94feb171d74601e4dee507982072843c580
[]
no_license
AntLJ/TestUploadFolder
53a7dae537071d2b1e3bab55e925c8782f3daa0f
31f9837abbd6968fc3a0be7610560370c4431217
refs/heads/master
2020-12-15T21:56:47.756829
2020-01-23T07:33:23
2020-01-23T07:33:23
235,260,509
1
1
null
null
null
null
SHIFT_JIS
C++
false
false
2,645
cpp
RWN.cpp
/* * Copyright (C) INCREMENT P CORP. All Rights Reserved. * * THIS SOFTWARE IS PROVIDED BY INCREMENT P CORP., 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ #include "stdafx.h" #include "RWN.h" bool CRWNDiv::SetData(const CString& strTableName, IFeaturePtr ipFeature, const std::map<long,CString>& mapFieldIndex2Name, const std::map<CString,long>& mapFieldName2Index, const std::map<CString,long>& mapAttrName2Index) { if(!CRecodeBase::SetData(strTableName, ipFeature, mapFieldIndex2Name, mapFieldName2Index, mapAttrName2Index)) return false; return true; } bool CRWNAll::LoadData() { bool bReturn = true; IFeatureCursorPtr ipFeatureCursor; if(!GetFeatureCursor(m_strTableName, m_ipFeatureClass, NULL, ipFeatureCursor)) return false; #ifdef _DEBUG long lFeatureCount = 0; if(!GetFeatureCount(m_strTableName, m_ipFeatureClass, NULL, lFeatureCount)) return false; long n = 0; #endif IFeaturePtr ipFeature; while(S_OK == ipFeatureCursor->NextFeature(&ipFeature) && ipFeature){ #ifdef _DEBUG n++; if(0 == n % 100) std::cout << " RWN : " << n << " / " << lFeatureCount << "\r" << std::flush; #endif // ノード情報取得 CRWNDiv cRWNDiv; if(!cRWNDiv.SetData(m_strTableName, ipFeature, m_mapFieldIndex2Name, m_mapFieldName2Index, m_mapAttrName2Index)){ bReturn = false; continue; } // ノード情報はOBJECTIDとDIVIDでユニークに std::pair<std::map<UNIQID,CRWNDiv>::const_iterator,bool> itData = m_mapData.insert(std::make_pair(cRWNDiv.eObjectID, cRWNDiv)); if(!itData.second){ // データ重複エラー CLog::GetInstance().PrintLog(false, false, false, true, err_type::fatal, err_code::NgRWNDuplicateData, m_strTableName, cRWNDiv.eObjectID.eID, cRWNDiv.eObjectID.eDivID); bReturn = false; } // 緯度経度とOIDのマップを保持(ノードマージ処理前は重複するケースもあるのでマルチマップで保持している) m_mapLonLat2OID.insert(std::make_pair(cRWNDiv.eVecLonLat.at(0), cRWNDiv.eObjectID)); // OBJECTIDに所属するDIVID群を確保 m_mapDivOID[cRWNDiv.eObjectID.eID].insert(cRWNDiv.eObjectID.eDivID); } #ifdef _DEBUG std::cout << " RWN : " << n << " / " << lFeatureCount << std::endl; #endif return bReturn; }
0e05ac284676b9ed1fabb74111c4a79c5f70f64d
412c58404a2937f180838a0d436ea77a1e88aa50
/src/tm_uint128/cpp_wrapper.h
4fb56815523ea5f9bd03c352f5368caa6d4c3359
[ "LicenseRef-scancode-public-domain" ]
permissive
ExternalRepositories/tm
6f54b0e6db0a90f27ba67027a538faec216e1187
c97a3c14aa769b5a8f94b394b4535cd42eeb31d2
refs/heads/master
2023-01-23T18:24:51.311720
2020-12-05T11:29:24
2020-12-05T11:29:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,056
h
cpp_wrapper.h
namespace tml { class uint128_t { private: tmi_uint128_t value; public: #ifdef TMI_ARGS_BY_POINTER typedef const uint128_t& uint128_t_arg; #else typedef uint128_t uint128_t_arg; #endif uint128_t(tmi_uint128_t x); uint128_t(uint64_t x); uint128_t(uint32_t x); uint128_t(uint16_t x); uint128_t(uint8_t x); uint128_t(uint64_t low, uint64_t high); uint128_t() = default; uint128_t(const uint128_t_arg&) = default; uint128_t& operator+=(uint128_t_arg rhs); uint128_t& operator-=(uint128_t_arg rhs); uint128_t& operator*=(uint128_t_arg rhs); uint128_t& operator/=(uint128_t_arg rhs); uint128_t& operator%=(uint128_t_arg rhs); uint128_t& operator&=(uint128_t_arg rhs); uint128_t& operator|=(uint128_t_arg rhs); uint128_t& operator^=(uint128_t_arg rhs); uint128_t& operator<<=(uint128_t_arg rhs); uint128_t& operator>>=(uint128_t_arg rhs); uint128_t& operator++(); uint128_t operator++(int); uint128_t operator~() const; friend uint128_t operator+(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator-(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator*(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator/(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator%(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator&(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator|(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator^(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator<<(uint128_t_arg lhs, uint128_t_arg rhs); friend uint128_t operator>>(uint128_t_arg lhs, uint128_t_arg rhs); friend bool operator==(uint128_t_arg lhs, uint128_t_arg rhs); friend bool operator!=(uint128_t_arg lhs, uint128_t_arg rhs); friend bool operator<(uint128_t_arg lhs, uint128_t_arg rhs); friend bool operator<=(uint128_t_arg lhs, uint128_t_arg rhs); friend bool operator>(uint128_t_arg lhs, uint128_t_arg rhs); friend bool operator>=(uint128_t_arg lhs, uint128_t_arg rhs); inline explicit operator bool() const { return tmi_is_not_zero(TMI_PASS(value)); } operator tmi_uint128_t(); operator const tmi_uint128_t&() const; }; uint128_t operator+(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator-(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator*(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator/(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator%(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator&(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator|(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator^(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator<<(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); uint128_t operator>>(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); bool operator==(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); bool operator!=(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); bool operator<(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); bool operator<=(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); bool operator>(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); bool operator>=(tml::uint128_t::uint128_t_arg lhs, tml::uint128_t::uint128_t_arg rhs); #ifndef TMI_NO_STL TMI_DEF std::string to_string(uint128_t v, int32_t base = 10); TMI_DEF std::string to_string(tmi_uint128_t v, int32_t base = 10); TMI_DEF uint128_t from_string(const char* nullterminated, int32_t base = 10); TMI_DEF uint128_t from_string(const char* str, tm_size_t maxlen, int32_t base = 10); #endif } // namespace tml
829c0e5c86f6d789972efec3dd52c3cea6d4d274
56eb04e5fcb8651b62fb89d0e7521278e7eff913
/libs/file_utils/pvm.cpp
6e5801d7de41728984f431a356c8f35772199f20
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "GPL-3.0-only", "MIT" ]
permissive
lquatrin/cpp_volume_rendering
dda046836d0c5a355341a408867d2f9eda0a0fc8
8cf7d918edb73ea0408941d14bc4cbadbd02303b
refs/heads/main
2022-05-31T20:27:34.967805
2022-05-24T00:44:53
2022-05-24T00:44:53
351,811,252
22
6
MIT
2022-01-25T02:36:53
2021-03-26T14:34:56
C++
UTF-8
C++
false
false
30,905
cpp
pvm.cpp
#include "pvm.h" #include <fstream> #include <iostream> #include <cmath> #include <glm/glm.hpp> #include <glm/exponential.hpp> #include <glm/ext.hpp> #include <glm/common.hpp> #include <cstdint> #include <cstdlib> #include <cstring> #include <cerrno> #define DDS_MAXSTR (256) #define DDS_BLOCKSIZE (1<<20) #define DDS_INTERLEAVE (1<<24) #define DDS_RL (7) Pvm::Pvm (const char *file_name) { std::string filename(file_name); DDSV3 ddsloader; unsigned char* raw = ddsloader.readPVMvolume(filename.c_str(), &width, &height, &depth, &components, &scalex, &scaley, &scalez); printf("Sizes: [%d %d %d]\n", width, height, depth); printf("Scale: [%.4f %.4f %.4f]\n", scalex, scaley, scalez); printf("Components: %d\n", components); pvm_data = PostProcessData(raw); free(raw); } Pvm::~Pvm () { if (pvm_data) delete[] pvm_data; pvm_data = nullptr; } void* Pvm::GetData () { return pvm_data; } void Pvm::GetDimensions (unsigned int* _width, unsigned int* _height, unsigned int* _depth) { *_width = width; *_height = height; *_depth = depth; } void Pvm::GetScale (double* sx, double* sy, double* sz) { *sx = (double)scalex; *sy = (double)scaley; *sz = (double)scalez; } void Pvm::GetScale (float* sx, float* sy, float* sz) { *sx = (float)scalex; *sy = (float)scaley; *sz = (float)scalez; } int Pvm::GetComponents () { return components; } void* Pvm::PostProcessData (unsigned char* data) { int v_array_size = width * height * depth; if(components == 1) { unsigned char* prc_data = new unsigned char[v_array_size]; for (int i = 0; i < width * height * depth; i++) prc_data[i] = data[i]; return prc_data; } else if(components == 2) { unsigned short* prc_data = new unsigned short[v_array_size]; unsigned short vl = 256; for (int i = 0; i < width * height * depth; i++) { unsigned short v1 = data[(i * 2)]; unsigned short v2 = data[(i * 2) + 1]; prc_data[i] = //((v2 << 8) | v1) ((v2 * vl) + v1) ; assert(((v2 * vl) + v1) == ((v2 << 8) | v1)); } return prc_data; } return nullptr; } // Reescale between 0 ~ 1 using max_density_value float* Pvm::GenerateNormalizeData () { float* custom_data = new float[width*height*depth]; float max_density_value = pow(2, components * 8) - 1; if (components == 1) { unsigned char* a_pvm_data = (unsigned char*)pvm_data; for (int i = 0; i < width*height*depth; i++) custom_data[i] = ((float)a_pvm_data[i] / max_density_value); } else if (components == 2) { unsigned short* a_pvm_data = (unsigned short*)pvm_data; for (int i = 0; i < width*height*depth; i++) custom_data[i] = ((float)a_pvm_data[i] / max_density_value); } return custom_data; } //float* Pvm::GenerateReescaledMinMaxData (bool normalized, float* fmin, float* fmax) //{ // float max_density_value = pow(2, components * 8) - 1; // float min = max_density_value; // float max = 0; // // for (int i = 0; i < width*height*depth; i++) // { // min = glm::min(min, pvm_data[i]); // max = glm::max(max, pvm_data[i]); // } // // if (fmin) *fmin = min; // if (fmax) *fmax = max; // // float* custom_data = new float[width*height*depth]; // // // First we reescale between 0 ~ 1 using min and max value found // for (int i = 0; i < width*height*depth; i++) // custom_data[i] = (pvm_data[i] - min) / (max - min); // // // if normalized is FALSE, reescale by the max_density_value // if (!normalized) // { // for (int i = 0; i < width*height*depth; i++) // custom_data[i] = custom_data[i] * max_density_value; // } // // return custom_data; //} // //void Pvm::TransformData (unsigned int dst_bytes_per_voxel) //{ // float old_max_density_value = pow(2, components * 8) - 1; // float new_max_density_value = pow(2, dst_bytes_per_voxel * 8) - 1; // // // First we reescale between 0~1 // for (int i = 0; i < width*height*depth; i++) // { // pvm_data[i] = (pvm_data[i] / old_max_density_value) * new_max_density_value; // } // // components = dst_bytes_per_voxel; //} //////////////////////////////////// // DDSV3 class methods //////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // PVM/DDS reader (8/16 bits): // Copyright: // (c) by Stefan Roettger, licensed under GPL 2+ // The Volume Library: http://www9.informatik.uni-erlangen.de/External/vollib/ // V^3 Package code: https://code.google.com/p/vvv/ // read a compressed PVM volume unsigned char* DDSV3::readPVMvolume (const char* filename, unsigned int* width, unsigned int* height, unsigned int* depth, unsigned int* components, float* scalex, float* scaley, float* scalez, unsigned char** description, unsigned char** courtesy, unsigned char** parameter, unsigned char** comment) { unsigned char* data; unsigned char* ptr; unsigned int bytes, numc; int version = 1; unsigned char* volume; float sx = 1.0f, sy = 1.0f, sz = 1.0f; unsigned int len1 = 0, len2 = 0, len3 = 0, len4 = 0; if ((data = readDDSfile(filename, &bytes)) == NULL) if ((data = readRAWfile(filename, &bytes)) == NULL) return(NULL); if (bytes<5) return(NULL); if ((data = (unsigned char*)realloc(data, bytes + 1)) == NULL) ERRORMSG(); data[bytes] = '\0'; if (strncmp((char*)data, "PVM\n", 4) != 0) { if (strncmp((char*)data, "PVM2\n", 5) == 0) version = 2; else if (strncmp((char*)data, "PVM3\n", 5) == 0) version = 3; else return(NULL); ptr = &data[5]; if (sscanf_s((char*)ptr, "%d %d %d\n%g %g %g\n", width, height, depth, &sx, &sy, &sz) != 6) ERRORMSG(); if (*width < 1 || *height < 1 || *depth < 1 || sx <= 0.0f || sy <= 0.0f || sz <= 0.0f) ERRORMSG(); ptr = (unsigned char*)strchr((char*)ptr, '\n') + 1; } else { ptr = &data[4]; while (*ptr == '#') while (*ptr++ != '\n'); if (sscanf_s((char*)ptr, "%d %d %d\n", width, height, depth) != 3) ERRORMSG(); if (*width < 1 || *height < 1 || *depth < 1) ERRORMSG(); } if (scalex != NULL && scaley != NULL && scalez != NULL) { *scalex = sx; *scaley = sy; *scalez = sz; } ptr = (unsigned char*)strchr((char*)ptr, '\n') + 1; if (sscanf_s((char *)ptr, "%d\n", &numc) != 1) ERRORMSG(); if (numc<1) ERRORMSG(); if (components != NULL) *components = numc; else if (numc != 1) ERRORMSG(); ptr = (unsigned char*)strchr((char*)ptr, '\n') + 1; if (version == 3) len1 = strlen((char*)(ptr + (*width)*(*height)*(*depth)*numc)) + 1; if (version == 3) len2 = strlen((char*)(ptr + (*width)*(*height)*(*depth)*numc + len1)) + 1; if (version == 3) len3 = strlen((char*)(ptr + (*width)*(*height)*(*depth)*numc + len1 + len2)) + 1; if (version == 3) len4 = strlen((char*)(ptr + (*width)*(*height)*(*depth)*numc + len1 + len2 + len3)) + 1; if ((volume = (unsigned char*)malloc((*width)*(*height)*(*depth)*numc + len1 + len2 + len3 + len4)) == NULL) ERRORMSG(); if (data + bytes != ptr + (*width)*(*height)*(*depth)*numc + len1 + len2 + len3 + len4) ERRORMSG(); memcpy(volume, ptr, (*width)*(*height)*(*depth)*numc + len1 + len2 + len3 + len4); free(data); if (description != NULL) if (len1 > 1) *description = volume + (*width)*(*height)*(*depth)*numc; else *description = NULL; //if (description != NULL) { // if (len1>1) *description = volume + (*width)*(*height)*(*depth)*numc; //} //else { // //*description=NULL; //} if (courtesy != NULL) if (len2 > 1) *courtesy = volume + (*width)*(*height)*(*depth)*numc + len1; else *courtesy = NULL; //if (courtesy != NULL) { // if (len2>1) *courtesy = volume + (*width)*(*height)*(*depth)*numc + len1; //} //else { // //*courtesy=NULL; //} if (parameter != NULL) if (len3 > 1) *parameter = volume + (*width)*(*height)*(*depth)*numc + len1 + len2; else *parameter = NULL; //if (parameter != NULL) { // if (len3>1) *parameter = volume + (*width)*(*height)*(*depth)*numc + len1 + len2; //} //else { // //*parameter=NULL; //} if (comment != NULL) if (len4 > 1) *comment = volume + (*width)*(*height)*(*depth)*numc + len1 + len2 + len3; else *comment = NULL; //if (comment != NULL) { // if (len4>1) *comment = volume + (*width)*(*height)*(*depth)*numc + len1 + len2 + len3; //} //else { // //*comment=NULL; //} return(volume); } // read a possibly compressed PNM image unsigned char* DDSV3::readPNMimage (const char* filename, unsigned int* width, unsigned int* height, unsigned int* components) { const int maxstr = 100; char str[maxstr]; unsigned char *data, *ptr1, *ptr2; unsigned int bytes; int pnmtype, maxval; unsigned char* image; if ((data = readDDSfile(filename, &bytes)) == NULL) if ((data = readRAWfile(filename, &bytes)) == NULL) return(NULL); if (bytes<4) return(NULL); memcpy(str, data, 3); str[3] = '\0'; if (sscanf_s(str, "P%1d\n", &pnmtype) != 1) return(NULL); ptr1 = data + 3; while (*ptr1 == '\n' || *ptr1 == '#') { while (*ptr1 == '\n') if (++ptr1 >= data + bytes) ERRORMSG(); while (*ptr1 == '#') if (++ptr1 >= data + bytes) ERRORMSG(); else while (*ptr1 != '\n') if (++ptr1 >= data + bytes) ERRORMSG(); } ptr2 = ptr1; while (*ptr2 != '\n' && *ptr2 != ' ') if (++ptr2 >= data + bytes) ERRORMSG(); if (++ptr2 >= data + bytes) ERRORMSG(); while (*ptr2 != '\n' && *ptr2 != ' ') if (++ptr2 >= data + bytes) ERRORMSG(); if (++ptr2 >= data + bytes) ERRORMSG(); while (*ptr2 != '\n' && *ptr2 != ' ') if (++ptr2 >= data + bytes) ERRORMSG(); if (++ptr2 >= data + bytes) ERRORMSG(); if (ptr2 - ptr1 >= maxstr) ERRORMSG(); memcpy(str, ptr1, ptr2 - ptr1); str[ptr2 - ptr1] = '\0'; if (sscanf_s(str, "%d %d\n%d\n", width, height, &maxval) != 3) ERRORMSG(); if (*width<1 || *height<1) ERRORMSG(); if (pnmtype == 5 && maxval == 255) *components = 1; else if (pnmtype == 5 && (maxval == 32767 || maxval == 65535)) *components = 2; else if (pnmtype == 6 && maxval == 255) *components = 3; else ERRORMSG(); if ((image = (unsigned char*)malloc((*width)*(*height)*(*components))) == NULL) ERRORMSG(); if (data + bytes != ptr2 + (*width)*(*height)*(*components)) ERRORMSG(); memcpy(image, ptr2, (*width)*(*height)*(*components)); free(data); return(image); } // decode a Differential Data Stream void DDSV3::DDS_decode (unsigned char* chunk, unsigned int size, unsigned char** data, unsigned int* bytes, unsigned int block) { unsigned int skip, strip; unsigned char *ptr1, *ptr2; unsigned int cnt, cnt1, cnt2; int bits, act; DDS_initbuffer(); DDS_clearbits(); DDS_loadbits(chunk, size); skip = DDS_readbits(2) + 1; strip = DDS_readbits(16) + 1; ptr1 = ptr2 = NULL; cnt = act = 0; while ((cnt1 = DDS_readbits(DDS_RL)) != 0) { bits = DDS_decode(DDS_readbits(3)); for (cnt2 = 0; cnt2<cnt1; cnt2++) { if (strip == 1 || cnt <= strip) act += DDS_readbits(bits) - (1 << bits) / 2; else act += *(ptr2 - strip) - *(ptr2 - strip - 1) + DDS_readbits(bits) - (1 << bits) / 2; while (act<0) act += 256; while (act>255) act -= 256; if ((cnt&(DDS_BLOCKSIZE - 1)) == 0) { if (ptr1 == NULL) { if ((ptr1 = (unsigned char*)malloc(DDS_BLOCKSIZE)) == NULL) MEMERROR(); ptr2 = ptr1; } else { if ((ptr1 = (unsigned char*)realloc(ptr1, cnt + DDS_BLOCKSIZE)) == NULL) MEMERROR(); ptr2 = &ptr1[cnt]; } } *ptr2++ = act; cnt++; } } if (ptr1 != NULL) if ((ptr1 = (uint8_t *)realloc(ptr1, cnt)) == NULL) MEMERROR(); DDS_interleave(ptr1, cnt, skip, block); *data = ptr1; *bytes = cnt; } // interleave a byte stream void DDSV3::DDS_interleave (unsigned char* data, unsigned int bytes, unsigned int skip, unsigned int block) { DDS_deinterleave(data, bytes, skip, block, true); } // deinterleave a byte stream void DDSV3::DDS_deinterleave (unsigned char* data, unsigned int bytes, unsigned int skip, unsigned int block, bool restore) { unsigned int i, j, k; unsigned char *data2, *ptr; if (skip <= 1) return; if (block == 0) { if ((data2 = (unsigned char*)malloc(bytes)) == NULL) MEMERROR(); if (!restore) for (ptr = data2, i = 0; i<skip; i++) for (j = i; j<bytes; j += skip) *ptr++ = data[j]; else for (ptr = data, i = 0; i<skip; i++) for (j = i; j<bytes; j += skip) data2[j] = *ptr++; memcpy(data, data2, bytes); } else { if ((data2 = (unsigned char*)malloc((bytes < skip*block) ? bytes : skip*block)) == NULL) MEMERROR(); if (!restore) { for (k = 0; k < bytes / skip / block; k++) { for (ptr = data2, i = 0; i < skip; i++) for (j = i; j<skip*block; j += skip) *ptr++ = data[k*skip*block + j]; memcpy(data + k*skip*block, data2, skip*block); } for (ptr = data2, i = 0; i<skip; i++) for (j = i; j<bytes - k*skip*block; j += skip) *ptr++ = data[k*skip*block + j]; memcpy(data + k*skip*block, data2, bytes - k*skip*block); } else { for (k = 0; k<bytes / skip / block; k++) { for (ptr = data + k*skip*block, i = 0; i<skip; i++) for (j = i; j<skip*block; j += skip) data2[j] = *ptr++; memcpy(data + k*skip*block, data2, skip*block); } for (ptr = data + k*skip*block, i = 0; i<skip; i++) for (j = i; j<bytes - k*skip*block; j += skip) data2[j] = *ptr++; memcpy(data + k*skip*block, data2, bytes - k*skip*block); } } free(data2); } // read a Differential Data Stream unsigned char* DDSV3::readDDSfile (const char *filename, unsigned int *bytes) { char DDS_ID[] = "DDS v3d\n"; char DDS_ID2[] = "DDS v3e\n"; int version = 1; FILE *file; errno_t err; int cnt; unsigned char *chunk, *data; unsigned int size; if ((err = fopen_s(&file, filename, "rb")) != 0) return(NULL); for (cnt = 0; DDS_ID[cnt] != '\0'; cnt++) { if (fgetc(file) != DDS_ID[cnt]) { fclose(file); version = 0; break; } } if (version == 0) { if ((err = fopen_s(&file, filename, "rb")) != 0) return(NULL); for (cnt = 0; DDS_ID2[cnt] != '\0'; cnt++) { if (fgetc(file) != DDS_ID2[cnt]) { fclose(file); return(NULL); } } version = 2; } if ((chunk = readRAWfiled(file, &size)) == NULL) IOERROR(); fclose(file); DDS_decode(chunk, size, &data, bytes, version == 1 ? 0 : DDS_INTERLEAVE); free(chunk); return(data); } // read from a RAW file unsigned char* DDSV3::readRAWfiled (FILE *file, unsigned int *bytes) { unsigned char* data; unsigned int cnt, blkcnt; data = NULL; cnt = 0; do { if (data == NULL) { if ((data = (unsigned char*)malloc(DDS_BLOCKSIZE)) == NULL) MEMERROR(); } else if ((data = (unsigned char*)realloc(data, cnt + DDS_BLOCKSIZE)) == NULL) MEMERROR(); blkcnt = fread(&data[cnt], 1, DDS_BLOCKSIZE, file); cnt += blkcnt; } while (blkcnt == DDS_BLOCKSIZE); if (cnt == 0) { free(data); return(NULL); } if ((data = (unsigned char*)realloc(data, cnt)) == NULL) MEMERROR(); *bytes = cnt; return(data); } // read a RAW file unsigned char* DDSV3::readRAWfile (const char *filename, unsigned int *bytes) { FILE* file; errno_t err; unsigned char* data; if ((err = fopen_s(&file, filename, "rb")) != 0) return(NULL); data = readRAWfiled(file, bytes); fclose(file); return(data); } /* inline void DDS_writebits(unsigned int value,unsigned int bits) { value&=DDS_shiftl(1,bits)-1; if (DDS_bufsize+bits<32) { DDS_buffer=DDS_shiftl(DDS_buffer,bits)|value; DDS_bufsize+=bits; } else { DDS_buffer=DDS_shiftl(DDS_buffer,32-DDS_bufsize); DDS_bufsize-=32-bits; DDS_buffer|=DDS_shiftr(value,DDS_bufsize); if (DDS_cachepos+4>DDS_cachesize) if (DDS_cache==NULL) { if ((DDS_cache=(unsigned char *)malloc(DDS_BLOCKSIZE))==NULL) MEMERROR(); DDS_cachesize=DDS_BLOCKSIZE; } else { if ((DDS_cache=(unsigned char *)realloc(DDS_cache,DDS_cachesize+DDS_BLOCKSIZE))==NULL) MEMERROR(); DDS_cachesize+=DDS_BLOCKSIZE; } if (DDS_ISINTEL) DDS_swapuint(&DDS_buffer); *((unsigned int *)&DDS_cache[DDS_cachepos])=DDS_buffer; DDS_cachepos+=4; DDS_buffer=value&(DDS_shiftl(1,DDS_bufsize)-1); } } inline void DDS_flushbits() { unsigned int bufsize; bufsize=DDS_bufsize; if (bufsize>0) { DDS_writebits(0,32-bufsize); DDS_cachepos-=(32-bufsize)/8; } } inline void DDS_savebits(unsigned char **data,unsigned int *size) { *data=DDS_cache; *size=DDS_cachepos; } // encode a Differential Data Stream void DDS_encode (unsigned char *data,unsigned int bytes,unsigned int skip,unsigned int strip, unsigned char **chunk,unsigned int *size, unsigned int block=0) { int i; unsigned char lookup[256]; unsigned char *ptr1,*ptr2; int pre1,pre2, act1,act2, tmp1,tmp2; unsigned int cnt,cnt1,cnt2; int bits,bits1,bits2; if (bytes<1) ERRORMSG(); if (skip<1 || skip>4) skip=1; if (strip<1 || strip>65536) strip=1; DDS_deinterleave(data,bytes,skip,block); for (i=-128; i<128; i++) { if (i<=0) for (bits=0; (1<<bits)/2<-i; bits++); else for (bits=0; (1<<bits)/2<=i; bits++); lookup[i+128]=bits; } DDS_initbuffer(); DDS_clearbits(); DDS_writebits(skip-1,2); DDS_writebits(strip-1,16); ptr1=ptr2=data; pre1=pre2=0; cnt=cnt1=cnt2=0; bits=bits1=bits2=0; while (cnt++<bytes) { tmp1=*ptr1; if (strip==1 || ptr1-strip<=data) act1=tmp1-pre1; else act1=tmp1-pre1-*(ptr1-strip)+*(ptr1-strip-1); pre1=tmp1; ptr1++; while (act1<-128) act1+=256; while (act1>127) act1-=256; bits=lookup[act1+128]; bits=DDS_decode(DDS_code(bits)); if (cnt1==0) { cnt1++; bits1=bits; continue; } if (cnt1<(1<<DDS_RL)-1 && bits==bits1) { cnt1++; continue; } if (cnt1+cnt2<(1<<DDS_RL) && (cnt1+cnt2)*max(bits1,bits2)<cnt1*bits1+cnt2*bits2+DDS_RL+3) { cnt2+=cnt1; if (bits1>bits2) bits2=bits1; } else { DDS_writebits(cnt2,DDS_RL); DDS_writebits(DDS_code(bits2),3); while (cnt2-->0) { tmp2=*ptr2; if (strip==1 || ptr2-strip<=data) act2=tmp2-pre2; else act2=tmp2-pre2-*(ptr2-strip)+*(ptr2-strip-1); pre2=tmp2; ptr2++; while (act2<-128) act2+=256; while (act2>127) act2-=256; DDS_writebits(act2+(1<<bits2)/2,bits2); } cnt2=cnt1; bits2=bits1; } cnt1=1; bits1=bits; } if (cnt1+cnt2<(1<<DDS_RL) && (cnt1+cnt2)*max(bits1,bits2)<cnt1*bits1+cnt2*bits2+DDS_RL+3) { cnt2+=cnt1; if (bits1>bits2) bits2=bits1; } else { DDS_writebits(cnt2,DDS_RL); DDS_writebits(DDS_code(bits2),3); while (cnt2-->0) { tmp2=*ptr2; if (strip==1 || ptr2-strip<=data) act2=tmp2-pre2; else act2=tmp2-pre2-*(ptr2-strip)+*(ptr2-strip-1); pre2=tmp2; ptr2++; while (act2<-128) act2+=256; while (act2>127) act2-=256; DDS_writebits(act2+(1<<bits2)/2,bits2); } cnt2=cnt1; bits2=bits1; } if (cnt2!=0) { DDS_writebits(cnt2,DDS_RL); DDS_writebits(DDS_code(bits2),3); while (cnt2-->0) { tmp2=*ptr2; if (strip==1 || ptr2-strip<=data) act2=tmp2-pre2; else act2=tmp2-pre2-*(ptr2-strip)+*(ptr2-strip-1); pre2=tmp2; ptr2++; while (act2<-128) act2+=256; while (act2>127) act2-=256; DDS_writebits(act2+(1<<bits2)/2,bits2); } } DDS_flushbits(); DDS_savebits(chunk,size); DDS_interleave(data,bytes,skip,block); } // write a RAW file void writeRAWfile(const char *filename,unsigned char *data,unsigned int bytes,BOOLINT nofree) { FILE *file; if (bytes<1) ERRORMSG(); if ((file=fopen(filename,"wb"))==NULL) IOERROR(); if (fwrite(data,1,bytes,file)!=bytes) IOERROR(); fclose(file); if (!nofree) free(data); } // write a Differential Data Stream void writeDDSfile(const char *filename,unsigned char *data,unsigned int bytes,unsigned int skip,unsigned int strip,BOOLINT nofree) { int version=1; FILE *file; unsigned char *chunk; unsigned int size; if (bytes<1) ERRORMSG(); if (bytes>DDS_INTERLEAVE) version=2; if ((file=fopen(filename,"wb"))==NULL) IOERROR(); fprintf(file,"%s",(version==1)?DDS_ID:DDS_ID2); DDS_encode(data,bytes,skip,strip,&chunk,&size,version==1?0:DDS_INTERLEAVE); if (chunk!=NULL) { if (fwrite(chunk,size,1,file)!=1) IOERROR(); free(chunk); } fclose(file); if (!nofree) free(data); } // write an optionally compressed PNM image void writePNMimage(const char *filename,unsigned char *image,unsigned int width,unsigned int height,unsigned int components,BOOLINT dds) { char str[DDS_MAXSTR]; unsigned char *data; if (width<1 || height<1) ERRORMSG(); switch (components) { case 1: snprintf(str,DDS_MAXSTR,"P5\n%d %d\n255\n",width,height); break; case 2: snprintf(str,DDS_MAXSTR,"P5\n%d %d\n32767\n",width,height); break; case 3: snprintf(str,DDS_MAXSTR,"P6\n%d %d\n255\n",width,height); break; default: ERRORMSG(); } if ((data=(unsigned char *)malloc(strlen(str)+width*height*components))==NULL) MEMERROR(); memcpy(data,str,strlen(str)); memcpy(data+strlen(str),image,width*height*components); if (dds) writeDDSfile(filename,data,strlen(str)+width*height*components,components,width); else writeRAWfile(filename,data,strlen(str)+width*height*components); } // write a compressed PVM volume void writePVMvolume(const char *filename,unsigned char *volume, unsigned int width,unsigned int height,unsigned int depth,unsigned int components, float scalex,float scaley,float scalez, unsigned char *description, unsigned char *courtesy, unsigned char *parameter, unsigned char *comment) { char str[DDS_MAXSTR]; unsigned char *data; unsigned int len1=1,len2=1,len3=1,len4=1; if (width<1 || height<1 || depth<1 || components<1) ERRORMSG(); if (description==NULL && courtesy==NULL && parameter==NULL && comment==NULL) if (scalex==1.0f && scaley==1.0f && scalez==1.0f) snprintf(str,DDS_MAXSTR,"PVM\n%d %d %d\n%d\n",width,height,depth,components); else snprintf(str,DDS_MAXSTR,"PVM2\n%d %d %d\n%g %g %g\n%d\n",width,height,depth,scalex,scaley,scalez,components); else snprintf(str,DDS_MAXSTR,"PVM3\n%d %d %d\n%g %g %g\n%d\n",width,height,depth,scalex,scaley,scalez,components); if (description==NULL && courtesy==NULL && parameter==NULL && comment==NULL) { if ((data=(unsigned char *)malloc(strlen(str)+width*height*depth*components))==NULL) MEMERROR(); memcpy(data,str,strlen(str)); memcpy(data+strlen(str),volume,width*height*depth*components); writeDDSfile(filename,data,strlen(str)+width*height*depth*components,components,width); } else { if (description!=NULL) len1=strlen((char *)description)+1; if (courtesy!=NULL) len2=strlen((char *)courtesy)+1; if (parameter!=NULL) len3=strlen((char *)parameter)+1; if (comment!=NULL) len4=strlen((char *)comment)+1; if ((data=(unsigned char *)malloc(strlen(str)+width*height*depth*components+len1+len2+len3+len4))==NULL) MEMERROR(); memcpy(data,str,strlen(str)); memcpy(data+strlen(str),volume,width*height*depth*components); if (description==NULL) *(data+strlen(str)+width*height*depth*components)='\0'; else memcpy(data+strlen(str)+width*height*depth*components,description,len1); if (courtesy==NULL) *(data+strlen(str)+width*height*depth*components+len1)='\0'; else memcpy(data+strlen(str)+width*height*depth*components+len1,courtesy,len2); if (parameter==NULL) *(data+strlen(str)+width*height*depth*components+len1+len2)='\0'; else memcpy(data+strlen(str)+width*height*depth*components+len1+len2,parameter,len3); if (comment==NULL) *(data+strlen(str)+width*height*depth*components+len1+len2+len3)='\0'; else memcpy(data+strlen(str)+width*height*depth*components+len1+len2+len3,comment,len4); writeDDSfile(filename,data,strlen(str)+width*height*depth*components+len1+len2+len3+len4,components,width); } } // check a file int checkfile(const char *filename) { FILE *file; if ((file=fopen(filename,"rb"))==NULL) return(0); fclose(file); return(1); } // simple checksum algorithm unsigned int checksum(unsigned char *data,unsigned int bytes) { const unsigned int prime=271; unsigned int i; unsigned char *ptr,value; unsigned int sum,cipher; sum=0; cipher=1; for (ptr=data,i=0; i<bytes; i++) { value=*ptr++; cipher=prime*cipher+value; sum+=cipher*value; } return(sum); } // swap the hi and lo byte of 16 bit data void swapbytes(unsigned char *data,long long bytes) { long long i; unsigned char *ptr,tmp; for (ptr=data,i=0; i<bytes/2; i++,ptr+=2) { tmp=*ptr; *ptr=*(ptr+1); *(ptr+1)=tmp; } } // convert from signed short to unsigned short void convbytes(unsigned char *data,long long bytes) { long long i; unsigned char *ptr; int v,vmin; for (vmin=32767,ptr=data,i=0; i<bytes/2; i++,ptr+=2) { v=256*(*ptr)+*(ptr+1); if (v>32767) v=v-65536; if (v<vmin) vmin=v; } for (ptr=data,i=0; i<bytes/2; i++,ptr+=2) { v=256*(*ptr)+*(ptr+1); if (v>32767) v=v-65536; *ptr=(v-vmin)/256; *(ptr+1)=(v-vmin)%256; } } // convert from float to unsigned short void convfloat(unsigned char **data,long long bytes) { long long i; unsigned char *ptr; float v,vmax; for (vmax=1.0f,ptr=*data,i=0; i<bytes/4; i++,ptr+=4) { if (DDS_ISINTEL) DDS_swapuint((unsigned int *)ptr); v=fabs(*((float *)ptr)); if (v>vmax) vmax=v; } for (ptr=*data,i=0; i<bytes/4; i++,ptr+=4) { v=fabs(*((float *)ptr))/vmax; (*data)[2*i]=ftrc(65535.0f*v+0.5f)/256; (*data)[2*i+1]=ftrc(65535.0f*v+0.5f)%256; } if ((*data=(unsigned char *)realloc(*data,bytes/4*2))==NULL) MEMERROR(); } // convert from rgb to byte void convrgb(unsigned char **data,long long bytes) { long long i; unsigned char *ptr1,*ptr2; for (ptr1=ptr2=*data,i=0; i<bytes/3; i++,ptr1+=3,ptr2++) *ptr2=((*ptr1)+*(ptr1+1)+*(ptr1+2)+1)/3; if ((*data=(unsigned char *)realloc(*data,bytes/3))==NULL) MEMERROR(); } // helper to get a short value from a volume inline int getshort(unsigned short int *data, long long width,long long height,long long depth, long long i,long long j,long long k) {return(data[i+(j+k*height)*width]);} // helper to get a gradient value from a volume inline double getgrad(unsigned short int *data, long long width,long long height,long long depth, long long i,long long j,long long k) { double gx,gy,gz; if (i>0) if (i<width-1) gx=(getshort(data,width,height,depth,i+1,j,k)-getshort(data,width,height,depth,i-1,j,k))/2.0; else gx=getshort(data,width,height,depth,i,j,k)-getshort(data,width,height,depth,i-1,j,k); else if (i<width-1) gx=getshort(data,width,height,depth,i+1,j,k)-getshort(data,width,height,depth,i,j,k); else gx=0.0; if (j>0) if (j<height-1) gy=(getshort(data,width,height,depth,i,j+1,k)-getshort(data,width,height,depth,i,j-1,k))/2.0; else gy=getshort(data,width,height,depth,i,j,k)-getshort(data,width,height,depth,i,j-1,k); else if (j<height-1) gy=getshort(data,width,height,depth,i,j+1,k)-getshort(data,width,height,depth,i,j,k); else gy=0.0; if (k>0) if (k<depth-1) gz=(getshort(data,width,height,depth,i,j,k+1)-getshort(data,width,height,depth,i,j,k-1))/2.0; else gz=getshort(data,width,height,depth,i,j,k)-getshort(data,width,height,depth,i,j,k-1); else if (k<depth-1) gz=getshort(data,width,height,depth,i,j,k+1)-getshort(data,width,height,depth,i,j,k); else gz=0.0; return(sqrt(gx*gx+gy*gy+gz*gz)); } // quantize 16 bit data to 8 bit using a non-linear mapping unsigned char *quantize(unsigned char *data, long long width,long long height,long long depth, BOOLINT msb, BOOLINT linear,BOOLINT nofree) { long long i,j,k; unsigned char *data2; unsigned short int *data3; long long idx; int v,vmin,vmax; double *err,eint; BOOLINT done; if ((data3=(unsigned short int*)malloc(width*height*depth*sizeof(unsigned short int)))==NULL) MEMERROR(); vmin=65535; vmax=0; for (k=0; k<depth; k++) for (j=0; j<height; j++) for (i=0; i<width; i++) { idx=i+(j+k*height)*width; if (msb) v=256*data[2*idx]+data[2*idx+1]; else v=data[2*idx]+256*data[2*idx+1]; data3[idx]=v; if (v<vmin) vmin=v; if (v>vmax) vmax=v; } if (!nofree) free(data); if (vmin==vmax) vmax=vmin+1; if (vmax-vmin<256) linear=TRUE; err=new double[65536]; if (linear) for (i=0; i<65536; i++) err[i]=255*(double)(i-vmin)/(vmax-vmin); else { for (i=0; i<65536; i++) err[i]=0.0; for (k=0; k<depth; k++) for (j=0; j<height; j++) for (i=0; i<width; i++) err[getshort(data3,width,height,depth,i,j,k)]+=sqrt(getgrad(data3,width,height,depth,i,j,k)); for (i=0; i<65536; i++) err[i]=pow(err[i],1.0/3); err[vmin]=err[vmax]=0.0; for (k=0; k<256; k++) { for (eint=0.0,i=0; i<65536; i++) eint+=err[i]; done=TRUE; for (i=0; i<65536; i++) if (err[i]>eint/256) { err[i]=eint/256; done=FALSE; } if (done) break; } for (i=1; i<65536; i++) err[i]+=err[i-1]; if (err[65535]>0.0f) for (i=0; i<65536; i++) err[i]*=255.0/err[65535]; } if ((data2=(unsigned char *)malloc(width*height*depth))==NULL) MEMERROR(); for (k=0; k<depth; k++) for (j=0; j<height; j++) for (i=0; i<width; i++) { idx=i+(j+k*height)*width; data2[idx]=(int)(err[data3[idx]]+0.5); } delete err; free(data3); return(data2); } // copy a PVM volume to a RAW volume char *processPVMvolume(const char *filename) { unsigned char *volume; unsigned int width,height,depth, components; float scalex,scaley,scalez; char *output,*dot; char *outname; // read and uncompress PVM volume if ((volume=readPVMvolume(filename, &width,&height,&depth,&components, &scalex,&scaley,&scalez))==NULL) return(NULL); // use input file name as output prefix output=strdup(filename); dot=strrchr(output,'.'); // remove suffix from output if (dot!=NULL) if (strcasecmp(dot,".pvm")==0) *dot='\0'; outname=NULL; #ifdef HAVE_MINI // copy PVM data to RAW file outname=writeRAWvolume(output,volume, width,height,depth,1, components,8,FALSE,TRUE, scalex,scaley,scalez); #endif free(volume); free(output); return(outname); } */
c45b585de5690803e76ab766943f82e33771b4fd
55ef8b7e4daa6b4c44961e12fdc7a5f268d5cc2e
/src/simple_examples/BinAddStr.cpp
54551c5716b0b1a5d48a67aefb3a00c3423c4e14
[]
no_license
leonardoaraujosantos/CPPBookCode
65297ce61e92e0974c9f805daa1068c97399b8b7
595b4072493b5e7ee89a97734658b28e87f565d9
refs/heads/master
2021-01-11T22:58:18.302742
2017-03-27T10:44:28
2017-03-27T10:44:28
78,529,225
0
0
null
null
null
null
UTF-8
C++
false
false
3,411
cpp
BinAddStr.cpp
#include <iostream> #include <string> #include <stack> using namespace std; inline int binChar2Num(const char ch){ int val = 1?(ch=='1'):0; return val; } // Alexey inline func inline int getVal(const std::string a, size_t ind) { if (a.size() <= ind) return 0; if (a[a.size() - ind - 1] == '1') return 1; else return 0; } /* Add 2 binary numbers defined as strings "101" + "11"=1000. Attention: The strings can be really big and will not fit on a long long variable 45 min to complete. */ string strBinSum(const string &num1, const string &num2){ // Initialize with the size of the biggest string plus one character (Worst sum case 11+11=110) string resp(max(num1.size(), num2.size())+1,'0'); // Select biggest operand const string &refBig = (num1.size()>num2.size())?num1:num2; const string &refSmall = (num1.size()<num2.size())?num1:num2; // Create stack for carry-bit stack<int> stCarry; // Iterate on num1 on reverse order auto itr2 = refSmall.rbegin(); auto itrResp = resp.rbegin(); for (auto itr1 = refBig.rbegin(); itr1 != refBig.rend(); ++itr1){ char c1 = *itr1; char c2 = *itr2; // Handle if there is no more binary digits on num2 (just return 0) if (itr2 != num2.rend()){ itr2++; } else { c2 = '0'; } int val1 = binChar2Num(c1); int val2 = binChar2Num(c2); // Get carry bit int carry = 0; if (stCarry.empty()){ carry = 0; } else { carry = stCarry.top(); stCarry.pop(); } // Do the sum including carry int res = val1 + val2 + carry; if (res > 1) { stCarry.push(1); res = 0; } *itrResp = to_string(res).at(0); itrResp++; } // Add carry there is still something to add if (!stCarry.empty()){ auto lastVal = stCarry.top(); stCarry.pop(); *itrResp = to_string(lastVal).at(0); } return resp; } // Alexey solution was coller than mine on the carry part, but he did not pre-allocate the result string string binary_string_sum(const string& a, const string& b){ // do some stupid checks that the number is correct and stuff like that // it is possible to use string initially not to reconvert in the end; but this will require some more complex calculations list<char> sum; int maxBits = std::max(a.size(), b.size()); int val3 = 0; for (int i = 0; i < maxBits; ++i) { // there is a possible optimisation - at some point we can just copy part of number, in case of '1010010101010101' + '1' like numbers int res = getVal(a, i) + getVal(b, i) + val3; val3 = (res >= 2); if (res % 2 == 0) sum.push_front('0'); else sum.push_front('1'); } if(val3 == 1) sum.push_front('1'); int numElements = sum.size(); string answer; int i = 0; for (const auto& it : sum) { answer.push_back(it); } return answer; } int main() { //string sumBin = strBinSum("101","11"); string sumBin = strBinSum("10001110001001100101","100110011"); auto resultRef = string("10001110001110011000"); cout << "10001110001001100101 + 100110011 = " << sumBin << endl; return 0; }
56a308421c357edf70860ff045990c20330d1d6e
47cec727aa95560ac54184fccab50d1a6c727083
/ReEngine/src/Runtime/GlobalAssets/CommonExt.h
ba16e47f87bbe3b109b22aa769c66aee189c2185
[]
no_license
kingdomheartstao/Renderer-Learning
303cd8f054178dfdc629d81f3569c7fcb2b1eb1d
b35f963414a4dabf6d2fd9ab7dee278ecf38284a
refs/heads/master
2023-07-28T01:07:32.919132
2021-09-10T09:24:46
2021-09-10T09:24:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
573
h
CommonExt.h
#pragma once #include <string> #include <vector> namespace Assets { const std::vector<std::string> PrefabExt { ".prefab" }; const std::vector<std::string> MaterialExt { ".mat" }; const std::vector<std::string> SceneExt { ".scene" }; const std::vector<std::string> MeshGroupExt { ".fbx", ".obj" }; const std::vector<std::string> ImageExt{ ".jpg", ".png" }; inline bool FindExt(const std::vector<std::string>& targetExts, const std::string& ext) { for (auto& targetExt : targetExts) { if(targetExt == ext) { return true; } } return false; } }
ce2f1407ebcfc7bc25332a86256b5ca329f683da
d3f0dc80a3e43fe9a14f1ba0dc6f71d6ff611f68
/sample/sample.cpp
d256a424c0ee16b0db942b0bf64b6658d05140cf
[]
no_license
Maxim-Doronin/lists
d58e568c74595d0826ebfbceac146c2ca81696fe
f2627555671395eb30adb1bae296e2ebfaf7590f
refs/heads/master
2021-01-10T16:16:24.435808
2015-11-25T08:13:42
2015-11-25T08:13:42
45,968,421
0
0
null
2015-11-24T20:51:38
2015-11-11T08:12:21
C++
UTF-8
C++
false
false
449
cpp
sample.cpp
#include "list.h" int main() { List list(0); list.insertionEnd(2); list.insertionEnd(10); list.insertionEnd(-2); list.insertionEnd(3); list.insertionEnd(5); List *list1 = new List(0); list1->insertionEnd(-2); list1->insertionEnd(3); List *list2 = new List(0); list2->insertionEnd(4); list2->insertionEnd(0); list2->insertionEnd(1); list.print(); list1->print(); list2->print(); list.replaceList(list1, list2); list.print(); }
9e3ecb1f5c78c5a178b8fd5c414fdc436b6b18d9
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2464487_0/C++/alpc27/A.cpp
6816aac55fb87f7476186d127522af32569fb3e7
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
945
cpp
A.cpp
#include <stdio.h> #include <string.h> #include <math.h> #include <algorithm> using namespace std; long long MAX = 1000000001; long long r,t; bool ok(long long c) { if (t < (r * c * 2 + c * (c * 2 - 1))) return 0; return 1; } long long cal() { int i,j; long long k,a,b,c; if (r * 2 + 1 > t) return 0; k = t / (r * 2) + 2; b = min(k, MAX); a = 1; //printf("%I64d %I64d %I64d\n", k, a, b); while (a < b - 1) { c = (a + b) / 2; if (ok(c)) a = c; else b = c; } return a; } int main() { freopen("A-small-attempt0.in","r",stdin); freopen("output.txt","w",stdout); int i,j,k; int T; scanf("%d", &T); for (k = 1;k <= T;k++) { scanf("%I64d%I64d", &r,&t); printf("Case #%d: ", k); printf("%I64d\n", cal()); } return 0; }
1c9b94d10f106c987a69480e9fd679fc275341b4
2e08cd3c9c8260075af6116a3ed8acf4c3548b77
/MyTest/Opencv_Clock/Opencv_Clock/test.cpp
a69dc207827f9ec314266eedb7c9239e6da9e4fc
[]
no_license
Dutch-Man/Company
628626e9a80745898101e52c02163dbf6276b327
48ebd163b3edd93d560304ec53f349c3293a5f8f
refs/heads/master
2021-01-09T20:43:25.176229
2016-08-10T17:27:38
2016-08-10T17:27:38
63,476,728
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
test.cpp
#include <iostream> #include "opencv2/opencv.hpp" #include <stdio.h> using namespace std; using namespace cv; void salt(Mat &img,int n) { } int main() { cout << rand() << endl << rand() << endl<<rand() << endl; waitKey(0); return 0; }
57a995320b40bde69a77433dbd4e945493fdc230
b0fdd5347dc3b821a057f6f079247ac81a91a91f
/T3Engine/sprite/picturetext.cpp
e3f50557599eac629eebed65cc4cf29039aede7b
[]
no_license
qwertylevel3/TestEngine
c4cd7c7d6c75df7d67cf4d5de9ff98aefc2c807e
dea2c11b3f0690f8dd87e4544ed746aa38ff07c9
refs/heads/master
2021-01-14T12:30:09.425614
2016-05-30T08:06:29
2016-05-30T08:06:29
48,836,891
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
cpp
picturetext.cpp
#include "picturetext.h" PictureText::PictureText() { textColor=Qt::white; textAlignment=Qt::AlignLeft; textFont=QFont("Arial", 20); } void PictureText::writeToImage(QImage &image) { textRect=QRect(image.width()/12, image.height()/5, image.width()-image.width()/12, image.height()-image.height()/5); QPainter p; p.begin(&image); p.setPen(textColor); p.setFont(textFont); p.drawText(textRect,textAlignment,content); p.end(); } QColor PictureText::getTextColor() const { return textColor; } void PictureText::setTextColor(const QColor &value) { textColor = value; } QFont PictureText::getTextFont() const { return textFont; } void PictureText::setTextFont(const QFont &value) { textFont = value; } QRect PictureText::getTextRect() const { return textRect; } void PictureText::setTextRect(const QRect &value) { textRect = value; } Qt::Alignment PictureText::getTextAlignment() const { return textAlignment; } void PictureText::setTextAlignment(const Qt::Alignment &value) { textAlignment = value; } QString PictureText::getContent() const { return content; } void PictureText::setContent(const QString &value) { content = value; }
3c1493072d3a84c9c44eea76e3dc92330b13f27e
847eaede760d346f7e0d21aa9b96345298655916
/Arduino/lees/lees.ino
97f334fcdd8be50080b3e52e3718f4f7aa8b928b
[]
no_license
aisaraysmagul/3rd_course
1b49c1dc00bfc08b764dea4577769d5133a03768
00f3c17028fb31acee3a0e082b205c17e69bfda7
refs/heads/master
2020-05-24T03:26:13.138930
2019-05-16T17:34:00
2019-05-16T17:34:00
187,072,256
0
0
null
null
null
null
UTF-8
C++
false
false
415
ino
lees.ino
const int ledPin = 2; // choose the pin for the LED const int inputPin = 7; // choose the input pin (for a pushbutton) int state = 0; void setup() { pinMode(ledPin, OUTPUT); // declare LED as output pinMode(inputPin, INPUT); // declare pushbutton as input } void loop() { state = digitalRead(inputPin); if (state == HIGH){ digitalWrite(ledPin, HIGH); }else{ digitalWrite(ledPin, LOW); } }
da034afbc4ec46970457a0e2758889bd2837554b
2f7fc196c78b10fd341aa2c959aacaa75363a4b6
/common/log.h
5af252ed06fe28beb585a26ca449528f0054502f
[ "MIT" ]
permissive
raddinet/raddi
71db78e74e7aa19cd1175bc5d427426bfb261511
af48e49675d2a4a524ecc4c6fa49d3173458e1cd
refs/heads/master
2023-06-10T05:42:37.081451
2023-05-28T23:50:55
2023-05-28T23:50:55
134,083,847
46
3
null
null
null
null
UTF-8
C++
false
false
15,190
h
log.h
#ifndef RADDI_LOG_H #define RADDI_LOG_H #ifndef RC_INVOKED #include <winsock2.h> #include <ws2tcpip.h> #include <guiddef.h> #endif // TODO: rewrite: // - remove note..error levels (let call-site decide importance) // - add 'object' distinction (below component) for classes (or merge with MAIN,SERVER,SOURCE,...) // - remove named components, just use code #undef ERROR #define NOTE 0x0A000 #define EVENT 0x0C000 #define DATA 0x0D000 #define ERROR 0x0E000 #define STOP 0x0F000 #define MAIN 0x00100 #define SERVER 0x00200 #define SOURCE 0x00300 #define DATABASE 0x00400 // #define COORDINATOR 0x00500 #ifndef RC_INVOKED #include <type_traits> #include <stdexcept> #include <cstdarg> #include <string> namespace raddi { // component // - list of basic components of the software to simplify tracking of message IDs // enum class component : short { main = MAIN, server = SERVER, source = SOURCE, database = DATABASE, }; namespace log { // level // - importance of reported event // enum class level : int { all = 0, note = NOTE, // standard behavior notifications event = EVENT, // significant runtime events data = DATA, // malformed/invalid data processed error = ERROR, // recoverable (reducing functionality) runtime errors stop = STOP, // irrecoverable errors disabled = 0xFFFFF }; namespace settings { extern log::level level; extern log::level display; } // scope // - distinguish different log paths, services run in machine scope, apps in user scope // enum class scope { user = 0, // HKCU, current user machine = 1, // HKLM, local machine (container) }; // initialize/display // - parses string to determine log path and level // for log file (initialize) or console output (display) // bool initialize (const wchar_t *, const wchar_t * subdir, const wchar_t * prefix, scope); void display (const wchar_t *); // get_scope_path // - abstracts platform // - 'buffer' must point to at least MAX_PATH (260) characters long buffer // bool get_scope_path (scope, wchar_t * buffer); // parse_level // - parses 'string' for known log level, writes it into 'level', if not null // - returns true for recognized string, false otherwise ('level' is unchanged) // bool parse_level (const wchar_t * string, raddi::log::level * level); // path // - whenever 'initialize' succeeds then 'path' contains full path to the log file // extern std::wstring path; // api_error // - adds type information to GetLastError // - TODO: use std::error_category etc? // struct api_error { unsigned long code; public: api_error (); // code (GetLastError ()) api_error (unsigned long code) : code (code) {}; }; // rsrc_string // - // struct rsrc_string { unsigned long code; public: rsrc_string (unsigned long code) : code (code) {}; }; // translate // - converts log function argument to string, according to second 'format' parameter // - provide overload to extend functionality // - TODO: since we now use ADL figure out better name that won't be confusing in global namespace // - TODO: use std::wstring_view where possible // inline std::wstring translate (long long argument, const std::wstring & format) { return std::to_wstring (argument); } inline std::wstring translate (unsigned long long argument, const std::wstring & format, int hexwidth = 16) { wchar_t buffer [64]; if (format == L"x") std::swprintf (buffer, sizeof buffer / sizeof buffer [0], L"%0*llx", hexwidth, argument); else if (format == L"X") std::swprintf (buffer, sizeof buffer / sizeof buffer [0], L"%0*llX", hexwidth, argument); else std::swprintf (buffer, sizeof buffer / sizeof buffer [0], L"%llu", argument); return buffer; } inline std::wstring translate (long argument, const std::wstring & format) { return translate ((long long) argument, format); } inline std::wstring translate (unsigned long argument, const std::wstring & format) { return translate ((unsigned long long) argument, format, 8); } inline std::wstring translate (int argument, const std::wstring & format) { return translate ((long long) argument, format); } inline std::wstring translate (unsigned int argument, const std::wstring & format) { return translate ((unsigned long long) argument, format, 8); } inline std::wstring translate (const std::wstring & argument, const std::wstring &) { return argument; } inline std::wstring translate (const wchar_t * argument, const std::wstring &) { return argument ? argument : L"<null>"; } inline std::wstring translate (std::nullptr_t argument, const std::wstring &) { return L""; } inline std::wstring translate (bool argument, const std::wstring &) { return argument ? L"true" : L"false"; } std::wstring translate (api_error, const std::wstring &); std::wstring translate (rsrc_string, const std::wstring &); std::wstring translate (const in_addr *, const std::wstring &); std::wstring translate (const in6_addr *, const std::wstring &); std::wstring translate (const sockaddr *, const std::wstring &); inline std::wstring translate (const in_addr & address, const std::wstring & format) { return translate (&address, format); } inline std::wstring translate (const in6_addr & address, const std::wstring & format) { return translate (&address, format); } inline std::wstring translate (const sockaddr & address, const std::wstring & format) { return translate (&address, format); } #ifdef _WIN32 // TODO: create custom 'tm' structure with milliseconds std::wstring translate (const std::tm &, const std::wstring &); std::wstring translate (const GUID &, const std::wstring &); std::wstring translate (const FILETIME &, const std::wstring &); std::wstring translate (const SYSTEMTIME &, const std::wstring &); std::wstring translate (const SOCKADDR_INET &, const std::wstring &); #endif std::wstring translate (const void * argument, const std::wstring &); std::wstring translate (const char * argument, const std::wstring &); std::wstring translate (const std::string & argument, const std::wstring &); // internal // - implementation details // namespace internal { struct provider_name { std::wstring instance; // TODO: use something with less overhead? const char * object = nullptr; }; bool evaluate_level (level l); std::wstring load_string (component c, level l, unsigned int id); void deliver (component c, level, const provider_name *, unsigned int, std::wstring); inline void capture_overriden_api_error (api_error &) {} template <typename... Args> void capture_overriden_api_error (api_error & e, api_error ee, Args ...remaining) { e = ee; capture_overriden_api_error (e, remaining...); } template <typename T, typename... Args> void capture_overriden_api_error (api_error & e, T, Args ...remaining) { capture_overriden_api_error (e, remaining...); } template <typename T> void replace_argument (std::wstring & string, std::wstring prefix, T argument, bool escape = true) { std::wstring::size_type offset = 0u; while ((offset = string.find (L"{" + prefix, offset)) != std::wstring::npos) { auto fo = prefix.size () + offset + 1; auto fe = string.find (L'}', fo); if (fe == std::wstring::npos) break; if (std::is_same <std::nullptr_t, T>::value) { string.replace (offset, fe + 1 - offset, std::wstring ()); } else { auto translated = translate (argument, fo != fe ? string.substr (fo + 1, fe - fo - 1) : std::wstring ()); if (escape) { translated = L"\x201C" + translated + L"\x201D"; } string.replace (offset, fe + 1 - offset, translated); offset += translated.size (); } } } inline void replace_arguments (std::wstring &, std::size_t) {} template <typename T, typename... Args> void replace_arguments (std::wstring & string, std::size_t total, T argument, Args ...remaining) { replace_arguments (string, total, remaining...); replace_argument (string, std::to_wstring (total - sizeof... (remaining)), argument); } } // provider // - virtually inheritable class to prerecord identity information for logging purposes // - allows errors to be reported as: return this->report (log::level::error, 123, ...); // - "\x0018" marks moved-from instance whose destruction is not reported // template <component c> class provider { public: // identity // - provides object an human-readable identity for (mainly) logging purposes // internal::provider_name identity; public: template <std::size_t N> provider (const char (&object) [N], const std::wstring & instance = std::wstring ()) : identity { instance, instance != L"\x0018" ? object : nullptr } { if (this->identity.instance != L"\x0018") { this->report (level::note, 0xA1F1); } } provider () { this->report (level::note, 0xA1F1); } provider (provider && from) noexcept { this->identity.object = from.identity.object; this->identity.instance = std::move (from.identity.instance); from.identity.instance.assign (1, L'\x0018'); } /*provider & operator = (provider && from) { this->internal::provider_name::operator = (from); from.instance = L"\x0018"; return *this; }*/ ~provider () { if (this->identity.instance != L"\x0018") { this->report (level::note, 0xA1F2); } } template <typename... Args> bool report (level l, unsigned int id, Args... args) const; }; // report // - primary reporting // - argument {ERR} is always API error (GetLastError ()), last by default, // but can be overriden by passing instance of api_error // - always returns false so it can be used within negative return statement // template <typename... Args> bool report (component c, level ll, const internal::provider_name * p, unsigned int id, Args... args) { if (internal::evaluate_level (ll)) { api_error error; std::wstring string = internal::load_string (c, ll, id); internal::capture_overriden_api_error (error, args...); internal::replace_arguments (string, sizeof... (args), args...); internal::replace_argument (string, L"ERR", error, false); internal::deliver (c, ll, p, id, std::move (string)); } // always return false! return false; } template <typename... Args> bool report (component c, level l, unsigned int id, Args... args) { return report (c, l, nullptr, id, args...); } template <component c> template <typename... Args> bool provider <c> ::report (level l, unsigned int id, Args... args) const { return raddi::log::report (c, l, &this->identity, id, args...); } // exception // - // class exception : public std::exception { public: template <typename... Args> exception (component c, unsigned int id, Args... args) { raddi::log::report (c, raddi::log::level::error, id, args...); } }; // note/event/data/error/stop // - shortcuts to 'report' particular condition // template <typename... Args> bool note (component c, unsigned int id, Args... args) { return report (c, raddi::log::level::note, id, args...); } template <typename... Args> bool event (component c, unsigned int id, Args... args) { return report (c, raddi::log::level::event, id, args...); } template <typename... Args> bool data (component c, unsigned int id, Args... args) { return report (c, raddi::log::level::data, id, args...); } template <typename... Args> bool error (component c, unsigned int id, Args... args) { return report (c, raddi::log::level::error, id, args...); } template <typename... Args> bool stop (component c, unsigned int id, Args... args) { return report (c, raddi::log::level::stop, id, args...); } template <typename... Args> bool note (unsigned int id, Args... args) { return report (raddi::component::main, raddi::log::level::note, id, args...); } template <typename... Args> bool event (unsigned int id, Args... args) { return report (raddi::component::main, raddi::log::level::event, id, args...); } template <typename... Args> bool data (unsigned int id, Args... args) { return report (raddi::component::main, raddi::log::level::data, id, args...); } template <typename... Args> bool error (unsigned int id, Args... args) { return report (raddi::component::main, raddi::log::level::error, id, args...); } template <typename... Args> bool stop (unsigned int id, Args... args) { return report (raddi::component::main, raddi::log::level::stop, id, args...); } } } #undef NOTE #undef EVENT #undef DATA #undef ERROR #undef STOP #undef MAIN #undef SERVER #undef SOURCE #undef DATABASE #endif #endif
7ed63ae9b68bf904c3316ad1489e6902cdef4de4
033b3613935215952868301eaf7ac283b4e49394
/Implementation/FileAccess.cpp
8c49cdb114e529b5b1a6b25ec7196c484486bde8
[]
no_license
ebunge1/Assembler
4ba33840bdc6fd1a468301971d9e13936d8c57fc
46cb18577e495d4b77fe542be84dfb30e84113ca
refs/heads/master
2021-01-20T14:52:59.339336
2017-05-09T00:11:01
2017-05-09T00:11:01
90,683,272
0
0
null
null
null
null
UTF-8
C++
false
false
1,984
cpp
FileAccess.cpp
// // Implementation of file access class. // #include "stdafx.h" #include "FileAccess.h" /* FileAccess::FileAccess() NAME FileAccess - constructor, opens file SYNOPSIS FileAccess::FileAccess() DESCRIPTION Gets the file name from the arguement line. Opens the file for reading RETURNS none */ FileAccess::FileAccess(int argc, char *argv[]) { // Check that there is exactly one run time parameter. if (argc != 2) { cerr << "Usage: Assem <FileName>" << endl; exit(1); } // Open the file. One might question if this is the best place to open the file. // One might also question whether we need a file access class. m_sfile.open(argv[1], ios::in); // If the open failed, report the error and terminate. if (!m_sfile) { cerr << "Source file could not be opened, assembler terminated." << endl; exit(1); } } /* FileAccess::~FileAccess() NAME ~FileAccess - destructor, closes file SYNOPSIS FileAccess::~FileAccess() DESCRIPTION closes file RETURNS none */ FileAccess::~FileAccess() { m_sfile.close(); } /* FileAccess::GetNextLine() NAME GetNextLine- reads line from file SYNOPSIS FileAccess::GetNextLine(string &a_buff) a_buff --> variable to read line into DESCRIPTION reads line into the buffer. returns status of the read. RETURNS bool - whether the read was successful */ bool FileAccess::GetNextLine(string &a_buff) { if (m_sfile.eof()) return false; getline(m_sfile, a_buff); // Return indicating success. return true; } /* FileAccess::rewind() NAME rewind - returns to begining of file SYNOPSIS FileAccess::rewind() DESCRIPTION clears eof flag and returns to begining of file RETURNS void */ void FileAccess::rewind() { // Clean the end of file flag and go back to the beginning of the file. m_sfile.clear(); m_sfile.seekg(0, ios::beg); }
a3fc684d561f811959e89bd11b44a26decf2796b
075d6888ff126d14aea6834a605984292b45a17e
/phone_cells_provider/user.cpp
8ab88e7ae1722382f7b3266eec8292f791f4306a
[]
no_license
Jabolo/TelephoneProviderSystem
ca35181d7a2a286f5bec3d38eab772d353906305
e93c20715a34a7e93050a0db4593a3bc1b0ca8af
refs/heads/master
2020-04-19T00:32:34.134573
2019-01-28T17:55:37
2019-01-28T17:55:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
cpp
user.cpp
#include "pch.h" #include "user.h" user::user(int num, string name, string psw, int prv) : cellNumber(num), userName(name), privileges(prv) { stringstream hashedPsswrd, fin; string xxx; hashedPsswrd << hex << transaction::hash(psw); xxx = hashedPsswrd.str(); this->psswrd = xxx; } void user::setIdUser(int x) { this->idUser = x; } void user::setCellNumber(int x) { this->cellNumber = x; } void user::setUserName(string x) { this->userName = x; } void user::setPsswrd(string x) { this->psswrd = x; } void user::setPrivileges(int x) { this->privileges = x; } int user::getIdUser() const { return idUser; } int user::getCellNumber() const { return cellNumber; } string user::getUserName() const { return userName; } string user::getPsswrd() const { return psswrd; } int user::getPrivileges() const { return privileges; } user::~user() { } ostream & operator<<(ostream &out, const user &y) { return out<< y.getUserName() << ".Your cell num: " << y.getCellNumber() << endl; }
c68874396b4897356d32ab844474a5b12842a837
7efb9e8596ddf7d67bcca8459d0647cd82399565
/Laby/ListaPracownikow.h
9747867a147944a9f278a255331ee1d91cdc53bf
[]
no_license
DarkRaven255/LabCpp
399f69adaf476bf8b5a7aad8e71152d0c089b3ef
9456e594b2b6c4c321ca05c9ea079476acd16740
refs/heads/master
2020-04-18T18:25:56.733334
2019-01-28T01:29:44
2019-01-28T01:29:44
167,683,174
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
ListaPracownikow.h
#pragma once #include "Pracownik.h" class ListaPracownikow { public: ListaPracownikow(); ~ListaPracownikow(); void Dodaj(const Pracownik& p); void Usun(const Pracownik& wzorzec); void WypiszPracownikow() const; const Pracownik* Szukaj(const char* nazwisko, const char* imie) const; void ZapiszDoPliku(); void WczytajZPliku(); void ZapiszDoPlikuM(); void WczytajZPlikuM(); private: Pracownik* m_pPoczatek; int m_nLiczbaPracownikow; };
9771681bf283256253905f39789e5ffe89592db2
b4ba3bc2725c8ff84cd80803c8b53afbe5e95e07
/Medusa/MedusaExtension/CocosStudio/Reader/ReaderFactory.h
1c31216b0056c1cced7eea2020269e960f6d4a72
[ "MIT" ]
permissive
xueliuxing28/Medusa
c4be1ed32c2914ff58bf02593f41cf16e42cc293
15b0a59d7ecc5ba839d66461f62d10d6dbafef7b
refs/heads/master
2021-06-06T08:27:41.655517
2016-10-08T09:49:54
2016-10-08T09:49:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
999
h
ReaderFactory.h
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #pragma once #include "MedusaExtensionPreDeclares.h" #include "CocosStudio/CocosDefines.h" //[PRE_DECLARE_NAMESPCAE] Cocos #include "Core/Pattern/Singleton.h" #include "Core/Pattern/Object/StaticObjectFactory.h" #include "INodeReader.h" MEDUSA_COCOS_BEGIN; class ReaderFactory :public Singleton < ReaderFactory >, public StaticObjectFactory < StringRef, INodeReader*() > { friend class Singleton < ReaderFactory > ; ReaderFactory(); ~ReaderFactory(void) {} public: using StaticObjectFactory<StringRef, INodeReader*()>::Register; using StaticObjectFactory<StringRef, INodeReader*()>::Create; template < typename T > void Register() { Register<T>(T::ClassStatic().Name()); } template < typename T > T* Create() { return (T*)Create(T::ClassStatic().Name()); } INodeReader* AssertCreate(StringRef name); }; MEDUSA_COCOS_END;
4f46a5baf01e1143d702eccdcc6c9b30d06918b9
e5541f3eb965a9e732b8587d98345acbeb3afcc9
/6-Pointers/3-Demos/2_creating_deleting_dynamic_objects.cpp
a748c5678a50b423cc9042caee85d0fb92040d84
[]
no_license
neerajkumarsj/Cpp-Satya
5951ee56f2e9d20ce7ae464d090f2fa03c725cd2
a5c36ea1d198d09c1ef5af32974781ebd1133ea9
refs/heads/main
2023-08-26T09:41:52.796254
2021-11-11T02:36:25
2021-11-11T02:36:25
410,327,981
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
2_creating_deleting_dynamic_objects.cpp
/* 1. Dynamic C - malloc, calloc, realloc, free run-time Heap segment 2. C++ - new and delete are operators - Runtime - Heap */ #include <iostream> using namespace std; class Sample { private: int a; int b; public: Sample() { cout << "Constructing an object\n"; a = 10; b = 20; } }; int main() { //Sample A; //Static mem alloc. Sample *ptr = new Sample; delete ptr; ptr = NULL; }
a550105b63dd9f29a07fdaf2dd9da02d8ffdfe9b
962413f97e3c7b8301d64d86a3570bd073b720ed
/src/Menu.cpp
f81acf01509ead6122c6dc18853e92300606f22b
[]
no_license
Bazard/HeroKart
33e674daa6243b8225f036f44e3b36094ad94d49
f03ae290cf1fad32463b52054015fec994a20fb0
refs/heads/master
2021-01-20T06:17:15.222285
2014-01-10T16:03:54
2014-01-10T16:03:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
51,216
cpp
Menu.cpp
#include <iostream> #include <cstdlib> #include <cmath> #include "VBO.hpp" #include "VAO.hpp" #include <vector> #include <ctime> #include <cstring> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Program.hpp" #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #include <GL/glew.h> #include "Menu.h" static const Uint32 FPS = 30; static const Uint32 FRAME_DURATION = 1000.f / FPS; static const Uint32 WINDOW_BPP = 32; Mix_Music *musique; using namespace glimac; int redirection(std::vector<Character*>& character,std::vector<Track*>& track){ int sortie=menuPrincipal(character, track); while(sortie!=-1 && sortie!=5){ if (sortie==0){ sortie=menuPrincipal(character,track); } else if (sortie==1){ sortie=menuPersonnage(character,track); } else if(sortie==2){ sortie=lancerJeuRandom(character,track); } else if(sortie==3){ sortie=menuOptions(); } else if(sortie==4){ sortie=menuCircuit(character,track); } } if (sortie==5){ menuChargement(); } return sortie; } int redirectionPause(){ int sortie=1; while(sortie!=2 && sortie!=-1){ sortie=menuPause(); if(sortie==1){ sortie=menuOptions(); } } } void menuChargement(){ VBO vbo; vbo.bind(GL_ARRAY_BUFFER); Vertex2DUV vertices[] = { Vertex2DUV(-1, -1, 0.0, 1.0), Vertex2DUV(-1, 1, 0.0, 0.0), Vertex2DUV(1, 1, 1.0, 0.0), Vertex2DUV(1, -1, 1.0, 1.0), }; //on remplit les donnees du bateau glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //on remet le bateau à la mer vbo.debind(GL_ARRAY_BUFFER); //Création du VAO VAO vao; //on binde le vao vao.bind(); //on attribue une position 2D qui aura pour id 0 glEnableVertexAttribArray(0); //on attribue une texture qui aura pour id 1 glEnableVertexAttribArray(1); //on remet le bateau au port vbo.bind(GL_ARRAY_BUFFER); //on définit les paramètres des attributs (position 2D) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, x))); //on définit les paramètres des attributs (textures) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, u))); //on débinde le VBO vbo.debind(GL_ARRAY_BUFFER); //on débinde le VAO vao.debind(); Program prog; prog= loadProgram("../shaders/tex2D.vs.glsl", "../shaders/tex2D.fs.glsl"); prog.use(); GLint locVarTexture; locVarTexture= glGetUniformLocation(prog.getGLId(), "uTexture"); //On loade l'image int img_width=0, img_height=0; unsigned char* img; switch (WINDOW_WIDTH){ case 1024: img=SOIL_load_image("../textures/chargement1024.jpg", &img_width, &img_height, NULL, 0); break; case 800: img=SOIL_load_image("../textures/chargement800.jpg", &img_width, &img_height, NULL, 0); break; case 600: img=SOIL_load_image("../textures/chargement600.jpg", &img_width, &img_height, NULL, 0); break; default: break; } //On créé la texture GLuint idMenu; glGenTextures(1, &idMenu); glBindTexture(GL_TEXTURE_2D, idMenu); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); /* Rendering code goes here */ //on nettoie la fenêtre glClear(GL_COLOR_BUFFER_BIT); //on rebinde le vao vao.bind(); glUniform1i(locVarTexture,0); //Premier triangle glBindTexture(GL_TEXTURE_2D,idMenu); glUniform1i(locVarTexture,0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindTexture(GL_TEXTURE_2D,0); //on débinde le vao vao.debind(); // Mise à jour de la fenêtre (synchronisation implicite avec OpenGL) SDL_GL_SwapBuffers(); glDeleteTextures(1,&idMenu); } int menuPause(){ int sortie=-1; VBO vbo; vbo.bind(GL_ARRAY_BUFFER); Vertex2DUV vertices[] = { Vertex2DUV(-1, -1, 0.0, 1.0), Vertex2DUV(-1, 1, 0.0, 0.0), Vertex2DUV(1, 1, 1.0, 0.0), Vertex2DUV(1, -1, 1.0, 1.0), }; //on remplit les donnees du bateau glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //on remet le bateau à la mer vbo.debind(GL_ARRAY_BUFFER); //Création du VAO VAO vao; //on binde le vao vao.bind(); //on attribue une position 2D qui aura pour id 0 glEnableVertexAttribArray(0); //on attribue une texture qui aura pour id 1 glEnableVertexAttribArray(1); //on remet le bateau au port vbo.bind(GL_ARRAY_BUFFER); //on définit les paramètres des attributs (position 2D) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, x))); //on définit les paramètres des attributs (textures) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, u))); //on débinde le VBO vbo.debind(GL_ARRAY_BUFFER); //on débinde le VAO vao.debind(); Program prog; prog= loadProgram("../shaders/tex2D.vs.glsl", "../shaders/tex2D.fs.glsl"); prog.use(); GLint locVarTexture; locVarTexture= glGetUniformLocation(prog.getGLId(), "uTexture"); //On loade l'image int img_width=0, img_height=0; unsigned char* img; switch (WINDOW_WIDTH){ case 1024: img=SOIL_load_image("../textures/menuCircuit1024.jpg", &img_width, &img_height, NULL, 0); break; case 800: img=SOIL_load_image("../textures/menuCircuit800.jpg", &img_width, &img_height, NULL, 0); break; case 600: img=SOIL_load_image("../textures/menuCircuit600.jpg", &img_width, &img_height, NULL, 0); break; default: break; } //On créé la texture GLuint idMenu; glGenTextures(1, &idMenu); glBindTexture(GL_TEXTURE_2D, idMenu); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); bool done = false; while (!done) { Uint32 tStart = SDL_GetTicks(); /* Rendering code goes here */ //on nettoie la fenêtre glClear(GL_COLOR_BUFFER_BIT); //on rebinde le vao vao.bind(); glUniform1i(locVarTexture,0); //Premier triangle glBindTexture(GL_TEXTURE_2D,idMenu); glUniform1i(locVarTexture,0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindTexture(GL_TEXTURE_2D,0); //on débinde le vao vao.debind(); // Application code goes here SDL_Event e; int xClicked, yClicked; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_MOUSEBUTTONDOWN: if (e.button.button==SDL_BUTTON_LEFT){ xClicked=(float)(e.button.x); yClicked=(float)(e.button.y); if (xClicked>=(278.0/800.0)*WINDOW_WIDTH && xClicked <=(533.0/800.0)*WINDOW_WIDTH && yClicked>=(265.0/600.0)*WINDOW_HEIGHT && yClicked<=(286.0/600.0)*WINDOW_HEIGHT){ std::cout << "Reprise du jeu" << std::endl; sortie=6; done=true; } else if (xClicked>=(346.0/800.0)*WINDOW_WIDTH && xClicked <=(468.0/800.0)*WINDOW_WIDTH && yClicked>=(322.0/600.0)*WINDOW_HEIGHT && yClicked<=(342.0/600.0)*WINDOW_HEIGHT){ std::cout << "Options" << std::endl; sortie=7; done=true; } else if (xClicked>=(347.0/800.0)*WINDOW_WIDTH && xClicked <=(462.0/800.0)*WINDOW_WIDTH && yClicked>=(397.0/600.0)*WINDOW_HEIGHT && yClicked<=(416.0/600.0)*WINDOW_HEIGHT){ std::cout << "Quitter" << std::endl; exit(0); } } break; case SDL_QUIT: done = true; break; default: break; } } // Mise à jour de la fenêtre (synchronisation implicite avec OpenGL) SDL_GL_SwapBuffers(); Uint32 tEnd = SDL_GetTicks(); Uint32 d = tEnd - tStart; if (d < FRAME_DURATION) { SDL_Delay(FRAME_DURATION - d); } } glDeleteTextures(1,&idMenu); return sortie; } int menuCircuit(std::vector<Character*>& character,std::vector<Track*>& track){ int sortie=-1; VBO vbo; vbo.bind(GL_ARRAY_BUFFER); Vertex2DUV vertices[] = { Vertex2DUV(-1, -1, 0.0, 1.0), Vertex2DUV(-1, 1, 0.0, 0.0), Vertex2DUV(1, 1, 1.0, 0.0), Vertex2DUV(1, -1, 1.0, 1.0), }; //on remplit les donnees du bateau glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //on remet le bateau à la mer vbo.debind(GL_ARRAY_BUFFER); //Création du VAO VAO vao; //on binde le vao vao.bind(); //on attribue une position 2D qui aura pour id 0 glEnableVertexAttribArray(0); //on attribue une texture qui aura pour id 1 glEnableVertexAttribArray(1); //on remet le bateau au port vbo.bind(GL_ARRAY_BUFFER); //on définit les paramètres des attributs (position 2D) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, x))); //on définit les paramètres des attributs (textures) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, u))); //on débinde le VBO vbo.debind(GL_ARRAY_BUFFER); //on débinde le VAO vao.debind(); Program prog; prog= loadProgram("../shaders/tex2D.vs.glsl", "../shaders/tex2D.fs.glsl"); prog.use(); GLint locVarTexture; locVarTexture= glGetUniformLocation(prog.getGLId(), "uTexture"); //On loade l'image int img_width=0, img_height=0; unsigned char* img; switch (WINDOW_WIDTH){ case 1024: img=SOIL_load_image("../textures/menuCircuit1024.jpg", &img_width, &img_height, NULL, 0); break; case 800: img=SOIL_load_image("../textures/menuCircuit800.jpg", &img_width, &img_height, NULL, 0); break; case 600: img=SOIL_load_image("../textures/menuCircuit600.jpg", &img_width, &img_height, NULL, 0); break; default: break; } //On créé la texture GLuint idMenu; glGenTextures(1, &idMenu); glBindTexture(GL_TEXTURE_2D, idMenu); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); Track* circuit1=new Track("../maps/Village.map",3); // circuit1->insertElt(); Track* circuit2=new Track("../maps/Montreal.map",3); Track* circuit3=new Track("../maps/Village.map",3); bool done = false; while (!done) { Uint32 tStart = SDL_GetTicks(); /* Rendering code goes here */ //on nettoie la fenêtre glClear(GL_COLOR_BUFFER_BIT); //on rebinde le vao vao.bind(); glUniform1i(locVarTexture,0); //Premier triangle glBindTexture(GL_TEXTURE_2D,idMenu); glUniform1i(locVarTexture,0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindTexture(GL_TEXTURE_2D,0); //on débinde le vao vao.debind(); // Application code goes here SDL_Event e; int xClicked, yClicked; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_MOUSEBUTTONDOWN: if (e.button.button==SDL_BUTTON_LEFT){ xClicked=(float)(e.button.x); yClicked=(float)(e.button.y); if (xClicked>=(88.0/800.0)*WINDOW_WIDTH && xClicked <=(277.0/800.0)*WINDOW_WIDTH && yClicked>=(226.0/600.0)*WINDOW_HEIGHT && yClicked<=(416.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi le circuit 1" << std::endl; track.push_back(circuit1); track.push_back(circuit2); track.push_back(circuit3); sortie=5; done=true; } else if (xClicked>=(298.0/800.0)*WINDOW_WIDTH && xClicked <=(492.0/800.0)*WINDOW_WIDTH && yClicked>=(226.0/600.0)*WINDOW_HEIGHT && yClicked<=(416.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi le circuit 2" << std::endl; track.push_back(circuit2); track.push_back(circuit1); track.push_back(circuit3); sortie=5; done=true; } else if (xClicked>=(512.0/800.0)*WINDOW_WIDTH && xClicked <=(705.0/800.0)*WINDOW_WIDTH && yClicked>=(226.0/600.0)*WINDOW_HEIGHT && yClicked<=(416.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi le circuit 3" << std::endl; track.push_back(circuit3); track.push_back(circuit2); track.push_back(circuit1); sortie=5; done=true; } else if (xClicked>=(68.0/800.0)*WINDOW_WIDTH && xClicked<=(148.0/800.0)*WINDOW_WIDTH && yClicked>=(38.0/600.0)*WINDOW_HEIGHT && yClicked<=(88.0/600.0)*WINDOW_HEIGHT){ for (std::vector<Track*>::iterator it = track.begin() ; it != track.end(); ++it) delete(*it); track.clear(); for (std::vector<Character*>::iterator it = character.begin() ; it != character.end(); ++it) delete(*it); character.clear(); sortie=1; done=true; } } break; case SDL_QUIT: done = true; break; default: break; } } // Mise à jour de la fenêtre (synchronisation implicite avec OpenGL) SDL_GL_SwapBuffers(); Uint32 tEnd = SDL_GetTicks(); Uint32 d = tEnd - tStart; if (d < FRAME_DURATION) { SDL_Delay(FRAME_DURATION - d); } } glDeleteTextures(1,&idMenu); return sortie; } int menuPersonnage(std::vector<Character*>& character, std::vector<Track*>& track){ std::vector<int> konami; int sortie=-1; VBO vbo; vbo.bind(GL_ARRAY_BUFFER); Vertex2DUV vertices[] = { Vertex2DUV(-1, -1, 0.0, 1.0), Vertex2DUV(-1, 1, 0.0, 0.0), Vertex2DUV(1, 1, 1.0, 0.0), Vertex2DUV(1, -1, 1.0, 1.0), }; //on remplit les donnees du bateau glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //on remet le bateau à la mer vbo.debind(GL_ARRAY_BUFFER); //Création du VAO VAO vao; //on binde le vao vao.bind(); //on attribue une position 2D qui aura pour id 0 glEnableVertexAttribArray(0); //on attribue une texture qui aura pour id 1 glEnableVertexAttribArray(1); //on remet le bateau au port vbo.bind(GL_ARRAY_BUFFER); //on définit les paramètres des attributs (position 2D) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, x))); //on définit les paramètres des attributs (textures) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, u))); //on débinde le VBO vbo.debind(GL_ARRAY_BUFFER); //on débinde le VAO vao.debind(); Program prog; prog= loadProgram("../shaders/tex2D.vs.glsl", "../shaders/tex2D.fs.glsl"); prog.use(); GLint locVarTexture; locVarTexture= glGetUniformLocation(prog.getGLId(), "uTexture"); //On loade l'image int img_width=0, img_height=0; unsigned char* img; switch (WINDOW_WIDTH){ case 1024: img=SOIL_load_image("../textures/menuPersonnage1024.jpg", &img_width, &img_height, NULL, 0); break; case 800: img=SOIL_load_image("../textures/menuPersonnage800.jpg", &img_width, &img_height, NULL, 0); break; case 600: img=SOIL_load_image("../textures/menuPersonnage600.jpg", &img_width, &img_height, NULL, 0); break; default: break; } //On créé la texture GLuint idMenu; glGenTextures(1, &idMenu); glBindTexture(GL_TEXTURE_2D, idMenu); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); bool done = false; while (!done) { Uint32 tStart = SDL_GetTicks(); /* Rendering code goes here */ //on nettoie la fenêtre glClear(GL_COLOR_BUFFER_BIT); //on rebinde le vao vao.bind(); glUniform1i(locVarTexture,0); //Premier triangle glBindTexture(GL_TEXTURE_2D,idMenu); glUniform1i(locVarTexture,0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindTexture(GL_TEXTURE_2D,0); //on débinde le vao vao.debind(); // Application code goes here Character *john=new Character(JOHN,10000, "John"); Character *klaus=new Character(KLAUS,10000, "Klaus"); Character *doug=new Character(DOUG,10000, "Doug"); Character *stan=new Character(STAN,10000, "Stan"); Character *steve=new Character(STEVE,10000, "Steve"); Character *burt=new Character(BURT,10000, "Burt"); Character *mckormack=new Character(MCKORMACK,10000, "McKormack"); Character *jennifer=new Character(JENNIFER,10000, "Jennifer"); Character *canada=new Character(CANADA,10000, "Captain Canada"); SDL_Event e; int xClicked, yClicked; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_MOUSEBUTTONDOWN: if (e.button.button==SDL_BUTTON_LEFT){ xClicked=(float)(e.button.x); yClicked=(float)(e.button.y); if (xClicked>=(64.0/800.0)*WINDOW_WIDTH && xClicked <=(221.0/800.0)*WINDOW_WIDTH && yClicked>=(126.0/600.0)*WINDOW_HEIGHT && yClicked<=(340.0/600.0)*WINDOW_HEIGHT){ sortie=4; std::cout << "Vous avez choisi John, bon choix" << std::endl; character.push_back(john); character.push_back(klaus); character.push_back(doug); character.push_back(stan); character.push_back(burt); character.push_back(steve); character.push_back(mckormack); character.push_back(jennifer); done=true; } else if (xClicked>=(234.0/800.0)*WINDOW_WIDTH && xClicked <=(391.0/800.0)*WINDOW_WIDTH && yClicked>=(126.0/600.0)*WINDOW_HEIGHT && yClicked<=(340.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi Klaus, bon choix" << std::endl; sortie=4; character.push_back(klaus); character.push_back(john); character.push_back(doug); character.push_back(stan); character.push_back(burt); character.push_back(steve); character.push_back(mckormack); character.push_back(jennifer); done=true; } else if (xClicked>=(403.0/800.0)*WINDOW_WIDTH && xClicked <=(559.0/800.0)*WINDOW_WIDTH && yClicked>=(126.0/600.0)*WINDOW_HEIGHT && yClicked<=(340.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi Doug, bon choix" << std::endl; sortie=4; character.push_back(doug); character.push_back(john); character.push_back(klaus); character.push_back(stan); character.push_back(burt); character.push_back(steve); character.push_back(mckormack); character.push_back(jennifer); done=true; } else if (xClicked>=(572.0/800.0)*WINDOW_WIDTH && xClicked <=(728.0/800.0)*WINDOW_WIDTH && yClicked>=(126.0/600.0)*WINDOW_HEIGHT && yClicked<=(340.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi Stan, bon choix" << std::endl; sortie=4; character.push_back(stan); character.push_back(john); character.push_back(klaus); character.push_back(doug); character.push_back(burt); character.push_back(steve); character.push_back(mckormack); character.push_back(jennifer); done=true; } else if (xClicked>=(64.0/800.0)*WINDOW_WIDTH && xClicked <=(221.0/800.0)*WINDOW_WIDTH && yClicked>=(346.0/600.0)*WINDOW_HEIGHT && yClicked<=(558.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi Steve, bon choix" << std::endl; sortie=4; character.push_back(steve); character.push_back(john); character.push_back(klaus); character.push_back(doug); character.push_back(stan); character.push_back(burt); character.push_back(mckormack); character.push_back(jennifer); done=true; } else if (xClicked>=(234.0/800.0)*WINDOW_WIDTH && xClicked <=(391.0/800.0)*WINDOW_WIDTH && yClicked>=(346.0/600.0)*WINDOW_HEIGHT && yClicked<=(558.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi Burt, bon choix" << std::endl; sortie=4; character.push_back(burt); character.push_back(john); character.push_back(klaus); character.push_back(doug); character.push_back(stan); character.push_back(steve); character.push_back(mckormack); character.push_back(jennifer); done=true; } else if (xClicked>=(403.0/800.0)*WINDOW_WIDTH && xClicked <=(559.0/800.0)*WINDOW_WIDTH && yClicked>=(346.0/600.0)*WINDOW_HEIGHT && yClicked<=(558.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi McKormack, bon choix" << std::endl; sortie=4; character.push_back(mckormack); character.push_back(john); character.push_back(klaus); character.push_back(doug); character.push_back(stan); character.push_back(burt); character.push_back(steve); character.push_back(jennifer); done=true; } else if (xClicked>=(572.0/800.0)*WINDOW_WIDTH && xClicked <=(728.0/800.0)*WINDOW_WIDTH && yClicked>=(346.0/600.0)*WINDOW_HEIGHT && yClicked<=(558.0/600.0)*WINDOW_HEIGHT){ std::cout << "Vous avez choisi Jennifer, vous êtes pas dans la merde !" << std::endl; sortie=4; character.push_back(jennifer); character.push_back(john); character.push_back(klaus); character.push_back(doug); character.push_back(stan); character.push_back(burt); character.push_back(steve); character.push_back(mckormack); done=true; } if (xClicked>=(68.0/800.0)*WINDOW_WIDTH && xClicked <=(148.0/800.0)*WINDOW_WIDTH && yClicked>=(38.0/600.0)*WINDOW_HEIGHT && yClicked<=(88.0/600.0)*WINDOW_HEIGHT){ sortie=0; done = true; } } break; case SDL_KEYDOWN: if(konami.size()>=10) break; konami.push_back(e.key.keysym.sym); switch(konami.size()){ case 1: if(konami[konami.size()-1]!=273) konami.clear(); break; case 2: if(konami[konami.size()-1]!=273) konami.clear(); break; case 3: if(konami[konami.size()-1]!=274) konami.clear(); break; case 4: if(konami[konami.size()-1]!=274) konami.clear(); break; case 5: if(konami[konami.size()-1]!=276) konami.clear(); break; case 6: if(konami[konami.size()-1]!=275) konami.clear(); break; case 7: if(konami[konami.size()-1]!=276) konami.clear(); break; case 8: if(konami[konami.size()-1]!=275) konami.clear(); break; case 9: if(konami[konami.size()-1]!=98) konami.clear(); break; case 10: if(konami[konami.size()-1]!=113) konami.clear(); else { std::cout << "Vous avez choisi Captain Canada, tabernacle, ca va chier !" << std::endl; sortie=4; character.push_back(canada); character.push_back(john); character.push_back(klaus); character.push_back(doug); character.push_back(stan); character.push_back(burt); character.push_back(steve); character.push_back(mckormack); done=true; } break; } break; case SDL_QUIT: done = true; break; default: break; } } // Mise à jour de la fenêtre (synchronisation implicite avec OpenGL) SDL_GL_SwapBuffers(); Uint32 tEnd = SDL_GetTicks(); Uint32 d = tEnd - tStart; if (d < FRAME_DURATION) { SDL_Delay(FRAME_DURATION - d); } } glDeleteTextures(1,&idMenu); return sortie; } int menuOptions(){ int sortie=-1; VBO vbo; vbo.bind(GL_ARRAY_BUFFER); Vertex2DUV vertices[] = { Vertex2DUV(-1, -1, 0.0, 1.0), Vertex2DUV(-1, 1, 0.0, 0.0), Vertex2DUV(1, 1, 1.0, 0.0), Vertex2DUV(1, -1, 1.0, 1.0), }; //on remplit les donnees du bateau glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //on remet le bateau à la mer vbo.debind(GL_ARRAY_BUFFER); //Création du VAO VAO vao; //on binde le vao vao.bind(); //on attribue une position 2D qui aura pour id 0 glEnableVertexAttribArray(0); //on attribue une texture qui aura pour id 1 glEnableVertexAttribArray(1); //on remet le bateau au port vbo.bind(GL_ARRAY_BUFFER); //on définit les paramètres des attributs (position 2D) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, x))); //on définit les paramètres des attributs (textures) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, u))); //on débinde le VBO vbo.debind(GL_ARRAY_BUFFER); //on débinde le VAO vao.debind(); Program prog; prog= loadProgram("../shaders/tex2D.vs.glsl", "../shaders/tex2D.fs.glsl"); prog.use(); GLint locVarTexture; locVarTexture= glGetUniformLocation(prog.getGLId(), "uTexture"); //On loade l'image int img_width=0, img_height=0; unsigned char* img; switch (WINDOW_WIDTH){ case 1024: img=SOIL_load_image("../textures/menuOptions1024.jpg", &img_width, &img_height, NULL, 0); break; case 800: img=SOIL_load_image("../textures/menuOptions800.jpg", &img_width, &img_height, NULL, 0); break; case 600: img=SOIL_load_image("../textures/menuOptions600.jpg", &img_width, &img_height, NULL, 0); break; default: break; } //On créé la texture GLuint idMenu; glGenTextures(1, &idMenu); glBindTexture(GL_TEXTURE_2D, idMenu); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); bool done = false; while (!done) { Uint32 tStart = SDL_GetTicks(); /* Rendering code goes here */ //on nettoie la fenêtre glClear(GL_COLOR_BUFFER_BIT); //on rebinde le vao vao.bind(); // glUniform1i(locVarTexture,0); //Premier triangle glBindTexture(GL_TEXTURE_2D,idMenu); glUniform1i(locVarTexture,0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindTexture(GL_TEXTURE_2D,0); //on débinde le vao vao.debind(); // Application code goes here SDL_Event e; int xClicked, yClicked; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_MOUSEBUTTONDOWN: if (e.button.button==SDL_BUTTON_LEFT){ xClicked=(float)(e.button.x); yClicked=(float)(e.button.y); if (xClicked>=(133.0/800.0)*WINDOW_WIDTH && xClicked <=(299.0/800.0)*WINDOW_WIDTH && yClicked>=(204.0/600.0)*WINDOW_HEIGHT && yClicked<=(351.0/600.0)*WINDOW_HEIGHT){ std::cout << "1024 x 768" << std::endl; WINDOW_WIDTH=1024; WINDOW_HEIGHT=768; restartSDL(); sortie=3; done=true; } else if (xClicked>=(337.0/800.0)*WINDOW_WIDTH && xClicked <=(471.0/800.0)*WINDOW_WIDTH && yClicked>=(227.0/600.0)*WINDOW_HEIGHT && yClicked<=(351.0/600.0)*WINDOW_HEIGHT){ std::cout << "800 x 600" << std::endl; WINDOW_WIDTH=800; WINDOW_HEIGHT=600; restartSDL(); sortie=3; done=true; } else if (xClicked>=(514.0/800.0)*WINDOW_WIDTH && xClicked <=(628.0/800.0)*WINDOW_WIDTH && yClicked>=(248.0/600.0)*WINDOW_HEIGHT && yClicked<=(351.0/600.0)*WINDOW_HEIGHT){ std::cout << "600 x 450" << std::endl; WINDOW_WIDTH=600; WINDOW_HEIGHT=450; restartSDL(); sortie=3; done=true; } else if (xClicked>=(151.0/800.0)*WINDOW_WIDTH && xClicked <=(275.0/800.0)*WINDOW_WIDTH && yClicked>=(445.0/600.0)*WINDOW_HEIGHT && yClicked<=(553.0/600.0)*WINDOW_HEIGHT){ std::cout << "Musique 1" << std::endl; musique = Mix_LoadMUS("../sounds/musique1.mp3"); Mix_PlayMusic(musique, -1); } else if (xClicked>=(343.0/800.0)*WINDOW_WIDTH && xClicked <=(465.0/800.0)*WINDOW_WIDTH && yClicked>=(445.0/600.0)*WINDOW_HEIGHT && yClicked<=(553.0/600.0)*WINDOW_HEIGHT){ std::cout << "Musique 2" << std::endl; musique = Mix_LoadMUS("../sounds/musique2.mp3"); Mix_PlayMusic(musique, -1); } else if (xClicked>=(512.0/800.0)*WINDOW_WIDTH && xClicked <=(635.0/800.0)*WINDOW_WIDTH && yClicked>=(445.0/600.0)*WINDOW_HEIGHT && yClicked<=(553.0/600.0)*WINDOW_HEIGHT){ std::cout << "Musique 3" << std::endl; musique = Mix_LoadMUS("../sounds/musique3.mp3"); Mix_PlayMusic(musique, -1); } if (xClicked>=(68.0/800.0)*WINDOW_WIDTH && xClicked <=(148.0/800.0)*WINDOW_WIDTH && yClicked>=(38.0/600.0)*WINDOW_HEIGHT && yClicked<=(88.0/600.0)*WINDOW_HEIGHT){ sortie=0; done = true; } } break; case SDL_QUIT: done = true; break; default: break; } } // Mise à jour de la fenêtre (synchronisation implicite avec OpenGL) SDL_GL_SwapBuffers(); Uint32 tEnd = SDL_GetTicks(); Uint32 d = tEnd - tStart; if (d < FRAME_DURATION) { SDL_Delay(FRAME_DURATION - d); } } glDeleteTextures(1,&idMenu); return sortie; } int menuPrincipal(std::vector<Character*>& character,std::vector<Track*>& track){ int sortie=-1; VBO vbo; vbo.bind(GL_ARRAY_BUFFER); Vertex2DUV vertices[] = { Vertex2DUV(-1, -1, 0.0, 1.0), Vertex2DUV(-1, 1, 0.0, 0.0), Vertex2DUV(1, 1, 1.0, 0.0), Vertex2DUV(1, -1, 1.0, 1.0), }; //on remplit les donnees du bateau glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //on remet le bateau à la mer vbo.debind(GL_ARRAY_BUFFER); //Création du VAO VAO vao; //on binde le vao vao.bind(); //on attribue une position 2D qui aura pour id 0 glEnableVertexAttribArray(0); //on attribue une texture qui aura pour id 1 glEnableVertexAttribArray(1); //on remet le bateau au port vbo.bind(GL_ARRAY_BUFFER); //on définit les paramètres des attributs (position 2D) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, x))); //on définit les paramètres des attributs (textures) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2DUV), (const GLvoid*)(offsetof(Vertex2DUV, u))); //on débinde le VBO vbo.debind(GL_ARRAY_BUFFER); //on débinde le VAO vao.debind(); Program prog; prog= loadProgram("../shaders/tex2D.vs.glsl", "../shaders/tex2D.fs.glsl"); prog.use(); GLint locVarTexture; locVarTexture= glGetUniformLocation(prog.getGLId(), "uTexture"); //On loade l'image int img_width=0, img_height=0; unsigned char* img; switch(WINDOW_WIDTH){ case 1024 : img=SOIL_load_image("../textures/menuPrincipal1024.jpg", &img_width, &img_height, NULL, 0); break; case 800 : img=SOIL_load_image("../textures/menuPrincipal800.jpg", &img_width, &img_height, NULL, 0); break; case 600 : img=SOIL_load_image("../textures/menuPrincipal600.jpg", &img_width, &img_height, NULL, 0); break; default: break; } //On créé la texture GLuint idMenu; glGenTextures(1, &idMenu); glBindTexture(GL_TEXTURE_2D, idMenu); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); bool done = false; while (!done) { Uint32 tStart = SDL_GetTicks(); /* Rendering code goes here */ //on nettoie la fenêtre glClear(GL_COLOR_BUFFER_BIT); //on rebinde le vao vao.bind(); glUniform1i(locVarTexture,0); //Premier triangle glBindTexture(GL_TEXTURE_2D,idMenu); glUniform1i(locVarTexture,0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindTexture(GL_TEXTURE_2D,0); //on débinde le vao vao.debind(); // Application code goes here SDL_Event e; int xClicked, yClicked; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_MOUSEBUTTONDOWN: if (e.button.button==SDL_BUTTON_LEFT){ xClicked=(float)(e.button.x); yClicked=(float)(e.button.y); if (xClicked>=(418.0/800.0)*WINDOW_WIDTH && xClicked <=(649.0/800.0)*WINDOW_WIDTH && yClicked>=(225.0/600.0)*WINDOW_HEIGHT && yClicked<=(268.0/600.0)*WINDOW_HEIGHT){ sortie=1; done = true; } else if (xClicked>=(402.0/800.0)*WINDOW_WIDTH && xClicked <=(666.0/800.0)*WINDOW_WIDTH && yClicked>=(276.0/600.0)*WINDOW_HEIGHT && yClicked<=(313.0/600.0)*WINDOW_HEIGHT){ sortie=2; done = true; } else if (xClicked>=(459.0/800.0)*WINDOW_WIDTH && xClicked <=(610.0/800.0)*WINDOW_WIDTH && yClicked>=(321.0/600.0)*WINDOW_HEIGHT && yClicked<=(363.0/600.0)*WINDOW_HEIGHT){ sortie=3; done = true; } else if (xClicked>=(459.0/800.0)*WINDOW_WIDTH && xClicked <=(610.0/800.0)*WINDOW_WIDTH && yClicked>=(371.0/600.0)*WINDOW_HEIGHT && yClicked<=(412.0/600.0)*WINDOW_HEIGHT){ sortie=-1; done = true; } } break; case SDL_QUIT: done = true; break; default: break; } } // Mise à jour de la fenêtre (synchronisation implicite avec OpenGL) SDL_GL_SwapBuffers(); Uint32 tEnd = SDL_GetTicks(); Uint32 d = tEnd - tStart; if (d < FRAME_DURATION) { SDL_Delay(FRAME_DURATION - d); } } glDeleteTextures(1,&idMenu); return sortie; } int lancerJeuRandom(std::vector<Character*>& character,std::vector<Track*>& track){ srand(time(NULL)); int r=rand()%9; std::cout << r << std::endl; r=7; switch(r){ case 0: character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); character.push_back(new Character(JENNIFER,10000, "Jennifer")); break; case 1: character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); character.push_back(new Character(JENNIFER,10000, "Jennifer")); break; case 2: character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); character.push_back(new Character(JENNIFER,10000, "Jennifer")); break; case 3: character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); character.push_back(new Character(JENNIFER,10000, "Jennifer")); break; case 4: character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); character.push_back(new Character(JENNIFER,10000, "Jennifer")); break; case 5: character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); character.push_back(new Character(JENNIFER,10000, "Jennifer")); break; case 6: character.push_back(new Character(MCKORMACK,10000, "McKormack")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(JENNIFER,10000, "Jennifer")); break; case 7: character.push_back(new Character(JENNIFER,10000, "Jennifer")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); break; case 8: character.push_back(new Character(CANADA,10000, "Captain Canada")); character.push_back(new Character(JOHN,10000, "John")); character.push_back(new Character(KLAUS,10000, "Klaus")); character.push_back(new Character(DOUG,10000, "Doug")); character.push_back(new Character(STAN,10000, "Stan")); character.push_back(new Character(BURT,10000, "Burt")); character.push_back(new Character(STEVE,10000, "Steve")); character.push_back(new Character(MCKORMACK,10000, "McKormack")); break; default: return -1; break; } r=rand()%4; Track* circuit1=new Track("../maps/Village.map",3); Track* circuit2=new Track("../maps/Montreal.map",3); Track* circuit3=new Track("../maps/Village.map",3); switch(r){ case 1: track.push_back(circuit1); track.push_back(circuit2); track.push_back(circuit3); break; case 2: track.push_back(circuit2); track.push_back(circuit1); track.push_back(circuit3); break; case 3: track.push_back(circuit3); track.push_back(circuit1); track.push_back(circuit2); break; default: return -1; break; } return 5; } void KartWithChar(std::vector<Character*>& Characters,std::vector<Kart*>& Karts){ Karts.clear(); for (std::vector<Character*>::iterator it = Characters.begin() ; it != Characters.end(); ++it){ Kart* kart; switch((*it)->getHero()){ case JOHN: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(-13,0,0)); kart->setScale(glm::vec3(0.7)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.8)); kart->LoadObjFromFile("../models/John.obj"); kart->LoadTexture("../textures/TexJohn.jpg"); kart->LoadTexture("../textures/TexJohn2.jpg",1); kart->build(); break; case KLAUS: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(-10,0,0)); kart->setScale(glm::vec3(0.5)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.6)); kart->LoadObjFromFile("../models/Klaus.obj"); kart->LoadTexture("../textures/TexKlaus.jpg"); kart->build(); break; case DOUG: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(-7,0,0)); kart->setScale(glm::vec3(0.5)); kart->setHitbox(glm::vec3(0.4, 0.5, 0.5)); kart->LoadObjFromFile("../models/Doug.obj"); kart->LoadTexture("../textures/TexDoug.jpg"); kart->build(); break; case CANADA: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(-4,0,0)); kart->setScale(glm::vec3(0.5)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.6)); kart->LoadObjFromFile("../models/ACC.obj"); kart->LoadTexture("../textures/CCTex.jpg"); kart->build(); break; case BURT: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(-1,0,0)); kart->setScale(glm::vec3(0.5)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.6)); kart->LoadObjFromFile("../models/Burt.obj"); kart->LoadTexture("../textures/TexBurt.jpg"); kart->build(); break; case MCKORMACK: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(2,0,0)); kart->setScale(glm::vec3(0.5)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.6)); kart->LoadObjFromFile("../models/MacKormack.obj"); kart->LoadTexture("../textures/TexMac.jpg"); kart->build(); break; case STEVE: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(5,0,0)); kart->setScale(glm::vec3(0.4)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.8)); kart->LoadObjFromFile("../models/Steve.obj"); kart->LoadTexture("../textures/TexSteve.jpg"); kart->build(); break; case STAN: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(8,0,0)); kart->setScale(glm::vec3(0.4)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.6)); kart->LoadObjFromFile("../models/Stan.obj"); kart->LoadTexture("../textures/TexStan.jpg"); kart->build(); break; case JENNIFER: kart=new Kart(2,0.01,0.75,5); kart->setPosition(glm::vec3(11,0,0)); kart->setScale(glm::vec3(0.5)); kart->setHitbox(glm::vec3(0.5, 0.5, 0.6)); kart->LoadObjFromFile("../models/Jennifer.obj"); kart->LoadTexture("../textures/TexJennifer.jpg"); kart->build(); break; } Karts.push_back(kart); } } void restartSDL(){ Mix_FreeMusic(musique); Mix_CloseAudio(); SDL_Quit(); SDL_Init(SDL_INIT_VIDEO); SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, SDL_OPENGL); SDL_WM_SetCaption("Hero Kaaaaart", NULL); glewInit(); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024); musique = Mix_LoadMUS("../sounds/musique3.mp3"); Mix_PlayMusic(musique, -1); } GLuint* PowerTexture(){ GLuint* tabTexture=new GLuint[7]; // Power boost int img_width, img_height; unsigned char* img=SOIL_load_image("../textures/powerboost.jpg", &img_width, &img_height, NULL, 0); GLuint id1; glGenTextures(1, &id1); glBindTexture(GL_TEXTURE_2D, id1); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[0]=id1; // Power front img=SOIL_load_image("../textures/powerfront.jpg", &img_width, &img_height, NULL, 0); GLuint id2; glGenTextures(1, &id2); glBindTexture(GL_TEXTURE_2D, id2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[1]=id2; // Power back img=SOIL_load_image("../textures/powerback.jpg", &img_width, &img_height, NULL, 0); GLuint id3; glGenTextures(1, &id3); glBindTexture(GL_TEXTURE_2D, id3); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[2]=id3; // Power all img=SOIL_load_image("../textures/powerall.jpg", &img_width, &img_height, NULL, 0); GLuint id4; glGenTextures(1, &id4); glBindTexture(GL_TEXTURE_2D, id4); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[3]=id4; // Power shield img=SOIL_load_image("../textures/powershield.jpg", &img_width, &img_height, NULL, 0); GLuint id5; glGenTextures(1, &id5); glBindTexture(GL_TEXTURE_2D, id5); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[4]=id5; // Power trap img=SOIL_load_image("../textures/powertrap.jpg", &img_width, &img_height, NULL, 0); GLuint id6; glGenTextures(1, &id6); glBindTexture(GL_TEXTURE_2D, id6); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[5]=id6; // Icone vide img=SOIL_load_image("../textures/vide.jpg", &img_width, &img_height, NULL, 0); GLuint id7; glGenTextures(1, &id7); glBindTexture(GL_TEXTURE_2D, id7); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[6]=id7; return tabTexture; } GLuint* RankTexture(){ GLuint* tabTexture=new GLuint[8]; // 1er int img_width, img_height; unsigned char* img=SOIL_load_image("../textures/chiffres/1.jpg", &img_width, &img_height, NULL, 0); GLuint id1; glGenTextures(1, &id1); glBindTexture(GL_TEXTURE_2D, id1); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[0]=id1; // 2ème img=SOIL_load_image("../textures/chiffres/2.jpg", &img_width, &img_height, NULL, 0); GLuint id2; glGenTextures(1, &id2); glBindTexture(GL_TEXTURE_2D, id2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[1]=id2; // 3ème img=SOIL_load_image("../textures/chiffres/3.jpg", &img_width, &img_height, NULL, 0); GLuint id3; glGenTextures(1, &id3); glBindTexture(GL_TEXTURE_2D, id3); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[2]=id3; // 4ème img=SOIL_load_image("../textures/chiffres/4.jpg", &img_width, &img_height, NULL, 0); GLuint id4; glGenTextures(1, &id4); glBindTexture(GL_TEXTURE_2D, id4); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[3]=id4; // 5ème img=SOIL_load_image("../textures/chiffres/5.jpg", &img_width, &img_height, NULL, 0); GLuint id5; glGenTextures(1, &id5); glBindTexture(GL_TEXTURE_2D, id5); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[4]=id5; // 6ème img=SOIL_load_image("../textures/chiffres/6.jpg", &img_width, &img_height, NULL, 0); GLuint id6; glGenTextures(1, &id6); glBindTexture(GL_TEXTURE_2D, id6); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[5]=id6; // 7ème img=SOIL_load_image("../textures/chiffres/7.jpg", &img_width, &img_height, NULL, 0); GLuint id7; glGenTextures(1, &id7); glBindTexture(GL_TEXTURE_2D, id7); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[6]=id7; // 8ème img=SOIL_load_image("../textures/chiffres/8.jpg", &img_width, &img_height, NULL, 0); GLuint id8; glGenTextures(1, &id8); glBindTexture(GL_TEXTURE_2D, id8); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[7]=id8; return tabTexture; } GLuint* PersoTexture(){ GLuint* tabTexture=new GLuint[8]; // John int img_width, img_height; unsigned char* img=SOIL_load_image("../textures/minipersos/john.jpg", &img_width, &img_height, NULL, 0); GLuint id1; glGenTextures(1, &id1); glBindTexture(GL_TEXTURE_2D, id1); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[0]=id1; // Klaus img=SOIL_load_image("../textures/minipersos/klaus.jpg", &img_width, &img_height, NULL, 0); GLuint id2; glGenTextures(1, &id2); glBindTexture(GL_TEXTURE_2D, id2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[1]=id2; // Doug img=SOIL_load_image("../textures/minipersos/doug.jpg", &img_width, &img_height, NULL, 0); GLuint id3; glGenTextures(1, &id3); glBindTexture(GL_TEXTURE_2D, id3); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[2]=id3; // Stan img=SOIL_load_image("../textures/minipersos/stan.jpg", &img_width, &img_height, NULL, 0); GLuint id4; glGenTextures(1, &id4); glBindTexture(GL_TEXTURE_2D, id4); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[3]=id4; // Steve img=SOIL_load_image("../textures/minipersos/steve.jpg", &img_width, &img_height, NULL, 0); GLuint id5; glGenTextures(1, &id5); glBindTexture(GL_TEXTURE_2D, id5); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[4]=id5; // Burt img=SOIL_load_image("../textures/minipersos/burt.jpg", &img_width, &img_height, NULL, 0); GLuint id6; glGenTextures(1, &id6); glBindTexture(GL_TEXTURE_2D, id6); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[5]=id6; // McKormack img=SOIL_load_image("../textures/minipersos/mckormack.jpg", &img_width, &img_height, NULL, 0); GLuint id7; glGenTextures(1, &id7); glBindTexture(GL_TEXTURE_2D, id7); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[6]=id7; // Jennifer img=SOIL_load_image("../textures/minipersos/jennifer.jpg", &img_width, &img_height, NULL, 0); GLuint id8; glGenTextures(1, &id8); glBindTexture(GL_TEXTURE_2D, id8); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); glBindTexture(GL_TEXTURE_2D,0); tabTexture[7]=id8; return tabTexture; }
09dfad572e7bebf2e67a99e1cbb6b31ed3dacc2f
f01ca8cd70c77f45174fdd7a2b6bcf60d8546299
/Core/MotionModels.cpp
837072cf2fef94433d5278f8e2e17fb9688778a6
[]
no_license
krzyyyy/Gra
0ef0df254b556d2d04ce017b066db75ff3cf945f
cc6f27044d1ef2a1484b4a8c9261c48451020d75
refs/heads/master
2023-08-16T10:18:43.193654
2021-10-06T19:11:24
2021-10-06T19:11:24
216,491,859
0
0
null
null
null
null
UTF-8
C++
false
false
2,295
cpp
MotionModels.cpp
#include "MotionModels.h" #include "..\SharedUtilities\MathHelperFunctions.h" namespace MotionModels { RectilinearMotion::RectilinearMotion() : _velocity(0) {} RectilinearMotion::RectilinearMotion(float velocity, glm::vec3 moveDirection) : _velocity(velocity), _moveDirection(moveDirection) {} RectilinearMotion::RectilinearMotion(glm::vec3 beginTrajectory, glm::vec3 endTrajetory, float velocity) noexcept: _velocity(velocity), _moveDirection(endTrajetory - beginTrajectory) { _moveDirection = _moveDirection / (glm::length(_moveDirection)); } void RectilinearMotion::GetNextPosition(std::chrono::duration<double> duration, glm::mat4& globalPosition) { globalPosition = glm::translate(globalPosition, _moveDirection * _velocity*(float)duration.count()); } glm::vec3 RectilinearMotion::GetNextDirection() const { return _moveDirection; } OrbitalMotion::OrbitalMotion():_angularVelocity(0), _center(0. , 0., 0.), _radius(0.), _rotationAxis(0., 0., 1.), _angle(0.) { perpendicularToRotation = glm::vec3(1., 0., 0.); } OrbitalMotion::OrbitalMotion(float angularVelocity, glm::vec3 center, float radius, glm::vec3 rotationAxis) : _angularVelocity(angularVelocity), _center(center), _radius(radius), _rotationAxis(rotationAxis), _angle(0.) { _rotationAxis = glm::normalize(_rotationAxis); perpendicularToRotation = glm::cross(rotationAxis, glm::vec3(1., 0., 0.)); if(glm::length(perpendicularToRotation) < 0.1) perpendicularToRotation = glm::cross(rotationAxis, glm::vec3(0., 1., 0.)); perpendicularToRotation = glm::normalize(perpendicularToRotation) * radius; } OrbitalMotion::OrbitalMotion(glm::vec3 beginTrajectory, glm::vec3 endTrajetory, float velocity) { } void OrbitalMotion::GetNextPosition(std::chrono::duration<double> duration, glm::mat4& globalPosition) { _angle += _angularVelocity * (float)duration.count(); auto objectPosition = glm::mat4(1); objectPosition = glm::translate(objectPosition, perpendicularToRotation); auto rotation = glm::rotate(glm::mat4(1), _angle, _rotationAxis); objectPosition = rotation* objectPosition; objectPosition = glm::translate(objectPosition, _center); globalPosition = objectPosition; } glm::vec3 OrbitalMotion::GetNextDirection() const { return glm::vec3(); } };
3b1157ed45c96cdfd939d72c21811fe4d1bd1067
401aa02f1b23d451c856e038bb71b91baec13eb4
/NeoML/Python/src/PyMathEngine.h
b0d4b3dd98a6d70aa966f38a7b74893138e018a9
[ "Apache-2.0", "NCSA", "BSD-3-Clause", "LLVM-exception", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-protobuf", "LicenseRef-scancode-arm-llvm-sga", "MIT", "Intel" ]
permissive
neoml-lib/neoml
fb189a74e0ce1474fdbe8c01d73fcb08d28d601c
b77ff503c8838d904f8db5f482eafb41de61c794
refs/heads/master
2023-08-18T13:28:19.727210
2023-08-17T12:49:49
2023-08-17T12:49:49
272,252,323
788
141
Apache-2.0
2023-09-14T11:59:19
2020-06-14T17:37:36
C++
UTF-8
C++
false
false
1,579
h
PyMathEngine.h
/* Copyright © 2017-2023 ABBYY Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------------------------------------------------*/ #pragma once #include <NeoML/NeoML.h> class CPyMathEngineOwner: public IObject { public: CPyMathEngineOwner() : owned( false ) {} explicit CPyMathEngineOwner( IMathEngine* _mathEngine, bool _owned = true ) : mathEngine( _mathEngine ), owned( _owned ) {} ~CPyMathEngineOwner() { if( !owned ) { mathEngine.release(); } } IMathEngine& MathEngine() const { return mathEngine.get() == 0 ? GetDefaultCpuMathEngine() : *mathEngine.get(); } private: std::unique_ptr<IMathEngine> mathEngine; bool owned; }; class CPyMathEngine final { public: explicit CPyMathEngine( CPyMathEngineOwner& owner ); CPyMathEngine( const std::string& type, int index ); std::string GetInfo() const; long long GetPeakMemoryUsage(); void CleanUp(); CPyMathEngineOwner& MathEngineOwner() const { return *mathEngineOwner; } private: CPtr<CPyMathEngineOwner> mathEngineOwner; }; void InitializeMathEngine(py::module& m);
496c132d06cb91bc107bdeec8cdeadb0efbd0cb4
6929c919911ddfaae5d03e44f1fe3b06595c970d
/ext/ceguicolor.cpp
651ae95aa42b331b761f567d59f68e1f6036f87c
[]
no_license
Hanmac/libcegui-ruby
a93f16f44d3a548e5a52783da2e8edaaf2b0996a
b38f63ecb06e8d8e1a1aec30cab931b76de4c4ee
refs/heads/master
2020-04-06T04:31:21.233123
2011-12-29T15:38:47
2011-12-29T15:38:47
2,022,261
2
0
null
null
null
null
UTF-8
C++
false
false
6,230
cpp
ceguicolor.cpp
#include "ceguicolor.hpp" #include "ceguiexception.hpp" #define _self wrap<CEGUI::Colour*>(self) VALUE rb_cCeguiColor; namespace CeguiColor { VALUE _alloc(VALUE self) { return wrap(new CEGUI::Colour); } macro_attr(Red,float) macro_attr(Green,float) macro_attr(Blue,float) macro_attr(Alpha,float) singlereturn(getHue) singlereturn(getSaturation) singlereturn(getLumination) /* * call-seq: * Color.new(red,green,blue[,alpha]) * * creates a new Color Object. */ VALUE _initialize(int argc,VALUE *argv,VALUE self) { VALUE red,green,blue,alpha; rb_scan_args(argc, argv, "31",&red,&green,&blue,&alpha); _setRed(self,red); _setGreen(self,green); _setBlue(self,blue); _setAlpha(self,NIL_P(alpha) ? DBL2NUM(1) : alpha); return self; } /* */ VALUE _initialize_copy(VALUE self, VALUE other) { VALUE result = rb_call_super(1,&other); _setRed(self,_getRed(other)); _setGreen(self,_getGreen(other)); _setBlue(self,_getBlue(other)); _setAlpha(self,_getAlpha(other)); return result; } /* * call-seq: * inspect -> String * * Human-readable description. * ===Return value * String */ VALUE _inspect(VALUE self) { VALUE array[6]; array[0]=rb_str_new2("#<%s:(%f, %f, %f, %f)>"); array[1]=rb_class_of(self); array[2]=_getRed(self); array[3]=_getGreen(self); array[4]=_getBlue(self); array[5]=_getAlpha(self); return rb_f_sprintf(6,array); } /* * call-seq: * to_s -> String * * hexadecimal, #AARRGGBB * ===Return value * String */ VALUE _to_s(VALUE self) { VALUE array[2]; array[0]=rb_str_new2("%.8X"); array[1]=LONG2NUM(_self->getARGB()); return rb_f_sprintf(2,array); } /* * */ VALUE _equal(VALUE self,VALUE val) { if(self == val) return true; if(!is_wrapable<CEGUI::Colour>(val)) return false; else return wrap(*_self == wrap<CEGUI::Colour>(val)); } /* * call-seq: * color + other_color -> new_color * * adds the colors * ===Return value * Color */ VALUE _plus(VALUE self,VALUE val) { return wrap(*_self + wrap<CEGUI::Colour>(val)); } /* * call-seq: * color - other_color -> new_color * * minus the colors * ===Return value * Color */ VALUE _minus(VALUE self,VALUE val) { return wrap(*_self - wrap<CEGUI::Colour>(val)); } /* * call-seq: * * Numeric -> new_color * * multipicate the colors * ===Return value * Color */ VALUE _mal(VALUE self,VALUE val) { return wrap(*_self * (float)NUM2DBL(val)); } /* * call-seq: * color / Numeric -> new_color * * devide the colors * ===Return value * Color */ VALUE _durch(VALUE self,VALUE val) { return wrap(*_self * (float)(1.0 / NUM2DBL(val))); } /* * call-seq: * marshal_dump -> string * * packs a ColorRect into an string. */ VALUE _marshal_dump(VALUE self) { VALUE result = rb_ary_new(); rb_ary_push(result,_getRed(self)); rb_ary_push(result,_getGreen(self)); rb_ary_push(result,_getBlue(self)); rb_ary_push(result,_getAlpha(self)); return rb_funcall(result,rb_intern("pack"),1,rb_str_new2("dddd")); } /* * call-seq: * marshal_load(string) -> self * * loads a string into an ColorRect. */ VALUE _marshal_load(VALUE self,VALUE load) { VALUE result = rb_funcall(load,rb_intern("unpack"),1,rb_str_new2("dddd")); _setAlpha(self,rb_ary_pop(result)); _setBlue(self,rb_ary_pop(result)); _setGreen(self,rb_ary_pop(result)); _setRed(self,rb_ary_pop(result)); return self; } VALUE _setHue(VALUE self,VALUE val) { _self->setHSL(NUM2DBL(val), _self->getSaturation(), _self->getLumination(), _self->getAlpha()); return val; } VALUE _setSaturation(VALUE self,VALUE val) { _self->setHSL(_self->getHue(), NUM2DBL(val), _self->getLumination(), _self->getAlpha()); return val; } VALUE _setLumination(VALUE self,VALUE val) { _self->setHSL(_self->getHue(), _self->getSaturation(), NUM2DBL(val), _self->getAlpha()); return val; } } /* * Document-class: CEGUI::Color * * This class represents an Color. */ /* Document-attr: red * returns the red value of Color. */ /* Document-attr: blue * returns the blue value of Color. */ /* Document-attr: green * returns the green value of Color. */ /* Document-attr: alpha * returns the alpha value of Color. */ /* Document-attr: hue * returns the hue value of Color. */ /* Document-attr: saturation * returns the saturation value of Color. */ /* Document-attr: lumination * returns the lumination value of Color. */ void Init_CeguiColor(VALUE rb_mCegui) { #if 0 rb_mCegui = rb_define_module("CEGUI"); rb_define_attr(rb_cCeguiColor,"red",1,1); rb_define_attr(rb_cCeguiColor,"blue",1,1); rb_define_attr(rb_cCeguiColor,"green",1,1); rb_define_attr(rb_cCeguiColor,"alpha",1,1); rb_define_attr(rb_cCeguiColor,"hue",1,1); rb_define_attr(rb_cCeguiColor,"saturation",1,1); rb_define_attr(rb_cCeguiColor,"lumination",1,1); #endif using namespace CeguiColor; rb_cCeguiColor = rb_define_class_under(rb_mCegui,"Color",rb_cObject); rb_define_alloc_func(rb_cCeguiColor,_alloc); rb_define_method(rb_cCeguiColor,"initialize",RUBY_METHOD_FUNC(_initialize),-1); rb_define_private_method(rb_cCeguiColor,"initialize_copy",RUBY_METHOD_FUNC(_initialize_copy),1); rb_define_attr_method(rb_cCeguiColor,"red",_getRed,_setRed); rb_define_attr_method(rb_cCeguiColor,"blue",_getBlue,_setBlue); rb_define_attr_method(rb_cCeguiColor,"green",_getGreen,_setGreen); rb_define_attr_method(rb_cCeguiColor,"alpha",_getAlpha,_setAlpha); rb_define_attr_method(rb_cCeguiColor,"hue",_getHue,_setHue); rb_define_attr_method(rb_cCeguiColor,"saturation",_getSaturation,_setSaturation); rb_define_attr_method(rb_cCeguiColor,"lumination",_getLumination,_setLumination); rb_define_method(rb_cCeguiColor,"inspect",RUBY_METHOD_FUNC(_inspect),0); rb_define_method(rb_cCeguiColor,"to_s",RUBY_METHOD_FUNC(_to_s),0); rb_define_method(rb_cCeguiColor,"==",RUBY_METHOD_FUNC(_equal),1); rb_define_method(rb_cCeguiColor,"marshal_dump",RUBY_METHOD_FUNC(_marshal_dump),0); rb_define_method(rb_cCeguiColor,"marshal_load",RUBY_METHOD_FUNC(_marshal_load),1); rb_define_method(rb_cCeguiColor,"+",RUBY_METHOD_FUNC(_plus),1); rb_define_method(rb_cCeguiColor,"-",RUBY_METHOD_FUNC(_minus),1); rb_define_method(rb_cCeguiColor,"*",RUBY_METHOD_FUNC(_mal),1); rb_define_method(rb_cCeguiColor,"/",RUBY_METHOD_FUNC(_durch),1); }
f7ebdc2363ff9ef6d7fefa37954f26dc61eba6f3
b1fdeb29c93e4ef35bbb840fe192251855d3746c
/runtime/object/core/Scene.cc
3e62167a252b107f1defd0fe470544c89fcd04d4
[]
no_license
WooZoo86/xEngine
b80e7fc2b64a30ed3d631fdd340c63a45f6e6566
0d9f7c262d04f53402d339bd815db0c50eaa9d24
refs/heads/master
2021-05-14T13:25:00.430222
2017-10-11T11:21:50
2017-10-11T11:21:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
848
cc
Scene.cc
#include "Scene.h" namespace xEngine { void Scene::Initialize() { } void Scene::Finalize() { game_objects_.clear(); } GameObjectPtr Scene::AddGameObject() { auto game_object = GameObject::Create(); game_objects_.push_back(game_object); return game_object; } void Scene::RemoveGameObject(GameObjectPtr game_object) { if (eastl::find(game_objects_.begin(), game_objects_.end(), game_object) == game_objects_.end()) return; game_objects_.remove(game_object); } GameObjectPtr Scene::FindGameObject(uint32 id) { for (auto &game_object : game_objects_) { if (game_object->id() == id) { return game_object; } } return nullptr; } void Scene::Update() { for (auto &game_object : game_objects_) { game_object->Update(); } } void Scene::Serialize() { } void Scene::Deserialize() { } } // namespace xEngine
aa43af81de7ab652bf12f121597056214d8c4b69
ef006d7e27df637e5588420278969aa79c4bf2f9
/plugin/main.cpp
1193caa56f6204011a127d161bf2cb1a757fa7ba
[]
no_license
leftp/lsarelayx
4671d622b8059831f7e18a5e3749d782af0ee634
abdbbd3e823bac15a665e592e3806bc269fe8c6d
refs/heads/main
2023-08-27T10:37:09.832799
2021-11-16T12:33:05
2021-11-16T12:33:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,276
cpp
main.cpp
#define WIN32_NO_STATUS #define SECURITY_WIN32 #define UNICODE #include <windows.h> #include <sspi.h> #include <ntsecapi.h> #include <ntsecpkg.h> #include <winternl.h> #include <string> #include <vector> #include <system_error> #include <map> #include <sddl.h> #include <ntdef.h> #include "lsarelayx.hxx" #include "pipe.hxx" #include "commands.h" #include "relaycontext.h" extern "C" NTSTATUS SpLsaModeInitialize(ULONG LsaVersion, PULONG PackageVersion, PSECPKG_FUNCTION_TABLE *ppTables, PULONG pcTables); win32_handle CreateTokenFromUserInfo(const LUID& sourceLUID, const UserInfo& userInfo); extern PLSA_SECPKG_FUNCTION_TABLE g_FunctionTable; extern MessageExchangeFactoryPtr g_messageExchangeFactory;; MessageBuffer ntlmType1 = { 0x4E, 0x54, 0x4C, 0x4D, 0x53, 0x53, 0x50, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x32, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x33, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x0B, 0x00, 0x28, 0x00, 0x00, 0x00, 0x05, 0x00, 0x93, 0x08, 0x00, 0x00, 0x00, 0x0F, 0x57, 0x4F, 0x52, 0x4B, 0x53, 0x54, 0x41, 0x54, 0x49, 0x4F, 0x4E, 0x44, 0x4F, 0x4D, 0x41, 0x49, 0x4E }; MessageBuffer ntlmType2 = { 0x4E, 0x54, 0x4C, 0x4D, 0x53, 0x53, 0x50, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x02, 0x81, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x62, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x44, 0x00, 0x4F, 0x00, 0x4D, 0x00, 0x41, 0x00, 0x49, 0x00, 0x4E, 0x00, 0x02, 0x00, 0x0C, 0x00, 0x44, 0x00, 0x4F, 0x00, 0x4D, 0x00, 0x41, 0x00, 0x49, 0x00, 0x4E, 0x00, 0x01, 0x00, 0x0C, 0x00, 0x53, 0x00, 0x45, 0x00, 0x52, 0x00, 0x56, 0x00, 0x45, 0x00, 0x52, 0x00, 0x04, 0x00, 0x14, 0x00, 0x64, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x03, 0x00, 0x22, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2E, 0x00, 0x64, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00 }; MessageBuffer ntlmType3 = { 0x4E, 0x54, 0x4C, 0x4D, 0x53, 0x53, 0x50, 0x00, 0x03, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00, 0x6A, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00, 0x82, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x40, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x4C, 0x00, 0x00, 0x00, 0x16, 0x00, 0x16, 0x00, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9A, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x44, 0x00, 0x4F, 0x00, 0x4D, 0x00, 0x41, 0x00, 0x49, 0x00, 0x4E, 0x00, 0x75, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x57, 0x00, 0x4F, 0x00, 0x52, 0x00, 0x4B, 0x00, 0x53, 0x00, 0x54, 0x00, 0x41, 0x00, 0x54, 0x00, 0x49, 0x00, 0x4F, 0x00, 0x4E, 0x00, 0xC3, 0x37, 0xCD, 0x5C, 0xBD, 0x44, 0xFC, 0x97, 0x82, 0xA6, 0x67, 0xAF, 0x6D, 0x42, 0x7C, 0x6D, 0xE6, 0x7C, 0x20, 0xC2, 0xD3, 0xE7, 0x7C, 0x56, 0x25, 0xA9, 0x8C, 0x1C, 0x31, 0xE8, 0x18, 0x47, 0x46, 0x6B, 0x29, 0xB2, 0xDF, 0x46, 0x80, 0xF3, 0x99, 0x58, 0xFB, 0x8C, 0x21, 0x3A, 0x9C, 0xC6 }; extern "C" NTSYSAPI NTSTATUS NtAllocateLocallyUniqueId(PLUID Luid); extern "C" NTSYSAPI NTSTATUS NtCreateToken( OUT PHANDLE TokenHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN TOKEN_TYPE TokenType, IN PLUID AuthenticationId, IN PLARGE_INTEGER ExpirationTime, IN PTOKEN_USER TokenUser, IN PTOKEN_GROUPS TokenGroups, IN PTOKEN_PRIVILEGES TokenPrivileges, IN PTOKEN_OWNER TokenOwner, IN PTOKEN_PRIMARY_GROUP TokenPrimaryGroup, IN PTOKEN_DEFAULT_DACL TokenDefaultDacl, IN PTOKEN_SOURCE TokenSource ); BOOL SetPrivilege( HANDLE hToken, // access token handle LPCTSTR lpszPrivilege, // name of privilege to enable/disable BOOL bEnablePrivilege // to enable or disable privilege ) { TOKEN_PRIVILEGES tp; LUID luid; if ( !LookupPrivilegeValue( NULL, // lookup privilege on local system lpszPrivilege, // privilege to lookup &luid ) ) // receives LUID of privilege { printf("LookupPrivilegeValue error: %u\n", GetLastError() ); return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if (bEnablePrivilege) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; else tp.Privileges[0].Attributes = 0; // Enable the privilege or disable all privileges. if ( !AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL) ) { printf("AdjustTokenPrivileges error: %u\n", GetLastError() ); return FALSE; } if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) { printf("The token does not have the specified privilege. \n"); return FALSE; } return TRUE; } NTSTATUS LsaCreateTokenEx( PLUID LogonId, PTOKEN_SOURCE TokenSource, SECURITY_LOGON_TYPE LogonType, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, LSA_TOKEN_INFORMATION_TYPE TokenInformationType, PVOID TokenInformation, PTOKEN_GROUPS TokenGroups, PUNICODE_STRING Workstation, PUNICODE_STRING ProfilePath, PVOID SessionInformation, SECPKG_SESSIONINFO_TYPE SessionInformationType, PHANDLE Token, PNTSTATUS SubStatus ){ OBJECT_ATTRIBUTES oa; InitializeObjectAttributes(&oa, nullptr, 0, nullptr, nullptr); LSA_TOKEN_INFORMATION_V2* lsaToken = (LSA_TOKEN_INFORMATION_V2*)TokenInformation; NTSTATUS result = NtCreateToken(Token, TOKEN_ALL_ACCESS, &oa, TokenPrimary, LogonId, &lsaToken->ExpirationTime, &lsaToken->User, lsaToken->Groups, lsaToken->Privileges, &lsaToken->Owner, &lsaToken->PrimaryGroup, nullptr, TokenSource); return result; } int main(int argc, char** argv){ HANDLE hToken = nullptr; TOKEN_STATISTICS tokenStats; DWORD retLen = 0; OpenProcessToken(GetCurrentProcess(),TOKEN_ALL_ACCESS, &hToken); GetTokenInformation(hToken, TokenStatistics, &tokenStats,sizeof(tokenStats), &retLen); SetPrivilege(hToken, L"SeCreateTokenPrivilege", TRUE); CloseHandle(hToken); g_FunctionTable = new LSA_SECPKG_FUNCTION_TABLE(); g_FunctionTable->AllocateLsaHeap = (PLSA_ALLOCATE_LSA_HEAP)malloc; g_FunctionTable->FreeLsaHeap = (PLSA_FREE_LSA_HEAP)free; g_FunctionTable->CreateLogonSession = NtAllocateLocallyUniqueId; g_FunctionTable->CreateTokenEx = LsaCreateTokenEx; ULONG pVersion; ULONG pcTables; PSECPKG_FUNCTION_TABLE ppTables; LoadLibraryA("msv1_0.dll"); LoadLibraryA("lsasrv.dll"); SpLsaModeInitialize(1, &pVersion, &ppTables, &pcTables); RelayContext ctx(g_messageExchangeFactory, true, 4); auto relayResponse = ctx.ForwardNegotiateMessage(0,ntlmType1); relayResponse = ctx.ForwardChallengeMessage(0,ntlmType2); auto relayFinshed = ctx.ForwardAuthenticateMessage(0,ntlmType3); CreateTokenFromUserInfo(tokenStats.AuthenticationId, relayFinshed.UserInfo); getchar(); return 0; }
0354486f622b8696f6b84f4010e417bbddea1687
bcceadbcd31c1c38d41d5515c38121cf7cd5492f
/structures/templateHead.hpp
aa05d36a5ac6d2a5dd269f23c1b1413639aa86b6
[ "MIT" ]
permissive
pat-laugh/websson-libraries
2ad7cfdc99109ac6b087afc14482a54a69ef047e
c5c99a98270dee45fcd9ec4e7f03e2e74e3b1ce2
refs/heads/master
2023-07-13T09:59:09.625566
2019-02-09T05:45:39
2019-02-09T05:45:39
78,256,423
0
0
null
null
null
null
UTF-8
C++
false
false
1,508
hpp
templateHead.hpp
//MIT License //Copyright 2017 Patrick Laughrea #pragma once #include "parameters.hpp" #include "webss.hpp" namespace webss { template <class Param> class BasicThead { public: using Params = BasicParams<Param>; using size_type = typename Params::size_type; BasicThead() {} BasicThead(Params params) : params(std::move(params)) {} bool operator==(const BasicThead& o) const { return params == o.params; } bool operator!=(const BasicThead& o) const { return !(*this == o); } //instead of the keys being shared, this creates an indepedent copy of the keys and the data BasicThead makeCompleteCopy() const { return BasicThead(params.makeCompleteCopy()); } bool empty() const { return params.empty(); } size_type size() const { return params.size(); } Param& back() { return params.back(); } const Param& back() const { return params.back(); } Param& last() { return back(); } const Param& last() const { return back(); } void attach(Param value) { params.add(std::move(value)); } void attachEmpty(std::string key) { attach(std::move(key), Param()); } void attach(std::string key, Param value) { params.addSafe(std::move(key), std::move(value)); } void attach(const BasicThead& value) { if (value.empty()) return; const auto& valueTuple = value.params; if (params.empty()) params = valueTuple.makeCompleteCopy(); else params.merge(valueTuple); } const Params& getParams() const { return params; } private: Params params; }; }
c4f06dc9bc3924bdcabb14495595006b8c3cc0e6
933c9f60bccedfa5a628d0980c861fa00766157f
/src/leetcode/leetcode9.cc
b643c616d739f260259685902dac968eae052243
[]
no_license
yujinghui/BeautyOfProgramming
376d053a0854bf288ef65d47407c69b34a2a65c5
9a7253e5c8501c7debb6cdbf67d9f9cbc966bd73
refs/heads/master
2023-07-11T00:11:45.495104
2021-08-12T06:35:24
2021-08-12T06:35:24
380,482,511
1
0
null
null
null
null
UTF-8
C++
false
false
555
cc
leetcode9.cc
#include <stdio.h> #include <math.h> #include <string> #include <iostream> #include <unordered_set> using namespace std; class Solution { public: bool isPalindrome(int x) { int newVal = 0, oldVal = x; while (x > 0) { newVal = newVal * 10; int remain = x % 10; x = x / 10; newVal = remain + newVal; } cout << newVal << " ==" << oldVal << endl; return newVal == oldVal; } }; int main() { Solution s; cout << s.isPalindrome(91234567899); }
e0945c6b91097c4c4025e17e021185ee1b98645c
f2540197958e6c11edf63b0281df9948d89795b2
/PSOSolver.cpp
2ca6f165835467b681bfc7be115ef0303ee317d7
[]
no_license
theazgra/BIA
8f39703c2658769f490ed4808cda830f8dcd93b5
19045bd4d0c97df852f82556176d854595ac77ea
refs/heads/master
2020-08-04T15:49:37.011619
2019-12-09T18:35:53
2019-12-09T18:35:53
212,191,239
0
0
null
null
null
null
UTF-8
C++
false
false
6,322
cpp
PSOSolver.cpp
#include "PSOSolver.h" PSOSolver::PSOSolver(const OptimizationProblem &problem, const size_t particleCount, const size_t iterationCount) { m_dimension = problem.dimensionCount; m_dimensionLimits = problem.dimensionLimits; m_fitnessFunction = problem.testFunction; m_iterationCount = iterationCount; m_particleCount = particleCount; m_generator = std::mt19937(m_rd()); m_01rand = std::uniform_real_distribution<f64>(0.0, 1.0); m_randomAttribute.resize(m_dimension); m_randomVelocity.resize(m_dimension); m_vMax.resize(m_dimension); for (size_t dim = 0; dim < m_dimension; ++dim) { const f64 dimMin = m_dimensionLimits[dim].min; const f64 dimMax = m_dimensionLimits[dim].max; const f64 dimensionSize = dimMin < 0 ? (dimMax + abs(dimMin)) : dimMax - dimMin; m_randomAttribute[dim] = std::uniform_real_distribution<f64>(dimMin, dimMax); const f64 vMax = dimensionSize / 20.0; m_vMax[dim] = vMax; m_randomVelocity[dim] = std::uniform_real_distribution<f64>(-vMax, vMax); } } void PSOSolver::init_gBest(const std::vector<PSOParticle> &particles) { f64 min = std::numeric_limits<f64>::max(); for (const auto &particle : particles) { if (particle.fitness < min) { m_gBest = particle; min = m_gBest.fitness; } } } PSOParticle PSOSolver::generate_random_particle() { PSOParticle particle = {}; particle.attributes.resize(m_dimension); particle.velocity.resize(m_dimension); for (size_t dim = 0; dim < m_dimension; ++dim) { particle.attributes[dim] = m_dimensionLimits[dim].min + (m_01rand(m_generator) * (m_dimensionLimits[dim].max - m_dimensionLimits[dim].min)); assert(particle.attributes[dim] >= m_dimensionLimits[dim].min && particle.attributes[dim] <= m_dimensionLimits[dim].max); particle.velocity[dim] = m_randomVelocity[dim](m_generator);// 0; particle.fitness = m_fitnessFunction(particle.attributes); particle.pBest = particle.attributes; particle.pBestFitness = particle.fitness; } return particle; } void PSOSolver::initialize_population() { m_particles.resize(m_particleCount); for (size_t particleIndex = 0; particleIndex < m_particleCount; ++particleIndex) { m_particles[particleIndex] = generate_random_particle(); } } f64 PSOSolver::average_fitness() const { auto sum = azgra::collection::sum(m_particles.begin(), m_particles.end(), [](const PSOParticle &particle) { return particle.fitness; }, 0.0f); f64 result = sum / static_cast<f64>(m_particleCount); return result; } f64 PSOSolver::average_p_best_fitness() const { auto sum = azgra::collection::sum(m_particles.begin(), m_particles.end(), [](const PSOParticle &particle) { return particle.pBestFitness; }, 0.0f); f64 result = sum / static_cast<f64>(m_particleCount); return result; } OptimizationResult PSOSolver::solve() { OptimizationResult result = {}; result.invidualsInTime.resize(m_iterationCount); initialize_population(); f64 avgFitness = average_fitness(); fprintf(stdout, "Initial average cost: %.5f\n", avgFitness); init_gBest(m_particles); for (size_t iteration = 0; iteration < m_iterationCount; ++iteration) { m_w = m_wStart - (((m_wStart - m_wEnd) * static_cast<f64>(iteration)) / static_cast<f64>(m_iterationCount)); result.invidualsInTime[iteration] = azgra::collection::select( m_particles.begin(), m_particles.end(), [](const PSOParticle &individual) { return individual.attributes; }); for (PSOParticle &particle : m_particles) { update_particle(particle); } avgFitness = average_fitness(); double avgPBEstFitness = average_p_best_fitness(); fprintf(stdout, "Iteration %lu/%lu average cost: %.5f avg. pBest cost: %.5f gBest cost: %.5f\n", iteration + 1, m_iterationCount, avgFitness, avgPBEstFitness, m_gBest.fitness); } fprintf(stdout, "Iteration %lu/%lu average cost: %.5f gBest cost: %.5f\n", m_iterationCount, m_iterationCount, avgFitness, m_gBest.fitness); result.result = m_gBest.fitness; return result; } void PSOSolver::update_particle(PSOParticle &particle) { for (size_t dim = 0; dim < m_dimension; ++dim) { const f64 r1 = m_01rand(m_generator); const f64 r2 = m_01rand(m_generator); assert(r1 >= 0.0 && r1 <= 1.0); assert(r2 >= 0.0 && r1 <= 1.0); particle.velocity[dim] = m_w * particle.velocity[dim] + (m_cPBest * r1 * (particle.pBest[dim] - particle.attributes[dim])) + (m_cGBest * r2 * (m_gBest.attributes[dim] - particle.attributes[dim])); if (particle.velocity[dim] < (-1.0 * m_vMax[dim]) || particle.velocity[dim] > m_vMax[dim]) { particle.velocity[dim] = m_randomVelocity[dim](m_generator); } } for (size_t dim = 0; dim < particle.velocity.size(); ++dim) { particle.attributes[dim] += particle.velocity[dim]; #if 1 if (particle.attributes[dim] < m_dimensionLimits[dim].min) { particle.attributes[dim] = m_dimensionLimits[dim].min; } else if (particle.attributes[dim] > m_dimensionLimits[dim].max) { particle.attributes[dim] = m_dimensionLimits[dim].max; } #else if ((particle.attributes[dim] < m_dimensionLimits[dim].min) || (particle.attributes[dim] > m_dimensionLimits[dim].max)) { particle.attributes[dim] = m_randomAttribute[dim](m_generator); } #endif } particle.fitness = m_fitnessFunction(particle.attributes); if (particle.fitness <= particle.pBestFitness) { particle.pBestFitness = particle.fitness; particle.pBest = particle.attributes; } if (particle.fitness <= m_gBest.fitness) { m_gBest.fitness = particle.fitness; m_gBest.attributes = particle.attributes; //m_gBest = particle; } }
c781dbd81aeef7bcba22fbbde1a3ce4fa929c224
3cc352b29b8042b4a9746796b851d8469ff9ff62
/src/btl/ValidateTALENs.cc
805dbe6504e780d1644dd38b2f2d6204675867f9
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
CompRD/BroadCRD
1412faf3d1ffd9d1f9907a496cc22d59ea5ad185
303800297b32e993abd479d71bc4378f598314c5
refs/heads/master
2020-12-24T13:53:09.985406
2019-02-06T21:38:45
2019-02-06T21:38:45
34,069,434
4
0
null
null
null
null
UTF-8
C++
false
false
13,622
cc
ValidateTALENs.cc
/////////////////////////////////////////////////////////////////////////////// // SOFTWARE COPYRIGHT NOTICE AGREEMENT // // This software and its documentation are copyright (2013) by the // // Broad Institute. All rights are reserved. This software is supplied // // without any warranty or guaranteed support whatsoever. The Broad // // Institute is not responsible for its use, misuse, or functionality. // /////////////////////////////////////////////////////////////////////////////// #include "CoreTools.h" #include "MainTools.h" #include "Basevector.h" #include "Qualvector.h" #include "VecUtilities.h" #include "btl/CMonoRep.h" #include "btl/LoaderTALENs.h" #include "btl/MonomerUtilsTALENs.h" #include "lookup/LookAlign.h" #include "pairwise_aligners/AlignTwoBasevectors.h" #include "pairwise_aligners/PerfectAlignment.h" #include "pairwise_aligners/SmithWatBandedA.h" #include "tiled/AlignsOnConsensus.h" #include "util/RunCommand.h" // MakeDepend: dependency Fastb // MakeDepend: dependency Qualb // MakeDepend: dependency FastAlignShortReads /** * Validate */ void Validate( const String &AB1_DIR, const String &OUT_DIR, const String &parts_file, const String &prod_name, const String &reference, const vecbvec &primers, const vecbvec &parts, const vecString &parts_ids, const bool &R2 ) { // File names. String strRC = ( R2 ? String( "R2" ) : String( "R1" ) ); String ab1F1_file = AB1_DIR + "/" + prod_name + "-F1.ab1"; String ab1F2_file = AB1_DIR + "/" + prod_name + "-F2.ab1"; String ab1R_file = AB1_DIR + "/" + prod_name + "-" + strRC + ".ab1"; String out_dir = OUT_DIR + "/" + prod_name; String log_file = out_dir + "/main.log"; String csvline_file = out_dir + "/csvline.txt"; String ref_head = out_dir + "/ref"; String tmp_file = out_dir + "/reads.tmp"; String fasta_file = out_dir + "/reads.fasta"; String qual_file = out_dir + "/reads.qual"; String fastb_file = out_dir + "/reads.fastb"; String qualb_file = out_dir + "/reads.qualb"; String consensus_head = out_dir + "/consensus"; String cbases_file = out_dir + "/consensus.fastb"; String cquals_file = out_dir + "/consensus.qualb"; String onreads_qlt_file = out_dir + "/on_reads.qlt"; String onconsensus_qlt_file = out_dir + "/on_consensus.qlt"; String visual_file = out_dir + "/aligns.visual"; String devnull = "/dev/null"; Mkpath( out_dir ); ofstream log( log_file.c_str( ) ); log << "Validation of " << prod_name << "\n"; // Clean from old runs, if needed. if ( IsRegularFile( tmp_file ) ) Remove ( tmp_file ); if ( IsRegularFile( fasta_file ) ) Remove( fasta_file ); if ( IsRegularFile( qual_file ) ) Remove( qual_file ); // Fasta first. RunCommand( "echo \">\"" + prod_name + "-F1 >> " + tmp_file ); RunCommand( "extract_seq " + ab1F1_file + " >> " + tmp_file ); RunCommand( "echo \">\"" + prod_name + "-" + strRC + " >> " + tmp_file ); RunCommand( "extract_seq " + ab1R_file + " >> " + tmp_file ); if ( IsRegularFile( ab1F2_file ) ) { RunCommand( "echo \">\"" + prod_name + "-F2 >> " + tmp_file ); RunCommand( "extract_seq " + ab1F2_file + " >> " + tmp_file ); } // Replace "-" with "N" (extract_seq uses "-" instead of "N"). String line; ofstream out( fasta_file.c_str( ) ); ifstream in( tmp_file.c_str( ) ); while ( in ) { getline( in, line ); if ( ! in ) break; if ( ! line.Contains( ">", 0 ) ) for (int ii=0; ii<line.isize( ); ii++) if ( line[ii] == '-' ) line[ii] = 'N'; out << line << "\n"; } in.close( ); out.close( ); // Remove tmp. if ( IsRegularFile( tmp_file ) ) Remove( tmp_file ); // Qual file. RunCommand( "echo \">\"" + prod_name + "-F1 >> " + qual_file ); RunCommand( "extract_qual " + ab1F1_file + " >> " + qual_file ); RunCommand( "echo \">\"" + prod_name + "-" + strRC + " >> " + qual_file ); RunCommand( "extract_qual " + ab1R_file + " >> " + qual_file ); if ( IsRegularFile( ab1F2_file ) ) { RunCommand( "echo \">\"" + prod_name + "-F2 >> " + qual_file ); RunCommand( "extract_qual " + ab1F2_file + " >> " + qual_file ); } // Fastb and qualb. RunCommandWithLog( "Fastb FASTAMB=True PRE= FILE=" + fasta_file, devnull ); RunCommandWithLog( "Qualb PRE= FILE=" + qual_file, devnull ); // Tag terminator parts. vec<bool> is_termin( parts_ids.size( ), false ); for (size_t ii=0; ii<parts_ids.size( ); ii++) if ( parts_ids[ii].Contains( "termin" ) ) is_termin[ii] = true; // Load bases and quals, sanity check. vecbvec rbases( fastb_file ); vecqvec rquals( qualb_file ); if ( rbases.size( ) != rquals.size( ) ) { log << "\nFATAL ERROR: bases and quals have different sizes" << endl; PrintErrorCsvLine( csvline_file, prod_name, reference ); return; } if ( rbases.size( ) != 2 && rbases.size( ) != 3 ) { log << "\nFATAL ERROR: bases and quals must have size 2 or 3" << endl; PrintErrorCsvLine( csvline_file, prod_name, reference ); return; } for (int ii=0; ii<(int)rbases.size( ); ii++) { if ( rbases[ii].size( ) != rquals[ii].size( ) ) { log << "\nFATAL ERROR: bases/quals entries have different sizes" << endl; PrintErrorCsvLine( csvline_file, prod_name, reference ); return; } } // Visual stream (to print various aligns). ofstream vis_out( visual_file.c_str( ) ); // Turn reference into a CMonoRep, and save bases/quals. CMonoRep mr_ref( "ref", &log ); mr_ref.SetFromReference( reference, primers, parts, parts_ids ); mr_ref.SaveBasesAndQuals( ref_head ); mr_ref.Print( parts_ids, log ); // Align parts to reads. String theCommand = "FastAlignShortReads TARGET=" + fastb_file + " QUERY=" + parts_file + " OUT=" + onreads_qlt_file + " K=8 MAX_ERRORS=64 MAX_INDELS=16"; RunCommandWithLog( theCommand, devnull ); // Reload aligns, and place monomers/terminators. vec<look_align_plus> hits; LoadLookAlignPlus( onreads_qlt_file, hits ); // Filter aligns, and find chains. vec<look_align_plus> chains; AlignsToChains( hits, is_termin, chains ); // Print chains. log << "\nAlignments of monomers/terminators to reads:\n\n"; PrintChains( chains, is_termin, parts_ids, log ); // Turn chains in CMonoReps. CMonoRep mr_fw1( "fw1", &log ); mr_fw1.SetFromHits( chains, parts, rbases[0], rquals[0], 0, false ); mr_fw1.VerbosePrint( parts_ids, parts, vis_out ); CMonoRep mr_fw2( "fw2", &log ); if ( rbases.size( ) > 2 ) { mr_fw2.SetFromHits( chains, parts, rbases[2], rquals[2], 2, false ); mr_fw2.VerbosePrint( parts_ids, parts, vis_out ); } CMonoRep mr_rc( "rc", &log ); mr_rc.SetFromHits( chains, parts, rbases[1], rquals[1], 1, true ); mr_rc.VerbosePrint( parts_ids, parts, vis_out ); // Remove nasty reads, if possible. if ( mr_fw1.IsAwful( ) ) { log << "\nWarning: fw1 is awful, discarding it" << endl; mr_fw1.Clear( ); } if ( mr_fw2.IsAwful( ) ) { log << "\nWarning: fw2 is awful, discarding it" << endl; mr_fw2.Clear( ); } if ( mr_rc.IsAwful( ) ) { log << "\nWarning: rc is awful, discarding it" << endl; mr_rc.Clear( ); } // Merge chains (build draft consensus). CMonoRep mr_consensus( "consensus", &log ); bool ok = false; if ( rbases.size( ) < 3 ) { ok = mr_consensus.Merge( mr_fw1, mr_rc ); mr_consensus.Print( parts_ids, log ); } else { int off_12 = 0; int mat_12 = 0; int mis_12 = 0; bool ok_12 = Offset( mr_fw1, mr_fw2, off_12, 0, &mat_12, &mis_12 ); int off_1r = 0; int mat_1r = 0; int mis_1r = 0; bool ok_1r = Offset( mr_fw1, mr_rc, off_1r, 0, &mat_1r, &mis_1r ); // Decide if we first merge fw1-fw, or fw1-rc. HEURISTICS embedded here! int len_12 = mat_12 + mis_12; bool poor_12 = ( (!ok_12) || ( len_12 < 3 && mis_12 > 0 ) ); bool good_1r = ( ok_1r && mat_1r >=2 && mis_1r < 1 ) || ( ok_1r && mat_1r >=3 && mis_1r < 2 ); // Merge fw1-rc first, and then add fw2. if ( poor_12 && good_1r ) { CMonoRep mr_inter( "inter", &log ); ok = mr_inter.Merge( mr_fw1, mr_rc ); mr_inter.Print( parts_ids, log ); if ( ok ) ok = mr_consensus.Merge( mr_inter, mr_fw2 ); mr_consensus.Print( parts_ids, log); } // Merge fw1-fw2 first, and then add rc. else { CMonoRep mr_inter( "inter", &log ); ok = mr_inter.Merge( mr_fw1, mr_fw2 ); mr_inter.Print( parts_ids, log ); if ( ok ) ok = mr_consensus.Merge( mr_inter, mr_rc ); mr_consensus.Print( parts_ids, log); } } if ( ! ok ) { log << "\nFATAL ERROR: merging failed" << endl; PrintErrorCsvLine( csvline_file, prod_name, reference ); return; } // Refine consensus. { mr_consensus.Refine( mr_fw1, mr_fw2, mr_rc, consensus_head ); mr_consensus.SaveBasesAndQuals( consensus_head ); theCommand = "FastAlignShortReads TARGET=" + cbases_file + " QUERY=" + parts_file + " OUT=" + onconsensus_qlt_file + " K=8 MAX_ERRORS=64 MAX_INDELS=16"; RunCommandWithLog( theCommand, devnull ); bvec cbases = mr_consensus.Bases( ); qvec cquals = mr_consensus.Quals( ); vec<look_align_plus> hits; LoadLookAlignPlus( onconsensus_qlt_file, hits ); vec<look_align_plus> chains; AlignsToChains( hits, is_termin, chains ); mr_consensus.SetFromHits( chains, parts, cbases, cquals, 0, false ); } // Evaluate on reference. log << "\n"; mr_consensus.EvalOnRef( mr_ref, parts_ids, prod_name, csvline_file, vis_out ); // Close streams. vis_out.close( ); log.close( ); } /** * ValidateTALENs * * Merge the two (or three) reads sequenced from a TALEN product, and * validate the consensus against a set of given parts. * * INPUT * * <AB1_DIR>: dir with the .ab1 files (traces). These are converted * into .fasta and .qual by the io-lib utilities extract_seq and * extract_qual. NOTE: the assumption is that there are two * paired reads for each product, with names <name>-F1.ab1 and * <name>-R1.ab1. <name> must be unique (two different products * must have different <name>s), and it is always assumed that F1 * is the fw read, and that R1 is the rc read. Optionally, a * third (fw) read can be added to the set, and this must be * called <name>-F2.ab1. * * <PARTS_DIR>: dir with the fasta of the monomers (and terminators) * used to construct (assemble) the TALENs. These must end with * ".fasta". * * <PRIMERS_FASTA>: fasta file with the 4 bases primers. * * <REF>: flat file with references (in monomer space). The file * must contain a list of lines (one per product), each * containing comma separated tag name and monomers, as in: * tale7,NG,HD,NI,NN,NN,HDcseq,NG,HD,NG,NN,NN,NI,NI * NB: the last monomer is assumed to be a terminator, and the * name of the product must match the given <name>. * * <PRODUCT>: if not empty, validate this product only. * * <SKIP>: if not empty, skip selected product. * * <R2>: if true, look for <name>-R2.ab1 reads, rather than * <name>-R1.ab1 (for rc reads only). * * OUTPUT * * <OUT_DIR>: where output will be stored. * * SANTEMP - TODO: * * Improve monomer-based aligner (SmithWaterman) in Validate( ). */ int main( int argc, char *argv[] ) { RunTime( ); BeginCommandArguments; CommandArgument_String( AB1_DIR ); CommandArgument_String( PARTS_DIR ); CommandArgument_String( PRIMERS_FASTA ); CommandArgument_String( OUT_DIR ); CommandArgument_String( REF ); CommandArgument_String_OrDefault( PRODUCT, "" ); CommandArgument_String_OrDefault( SKIP, "" ); CommandArgument_Bool_OrDefault( R2, False ); EndCommandArguments; // Make sure extract_qual and extract_seq are in the path. TestExecutableByWhich( "extract_qual" ); TestExecutableByWhich( "extract_seq" ); // Make output dir and log stream. Mkpath( OUT_DIR ); // Load products and references (the latter only if REF != "skip"). vec<String> prod_names; LoadProducts( AB1_DIR, R2, prod_names, cout ); if ( PRODUCT != "" ) { prod_names.clear( ); prod_names.resize( 1, PRODUCT ); } vec<String> references; if ( ! LoadReferences( REF, prod_names, references, &cout ) ) return 1; // Exit on failure! // Load parts, and parts ids (used to tag terminators). String parts_file = LoadParts( PARTS_DIR, &cout ); String parts_ids_file = parts_file.SafeBefore( ".fastb" ) + ".ids"; if ( parts_file == "" ) return 1; // Exit on failure! vecbvec parts( parts_file ); vecString parts_ids( parts_ids_file ); { for (size_t ii=0; ii<parts_ids.size( ); ii++) { bool monomer = parts_ids[ii].Contains( "monomer" ); bool termin = parts_ids[ii].Contains( "termin" ); ForceAssert( monomer || termin ); } } // Load primers. vecbvec primers; LoadPrimers( PRIMERS_FASTA, primers ); // Loop over all products. for (size_t prod_id=0; prod_id<prod_names.size( ); prod_id++) { const String &name = prod_names[prod_id]; const String &ref = references[prod_id]; if ( PRODUCT != "" && name != PRODUCT ) continue; if ( SKIP != "" && name == SKIP ) continue; cout << Date( ) << ": validating " << name << endl; Validate(AB1_DIR,OUT_DIR,parts_file,name,ref,primers,parts,parts_ids,R2); } cout << endl; // Done. cout << Date( ) << ": ValidateTALENs done" << endl; }
0c5b56db7eaaadb07ccadb27ede134e58328f5aa
0c67576053f75679bca0162ec0f644f3659dc4fc
/RA_TempSensor/RA_TempSensor.h
70e75b7a12bc90dc23dd1202c926bc626021ce52
[]
no_license
mjpelmear/Libraries
8942ee36aacaf51030036ce3828b0391e2d13178
bf32c5ecffb22711c2028d38b79ee690f672e787
refs/heads/master
2021-01-18T06:47:59.068524
2013-05-10T01:51:47
2013-05-10T01:51:47
9,928,435
1
0
null
null
null
null
UTF-8
C++
false
false
1,045
h
RA_TempSensor.h
/* * Copyright 2010 Reef Angel / Roberto Imai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Updated by: Curt Binder * Updates Released under Apache License, Version 2.0 */ #ifndef __RA_TEMPSENSOR_H__ #define __RA_TEMPSENSOR_H__ #include <Globals.h> class RA_TempSensorClass { public: RA_TempSensorClass(); void Init(); void RequestConversion(); int ReadTemperature(byte addr[8]); void SendRequest(byte addr[8]); byte addrT1[8]; byte addrT2[8]; byte addrT3[8]; byte unit; }; #endif // __RA_TEMPSENSOR_H__
3159c68d4f993f97c2f56614b55c30d28469bfa1
9f1fa0a8259aebe001d1f2a3591963e200c91ff8
/Windows/Windows_Print.cpp
481ff0caeba72bcd91f1ce870f2c945b59423a46
[ "Zlib" ]
permissive
tringi/emphasize
0e95a697d69c5a580a5b7196fe1f87e1731977b9
ad017ec3e7a4f03267943ccfa3b9a4fead4a5930
refs/heads/master
2022-06-30T08:20:00.258569
2022-06-17T18:45:19
2022-06-17T18:45:19
98,049,754
1
0
null
null
null
null
MacCentralEurope
C++
false
false
130,193
cpp
Windows_Print.cpp
#ifndef NOMINMAX #define NOMINMAX #endif #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #include "Windows_Print.hpp" /* Windows Print // Windows_Print.cpp // // Author: Jan Ringos, http://Tringi.TrimCore.cz, jan@ringos.cz // Version: 1.9 // // Changelog: // 18.05.2016 - initial version */ #include <cstdio> #include <cmath> #include <cwchar> #include <cwctype> #include <cstring> #include <algorithm> #include "../Resources/Resources_String.hpp" #include "../Resources/Resources_VersionInfo.hpp" #include "../Resources/Resources_ErrorMessage.hpp" static_assert (sizeof (wchar_t) == sizeof (char16_t), "_WIN32/64 ABI required"); static_assert (sizeof (int) == sizeof (long), "LLP64 ABI required"); #ifdef __GNUC__ static_assert (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, "Little endian platform required"); #else static_assert (REG_DWORD == REG_DWORD_LITTLE_ENDIAN, "Little endian platform required"); #endif #ifndef UNICODE #error "Windows::Print use without UNICODE defined is not supported!" #endif namespace ext { template <typename T, typename U, unsigned long long N> bool exists_in (T (&arr) [N], U c) { for (auto a : arr) { if (a == c) return true; }; return false; }; }; namespace { class Input { protected: const wchar_t * format; const wchar_t * const end; std::va_list va; wchar_t temporary_format [48]; // for cleaned string struct Conversion { public: const wchar_t * begin; const wchar_t * end; const wchar_t * spec; const wchar_t * spec_end; wchar_t letter; unsigned short stars; int star [2]; // max supported stars now public: Conversion (const wchar_t * begin = nullptr, const wchar_t * end = nullptr, const wchar_t * sbegin = nullptr, const wchar_t * send = nullptr) : begin (begin), end (end), spec (sbegin), spec_end (send), letter (end ? *(end - 1) : L'\0'), stars (0) {}; Conversion (const Conversion &) = default; public: std::size_t count (wchar_t); bool contains (wchar_t);// __attribute__((pure)); template <unsigned N> bool any_of (const wchar_t (&) [N]); template <unsigned N> bool contains (const wchar_t (&) [N]); int initstars (std::va_list &); int precision (int = 6); int width (int = 0); unsigned int resource_string_base (unsigned int = 0u); } conversion; public: explicit Input (unsigned int, std::va_list, unsigned int = 0u); explicit Input (const wchar_t *, std::va_list, unsigned int = 0u); public: Input (const Input &) = default; enum CleanMode : unsigned int { NormalClean = 0, RemoveBigLongClean = 1, ChangeLongLongToI64Clean = 2, ForceNumbersToStarsClean = 4, }; const wchar_t * next () const; static Conversion BreakConversion (const wchar_t * format); wchar_t * CleanConversion (unsigned int = NormalClean); const wchar_t * GetCurrentFormatPointer () const { return this->format; }; }; class Memory { private: HANDLE heap; void * data; std::size_t size; // HeapSize? public: Memory () : heap (GetProcessHeap ()), data (nullptr), size (0u) {}; ~Memory () { if (this->size) { HeapFree (this->heap, 0, this->data); }; }; bool Resize (std::size_t n) { if (this->size) { if (auto p = HeapReAlloc (this->heap, 0, this->data, n)) { this->data = p; this->size = n; return true; }; } else { if ((this->data = HeapAlloc (this->heap, 0, n))) { this->size = n; return true; }; }; // GetLastError returns ERROR_NOT_ENOUGH_MEMORY at this point // but it's documented NOT to, so better be safe and set it SetLastError (ERROR_NOT_ENOUGH_MEMORY); return false; }; bool Ensure (std::size_t n) { if (n > this->size) { return this->Resize (n); } else return true; }; std::size_t Size () const { return this->size; }; unsigned char * Data () const { return static_cast <unsigned char *> (this->data); }; private: Memory (const Memory &) = delete; Memory & operator = (const Memory &) = delete; }; class Output { public: std::size_t n_out = 0; public: virtual ~Output () = 0; virtual bool String (const wchar_t *, std::size_t) = 0; virtual bool Repeat (wchar_t, std::size_t); virtual bool IsConsole (CONSOLE_SCREEN_BUFFER_INFO *); virtual void MoveCursor (unsigned short, unsigned short); }; Output::~Output () { }; class OutputConsole : public Output { private: HANDLE handle; public: OutputConsole (HANDLE h) : handle (h) {}; virtual bool String (const wchar_t *, std::size_t) override; virtual bool IsConsole (CONSOLE_SCREEN_BUFFER_INFO *) override; virtual void MoveCursor (unsigned short, unsigned short) override; }; class OutputHandle : public Output { private: Memory memory; HANDLE handle; UINT codepage; public: OutputHandle (HANDLE h, UINT cp) : handle (h), codepage (cp) {}; virtual bool String (const wchar_t *, std::size_t) override; }; class OutputBuffer : public Output { private: unsigned char * buffer; std::size_t size; unsigned int codepage; public: OutputBuffer (void * buffer, std::size_t size, unsigned int cp) : buffer (static_cast <unsigned char *> (buffer)), size (NulTerminatorSpace (cp, size)), codepage (cp) {}; virtual ~OutputBuffer () override { std::memset (this->buffer, 0, NulTerminatorLength (codepage)); }; virtual bool String (const wchar_t *, std::size_t) override; public: static std::size_t NulTerminatorSpace (int cp, std::size_t offset); static std::size_t NulTerminatorLength (int cp); }; Input::Input (unsigned int id, std::va_list va, unsigned int length) : format (Resources::String (id, &length)), end (format + length), va (va) { this->temporary_format [0] = L'%'; return; }; Input::Input (const wchar_t * string, std::va_list va, unsigned int length) : format (reinterpret_cast <unsigned long long> (string) < 0x10000uLL ? Resources::String ((unsigned int) reinterpret_cast <unsigned long long> (string), &length) : string), end (reinterpret_cast <unsigned long long> (string) < 0x10000uLL ? string + length : string + std::wcslen (string)), va (va) { this->temporary_format [0] = L'%'; return; }; class Encoder { private: const wchar_t * const string; std::size_t const length; unsigned int const codepage; public: std::size_t mutable encoded; public: Encoder (unsigned int cp, const wchar_t * string, std::size_t length) : string (string), length (length), codepage (cp), encoded (0u) {}; bool Encode (unsigned char *& buffer, std::size_t & max) const; std::size_t Size () const; // in bytes }; // Remaining letters that can be used as modifiers are: // - H, J, N, O, R, w, W static const char proprietary_modifiers [] = { 'B', // byte (format of integers, pointers, ...) 'b', // byte (format of pointers, ...) 'k', // kernel error code (hexa lowercase) 'K', // kernel error code (hexa uppercase) 'r', // loaded from resources 'R', // 'U', // Unicode (symbols) or User 'v', // version info of current module 'V', // version info 'Q', // formatted for visual quality '?', // '$', // localized currency }; static const char standard_modifiers [] = { 'h', // standard - half precision (or hh - byte) 'I', // windows - as in 'I64' 'j', // standard - intmax_t 'l', // standard - long (or ll - long long) 'L', // standard - long long (long double) 'q', // standard - long long 't', // standard - ptrdiff_t 'z', // standard - size_t }; const wchar_t * find_closing_bracket (const wchar_t * p) { auto nesting = 0u; while (true) { switch (*p) { case L'\0': return nullptr; case L'[': ++nesting; break; case L']': if (!nesting--) return p; }; ++p; }; }; Input::Conversion Input::BreakConversion (const wchar_t * format) { const wchar_t * p = format; const wchar_t * spec = nullptr; const wchar_t * send = nullptr; while (true) { auto c = *p++; // ASCII letter terminates convention // - unless it's one of modifiers listed below if ((c >= L'a' && c <= L'z') || (c >= L'A' && c <= L'Z')) { if (ext::exists_in (standard_modifiers, c)) continue; if (ext::exists_in (proprietary_modifiers, c)) continue; return Conversion (format, p, spec, send); } switch (c) { // end of format string // - invalid convention, should be ignored case L'%': case L'\0': return Conversion (format, p); // specification string // - PROPRIETARY extension // - searching for MATCHING bracket! case L'[': spec = p; if ((send = find_closing_bracket (spec)) != nullptr) { p = send; continue; } else return Conversion (format, p); }; }; }; bool IsDigit (wchar_t c) { return c >= L'0' && c <= L'9'; }; wchar_t * Input::CleanConversion (unsigned int mode) { const auto tmplen = sizeof this->temporary_format / sizeof this->temporary_format [0]; // initial char is always '%' character, starting after it // and leaving 4 characters left for optionally adding "*.*" at the end wchar_t * out = &this->temporary_format [1]; wchar_t * end = &this->temporary_format [tmplen - 5u]; auto stars = 0u; struct { const wchar_t * begin; const wchar_t * end; } range [2] = { { this->conversion.begin, this->conversion.spec - 1 }, { this->conversion.spec_end + 1, this->conversion.end } }; if (this->conversion.spec == nullptr) { range [0] .end = this->conversion.end; range [1] .begin = this->conversion.end; }; for (auto r = 0u; r != sizeof range / sizeof range [0]; ++r) { auto in = range [r] .begin; auto ie = range [r] .end; // remove all proprietary modifiers and characters while ((in != ie) && (out != end)) { if (ext::exists_in (proprietary_modifiers, *in)) { ++in; } else { if (mode & RemoveBigLongClean) { if (*in == L'L') { ++in; continue; }; }; if (mode & ChangeLongLongToI64Clean) { if ((in[0] == L'l') && (in[1] == L'l')) { *out++ = L'I'; *out++ = L'6'; *out++ = L'4'; in += 2; continue; }; }; if (mode & ForceNumbersToStarsClean) { if (*in == L'*') { ++stars; } else if (IsDigit (*in)) { if (out == &this->temporary_format [1] || out [-1] != L'*') { *out++ = L'*'; ++stars; }; ++in; continue; }; }; *out++ = *in++; }; }; }; *out = L'\0'; if (mode & ForceNumbersToStarsClean) { switch (stars) { case 0u: std::memmove (&this->temporary_format [4], &this->temporary_format [1], sizeof (wchar_t) * (out - this->temporary_format)); // sizeof (wchar_t) * (tmplen - 5u)); this->temporary_format [1] = L'*'; this->temporary_format [2] = L'.'; this->temporary_format [3] = L'*'; break; case 1u: if (auto pdot = std::wcschr (&this->temporary_format [1], L'.')) { // found ".*" (no other situation can happen) // - shift all 1 character right and prepend '*' std::memmove (pdot + 1, pdot, sizeof (wchar_t) * (out - pdot + 1)); *pdot = L'*'; } else if (auto pstar = std::wcschr (&this->temporary_format [1], L'*')) { // prepend "*." to existing '*' std::memmove (pstar + 2, pstar, sizeof (wchar_t) * (out - pstar + 1)); pstar [0] = L'*'; pstar [1] = L'.'; }; break; }; }; return this->temporary_format; }; class Printer : public Input { public: Printer (Input input, Output & output) : Input (input), output (output) {}; void operator () (); private: Memory memory; Output & output; private: // passing output bool String (const wchar_t *, std::size_t); bool Forward (const wchar_t *, const wchar_t *); bool Forward (wchar_t c) { return this->Repeat (c, 1u); }; bool Repeat (wchar_t character, std::size_t n); // rendering bool Character (); bool String (); bool DecimalInteger (); bool NonDecimalInteger (); bool FloatingPoint (); bool ZeroTermination (bool & terminate); bool DateTime (); bool BinaryData (); bool IPAddress (); // common rendering bool CharacterString (UINT, const void *, const void *); // data prepare bool LoadStringCodePageParameter (UINT &); bool LoadLocalizedConversionParameters (LCID &, DWORD &); std::intmax_t LoadSignedInteger (); std::uintmax_t LoadUnsignedInteger (); bool LoadSpecStringNumber (unsigned int &); template <typename T> void ApplyValueLowercaseHCrop (T &); template <typename T> bool LoadVersionInfoInteger (T &); unsigned long long Float16ToFloat64 (unsigned short); wchar_t ErrorCodeHexadecimal (std::intptr_t, bool); // special rendering bool LocalNumber (const wchar_t *, LCID, DWORD flags, int precision, bool neg); bool LocalCurrency (const wchar_t *, LCID, DWORD flags, int precision, bool neg); // defaults template <typename T, typename... Params> bool DefaultOperation (const wchar_t *, T value, Params... p); public: bool success = true; std::size_t n_ops = 0u; }; const wchar_t * Input::next () const { auto p = this->format; while (p != this->end && *p != L'%') { ++p; }; if (p && *p == L'%') return p; else return nullptr; }; void Printer::operator () () { while (auto p = this->next ()) { this->success &= this->Forward (this->format, p + (p[1] == L'%')); this->format = p + 1; this->conversion = this->BreakConversion (this->format); switch (this->conversion.letter) { case L'c': this->success &= this->Character (); break; case L's': this->success &= this->String (); break; case L'u': case L'i': case L'd': this->success &= this->DecimalInteger (); break; case L'o': case L'x': case L'X': this->success &= this->NonDecimalInteger (); break; case L'f': case L'F': case L'e': case L'E': case L'g': case L'G': case L'a': case L'A': this->success &= this->FloatingPoint (); break; case L'Z': { bool terminate = false; this->success &= this->ZeroTermination (terminate); if (terminate) return; } break; case L'C': // color [irgb:irgb] color on color, numbers case L'W': // window // case L'M': // this->ConsoleModeOperation (convention); break; case L'D': case L'T': this->success &= this->DateTime (); break; case L'p': if (this->conversion.contains (L'B') || this->conversion.contains (L'b')) { this->success &= this->BinaryData (); } else { this->success &= this->DefaultOperation (this->CleanConversion (), va_arg (this->va, void *)); }; break; case L'P': if (this->conversion.contains (L'I')) { this->success &= this->IPAddress (); } else { // this->success &= this->DefaultOperation (this->CleanConversion (), // va_arg (this->va, void *)); }; break; // case L'G': // ?? // TODO: GUID // break; case L'%': break; }; if (!this->success) return; this->format = conversion.end; this->n_ops++; }; // displaying rest of the string this->success &= this->Forward (this->format, this->end); return; }; template <typename T> inline T Swap16 (T v) { #ifdef __GCC__ return __builtin_bswap16 (v); #else return ((v & 0x00ff) << 8) | ((v & 0xff00) >> 8); #endif }; template <typename T> inline T Swap24 (T v) { std::swap <unsigned char> (reinterpret_cast <unsigned char *> (&v) [0], reinterpret_cast <unsigned char *> (&v) [2]); return v; // return ((v & 0x0000ff) << 16) // | ((v & 0x00ff00)) // | ((v & 0xff0000) >> 16); }; template <typename T> inline T Swap32 (T v) { #ifdef __GCC__ return __builtin_bswap32 (v); #else return ((v & 0x000000ff) << 24) | ((v & 0x0000ff00) << 8) | ((v & 0x00ff0000) >> 8) | ((v & 0xff000000) >> 24); #endif }; bool Printer::Character () { // additional star arguments conversion.initstars (this->va); // codepage argument UINT codepage = 0u; this->LoadStringCodePageParameter (codepage); // character value // - relying on little endian architecture here // - converting into string unsigned int c[2] = { va_arg (this->va, unsigned int), 0u }; // EXTENSION: ? = zero prints nothing if (conversion.contains (L'?')) { if (c[0] == 0) { return true; }; }; // codepage-specific switch (codepage) { // drop not-a-characters for UTF-16 and UTF-32 case CP_UTF16: case CP_UTF16_BE: case CP_UTF32: if (c[0] == 0xFFFFu || c[0] == 0xFEFFu || c[0] == 0xFFFEu) return true; break; case CP_UTF32_BE: if (c[0] == 0xFFFF0000u || c[0] == 0xFEFF0000u || c[0] == 0xFFFE0000u) return true; break; // reverse bytes for multibyte character constants // - TODO: MSVC? default: if (c[0] > 0xFFFFFFu) { c[0] = Swap32 (c[0]); } else if (c[0] > 0xFFFFu) { c[0] = Swap24 (c[0]); } else if (c[0] > 0xFFu) { c[0] = Swap16 (c[0]); }; }; // process as string return this->CharacterString (codepage, c, nullptr); }; bool IsBlank (wchar_t c) { return c == L' ' || c == L'\t' || c == L'\r' || c == L'\n' ; }; wchar_t Printer::ErrorCodeHexadecimal (std::intptr_t value, bool signedvalue) { if ((value >= 100000) || (signedvalue && value < -61440)) { if (conversion.contains (L'K')) { return L'X'; } else { return L'x'; }; } else return L'\0'; }; bool Printer::String () { // additional star arguments conversion.initstars (this->va); // additional arguments UINT codepage = 0u; UINT language = 0u; HMODULE module = GetModuleHandle (NULL); if (conversion.contains (L'V') || conversion.contains (L'R')) { // HMODULE is always the first module = va_arg (this->va, HMODULE); } else if (!conversion.contains (L'v') && !conversion.contains (L'r') && !conversion.contains (L'k') && !conversion.contains (L'K')) { // for normal string pointers, convert spec string to codepage this->LoadStringCodePageParameter (codepage); }; // language // - used for resource ID strings // - count of 1 since user might be tempted to write "LL" to request // current language the same as for numeric/currency %f notation if (conversion.count (L'L') == 1u) { language = va_arg (this->va, unsigned int); }; // load the actual parameter // - 'v' and 'V' need to support int/string provided in spec string const void * parameter = nullptr; wchar_t vstringname [20]; wchar_t altnumber [16]; unsigned int altprepare = 0; const wchar_t * alternative = nullptr; const wchar_t * alternative_end = nullptr; if ((conversion.contains (L'v') || conversion.contains (L'V')) && this->conversion.spec != nullptr && this->conversion.spec [0] != L'*') { unsigned int id = 0; if (IsDigit (*this->conversion.spec) && this->LoadSpecStringNumber (id)) { parameter = static_cast <const char *> (0) + id; } else { auto vo = &vstringname [0]; if (std::size_t (this->conversion.spec_end - this->conversion.spec) < (sizeof vstringname / sizeof vstringname [0])) { for (auto p = this->conversion.spec; p != this->conversion.spec_end; ) { *vo++ = *p++; }; }; *vo = L'\0'; parameter = vstringname; }; } else { // for r/R/k/K get alternative string // - if spec == [*] fetch another parameter // - if fetched value is number, get rsrc, otherwise use the ptr // - if spec == [#] render number if (this->conversion.spec != nullptr && (conversion.contains (L'r') || conversion.contains (L'k') || conversion.contains (L'R') || conversion.contains (L'K'))) { if (std::wcsncmp (this->conversion.spec, L"*]", 2) == 0) { auto ap = va_arg (this->va, const wchar_t *); std::size_t aid = reinterpret_cast <const char *> (ap) - static_cast <const char *> (0); if (aid < 65536u) { // load string if alternative parameter is short integer auto length = 0u; if (auto astr = Resources::String (module, (unsigned int) aid, &length, language)) { alternative = astr; alternative_end = astr + length; }; } else { // use the pointer if alternative parameter is pointer alternative = ap; }; } else if (std::wcsncmp (this->conversion.spec, L"#]", 2) == 0) { altprepare = 1; alternative = altnumber; } else if (std::wcsncmp (this->conversion.spec, L"#x]", 3) == 0) { altprepare = 2; alternative = altnumber; } else if (std::wcsncmp (this->conversion.spec, L"#X]", 3) == 0) { altprepare = 3; alternative = altnumber; } else { // otherwise just use the string alternative = this->conversion.spec; alternative_end = this->conversion.spec_end; }; }; // finally the primary string pointer/id last parameter = va_arg (this->va, const void *); }; // everything is loaded as a pointer, get the ID std::size_t string_id = static_cast <const char *> (parameter) - static_cast <const char *> (0); // EXTENSION: ? = zero prints nothing if (conversion.contains (L'?')) { if (parameter == nullptr) { return true; }; }; // prepare alternative string number switch (altprepare) { case 1: _snwprintf (altnumber, sizeof altnumber / sizeof altnumber [0], L"#%u", (unsigned int) string_id); break; case 2: _snwprintf (altnumber, sizeof altnumber / sizeof altnumber [0], L"#%x", (unsigned int) string_id); break; case 3: _snwprintf (altnumber, sizeof altnumber / sizeof altnumber [0], L"#%X", (unsigned int) string_id); break; }; // print if (conversion.contains (L'v') || conversion.contains (L'V')) { Resources::VersionInfo versioninfo (module, language); if (string_id < 65536u) { return this->CharacterString (CP_UTF16, versioninfo [(unsigned int) string_id], nullptr); } else { return this->CharacterString (CP_UTF16, versioninfo [static_cast <const wchar_t *> (parameter)], nullptr); }; } else if (conversion.contains (L'k') || conversion.contains (L'K')) { if (conversion.contains (L'#')) { wchar_t fmt [6]; if (auto c = this->ErrorCodeHexadecimal (string_id, true)) { _snwprintf (fmt, sizeof fmt / sizeof fmt [0], L"0x%%%c", c); } else { fmt [0] = L'%'; fmt [1] = L'd'; fmt [2] = L'\0'; }; wchar_t buffer [20]; auto length = _snwprintf (buffer, sizeof buffer / sizeof buffer [0], fmt, string_id); if (!this->String (buffer, length)) return false; if (!this->String (L": ", 2u)) return false; }; const auto length = 512u; // ??? if (this->memory.Ensure (sizeof (wchar_t) * length)) { auto output = reinterpret_cast <wchar_t *> (this->memory.Data ()); if ((string_id & 0x87FF0000) == MAKE_HRESULT (SEVERITY_ERROR, FACILITY_WIN32)) { string_id = HRESULT_CODE (string_id); } if (auto n = Resources::ErrorMessage (output, length, (unsigned int) string_id, language)) { // rtrim while (n && IsBlank (output [n - 1])) { --n; }; // output return this->CharacterString (CP_UTF16, output, output + n); } else { // display alternative, if any return this->CharacterString (CP_UTF16, alternative, alternative_end); }; } else return false; } else if (conversion.contains (L'r') || conversion.contains (L'R') || string_id < 65536u) { auto length = 0u; auto string_ptr = Resources::String (module, conversion.resource_string_base () + (unsigned int) string_id, &length, language); if (string_ptr) { return this->CharacterString (CP_UTF16, string_ptr, string_ptr + length); } else { return this->CharacterString (CP_UTF16, alternative, alternative_end); }; } else { // TODO: if LoadStringCodePageParameter failed, try detect and skip BOM here return this->CharacterString (codepage, parameter, nullptr); }; }; template <typename T> const T * FindNulTerminator (const void * input) { auto p = static_cast <const T *> (input); while (*p) { ++p; }; return p; }; bool Printer::CharacterString (UINT codepage, const void * input, const void * end) { // for simplicity this check is ommited everywhere else if (!input) return true; // end is nullptr for NUL-terminated strings of unknown charset if (!end) { switch (codepage) { default: end = FindNulTerminator <char> (input); break; case CP_UTF16: case CP_UTF16_BE: end = FindNulTerminator <wchar_t> (input); break; case CP_UTF32: case CP_UTF32_BE: end = FindNulTerminator <unsigned int> (input); break; }; }; // empty string means we are done here if (end == input) return true; // decode const wchar_t * string = nullptr; std::size_t length = 0u; switch (codepage) { default: if ((length = MultiByteToWideChar (codepage, 0u, static_cast <const char *> (input), (int) (static_cast <const char *> (end) - static_cast <const char *> (input)), nullptr, 0))) { if (this->memory.Ensure (sizeof (wchar_t) * length)) { auto output = reinterpret_cast <wchar_t *> (this->memory.Data ()); if (MultiByteToWideChar (codepage, 0u, static_cast <const char *> (input), (int) (static_cast <const char *> (end) - static_cast <const char *> (input)), output, (int) length)) { string = output; }; }; }; break; // case CP_ID5: // break; case CP_UTF16: // this is native string, no conversion string = static_cast <const wchar_t *> (input); length = static_cast <const wchar_t *> (end) - string; break; case CP_UTF16_BE: case CP_UTF32: case CP_UTF32_BE: switch (codepage) { case CP_UTF16_BE: length = static_cast <const wchar_t *> (end) - static_cast <const wchar_t *> (input); break; case CP_UTF32: case CP_UTF32_BE: length = static_cast <const char32_t *> (end) - static_cast <const char32_t *> (input); break; }; // detect supplementary plane characters // - need to be converted to surrogate pairs const auto inlen = length; switch (codepage) { case CP_UTF32: for (std::size_t i = 0u; i != inlen; ++i) { if (static_cast <const char32_t *> (input) [i] >= 65536u) { ++length; }; }; break; case CP_UTF32_BE: for (std::size_t i = 0u; i != inlen; ++i) { if (Swap32 (static_cast <const char32_t *> (input) [i]) >= 65536u) { ++length; }; }; break; }; // allocate resulting string in scratch memory if (this->memory.Ensure (sizeof (wchar_t) * length)) { auto output = reinterpret_cast <wchar_t *> (this->memory.Data ()); // generate native string // - swap bytes for BE UTFs // - split to surrogate pairs for 32-bit UTFs for (std::size_t i = 0u, o = 0u; (i != inlen) && (o != length); ++i) { char32_t c = 0; switch (codepage) { case CP_UTF16_BE: c = Swap16 (static_cast <const wchar_t *> (input) [i]); break; case CP_UTF32_BE: c = Swap32 (static_cast <const char32_t *> (input) [i]); break; case CP_UTF32: c = static_cast <const char32_t *> (input) [i]; break; }; if (c >= 65536u) { if (c < 0x110000u) { // high surrogate pair output [o++] = 0xD800 | (wchar_t) ((c - 0x10000u) >> 10u); // low surrogate pair output [o++] = 0xDC00 | (wchar_t) ((c - 0x10000u) & 0x03FFu); } else { // outside supplementary planes // - render as not-a-character output [o++] = 0xFFFD; --length; }; } else { output [o++] = (wchar_t) c; }; }; // done string = output; }; break; }; // render string/length if (string) { auto elipsis = L'\0'; auto elipsis_length = 0u; // if precision entry is provided, it's used as char count limit std::size_t maxlen = conversion.precision (-1); if (maxlen != std::size_t (-1)) { // count surrogate pair as single character for string length purposes // - OPTIMIZE: in some cases can be computed above already for (std::size_t i = 0u; i != length; ++i) { if (string [i] >= 0xD800 && string [i] < 0xDC00) { ++maxlen; }; }; // apply limit if (length > maxlen) { length = maxlen; // three dots ... request truncation and appending ... // - TODO: attempt word truncation, search space? // if there is no space, search for spacing unicodes if (conversion.contains (L"...")) { if (conversion.contains (L'U')) { if (length > 2) { elipsis = L'\x2026'; elipsis_length = 1; length = maxlen - elipsis_length; }; } else { if (length > 2) { elipsis = L'.'; elipsis_length = 3; length = maxlen - elipsis_length; }; }; }; }; }; auto width = conversion.width (0); if (conversion.contains (L'-')) { width = -width; }; // when width is positive and longer than length // then prefix with enough spaces if (width > 0 && width > length) { if (!this->Repeat (L' ', width - length)) return false; }; if (this->String (string, length)) { // append elipsis, if any if (!this->Repeat (elipsis, elipsis_length)) return false; // when width is negative and longer than length // then append enough spaces if (width < 0 && -width > length) { if (!this->Repeat (L' ', -width - length)) return false; }; return true; }; }; return false; }; wchar_t * WcsNChr (wchar_t * s, std::size_t n, wchar_t c) { if (s) { while (n--) { if (*s == c) return s; else ++s; }; }; return nullptr; }; const wchar_t * WcsNChr (const wchar_t * s, std::size_t n, wchar_t c) { if (s) { while (n--) { if (*s == c) return s; else ++s; }; }; return nullptr; }; const wchar_t * GetBytesLocalizedString (unsigned int * length, LCID language) { if (language == LOCALE_INVARIANT) return nullptr; if (auto hShell32 = GetModuleHandleW (L"SHELL32")) { return Resources::String (hShell32, 4113, length, (unsigned short) language); } else { return nullptr; }; }; bool Printer::DecimalInteger () { // additional star arguments conversion.initstars (this->va); // for L$ and LL, eat another argument for 'language' (if present) // - language/flags are for GetCurrencyFormat/GetNumberFormat DWORD flags = 0; LCID language = LOCALE_USER_DEFAULT; // Resources::GetPreferredLanguage () ??? this->LoadLocalizedConversionParameters (language, flags); // value // - loading below relies on little endian architecture std::intmax_t value; bool signedvalue; if (this->LoadVersionInfoInteger (value)) { signedvalue = false; } else switch (conversion.letter) { case L'd': case L'i': value = this->LoadSignedInteger (); signedvalue = true; break; case L'u': default: value = this->LoadUnsignedInteger (); signedvalue = false; break; }; // EXTENSION: restrict size: h (short), hh (char), hhh (nibble), hhhh (bool) this->ApplyValueLowercaseHCrop (value); // EXTENSION: ? = zero prints nothing if (conversion.contains (L'?')) { if (value == 0) { return true; }; }; // EXTENSION: $ = displays monetary value if (conversion.contains (L'$')) { wchar_t number [22]; if (_snwprintf (number, sizeof number / sizeof number [0], signedvalue ? L"%I64d" : L"%I64u", value)) { // precision of 2 is typical for currency auto precision = std::abs (conversion.precision (2)); return this->LocalCurrency (number, language, flags, precision, signedvalue ? (value < 0) : false); }; }; // EXTENSION: B = size information if (conversion.contains (L'B')) { // value unsigned 64-bit tops at 16 EB - 1 static const char prefix [] = { 'k', 'M', 'G', 'T', 'P', 'E' }; static const char c0x20 = ' '; static const char cB = 'B'; static const char cK = 'K'; static const char ci = 'i'; // Example, for Czech locale // 0 ... 921 - 921 bajtý // 1000 ... 10239 - 0,9 kB ... 9,9 kB // 10240 ... 1023999 - 10 kB ... 999 kB // 1024000 ... 1048575 - 0,9 MB ... 1,0 MB if (((signedvalue && (std::abs (value) < 922)) || (!signedvalue && (((std::uintmax_t) value) < 922uLL)))) { // Attempt to use "%s bytes" (bytes) string auto byteslength = 0u; auto bytesformat = GetBytesLocalizedString (&byteslength, language); auto bytesplaceholder = WcsNChr (bytesformat, byteslength, L'%'); // First part of the string, if any if (bytesplaceholder && bytesplaceholder != bytesformat) { if (!this->Forward (bytesformat, bytesplaceholder)) return false; }; // The value wchar_t number [4]; if (_snwprintf (number, sizeof number / sizeof number [0], signedvalue ? L"%I64d" : L"%I64u", value)) { if (!this->LocalNumber (number, language, flags, 0, signedvalue ? (value < 0) : false)) return false; }; if (!this->Forward (c0x20)) return false; // Trailing part of the 'bytes' string if (bytesformat) { if (bytesplaceholder) { auto traillength = byteslength - (bytesplaceholder - bytesformat); if (auto trail = WcsNChr (bytesplaceholder, traillength, L' ')) { return this->String (trail + 1, byteslength - (trail - bytesformat) - 1); } else if (traillength > 2) { return this->String (trail + 2, traillength - 2); } else return true; } else return this->String (bytesformat, byteslength); } else return this->Forward (cB); } else { auto v = 0.0; if (signedvalue) { v = (double) value; } else { v = (double) (std::uintmax_t) value; }; auto m = -1; while (std::abs (v) >= 922) { v /= 1024.0; m++; }; wchar_t number [16]; if (v < 10.0) { if (_snwprintf (number, sizeof number / sizeof number [0], L"%.1f", v)) { if (!this->LocalNumber (number, language, flags, 1, false)) return false; }; } else { if (_snwprintf (number, sizeof number / sizeof number [0], L"%.0f", v)) { if (!this->LocalNumber (number, language, flags, 0, false)) return false; }; }; // Units if (!this->Forward (c0x20)) return false; if (conversion.contains (L'#')) { return this->Forward (m ? prefix [m] : cK) && this->Forward (ci) && this->Forward (cB); } else return this->Forward (prefix [m]) && this->Forward (cB); }; }; // EXTENSION: L = displays value in locale-specific manner if (conversion.contains (L'L')) { wchar_t number [22]; if (_snwprintf (number, sizeof number / sizeof number [0], signedvalue ? L"%I64d" : L"%I64u", value)) { return this->LocalNumber (number, language, flags, 0, signedvalue ? (value < 0) : false); }; }; // following conversions need clean format string auto fmt = this->CleanConversion (ChangeLongLongToI64Clean); // EXTENSION: k/K = error code formatting // - NOTE: mind the continuation to standard rendering! if (conversion.contains (L'k') || conversion.contains (L'K')) { if (auto c = this->ErrorCodeHexadecimal (value, signedvalue)) { fmt [std::wcslen (fmt) - 1] = c; if (!this->String (L"0x", 2u)) return false; }; }; // standard rendering switch (conversion.stars) { default: return this->DefaultOperation (fmt, value); case 1: return this->DefaultOperation (fmt, value, conversion.star [0]); case 2: return this->DefaultOperation (fmt, value, conversion.star [0], conversion.star [1]); }; }; bool Printer::NonDecimalInteger () { // additional star arguments conversion.initstars (this->va); // value // - relying on little endian architecture here std::uintmax_t value; if (!this->LoadVersionInfoInteger (value)) { value = this->LoadUnsignedInteger (); }; // EXTENSION: restrict size: h (short), hh (char), hhh (nibble), hhhh (bool) this->ApplyValueLowercaseHCrop (value); // EXTENSION: ? = zero prints nothing if (conversion.contains (L'?')) { if (value == 0) { return true; }; }; // standard rendering auto fmt = this->CleanConversion (ChangeLongLongToI64Clean); switch (conversion.stars) { default: return this->DefaultOperation (fmt, value); case 1: return this->DefaultOperation (fmt, value, conversion.star [0]); case 2: return this->DefaultOperation (fmt, value, conversion.star [0], conversion.star [1]); }; }; bool Printer::FloatingPoint () { // additional star arguments conversion.initstars (this->va); // for L$ and LL, eat another argument for 'language' (if present) // - language/flags are for GetCurrencyFormat/GetNumberFormat const bool decimal = conversion.letter == L'f' || conversion.letter == L'g' || conversion.letter == L'F' || conversion.letter == L'G'; DWORD flags = 0; LCID language = LOCALE_USER_DEFAULT; if (decimal) { this->LoadLocalizedConversionParameters (language, flags); }; // MSVCRT doesn't know that standard 'L' == "long double" // - using 'll' instead because 'L' here means 'local' // - TODO: support 'j' for '128-bit quadruple float' double value; if (conversion.count (L'h')) { auto half = va_arg (this->va, unsigned int); auto converted = this->Float16ToFloat64 (half); std::memcpy (&value, &converted, sizeof value); } else if (conversion.contains (L"ll")) { value = va_arg (this->va, long double); } else { value = va_arg (this->va, double); }; // EXTENSION: ? = displays nothing if NaN if (conversion.contains (L'?')) { if (std::isnan (value)) { return true; }; }; // EXTENSION: U = displays unicode symbol for negative and not finite values if (conversion.contains (L'U')) { if (std::isnan (value)) { return this->String (L"\x00F8", 1u); // TODO: negative NaN? // TODO: NaN payload to string ID conversion? } else if (std::isinf (value)) { if (value > 0.0) { if (conversion.contains (L'+')) { return this->String (L"+\x221E", 2u); } else if (conversion.contains (L' ')) { return this->String (L" \x221E", 2u); } else { return this->String (L"\x221E", 1u); }; } else { return this->String (L"\x2013\x221E", 2u); }; /* } else if (value < 0.0) { value = -value; this->String (L"\x2013", 1u);*/ }; }; if (decimal) { // currency/numeric extensions require finite numbers if (std::isfinite (value)) { // EXTENSION: Q = guess best precision // - precision means number of consequent 0's or 9's concatenated if (conversion.contains (L'Q')) { // default precision is 3 // - 16 is maximum precision for which msvcrt.dll printf can // render fractional part auto precision = std::abs (conversion.precision (3)); if (precision) { if (precision > 16) { precision = 16; }; // render // - cannot use less memory to support large floats if (this->memory.Ensure (384 * sizeof (wchar_t))) { auto number = reinterpret_cast <wchar_t *> (this->memory.Data ()); auto nchars = this->memory.Size () / sizeof (wchar_t); if (_snwprintf (number, nchars, L"%.*f", 316, value)) { // generate needles wchar_t zeros [17]; wchar_t nines [17]; for (auto i = 0; i != precision; ++i) { zeros [i] = L'0'; nines [i] = L'9'; }; zeros [precision] = L'\0'; nines [precision] = L'\0'; // search if (auto pDot = std::wcschr (number, L'.')) { auto pZeros = std::wcsstr (pDot, zeros); auto pNines = std::wcsstr (pDot, nines); // compute distance if (pZeros && pNines) { precision = (int) std::min (pZeros - pDot - 1, pNines - pDot - 1); } else if (pZeros) { precision = (int) (pZeros - pDot) - 1; } else if (pNines) { precision = (int) (pNines - pDot) - 1; }; // when L or LL is present then render as localized number if (conversion.contains (L'L') && !conversion.contains (L'$')) { return this->LocalNumber (number, language, flags, precision, value < 0.0); } else { // otherwise replacing numbers in string by '*' and passing computed precision auto fmt = this->CleanConversion (RemoveBigLongClean | ForceNumbersToStarsClean); return this->DefaultOperation (fmt, value, conversion.width (), precision); }; }; }; }; }; }; // EXTENSION: $ = displays monetary value if (conversion.contains (L'$')) { // format undecorated string for GetCurrencyFormat // - precision of 2 is typical for currency auto precision = conversion.precision (2); // 128 should suffice for readably long currency amounts if (this->memory.Ensure (128 * sizeof (wchar_t))) { auto number = reinterpret_cast <wchar_t *> (this->memory.Data ()); auto nchars = this->memory.Size () / sizeof (wchar_t); if (_snwprintf (number, nchars, L"%.*f", precision, value)) { return this->LocalCurrency (number, language, flags, precision, value < 0.0); }; }; }; // EXTENSION: L = displays value in locale-specific manner if (conversion.contains (L'L')) { // format undecorated string for GetNumberFormat // - precision 6 is specified in standard auto precision = conversion.precision (6); // 316 is length of largest double plus some precission (alloc?) if (this->memory.Ensure (384 * sizeof (wchar_t))) { auto number = reinterpret_cast <wchar_t *> (this->memory.Data ()); auto nchars = this->memory.Size () / sizeof (wchar_t); if (_snwprintf (number, nchars, L"%.*f", precision, value)) { return this->LocalNumber (number, language, flags, precision, value < 0.0); }; }; }; }; }; // standard rendering auto fmt = this->CleanConversion (RemoveBigLongClean); switch (conversion.stars) { default: return this->DefaultOperation (fmt, value); case 1: return this->DefaultOperation (fmt, value, conversion.star [0]); case 2: return this->DefaultOperation (fmt, value, conversion.star [0], conversion.star [1]); }; }; bool Printer::ZeroTermination (bool & terminate) { // value // - relying on little endian architecture here auto value = this->LoadUnsignedInteger (); // EXTENSION: restrict size: h (short), hh (char), hhh (nibble), hhhh (bool) this->ApplyValueLowercaseHCrop (value); // MODIFIER: - means negative logic if (conversion.contains (L'-')) { value = !value; }; // non-zero means terminate string at this point // - displaying spec string if any if (value) { terminate = true; if (this->conversion.spec) return this->Forward (this->conversion.spec, this->conversion.spec_end); }; return true; }; bool Printer::DateTime () { DWORD flags = 0; LCID language; wchar_t * format = nullptr; if (this->conversion.spec) { const auto length = this->conversion.spec_end - this->conversion.spec; if (length == 2u && (this->conversion.spec [0] == 'd' || this->conversion.spec [0] == 'D') && (this->conversion.spec [1] == 'b' || this->conversion.spec [1] == 'B')) { switch (conversion.letter) { case L'D': format = L"yyyy-MM-dd"; break; case L'T': format = L"HH:mm:ss"; break; // TODO: milliseconds? }; } else if (this->memory.Ensure (sizeof (wchar_t) * (length + 1))) { format = reinterpret_cast <wchar_t *> (this->memory.Data ()); std::wcsncpy (format, this->conversion.spec, length); format [length] = L'\0'; } else return false; }; switch (conversion.count (L'L')) { case 0u: language = LOCALE_INVARIANT; break; case 1u: language = LOCALE_USER_DEFAULT; break; default: if (format == nullptr) { flags = LOCALE_NOUSEROVERRIDE; } language = va_arg (this->va, unsigned int); break; }; if (conversion.contains (L'+')) { switch (conversion.letter) { case L'D': flags |= DATE_LONGDATE; break; case L'T': flags |= TIME_FORCE24HOURFORMAT; break; }; }; if (conversion.contains (L'-')) { switch (conversion.letter) { case L'D': flags |= DATE_SHORTDATE; break; case L'T': flags |= TIME_NOSECONDS; break; }; }; // date/time to render // - K - do not load parameter, use system time // - otherwise parameter is either pointer to SYSTEMTIME or NULL // in which case current local time is used SYSTEMTIME st; if (conversion.contains (L'K')) { GetSystemTime (&st); } else { if (auto pst = va_arg (this->va, SYSTEMTIME *)) { st = *pst; } else { GetLocalTime (&st); }; }; // 384 bytes should cover even esoteric date/time formats very well wchar_t output [384]; switch (conversion.letter) { case L'D': if (int length = GetDateFormat (language, flags, &st, format, output, sizeof output / sizeof output [0])) { return this->String (output, length - 1); }; break; case L'T': if (int length = GetTimeFormat (language, flags, &st, format, output, sizeof output / sizeof output [0])) { return this->String (output, length - 1); }; break; }; return false; }; wchar_t NibbleToHex (unsigned char v, wchar_t base = L'A') { if (v < 10) return L'0' + v; else return base + v - 10; }; bool Printer::BinaryData () { // additional star arguments // - width = row length in printed bytes // - precision = bytes grouping conversion.initstars (this->va); // data auto data = va_arg (this->va, const unsigned char *); auto size = va_arg (this->va, std::size_t); // parameters const auto nth = conversion.precision (1); const auto base = conversion.contains (L'B') ? L'A' : L'a'; const auto prefix = L'\''; const auto readable = conversion.contains (L'h'); const auto nice = conversion.contains (L'Q'); auto width = conversion.width (65536); auto leads = 0; auto row = 0; // TODO: specifying width results in 'nice' positioning if (nice) { CONSOLE_SCREEN_BUFFER_INFO info; if (this->output.IsConsole (&info)) { row = info.dwCursorPosition.Y; leads = info.dwCursorPosition.X; if (width == 65536) { width = info.dwSize.X - leads; // columns available if (nth) { width -= ((width / nth) + 2) / 3; // TODO: compute width }; width /= 2; }; }; }; if (width != 65536 && conversion.contains (L'-')) { // set leads to align right }; if (size) { bool first = true; for (std::size_t i = 0u; i != size; ++i, ++data) { if (!first && nth && !(i % nth)) { if (!this->Forward (L' ')) return false; }; if (readable) { if ((*data >= '0' && *data <= '9') || (*data >= 'a' && *data <= 'f') || (*data >= 'A' && *data <= 'F')) { this->Forward (prefix); this->Forward ((wchar_t) *data); } else { this->Forward (NibbleToHex (*data >> 4, base)); this->Forward (NibbleToHex (*data & 0x0F, base)); }; } else { this->Forward (NibbleToHex (*data >> 4, base)); this->Forward (NibbleToHex (*data & 0x0F, base)); }; if (nice && !((i + 1) % width)) { this->output.MoveCursor (leads, ++row); first = true; } else first = false; }; }; return true; }; #ifdef _MSC_VER uint32_t __inline ctz (uint32_t value) { DWORD trailing_zero = 0; if (_BitScanForward (&trailing_zero, value)) { return trailing_zero; } else { return 32; } } #elif __GNUC__ static uint32_t ctz (uint32_t x) { return __builtin_ctz (x); }; #else static uint32_t clz (uint32_t x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); return 32 - popcnt (x); }; static uint32_t ctz (uint32_t x) { return popcnt ((x & -x) - 1); }; #endif bool longest_set_bits_string_in_byte (unsigned int mask, int & _o, int & _n) { unsigned int ii = 0; unsigned int nn = 0; while (mask) { ii = ctz (mask); ++nn; mask &= (mask >> 1u); }; if (nn > 1u) { _o = ii; _n = nn; return true; } else return false; }; bool Printer::IPAddress () { auto address = va_arg (this->va, const sockaddr_storage *); bool decorate6 = true; bool showport = true; /*switch (ss->ss_family) { case AF_INET: family = ss->ss_family; in4 = &reinterpret_cast <const sockaddr_in *> (ss)->sin_addr; port = bswap16 (reinterpret_cast <const sockaddr_in *> (ss)->sin_port); break; case AF_INET6: family = ss->ss_family; in6 = &reinterpret_cast <const sockaddr_in6 *> (ss)->sin6_addr; port = bswap16 (reinterpret_cast <const sockaddr_in6 *> (ss)->sin6_port); break; };*/ wchar_t string [64]; wchar_t * p = string; switch (address->ss_family) { default: string [0] = 0; // symbol??? break; case AF_INET: /* switch (special) { case 2: snwprintf (string, 40u, L"%u.%u%s", in4->s_net, 65536 * in4->s_host + 256 * in4->s_lh + in4->s_impno, portsz); break; case 1: snwprintf (string, 40u, L"%u.%u.%u%s", in4->s_net, in4->s_host, 256 * in4->s_lh + in4->s_impno, portsz); break; default:*/ _snwprintf (p, sizeof string / sizeof string [0] - 8, L"%u.%u.%u.%u", reinterpret_cast <const sockaddr_in *> (address)->sin_addr.s_net, reinterpret_cast <const sockaddr_in *> (address)->sin_addr.s_host, reinterpret_cast <const sockaddr_in *> (address)->sin_addr.s_lh, reinterpret_cast <const sockaddr_in *> (address)->sin_addr.s_impno); if (auto port = Swap16 (reinterpret_cast <const sockaddr_in *> (address)->sin_port)) { _snwprintf (p + std::wcslen (p), 8, L":%u", port); }; /* break; };*/ break; case AF_INET6: decorate6 = (reinterpret_cast <const sockaddr_in6 *> (address)->sin6_port != 0); int o = 0; // index of first shortened part int n = 0; // number of shortened parts unsigned char mask = 0u; auto w = reinterpret_cast <const unsigned short *> (&reinterpret_cast <const sockaddr_in6 *> (address)->sin6_addr); for (unsigned int j = 0u; j != 8u; ++j) if (!w [j]) mask |= 1 << j; int i = 0; if (decorate6) { *p++ = L'['; }; if (longest_set_bits_string_in_byte (mask, o, n)) { for (; i != o; ++i) { if (i) { *p++ = L':'; }; _snwprintf (p, 5, L"%x", Swap16 (w [i])); while (*p) ++p; }; *p++ = L':'; *p++ = L':'; i += n; }; for (; i != 8; ++i) { _snwprintf (p, 5, L"%x", Swap16 (w [i])); while (*p) ++p; if (i != 7) { *p++ = L':'; }; }; if (decorate6) { *p++ = L']'; }; if (decorate6) { // TODO: separate parameter for port _snwprintf (p, 7, L":%u", Swap16 (reinterpret_cast <const sockaddr_in *> (address)->sin_port)); }; break; }; // unsigned int port; this->String (string, std::wcslen (string)); return true; }; bool CheckCodePageStringPrefix (const wchar_t * generalized, const wchar_t * prefix, UINT & codepage, unsigned int offset = 0u) { auto length = std::wcslen (prefix); if (std::wcsncmp (generalized, prefix, length) == 0) { if (IsDigit (generalized [length])) { codepage = offset + std::wcstoul (&generalized [length], nullptr, 10); return true; }; }; return false; }; bool ParseCodePageString (const wchar_t * sp, const wchar_t * se, UINT & codepage) { wchar_t generalized [14]; wchar_t * gp = &generalized [0]; if (se == nullptr) { se = sp + std::wcslen (sp); }; // generalize the string while ((sp != se) && (gp != &generalized [sizeof generalized / sizeof generalized [0]])) { switch (auto c = *sp++) { case L'-': case L'_': case L' ': case L'.': case L'/': break; default: if (c >= L'A' && c <= L'Z') { *gp++ = c - L'A' + L'a'; } else { *gp++ = c; } break; }; }; *gp = L'\0'; // find meaningful code page prefix if (IsDigit (generalized [0])) { codepage = std::wcstoul (generalized, nullptr, 10); return true; }; if (CheckCodePageStringPrefix (generalized, L"cp", codepage) || CheckCodePageStringPrefix (generalized, L"dos", codepage) || CheckCodePageStringPrefix (generalized, L"xcp", codepage) || CheckCodePageStringPrefix (generalized, L"windows", codepage) || CheckCodePageStringPrefix (generalized, L"iso8859", codepage, 28590)) return true; if (std::wcsncmp (generalized, L"ibm", 3) == 0) { if (auto cp = std::wcstoul (&generalized [3], nullptr, 10)) { if ((cp >= 273 && cp < 300) || (cp >= 420 && cp < 425)) { codepage = 20000 + cp; } else switch (cp) { case 871: case 880: case 905: case 924: codepage = 20000 + cp; break; default: codepage = cp; break; }; return true; }; }; if (std::wcsncmp (generalized, L"utf", 3) == 0) { // TODO: check for BOM wchar_t * endianess = nullptr; switch (std::wcstoul (&generalized [3], &endianess, 10)) { case 7: codepage = CP_UTF7; return true; case 8: codepage = CP_UTF8; return true; case 16: if (*endianess != L'b') codepage = CP_UTF16; else codepage = CP_UTF16_BE; return true; case 32: if (*endianess != L'b') codepage = CP_UTF32; else codepage = CP_UTF32_BE; return true; }; }; if (std::wcscmp (generalized, L"usascii") == 0) { codepage = 20127; return true; }; if (std::wcscmp (generalized, L"xebcdic") == 0) { codepage = 20833; return true; }; if (std::wcscmp (generalized, L"koi8r") == 0) { codepage = 20866; return true; }; if (std::wcscmp (generalized, L"koi8u") == 0) { codepage = 21866; return true; }; if (std::wcscmp (generalized, L"big5") == 0) { codepage = 950; return true; }; if (std::wcscmp (generalized, L"eucjp") == 0) { codepage = 20932; return true; }; if (std::wcscmp (generalized, L"gb2312") == 0) { codepage = 936; return true; }; // TODO: 'id5' // TODO: 'base64' return false; }; bool Printer::LoadSpecStringNumber (unsigned int & result) { if (this->conversion.spec) { switch (this->conversion.spec [0]) { // decimal or hexadecimal number as provided case L'0': switch (this->conversion.spec [1]) { case L'x': case L'X': result = std::wcstoul (&this->conversion.spec [2], nullptr, 16); return true; default: ; // continues to base-10 (explicitely no octal support)... }; case L'1': case L'2': case L'3': case L'4': case L'5': case L'6': case L'7': case L'8': case L'9': result = std::wcstoul (this->conversion.spec, nullptr, 10); return true; }; }; return false; }; bool Printer::LoadStringCodePageParameter (UINT & codepage) { if (this->conversion.spec) { switch (this->conversion.spec [0]) { // * - fetch from variable arguments case L'*': { auto parameter = va_arg (this->va, const wchar_t *); auto numeric = reinterpret_cast <const char *> (parameter) - static_cast <const char *> (0); if ((std::size_t) numeric >= 65536u) { if (ParseCodePageString (parameter, nullptr, codepage)) return true; } else { codepage = (unsigned int) numeric; return true; }; } break; // decimal or hexadecimal number as provided case L'0': case L'1': case L'2': case L'3': case L'4': case L'5': case L'6': case L'7': case L'8': case L'9': return this->LoadSpecStringNumber (codepage); // string name // - generalized: lowercase, removed dashes, underscores, spaces and dots default: if (ParseCodePageString (this->conversion.spec, this->conversion.spec_end, codepage)) return true; }; }; // no explicit codepage, use defaults if (this->conversion.contains (L'h')) { codepage = CP_ACP; return true; } else if (this->conversion.contains (L"ll")) { codepage = CP_UTF32; return true; } else { codepage = CP_UTF16; return false; }; }; bool Printer::LoadLocalizedConversionParameters (LCID & language, DWORD & flags) { if (conversion.contains (L'$')) { if (conversion.count (L'L') == 1) { // currency formatting, but not local (i.e. by provided LCID) language = va_arg (this->va, unsigned int); flags = LOCALE_NOUSEROVERRIDE; return true; }; } else { if (conversion.count (L'L') == 2) { // localized number, but not local (i.e. localized by LCID) language = va_arg (this->va, unsigned int); flags = LOCALE_NOUSEROVERRIDE; return true; }; }; return false; }; std::intmax_t Printer::LoadSignedInteger () { if (conversion.contains (L"ll")) { return va_arg (this->va, long long); // 64 } else if (conversion.contains (L'j')) { return va_arg (this->va, std::intmax_t); // 64 } else if (conversion.contains (L't')) { return va_arg (this->va, std::ptrdiff_t); // 64/32 } else if (conversion.contains (L'z')) { return va_arg (this->va, std::size_t); // 64/32 } else if (conversion.contains (L'l')) { return va_arg (this->va, long); // 32 } else return va_arg (this->va, int); // 32 }; std::uintmax_t Printer::LoadUnsignedInteger () { if (conversion.contains (L"ll")) { return va_arg (this->va, unsigned long long); // 64 } else if (conversion.contains (L'j')) { return va_arg (this->va, std::uintmax_t); // 64 } else if (conversion.contains (L't')) { return va_arg (this->va, std::ptrdiff_t); // 64/32 } else if (conversion.contains (L'z')) { return va_arg (this->va, std::size_t); // 64/32 } else if (conversion.contains (L'l')) { return va_arg (this->va, unsigned long); // 32 } else return va_arg (this->va, unsigned int); // 32 }; template <typename T> unsigned short VersionInfoValue (const T & info, int index) { switch (index) { case 0: case '0': case 'M': case 'm': return info.major; case 1: case '1': case 'N': case 'n': return info.minor; case 2: case '2': case 'R': case 'r': return info.release; case 3: case '3': case 'B': case 'b': return info.build; default: return 0xFFFF; }; }; unsigned short VersionInfoValue (HMODULE module, bool product, int index) { // OPTIMIZE: cache 'versioninfo' for given 'module' in 'Printer' Resources::VersionInfo vi (module); if (product) { return VersionInfoValue (vi.info->product, index); } else return VersionInfoValue (vi.info->file, index); }; unsigned short VersionInfoValue (HMODULE module, const char * p) { switch (p [0]) { // product case 'p': case 'P': switch (p [1]) { // wchar_t string? try third byte case '\0': return VersionInfoValue (module, true, p [2]); // char string, use second byte default: return VersionInfoValue (module, true, p [1]); }; // file case 'f': case 'F': switch (p [1]) { // wchar_t string? try third byte case '\0': return VersionInfoValue (module, false, p [2]); // char string, use second byte default: return VersionInfoValue (module, false, p [1]); }; default: return VersionInfoValue (module, false, p [0]); }; }; template <typename T> bool Printer::LoadVersionInfoInteger (T & value) { // module is always the first HMODULE module; if (conversion.contains (L'V')) { module = va_arg (this->va, HMODULE); } else if (conversion.contains (L'v')) { module = GetModuleHandle (NULL); } else return false; // using spec string if any if (conversion.spec != nullptr) { value = VersionInfoValue (module, reinterpret_cast <const char *> (conversion.spec)); return true; } else { auto parameter = va_arg (this->va, const char *); auto integer = parameter - static_cast <const char *> (0); if (integer > 65535) { // string pointer value = VersionInfoValue (module, parameter); return true; } else { // character or two-character constant // - if 'pX' or 'PX' then read product info, otherwise file info const auto index = integer & 0xFF; const auto product = (((integer >> 8) & 0xFF) == 'p') || (((integer >> 8) & 0xFF) == 'P'); value = VersionInfoValue (module, product, (unsigned int) index); return true; }; }; return false; }; template <typename T> void Printer::ApplyValueLowercaseHCrop (T & value) { // restricts size: h (short), hh (char), hhh (nibble), hhhh (bool) switch (conversion.count (L'h')) { case 0u: break; case 1u: value &= 0x0000FFFFuLL; break; case 2u: value &= 0x000000FFuLL; break; case 3u: value &= 0x0000000FuLL; break; case 4u: value &= 0x00000001uLL; break; }; }; unsigned long long Printer::Float16ToFloat64 (unsigned short half) { auto exponent = half & 0x7c00u; auto sign = ((unsigned long long) (half & 0x8000u)) << 48; switch (exponent) { // zero or subnormal case 0x0000u: if (auto significant = half & 0x03ffu) { // subnormal significant <<= 1; while ((significant & 0x0400u) == 0) { significant <<= 1; exponent++; }; return sign | (((unsigned long long) (1023 - 15 - exponent)) << 52) | (((unsigned long long) (significant & 0x03ffu)) << 42); } else // zero return sign; // inf or NaN case 0x7c00u: // all-ones exponent and a copy of the significand return sign | 0x7ff0000000000000uLL | (((unsigned long long) (half & 0x03ffu)) << 42); // normalized default: // adjust the exponent and shift return sign | (((unsigned long long) (half & 0x7fffu) + 0xfc000u) << 42); }; }; bool Printer::LocalNumber (const wchar_t * number, LCID language, DWORD flags, int precision, bool negative) { NUMBERFMT fmt; std::memset (&fmt, 0, sizeof fmt); wchar_t decimal [16]; wchar_t thousand [16]; wchar_t grouping [32]; #define NUMBERFMT_FIELD(name) reinterpret_cast <LPWSTR> (&name), sizeof (name) / sizeof (WCHAR) if (GetLocaleInfo (language, flags | LOCALE_RETURN_NUMBER | LOCALE_IDIGITS, NUMBERFMT_FIELD (fmt.NumDigits)) && fmt.NumDigits != (unsigned int) precision) { if ( GetLocaleInfo (language, flags | LOCALE_RETURN_NUMBER | LOCALE_ILZERO, NUMBERFMT_FIELD (fmt.LeadingZero)) && GetLocaleInfo (language, flags | LOCALE_RETURN_NUMBER | LOCALE_INEGNUMBER, NUMBERFMT_FIELD (fmt.NegativeOrder)) && GetLocaleInfo (language, flags | LOCALE_SDECIMAL, decimal, sizeof decimal / sizeof decimal [0]) && GetLocaleInfo (language, flags | LOCALE_STHOUSAND, thousand, sizeof thousand / sizeof thousand [0]) && GetLocaleInfo (language, flags | LOCALE_SGROUPING, grouping, sizeof grouping / sizeof grouping [0])) { fmt.NumDigits = precision; fmt.lpDecimalSep = decimal; fmt.lpThousandSep = thousand; auto * p = grouping; while (*p) { if ((*p >= L'1') && (*p <= L'9')) { fmt.Grouping = fmt.Grouping * 10u + (*p - L'0'); }; if ((*p != L'0') && !p[1]) { fmt.Grouping *= 10u; }; ++p; }; } else { precision = -1; }; // when using custom NUMBERFMT, flags must be 0 (propagated above) flags = 0; } else { // precision provided is same as default or error, use NULL below precision = -1; }; #undef NUMBERFMT_FIELD // cannot use this->memory since it is already used for 'number' // 512 should be enough to format up-to about 316 characters long number // - wcslen (thousand) * (wcslen (number) / 3) // 3 - from Grouping??? wchar_t localized [512]; if (auto nlocalized = GetNumberFormat (language, flags, number, (precision == -1) ? NULL : &fmt, &localized[1], sizeof localized / sizeof localized [0] - 1)) { // make proper string conversion format // - reusing requested width, alignmnt (-) and plus symbol request auto width = conversion.width (); if (conversion.contains (L'-')) { width = -width; }; int offset = 1; if (conversion.contains (L'+') && !negative) { localized [0] = L'+'; offset = 0; }; if (conversion.contains (L' ') && !negative) { localized [0] = L' '; offset = 0; }; // request buffer to fit currency string // - or whatever minimum field width was required using namespace std; auto size = max ((int) (nlocalized - 1), std::abs (width)) + 1; if (this->memory.Ensure (size * sizeof (wchar_t))) { // ask msvcrt to format the string appropriately auto p = reinterpret_cast <wchar_t *> (this->memory.Data ()); if (_snwprintf (p, size, L"%*s", width, localized + offset)) { if (conversion.contains (L'U') && negative) { if (auto minus = WcsNChr (p, size, L'-')) { *minus = L'\x2013'; }; }; // pass to Output return this->String (p, size - 1); }; }; }; return false; }; bool Printer::LocalCurrency (const wchar_t * number, LCID language, DWORD flags, int precision, bool negative) { CURRENCYFMT fmt; std::memset (&fmt, 0, sizeof fmt); wchar_t decimal [16]; wchar_t thousand [16]; wchar_t grouping [32]; wchar_t symbol [32]; #define NUMBERFMT_FIELD(name) reinterpret_cast <LPWSTR> (&name), sizeof (name) / sizeof (WCHAR) if (GetLocaleInfo (language, flags | LOCALE_RETURN_NUMBER | LOCALE_ICURRDIGITS, NUMBERFMT_FIELD (fmt.NumDigits)) && fmt.NumDigits != (unsigned int) precision) { if ( GetLocaleInfo (language, flags | LOCALE_RETURN_NUMBER | LOCALE_ILZERO, NUMBERFMT_FIELD (fmt.LeadingZero)) && GetLocaleInfo (language, flags | LOCALE_RETURN_NUMBER | LOCALE_INEGCURR, NUMBERFMT_FIELD (fmt.NegativeOrder)) && GetLocaleInfo (language, flags | LOCALE_RETURN_NUMBER | LOCALE_ICURRENCY, NUMBERFMT_FIELD (fmt.PositiveOrder)) && GetLocaleInfo (language, flags | LOCALE_SDECIMAL, decimal, sizeof decimal / sizeof decimal [0]) && GetLocaleInfo (language, flags | LOCALE_STHOUSAND, thousand, sizeof thousand / sizeof thousand [0]) && GetLocaleInfo (language, flags | LOCALE_SGROUPING, grouping, sizeof grouping / sizeof grouping [0]) && GetLocaleInfo (language, flags | LOCALE_SCURRENCY, symbol, sizeof symbol / sizeof symbol [0])) { fmt.NumDigits = precision; fmt.lpDecimalSep = decimal; fmt.lpThousandSep = thousand; fmt.lpCurrencySymbol = symbol; auto * p = grouping; while (*p) { if ((*p >= L'1') && (*p <= L'9')) { fmt.Grouping = fmt.Grouping * 10u + (*p - L'0'); }; if ((*p != L'0') && !p [1]) { fmt.Grouping *= 10u; }; ++p; }; } else { precision = -1; }; // when using custom CURRENCYFMT, flags must be 0 (propagated above) flags = 0; } else { // precision provided is same as default or error, use NULL below precision = -1; }; #undef NUMBERFMT_FIELD // cannot use this->memory since it is already used for 'number' // 192 should be enough considering we use 128 as max length for 'number' wchar_t currency [192]; if (auto ncurrency = GetCurrencyFormat (language, flags, number, (precision == -1) ? NULL : &fmt, &currency[1], sizeof currency / sizeof currency [0] - 1)) { // make proper string conversion format // - reusing requested width, alignmnt (-) and plus symbol request auto width = conversion.width (); if (conversion.contains (L'-')) { width = -width; }; int offset = 1; if (conversion.contains (L'+') && !negative) { currency [0] = L'+'; offset = 0; }; if (conversion.contains (L' ') && !negative) { currency [0] = L' '; offset = 0; }; // request buffer to fit currency string // - or whatever minimum field width was required using namespace std; auto size = max ((int) ncurrency, std::abs (width)) + 1; if (this->memory.Ensure (size * sizeof (wchar_t))) { // ask msvcrt to format the string appropriately auto p = reinterpret_cast <wchar_t *> (this->memory.Data ()); if (_snwprintf (p, size, L"%*s", width, currency + offset)) { // pass to Output return this->String (p, size - 1); }; }; }; return false; }; template <typename T> struct MantissaMax { static const auto value = 22; /* octal int64 */ }; template <> struct MantissaMax <float> { static const auto value = 50; }; template <> struct MantissaMax <double> { static const auto value = 320; }; template <> struct MantissaMax <long double> { static const auto value = 4945; }; template <typename T, typename... Params> bool Printer::DefaultOperation (const wchar_t * fmt, T value, Params... parameters) { using namespace std; auto size = 2 + max (abs (conversion.width ()), MantissaMax <T> ::value + conversion.precision ()); if (this->memory.Ensure (size * sizeof (wchar_t))) { // printf (" >%ls;%u;%f,%d< ", fmt, (unsigned int) sizeof value, value, parameters...); auto p = reinterpret_cast <wchar_t *> (this->memory.Data ()); auto length = _snwprintf (p, size, fmt, parameters..., value); // printf (" >%d;%d< ", length, errno); if (length >= 0 && length <= size) return this->String (p, length); }; return false; }; bool Printer::String (const wchar_t * ptr, std::size_t length) { if (length) return this->output.String (ptr, length); else return true; }; bool Printer::Forward (const wchar_t * begin, const wchar_t * end) { return this->String (begin, end - begin); }; bool Printer::Repeat (wchar_t character, std::size_t n) { return this->output.Repeat (character, n); }; bool Output::Repeat (wchar_t character, std::size_t n) { for (std::size_t i = 0u; i != n; ++i) { if (!this->String (&character, 1u)) return false; }; return true; }; bool Output::IsConsole (CONSOLE_SCREEN_BUFFER_INFO *) { return false; }; bool OutputConsole::IsConsole (CONSOLE_SCREEN_BUFFER_INFO * info) { return GetConsoleScreenBufferInfo (this->handle, info); }; void Output::MoveCursor (unsigned short, unsigned short) {}; void OutputConsole::MoveCursor (unsigned short x, unsigned short y) { SetConsoleCursorPosition (this->handle, { (SHORT) x, (SHORT) y }); }; // TODO: override OutputConsole::Repeat to minimize WriteConsole calls // TODO: override OutputHandle::Repeat to minimize WriteFile calls bool OutputConsole::String (const wchar_t * string, std::size_t length) { DWORD written = 0u; BOOL result = WriteConsole (this->handle, string, (DWORD) length, &written, NULL); this->n_out += written; return result && written == length; }; bool OutputHandle::String (const wchar_t * string, std::size_t length) { DWORD written = 0u; switch (this->codepage) { case CP_UTF16: { length *= sizeof (wchar_t); auto result = WriteFile (this->handle, string, (DWORD) length, &written, NULL); this->n_out += written / sizeof (wchar_t); return result && written == length; } break; default: Encoder e (this->codepage, string, length); if (auto n = e.Size ()) { if (!this->memory.Ensure (n)) { return false; }; auto output = this->memory.Data (); auto maxout = this->memory.Size (); auto all = e.Encode (output, maxout); auto write = output - this->memory.Data (); auto result = WriteFile (this->handle, this->memory.Data (), (DWORD) write, &written, NULL); this->n_out += written; return result && written == (DWORD) write && all; } else return false; }; }; bool OutputBuffer::String (const wchar_t * string, std::size_t length) { Encoder e (this->codepage, string, length); auto result = e.Encode (this->buffer, this->size); this->n_out += e.encoded; return result; }; std::size_t Input::Conversion::count (wchar_t c) { if (this->spec) { return std::count (this->begin, this->spec, c) + std::count (this->spec_end, this->end, c); } else { return std::count (this->begin, this->end, c); }; }; template <unsigned N> bool Input::Conversion::contains (const wchar_t (&substring) [N]) { const wchar_t * sb = &substring [0]; const wchar_t * se = &substring [N - 1]; if (this->spec) { return std::search (this->begin, this->spec, sb, se) != this->spec || std::search (this->spec_end, this->end, sb, se) != this->end; } else { return std::search (this->begin, this->end, sb, se) != this->end; }; }; bool Input::Conversion::contains (wchar_t c) { if (this->spec) { return std::find (this->begin, this->spec, c) != this->spec || std::find (this->spec_end, this->end, c) != this->end; } else { return std::find (this->begin, this->end, c) != this->end; }; }; template <typename IT, typename LT> bool any_of_helper (IT i, IT e, LT lb, LT le) { for (; i != e; ++i) for (auto li = lb; li != le; ++li) if (*i == *li) return true; return false; }; template <unsigned N> bool Input::Conversion::any_of (const wchar_t (&list) [N]) { const wchar_t * lb = &list [0]; const wchar_t * le = &list [N - 1]; if (this->spec) { return any_of_helper (this->begin, this->spec, lb, le) || any_of_helper (this->spec_end, this->end, lb, le); } else { return any_of_helper (this->begin, this->end, lb, le); }; }; int Input::Conversion::initstars (std::va_list & va) { const auto max = sizeof this->star / sizeof this->star [0]; this->stars = (unsigned short) this->count ('*'); if (this->stars > max) { this->stars = max; }; for (auto i = 0u; i != this->stars; ++i) { this->star [i] = va_arg (va, int); }; return this->stars; }; int Input::Conversion::precision (int default_) { using namespace std; switch (this->stars) { case 2: return this->star [1]; case 1: if (this->contains (L".*")) { return this->star [0]; } else { case 0: long result; wchar_t * e; if (this->spec) { auto i = std::find (this->begin, this->spec, L'.'); if (i != this->spec) if ((result = wcstol (i + 1, &e, 10)) || (e != i + 1)) return result; auto j = std::find (this->spec_end, this->end, L'.'); if (j != this->end) if ((result = wcstol (j + 1, &e, 10)) || (e != j + 1)) return result; } else { auto i = std::find (this->begin, this->end, L'.'); if (i != this->end) if ((result = wcstol (i + 1, &e, 10)) || (e != i + 1)) return result; }; }; }; return default_; }; int Input::Conversion::width (int default_) { using namespace std; switch (this->stars) { case 2: return this->star [0]; case 1: if (!this->contains (L".*")) { return this->star [0]; } else { case 0: bool r = (this->letter == L's') && (this->contains (L'r') || this->contains (L'R')); if (this->spec) { for (auto i = this->begin; i != this->spec; ++i) { if (*i == L'.' || (r && (*i == L'+'))) return default_; if (IsDigit (*i)) return wcstol (i, nullptr, 10); }; for (auto i = this->spec_end; i != this->end; ++i) { if (*i == L'.' || (r && (*i == L'+'))) return default_; if (IsDigit (*i)) return wcstol (i, nullptr, 10); }; } else { for (auto i = this->begin; i != this->end; ++i) { if (*i == L'.' || (r && (*i == L'+'))) return default_; if (IsDigit (*i)) return wcstol (i, nullptr, 10); }; }; }; }; return default_; }; unsigned int Input::Conversion::resource_string_base (unsigned int default_) { if ((this->letter == L's') && (this->contains (L'r') || this->contains (L'R'))) { if (this->spec) { auto i = std::find (this->begin, this->spec, L'+'); if (i != this->spec) return wcstol (i + 1, nullptr, 10); auto j = std::find (this->spec_end, this->end, L'+'); if (j != this->end) return wcstol (j + 1, nullptr, 10); } else { auto i = std::find (this->begin, this->end, L'+'); if (i != this->end) return wcstol (i + 1, nullptr, 10); }; }; return default_; }; // default code pages int default_cp_print = -1; int default_cp_error = -1; int default_cp_string = -1; int default_cp_socket = -1; int default_cp_file = -1; int default_cp_pipe = -1; int CurrentCharSPrintCP () { if (default_cp_string != -1) return default_cp_string; else return CP_ACP; }; int CurrentErrorPrintCP (int cp) { if (cp != -1) return cp; else if (default_cp_error != -1) return default_cp_error; else return -1; }; int CurrentFilePrintCP (int cp) { if (cp != -1) return cp; else if (default_cp_file != -1) return default_cp_file; else return CP_UTF16; }; int CurrentPipePrintCP (int cp) { if (cp != -1) return cp; else if (default_cp_pipe != -1) return default_cp_pipe; else return CP_UTF16; }; int CurrentPrintCP (int cp) { if (cp != -1) return cp; else if (default_cp_print != -1) return default_cp_print; else return CP_ACP; }; int CurrentWSAPrintCP (int cp) { if (cp != -1) return cp; else if (default_cp_socket != -1) return default_cp_socket; else return 20127; // US-ASCII }; bool ResolvePrintCP (void * handle, unsigned int & cp) { DWORD dw; switch (GetFileType (handle)) { case FILE_TYPE_DISK: // file cp = CurrentFilePrintCP (cp); return true; case FILE_TYPE_PIPE: // pipe, also redirection cp = CurrentPipePrintCP (cp); return true; case FILE_TYPE_CHAR: if (GetConsoleMode (handle, &dw)) { // console return false; }; // else? default: cp = CurrentPrintCP (cp); return true; }; }; bool SetDefaultCodePage (int & tg, int cp) { switch (cp) { case -1: // default case CP_ACP: case CP_OEMCP: case CP_MACCP: case CP_THREAD_ACP: case CP_UTF16: case CP_UTF16_BE: case CP_UTF32: case CP_UTF32_BE: case CP_UTF7: case CP_UTF8: tg = cp; return true; case 0xFEFF: tg = CP_UTF16; return true; case 0xFFFE: tg = CP_UTF16_BE; return true; default: if (IsValidCodePage (cp)) { tg = cp; return true; } else { SetLastError (ERROR_INVALID_PARAMETER); return false; }; }; }; std::size_t OutputBuffer::NulTerminatorLength (int cp) { switch (cp) { default: return 1u; case CP_UTF16: case CP_UTF16_BE: return 2u; case CP_UTF32: case CP_UTF32_BE: return 4; }; }; std::size_t OutputBuffer::NulTerminatorSpace (int cp, std::size_t offset) { offset -= NulTerminatorLength (cp); switch (cp) { default: return offset; case CP_UTF16: case CP_UTF16_BE: return offset & ~1; case CP_UTF32: case CP_UTF32_BE: return offset & ~3; }; }; std::size_t Encoder::Size () const { switch (this->codepage) { default: return WideCharToMultiByte (this->codepage, 0u, this->string, (int) this->length, NULL, 0, NULL, NULL); case CP_UTF16: case CP_UTF16_BE: return this->length * sizeof (char16_t); case CP_UTF32: case CP_UTF32_BE: std::size_t surrogates = 0u; for (std::size_t i = 0u; i != this->length; ++i) { if (this->string [i] >= 0xD800 && this->string [i] < 0xDC00) { if (i + 1u != this->length) { if (this->string [i + 1u] >= 0xDC00 && this->string [i + 1u] < 0xE000) { ++surrogates; }; }; }; }; return (this->length - surrogates) * sizeof (char32_t); }; }; bool Encoder::Encode (unsigned char *& buffer, std::size_t & max) const { bool result = true; auto n = this->length; auto p = this->string; switch (this->codepage) { case CP_UTF16: // no conversion n *= sizeof (char16_t); if (n > max) { n = max; result = false; }; std::memcpy (buffer, p, n); buffer += n; max -= n; this->encoded = n; break; case CP_UTF16_BE: if (n > max / sizeof (char16_t)) { n = max / sizeof (char16_t); result = false; }; this->encoded = n; while (n--) { *buffer++ = *p >> 8u; *buffer++ = *p++ & 0xFF; }; break; case CP_UTF32: case CP_UTF32_BE: while (n-- && max) { char32_t c = *p++; if (c >= 0xD800 && c < 0xDC00) { // high surrogate char16_t x = *p++; if (x >= 0xDC00 && x < 0xE000) { // low surrogate c = 0x10000u + ((c - 0xD800) << 10) + ((x - 0xDC00)); } else { c = 0xFFFD; // not low surrogate, error }; } else if (c >= 0xDC00 && c < 0xE000) { // low surrogate, error c = 0xFFFD; }; if (this->codepage == CP_UTF32_BE) { c = Swap32 (c); }; std::memcpy (buffer, &c, sizeof c); buffer += sizeof c; max -= sizeof c; ++this->encoded; }; result = !n; break; default: auto w = WideCharToMultiByte (this->codepage, 0u, this->string, (int) this->length, (LPSTR) buffer, (int) max, NULL, NULL); if (w) { buffer += w; max -= w; this->encoded = w; } else { if (this->codepage != CP_SYMBOL // documented && GetLastError () == ERROR_INSUFFICIENT_BUFFER) { this->encoded = max; buffer += max; max = 0u; }; result = false; }; break; }; return result; }; }; bool Windows::SetDefaultPrintCodePage (int cp) { return SetDefaultCodePage (default_cp_print, cp); }; bool Windows::SetDefaultErrPrintCodePage (int cp) { return SetDefaultCodePage (default_cp_error, cp); }; bool Windows::SetDefaultSPrintCodePage (int cp) { return SetDefaultCodePage (default_cp_string, cp); }; bool Windows::SetDefaultWSAPrintCodePage (int cp) { return SetDefaultCodePage (default_cp_socket, cp); }; bool Windows::SetDefaultFilePrintCodePage (int cp) { return SetDefaultCodePage (default_cp_file, cp); }; bool Windows::SetDefaultPipePrintCodePage (int cp) { return SetDefaultCodePage (default_cp_pipe, cp); }; Windows::PR <void> Windows::FilePrintCPVA (void * handle, unsigned int cp, const wchar_t * format, std::va_list va) { if (ResolvePrintCP (handle, cp)) { OutputHandle output (handle, cp); Printer printer (Input (format, va), output); printer (); return { printer.success, nullptr, printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; } else { OutputConsole output (handle); Printer printer (Input (format, va), output); printer (); return { printer.success, nullptr, printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; }; }; Windows::PR <void> Windows::FilePrintCPVA (void * handle, unsigned int cp, unsigned int format, std::va_list va) { if (ResolvePrintCP (handle, cp)) { OutputHandle output (handle, cp); Printer printer (Input (format, va), output); printer (); return { printer.success, nullptr, printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; } else { OutputConsole output (handle); Printer printer (Input (format, va), output); printer (); return { printer.success, nullptr, printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; }; }; Windows::PR <void> Windows::WSAPrintCPVA (unsigned int socket, unsigned int cp, const wchar_t * format, std::va_list va) { OutputHandle output (reinterpret_cast <void *> ((std::uintptr_t) socket), CurrentWSAPrintCP (cp)); Printer printer (Input (format, va), output); printer (); return { printer.success, nullptr, printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; }; Windows::PR <void> Windows::WSAPrintCPVA (unsigned int socket, unsigned int cp, unsigned int format, std::va_list va) { OutputHandle output (reinterpret_cast <void *> ((std::uintptr_t) socket), CurrentWSAPrintCP (cp)); Printer printer (Input (format, va), output); printer (); return { printer.success, nullptr, printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; }; Windows::PR <char> Windows::SPrintCPVA (void * buffer, std::size_t size, unsigned int cp, const wchar_t * format, std::va_list va) { // if (!size) return ... OutputBuffer output (buffer, size, cp); Printer printer (Input (format, va), output); printer (); return { printer.success, static_cast <char *> (buffer), printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; }; Windows::PR <char> Windows::SPrintCPVA (void * buffer, std::size_t size, unsigned int cp, unsigned int format, std::va_list va) { OutputBuffer output (buffer, size, cp); Printer printer (Input (format, va), output); printer (); return { printer.success, static_cast <char *> (buffer), printer.GetCurrentFormatPointer (), printer.n_ops, output.n_out }; }; // CodePage and VA_LIST forwarders // - XxxPrint (Ppp, ...) -> XxxPrintVA (Ppp, va_args) // - XxxPrintVA (Ppp, va_list) -> XxxPrintCPVA (Ppp, -1, va_args) // - XxxPrintCP (Ppp, cp, ...) -> XxxPrintCPVA (Ppp, cp, va_args) #define DEFINE_BASE0_FORWARDERS(rtype,name,ftype) \ Windows::PR <rtype> Windows::name (ftype format, ...) { \ va_list args; \ va_start (args, format); \ auto result = Windows::name ## VA (format, args); \ va_end (args); \ return result; \ }; \ Windows::PR <rtype> Windows::name ## VA (ftype format, std::va_list va) { \ return Windows::name ## CPVA (-1, format, va); \ }; \ Windows::PR <rtype> Windows::name ## CP (unsigned int cp, ftype format, ...) { \ va_list args; \ va_start (args, format); \ auto result = Windows::name ## CPVA (cp, format, args); \ va_end (args); \ return result; \ } #define DEFINE_BASE1_FORWARDERS(rtype,p0type,name,ftype) \ Windows::PR <rtype> Windows::name (p0type p0, ftype format, ...) { \ va_list args; \ va_start (args, format); \ auto result = Windows::name ## VA (p0, format, args); \ va_end (args); \ return result; \ }; \ Windows::PR <rtype> Windows::name ## VA (p0type p0, ftype format, std::va_list va) { \ return Windows::name ## CPVA (p0, -1, format, va); \ }; \ Windows::PR <rtype> Windows::name ## CP (p0type p0, unsigned int cp, ftype format, ...) { \ va_list args; \ va_start (args, format); \ auto result = Windows::name ## CPVA (p0, cp, format, args); \ va_end (args); \ return result; \ } #define DEFINE_BASE2S_FORWARDERS(rtype,p0type,p1type,name,ftype) \ Windows::PR <rtype> Windows::name (p0type p0, p1type p1, ftype format, ...) { \ va_list args; \ va_start (args, format); \ auto result = Windows::name ## VA (p0, p1, format, args); \ va_end (args); \ return result; \ }; \ Windows::PR <rtype> Windows::name ## VA (p0type p0, p1type p1, ftype format, std::va_list va) { \ auto r = Windows::name ## CPVA (p0, p1, CP_UTF16, format, va); \ return { r.success, reinterpret_cast <rtype *> (r.buffer), r.next, r.n, r.size }; \ }; \ Windows::PR <char> Windows::name ## CP (void * p0, p1type p1, unsigned int cp, ftype format, ...) { \ va_list args; \ va_start (args, format); \ auto result = Windows::name ## CPVA (p0, p1, cp, format, args); \ va_end (args); \ return result; \ } #define DEFINE_STRING_CP_FORWARDERS(outtype,cp,ftype) \ Windows::PR <outtype> Windows::SPrint (outtype * buffer, std::size_t length, ftype format, ...) { \ va_list args; \ va_start (args, format); \ auto r = Windows::SPrintCPVA (buffer, length, cp, format, args); \ va_end (args); \ return { r.success, reinterpret_cast <outtype *> (r.buffer), r.next, r.n, r.size }; \ }; \ Windows::PR <outtype> Windows::SPrintVA (outtype * buffer, std::size_t length, ftype format, std::va_list va) { \ auto r = Windows::SPrintCPVA (buffer, length, cp, format, va); \ return { r.success, reinterpret_cast <outtype *> (r.buffer), r.next, r.n, r.size }; \ } DEFINE_BASE0_FORWARDERS (void, Print, const wchar_t *); DEFINE_BASE0_FORWARDERS (void, Print, unsigned int); DEFINE_BASE0_FORWARDERS (void, ErrPrint, const wchar_t *); DEFINE_BASE0_FORWARDERS (void, ErrPrint, unsigned int); DEFINE_BASE1_FORWARDERS (void, void *, FilePrint, const wchar_t *); DEFINE_BASE1_FORWARDERS (void, void *, FilePrint, unsigned int); DEFINE_BASE1_FORWARDERS (void, unsigned int, WSAPrint, const wchar_t *); DEFINE_BASE1_FORWARDERS (void, unsigned int, WSAPrint, unsigned int); DEFINE_BASE2S_FORWARDERS (wchar_t, wchar_t *, std::size_t, SPrint, const wchar_t *); DEFINE_BASE2S_FORWARDERS (wchar_t, wchar_t *, std::size_t, SPrint, unsigned int); DEFINE_STRING_CP_FORWARDERS (char16_t, CP_UTF16, const wchar_t *); DEFINE_STRING_CP_FORWARDERS (char16_t, CP_UTF16, unsigned int); DEFINE_STRING_CP_FORWARDERS (char32_t, CP_UTF32, const wchar_t *); DEFINE_STRING_CP_FORWARDERS (char32_t, CP_UTF32, unsigned int); Windows::PR <void> Windows::PrintCPVA (unsigned int cp, const wchar_t * format, std::va_list va) { // TODO: ability to redirect return Windows::FilePrintCPVA (GetStdHandle (STD_OUTPUT_HANDLE), cp, format, va); }; Windows::PR <void> Windows::PrintCPVA (unsigned int cp, unsigned int format, std::va_list va) { // TODO: ability to redirect return Windows::FilePrintCPVA (GetStdHandle (STD_OUTPUT_HANDLE), cp, format, va); }; Windows::PR <void> Windows::ErrPrintCPVA (unsigned int cp, const wchar_t * format, std::va_list va) { // TODO: ability to redirect return Windows::FilePrintCPVA (GetStdHandle (STD_ERROR_HANDLE), CurrentErrorPrintCP (cp), format, va); }; Windows::PR <void> Windows::ErrPrintCPVA (unsigned int cp, unsigned int format, std::va_list va) { // TODO: ability to redirect return Windows::FilePrintCPVA (GetStdHandle (STD_ERROR_HANDLE), CurrentErrorPrintCP (cp), format, va); }; Windows::PR <char> Windows::SPrint (char * buffer, std::size_t size, const wchar_t * format, ...) { va_list args; va_start (args, format); auto result = Windows::SPrintCPVA (buffer, size, CurrentCharSPrintCP (), format, args); va_end (args); return result; }; Windows::PR <char> Windows::SPrint (char * buffer, std::size_t size, unsigned int format, ...) { va_list args; va_start (args, format); auto result = Windows::SPrintCPVA (buffer, size, CurrentCharSPrintCP (), format, args); va_end (args); return result; }; Windows::PR <char> Windows::SPrintVA (char * buffer, std::size_t size, const wchar_t * format, std::va_list va) { return Windows::SPrintCPVA (buffer, size, CurrentCharSPrintCP (), format, va); }; Windows::PR <char> Windows::SPrintVA (char * buffer, std::size_t size, unsigned int format, std::va_list va) { return Windows::SPrintCPVA (buffer, size, CurrentCharSPrintCP (), format, va); };
3dad8b86b64a7cc5d44d149199eb8f4e03fc7eed
8d4c446a130e781bfde9f39413669083dd1f9369
/qt_viewer/mainwindow.h
628e2f5127ecde2ee8c84e451cba4020270a25b6
[]
no_license
newmen/d_life
7f09ddef2e8b8ecf636350cde60e90ddd8db6473
d7aad54030dbb17d323ff8c2f335bb4aea572eeb
refs/heads/master
2016-09-11T02:17:16.632174
2013-07-22T20:54:11
2013-07-22T20:54:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
395
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QWidget> #include "renderarea.h" #include "playbutton.h" class MainWindow : public QWidget { Q_OBJECT public: explicit MainWindow(); ~MainWindow(); private: RenderArea *_renderArea; Button *_nextButton; Button *_saveButton; Button *_restoreButton; PlayButton *_playButton; }; #endif // MAINWINDOW_H
b44860ae5fca4934a9a644e65096f728008e7e09
0ef9c87bd9a27cddef27768c5902a185c0b319b4
/filterdesigner.h
4123b942dd780e90d455276d52e288bd2a00f62a
[ "MIT" ]
permissive
aliihsancengiz/FirFilterDesigner
d19647cc911c247b280db3fbe6a9cbb49c98d39f
64aec54ae19e86df099f225805cbc68da3163d47
refs/heads/main
2023-01-31T22:39:35.956272
2020-12-08T16:02:25
2020-12-08T16:02:25
319,688,143
1
0
null
null
null
null
UTF-8
C++
false
false
848
h
filterdesigner.h
#ifndef FILTERDESIGNER_H #define FILTERDESIGNER_H #include <QMainWindow> #include <QDebug> #include <QtMath> #include <QFileDialog> #include <algorithm> #include <numeric> #include <fstream> #include "fft/FFTReal.h" #include "qcustomplot.h" #include "windowfunction.h" #include "filtercoeffgenrator.h" QT_BEGIN_NAMESPACE namespace Ui { class FilterDesigner; } QT_END_NAMESPACE class FilterDesigner : public QMainWindow { Q_OBJECT public: FilterDesigner(QWidget *parent = nullptr); ~FilterDesigner(); private slots: void on_DesignButton_clicked(); void on_pushButton_clicked(); private: Ui::FilterDesigner *ui; QVector<double> coeff,window; WindowFunction mWindowDesigner; FilterCoeffGenrator mCoeffGenerator; void performFilterBuilding(); bool isDesigned=false; }; #endif // FILTERDESIGNER_H
5567c65768579803f4abcbb2fe87ee2005bb3fcd
3ac7658c1554f63865eb92a92a9a9b29f462b797
/EXP/2018-2019(2) EXP/实验7 王程飞 201806061219/Visual Studio Project/Transportation/Transportation.cpp
dfc19a2956853b7ded659420c3715d60fb25f8eb
[]
no_license
yuhuarong/MyCPPExperiment
9d8f050c616d97f9725fd5809867aedbaddcf637
13cac9edb0a1857a456409ba92151c6a90183ac3
refs/heads/master
2020-09-22T16:25:04.214263
2019-11-26T17:41:52
2019-11-26T17:41:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
Transportation.cpp
#include <iostream> #include "Vehicle.h" #include "Taxi.h" #include "Trunk.h" using namespace std; int main() { Vehicle v(2, 6, 3, "blue", 14.6); cout << v << endl; Taxi t(4, 6, 5, "yellow", 3.3, 0); cout << t << endl; Trunk r(4, 6, 5, "black", 3.3, 1); cout << r << endl; }
c2b4115d3179ffd327cd30aad22cb83349d88079
1c6065d97f72014f90dcf2c21547c20bd1ccac29
/Tema05LinearStructures/Ejercicios/Ejercicio03/Ejercicio03/Transaccion.cpp
ad0cc9b5a5fbfc5c76d571db27185d306eafdc9e
[]
no_license
gerardogtn/EstructuraDatos
2627d2de3d02f0abe80af95bb953d305803a9098
143c1eee53c3a339f58913a0a6a1b802acd4baa6
refs/heads/master
2020-05-28T14:15:22.376379
2015-05-12T19:35:03
2015-05-12T19:35:03
31,332,419
0
1
null
null
null
null
UTF-8
C++
false
false
464
cpp
Transaccion.cpp
// // Transaccion.cpp // Ejercicio03 // // Created by Gerardo Teruel on 3/23/15. // Copyright (c) 2015 Gerardo Teruel. All rights reserved. // #include <functional> #include "Transaccion.h" //using namespace std; class Transaccion{ private: enum tipoDeTransaccion {RETIRO, DEPOSITO, CONSULTA, ACTUALIZACION, PAGOS}; double time; public: Transaccion() {} void establecerTipo(std::string); void establecerTipo(int); };
aeed6ee5b4d05f838d9720d24dc251ba58aa2abb
baf133d09dc0239c62abe63e8da4e3cb9e205f38
/1st-Year/Intro-to-Computer-Science/HW7-Array-Algorithms/3.sortPyramids.cpp
f5c1c3901f3ad80a83c93a03657d38a73821d85a
[]
no_license
abrahammurciano/homework
b7c9555688221299e4eea7fe635299d4a6ab01ba
879607be45c24f49c03cfad4c7eaa0c1f81afa4d
refs/heads/master
2022-03-18T20:38:10.283054
2021-09-19T20:09:52
2021-09-19T20:09:52
154,134,294
11
10
null
2022-03-02T19:16:55
2018-10-22T11:47:39
TeX
UTF-8
C++
false
false
5,137
cpp
3.sortPyramids.cpp
/* * File Name: 3.sortPyramids.cpp * Program Description: Takes input of 10 by 10 matrix, then sorts the bottom left triangle and * the top right triangle * Course Name: Introduction to Computer Science * Assignment Number: 7 * Question Number: 3 * Author: Abraham Murciano * * Created on: Wed Nov 21 2018 * Last Modified on: Thu Nov 22 2018 */ #include <climits> #include <iostream> using namespace std; // Function that takes an input between min and max inclusive, then returns the input. // Outputs ERROR whenever input is invalid int input(int min = INT_MIN, int max = INT_MAX) { int input; while (true) { cin >> input; if (input >= min && input <= max) { return input; } cout << "ERROR" << endl; } } // Function that performs insertion sort on given array void sort(int array[], int size) { int notSorted = 1; // Holds index of first element of unsorted section of array while (notSorted < size) { // While there are unsorted elements int val = array[notSorted]; // Take the first value of the unsorted section // Perform binary search to find the index that val should be moved to within the sorted // section of the array int min = 0, max = notSorted; int mid; // mid is the average of min and max do { mid = (min + max) / 2; // mid is the average of min and max if (val < array[mid]) { // If val is between positions 0 and mid-1 max = mid; // max is the value of mid } else { // If val is between positions mid and max min = mid; // min is now mid } } while (max - min > 1); // When max and min have a difference of 1, the search is over int index = max; // The index to place val is max // Shift everything right to make room for val in the sorted section of the array and // increment notSorted for (int i = notSorted++; i > index; i--) { array[i] = array[i - 1]; } array[index] = val; // Put val into the correct position of the sorted section of the array } } // Function that prints the values of a 1D array of integers separated by a space void printArray(int array[], int n, bool newLine = true) { if (n < 1) { return; } cout << array[0]; for (int i = 1; i < n; i++) { cout << " " << array[i]; } if (newLine) { cout << endl; } } int main() { cout << "enter 100 numbers:" << endl; // Prompt for input const int N = 10; // Size of square matrix int matrix[N][N]; // Declare matrix of size N*N for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { matrix[i][j] = input(1); // Input values into matrix } } // Define 1D array 'triangle' to contain a copy of the triangles to sort them const int triangleSize = N * (N / 2) - (N / 2) * (-N % 2 + 1); // Number of elements in each triangle (45 when N=10) int triangle[triangleSize]; int ti; // triangle index to copy values to and from triangle // Sort bottom right triangle // Copy the bottom right triangle into 1D array 'triangle' in order to sort it ti = 0; // Set triangle index to 0 for (int i = 1; i < N; i++) { // Loop through rows for (int j = 0; j < i; j++) { // Loop through elements in each row triangle[ti++] = matrix[i][j]; // Copy a value from the matrix into triangle } } sort(triangle, triangleSize); // Sort the triangle // Copy 1D array 'triangle' back into the matrix ti = 0; // Set triangle index to 0 for (int i = 1; i < N; i++) { // Loop through rows for (int j = 0; j < i; j++) { // Loop through elements in each row matrix[i][j] = triangle[ti++]; // Copy a value from triangle into the matrix } } // Sort top left triangle // Copy the top left triangle into 1D array 'triangle' in order to sort it ti = 0; // Set triangle index to 0 for (int i = 0; i < N - 1; i++) { // Loop through rows for (int j = i + 1; j < N; j++) { // Loop through elements in each row triangle[ti++] = matrix[i][j]; // Copy a value from the matrix into triangle } } sort(triangle, triangleSize); // Sort the triangle // Copy 1D array 'triangle' back into the matrix ti = 0; // Set triangle index to 0 for (int i = 0; i < N - 1; i++) { // Loop through rows for (int j = i + 1; j < N; j++) { // Loop through elements in each row matrix[i][j] = triangle[ti++]; // Copy a value from triangle into the matrix } } cout << endl << "sorted matrix:" << endl; // Print each row of the matrix for (int i = 0; i < N; i++) { printArray(matrix[i], N); } return 0; } /* Sample Run: enter 100 numbers: 1 11 21 31 41 51 61 71 81 91 2 12 22 32 42 52 62 72 82 92 3 13 23 33 43 53 63 73 83 93 4 14 24 34 44 54 64 74 84 94 5 15 25 35 45 55 65 75 85 95 6 16 26 36 46 56 66 76 86 96 7 17 27 37 47 57 67 77 87 97 8 18 28 38 48 58 68 78 88 98 9 19 29 39 49 59 69 79 89 99 10 20 30 40 50 60 70 80 90 100 sorted matrix: 1 11 21 22 31 32 33 41 42 43 2 12 44 51 52 53 54 55 61 62 3 4 23 63 64 65 66 71 72 73 5 6 7 34 74 75 76 77 81 82 8 9 10 13 45 83 84 85 86 87 14 15 16 17 18 56 88 91 92 93 19 20 24 25 26 27 67 94 95 96 28 29 30 35 36 37 38 78 97 98 39 40 46 47 48 49 50 57 89 99 58 59 60 68 69 70 79 80 90 100 */
3d209e8d3ef56a0c8be7cc88891f1131b4ef7b1d
6840356bb8428865c1c64fa8ca9b42c0aca348a7
/Core/KernelSML/src/sml_AgentOutputFlusher.h
c78034985e74e9c9c4eca8f1cb98dab23585cd0f
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
SoarGroup/Soar
a5c7281e0673665a4b7eddd39ae4e5eb2a507aef
ef42bb24f7b58f9d244c83f5a2f2153c3ee17b77
refs/heads/development
2023-09-01T08:47:44.349033
2023-08-31T22:54:57
2023-08-31T22:54:57
21,206,914
289
86
NOASSERTION
2023-09-14T05:14:06
2014-06-25T14:50:12
C++
UTF-8
C++
false
false
911
h
sml_AgentOutputFlusher.h
///////////////////////////////////////////////////////////////// // AgentOutputFlusher class file. // // Author: Jonathan Voigt // Date : February 2005 // ///////////////////////////////////////////////////////////////// #ifndef AGENT_OUTPUT_FLUSHER_H #define AGENT_OUTPUT_FLUSHER_H #include "sml_KernelCallback.h" #include "sml_Events.h" namespace sml { class PrintListener; class AgentOutputFlusher : public KernelCallback { protected: int m_EventID ; // Only one listener will be filled in. PrintListener* m_pPrintListener; public: AgentOutputFlusher(PrintListener* pPrintListener, AgentSML* pAgent, smlPrintEventId eventID); virtual ~AgentOutputFlusher(); virtual void OnKernelEvent(int eventID, AgentSML* pAgentSML, void* pCallData) ; }; } #endif
ce4e7122f92b0a7571c6d6db5e31d64aaf1970b0
062b08f57ce7e3dc88862fd1bdfa321c7e2bbbd7
/src/Gpio/GpioSim.hpp
a05d59cbe74716ae0916082a129ef802fd368354
[]
no_license
maeseee/Raspberry-AirController
fdfe4cb2db82ba9d8ff3925d92fbfcfd1681d325
8a352992f7a71d32c2cf508e1711df73a62455dd
refs/heads/master
2023-03-21T11:33:12.388896
2021-03-04T13:43:43
2021-03-04T13:43:43
282,379,247
0
0
null
null
null
null
UTF-8
C++
false
false
830
hpp
GpioSim.hpp
#pragma once #include <Gpio/IGpio.hpp> #include <string> // FWD namespace logger { class SysLogger; using SysLoggerPtr = std::shared_ptr<SysLogger>; } // namespace logger // Class namespace gpio { /** * @brief The Gpio class controls one GPIO pin */ class GpioSim : public IGpio { public: explicit GpioSim(const Function function, const logger::SysLoggerPtr& sysLogger); bool setDirection(const size_t controllerId, const Direction dir) override; Direction getDirection() const override; bool setValue(const size_t id, const Value val) override; Value getValue() const override; size_t getPinNumber() const override; private: Direction m_dir{Direction::UNSET}; Value m_val{Value::INVALID}; const logger::SysLoggerPtr m_sysLogger; const size_t m_loggerId; }; } // namespace gpio
c6cab5fadafac7c91aec467c26584198e1c78f38
7607201e01c7d45140a8d1cf0852259c1eb5c667
/snippet/src/Ch10/Reduction/reduction_serial.cpp
444b625b4d00ed74ecd38fc3af103482a2c84f0b
[]
no_license
nhanloukiala/OpenCL-Benchmark
1f5f3b56c2554cccf2a7fe62103958e4c1323203
3dce52cb9947f77657d4a0af8e1ba1549996eabc
refs/heads/master
2021-01-10T07:08:01.492871
2018-12-14T19:05:03
2018-12-14T19:05:03
51,155,774
4
3
null
null
null
null
UTF-8
C++
false
false
520
cpp
reduction_serial.cpp
#include <cstdlib> #include <iostream> template<typename T> T reduce(T (*f)(T, T), size_t n, T a[], T identity) { T accum = identity; for(size_t i = 0; i < n ; ++i) accum = f(accum, a[i]); return accum; } int add(int a, int b) {return a + b;} int identity = 0; int main(int argc, char** argv) { int a[100]; for(int i = 0; i < 100; ++i) a[i] = i+1; int sum = reduce<int>(add, 100, a, identity); std::cout << "Total sum = " << sum << std::endl; }
99e03b7e81e3fe134da70981e23577e2d9ed6480
e3f578e81aa4402c2fa4bc3434be80c2e203dbf9
/libs/bitblocks/block.hpp
d84bb23c7b66219d83840e259d6f2f5f450b8539
[]
no_license
bytemaster/GeneralPublicMarket
b4d53a651bfe3cacb7c363517dc24224ae51e9d9
70f73235f33be1feac6f209b719d2bb79d6da0b3
refs/heads/master
2016-09-10T18:58:42.152557
2011-05-23T04:08:52
2011-05-23T04:08:52
1,485,893
5
3
null
null
null
null
UTF-8
C++
false
false
2,024
hpp
block.hpp
#ifndef _BLOCK_HPP_ #define _BLOCK_HPP_ #include <boost/reflect/reflect.hpp> #include <bitblocks/keyvalue_db.hpp> using boost::rpc::sha1_hashcode; struct block { uint64_t publish_date; uint64_t last_request; uint64_t total_btc; uint64_t total_requests; // total_btc/total_request = avg BTC/req std::string payto_address; std::vector<char> data; }; struct user_id { uint32_t ip; uint16_t port; bool operator > ( const user_id& r ) const { return ip > r.ip || (ip == r.ip && port > r.port ); } bool operator == ( const user_id& r ) const { return ip == r.ip && ip == r.ip; } }; struct metafile { metafile( const std::string& n = "" ):name(n){} std::string name; uint64_t size; std::vector<sha1_hashcode> blocks; }; BOOST_REFLECT( metafile, BOOST_PP_SEQ_NIL, (name)(size)(blocks) ) struct user_info { uint64_t created_utc; uint64_t last_recv_utc; std::string payto_address; // send money to user std::string receive_address; // receive money from user uint64_t total_received; // total money received at receive_address uint64_t total_spent; // total money consumed uint64_t total_earned; // total money earned, but not yet sent uint64_t total_paid; // total money sent to payto address int64_t balance()const { return total_received + total_earned - total_spent - total_paid; } }; BOOST_REFLECT( block, BOOST_PP_SEQ_NIL, (publish_date) (last_request) (total_btc) (total_requests) (payto_address) (data) ) BOOST_REFLECT( user_id, BOOST_PP_SEQ_NIL, (ip)(port) ) BOOST_REFLECT( user_info, BOOST_PP_SEQ_NIL, (created_utc) (last_recv_utc) (total_received) (total_spent) (total_earned) (total_paid) (payto_address) (receive_address) ) typedef bdb::keyvalue_db<user_id,user_info> user_db; typedef bdb::keyvalue_db<sha1_hashcode,block> block_db; #endif
07eeac43912c1eed7a24d6ed746dd6ce2156b97a
5288f2d9dc811d0a06bbc23302329ca25174d5d1
/src/main.cpp
6e171f5a2ea0903319bb524dc262a326c7ab1445
[ "MIT" ]
permissive
S-YOU/GrayBlue
1c339126fb2c699deb368ba1d1994c52da32845f
b649fdb642c197ea740c201b9d4fc28c2ed5845a
refs/heads/master
2020-06-10T17:36:35.377725
2019-06-09T10:28:21
2019-06-09T10:28:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,433
cpp
main.cpp
#include <M5Stack.h> #include "imu/IMU.h" #include "ble/BLE.h" #include "ble/BLEData.h" #include "input/ButtonCheck.h" #define SERIAL_PRINT 0 void printSerial(unsigned long t, const float a[], const float g[], const float m[], const float q[]); void printLcd(unsigned long t, const float a[], const float g[], const float m[], const float q[]); imu::IMU _imu; ble::BLE _ble; input::ButtonCheck _button; void setup() { M5.begin(); M5.Lcd.fillScreen(BLACK); M5.Lcd.setTextColor(GREEN ,BLACK); M5.Lcd.setCursor(0, 0); M5.Lcd.println("awaken..."); if (Wire.begin()) { Wire.setClock(400000UL); // i2c 400kHz M5.Lcd.println("i2c OK!"); } else { M5.Lcd.println("i2c NG!!!"); } if (_imu.Setup(50)) { // 50Hz M5.Lcd.println("imu OK!"); } else { M5.Lcd.println("imu NG!!!"); } if (_ble.Initialize() && _ble.Start()) { // 50Hz M5.Lcd.println("ble OK!"); } else { M5.Lcd.println("ble NG!!!"); } #if SERIAL_PRINT //Serial.begin(115200); Serial.println("serial OK!"); M5.Lcd.println("serial OK!"); #endif M5.Lcd.fillScreen(BLACK); } void loop() { // Button condition if (_button.containsUpdate(M5)) { for (int i = 0; i < INPUT_BTN_NUM; i++) { input::Btn btn = input::AllBtns[i]; if (_button.isBtnUpdate(btn)) { input::BtnState btnState = _button.getBtnState(btn); uint8_t btnCode = input::toBtnCode(btn); uint8_t btnPress = input::toBtnPress(btnState); uint32_t btnPressTime = (btnPress == 0) ? _button.getBtnPressTime(btn) : 0; #if SERIAL_PRINT Serial.print(btnCode); Serial.print(" "); Serial.print(btnPress); Serial.print(" "); Serial.println(btnPressTime); #endif ble::ButtonData data; data.btnCode = btnCode; data.btnPress = btnPress; data.pressTime = (uint16_t)btnPressTime; _ble.GetButtonCharacteristic().setValue((uint8_t*)&data, BLE_BUTTON_DATA_LEN); _ble.GetButtonCharacteristic().notify(); } } } // IMU condition if (_imu.Update()) { ble::IMUData data; memcpy(&data.accX, _imu.getAcc(), sizeof(float)*3); memcpy(&data.gyroX, _imu.getGyro(), sizeof(float)*3); memcpy(&data.magX, _imu.getMag(), sizeof(float)*3); memcpy(&data.quatW, _imu.getQuat(), sizeof(float)*4); _ble.GetNineAxisCharacteristic().setValue((uint8_t*)&data, BLE_IMU_DATA_LEN); _ble.GetNineAxisCharacteristic().notify(); #if SERIAL_PRINT printSerial(_imu.getTime(), _imu.getAcc(), _imu.getGyro(), _imu.getMag(), _imu.getQuat()); #endif printLcd(_imu.getTime(), _imu.getAcc(), _imu.getGyro(), _imu.getMag(), _imu.getQuat()); } // device update M5.update(); } void printLcd(unsigned long t, const float a[], const float g[], const float m[], const float q[]) { M5.Lcd.setCursor(0, 0); M5.Lcd.print(" x y z "); M5.Lcd.setCursor(0, 24); M5.Lcd.printf("% 6d % 6d % 6d mg \r\n", (int)(1000*a[0]), (int)(1000*a[1]), (int)(1000*a[2])); M5.Lcd.setCursor(0, 44); M5.Lcd.printf("% 6d % 6d % 6d o/s \r\n", (int)(g[0]), (int)(g[1]), (int)(g[2])); M5.Lcd.setCursor(0, 64); M5.Lcd.printf("% 6d % 6d % 6d mG \r\n", (int)(m[0]), (int)(m[1]), (int)(m[2])); M5.Lcd.setCursor(0, 100); M5.Lcd.print(" qw qx qy qz "); M5.Lcd.setCursor(0, 128); M5.Lcd.printf(" %2.3f % 2.3f %2.3f %2.3f \r\n", q[0], q[1], q[2], q[3]); } #if SERIAL_PRINT void printSerial(unsigned long t, const float a[], const float g[], const float m[], const float q[]) { return; Serial.print(t); Serial.print(","); Serial.print(a[0], 3); Serial.print(","); Serial.print(a[1], 3); Serial.print(","); Serial.print(a[2], 3); Serial.print(","); Serial.print(g[0], 3); Serial.print(","); Serial.print(g[1], 3); Serial.print(","); Serial.print(g[2], 3); Serial.print(","); Serial.print(m[0], 3); Serial.print(","); Serial.print(m[1], 3); Serial.print(","); Serial.print(m[2], 3); Serial.print(","); Serial.print(q[0], 3); Serial.print(","); Serial.print(q[1], 3); Serial.print(","); Serial.print(q[2], 3); Serial.print(","); Serial.print(q[3], 3); Serial.println(); } #endif
301641fb1ac1df53b08d6540acb461e9ef957d6f
009956c413ac892b90d3cfadea05caa08086c193
/src/modules/ioc/FFEADContext.h
ce83c23643fdee7bf6736bc7f35ceebf4fa27808
[]
no_license
sumeetchhetri/ffead-cpp
b12c6389877c87acff88349456bde5758861d8eb
8072c7a0b4c81d1558e10e091d239fbf474993ce
refs/heads/master
2023-05-14T02:00:29.875099
2023-04-29T13:25:49
2023-04-29T13:25:49
4,089,214
611
135
null
2022-09-24T09:51:35
2012-04-20T17:19:47
C++
UTF-8
C++
false
false
2,841
h
FFEADContext.h
/* Copyright 2009-2020, Sumeet Chhetri Licensed under the Apache License, Version 2.0 (const the& "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * FFEADContext.h * * Created on: Oct 17, 2010 * Author: root */ #ifndef FFEADCONTEXT_H_ #define FFEADCONTEXT_H_ #include "SimpleXmlParser.h" #include "Reflector.h" #include "CastUtil.h" #include "StringUtil.h" #include "LoggerFactory.h" #ifdef HAVE_UUIDINC #include <uuid/uuid.h> #elif defined(HAVE_BSDUUIDINC) #include <uuid.h> #elif defined(HAVE_OSSPUUIDINC) #include <ossp/uuid.h> #elif defined(HAVE_OSSPUUIDINC_2) #include <uuid.h> #endif #include "Timer.h" #include "map" class Bean { friend class FFEADContext; std::string name,inbuilt,value,clas,bean,intfType,injectAs,scope; bool realbean; bool isController; std::vector<std::string> injs,names,types; std::string appName; public: Bean(); Bean(const std::string& name, const std::string& value, const std::string& clas, const std::string& scope, const bool& isInbuilt, bool isController, const std::string& appName= "default"); ~Bean(); }; typedef std::map<std::string,Bean> beanMap; class FFEADContext { Logger logger; beanMap beans,injbns; std::map<std::string, void*> objects; std::map<std::string, ClassInfo*> contInsMap; bool cleared; Reflector* reflector; friend class ControllerHandler; friend class ExtHandler; friend class FormHandler; friend class SecurityHandler; friend class FilterHandler; friend class ServiceTask; friend class ConfigurationData; public: FFEADContext(const std::string&, const std::string& appName= "default"); FFEADContext(); virtual ~FFEADContext(); void* getBean(const std::string&, const std::string& appName= "default"); void* getBean(const std::string&, std::string_view); void* getBean(const Bean&); void clear(const std::string& appName= "default"); void addBean(Bean& bean); void initializeAllSingletonBeans(const std::map<std::string, bool, std::less<> >& servingContexts, Reflector* reflector); void clearAllSingletonBeans(const std::map<std::string, bool, std::less<> >& servingContexts); Reflector* getReflector(); void release(void* instance, const std::string& beanName, const std::string& appName); //TODO optimize for string_view later void release(void* instance, const std::string& beanName, std::string_view appName); }; #endif /* FFEADCONTEXT_H_ */
70fed3639e0c02ca84be10739c7c98bb3e349fa6
733de464662408d2ed3fa637b0c7ecdc7c281c0a
/scene/visitor/render/direct_gpx_render.cpp
0f9358340ce5400375e4861b030d84aae12729af
[ "MIT" ]
permissive
aconstlink/snakeoil
f15740eb93d3e36b656621bb57a0f7eb2592f252
3c6e02655e1134f8422f01073090efdde80fc109
refs/heads/master
2021-01-01T17:39:53.820180
2020-02-23T20:56:36
2020-02-23T20:56:36
98,117,868
1
0
null
null
null
null
UTF-8
C++
false
false
6,886
cpp
direct_gpx_render.cpp
//------------------------------------------------------------ // snakeoil (c) Alexis Constantin Link // Distributed under the MIT license //------------------------------------------------------------ #include "direct_gpx_render.h" #include "../../node/transform/transform_3d.h" #include "../../node/render/renderable.h" #include "../../node/render/render_state.h" #include "../../node/camera/camera.h" #include <snakeoil/gpx/driver/driver_async.h> #include <snakeoil/gpx/system/iuser_system.h> #include <snakeoil/math/matrix/matrix4.hpp> #include <snakeoil/core/macros/move.h> using namespace so_scene ; using namespace so_scene::so_visitor ; //************************************************************************************* direct_gpx_render::this_ptr_t direct_gpx_render::create( so_memory::purpose_cref_t p ) { return so_scene::memory::alloc( this_t(), p ) ; } //************************************************************************************* direct_gpx_render::this_ptr_t direct_gpx_render::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_scene::memory::alloc( std::move(rhv), p ) ; } //************************************************************************************* void_t direct_gpx_render::destroy( this_ptr_t ptr ) { so_scene::memory::dealloc( ptr ) ; } //************************************************************************************* direct_gpx_render::direct_gpx_render( void_t ) { _trafo_stack.push( so_math::mat4f_t( so_math::so_matrix::with_identity() ) ) ; } //************************************************************************************* direct_gpx_render::direct_gpx_render( so_gpx::iuser_system_ptr_t sys_ptr ) : direct_gpx_render() { _gpx_system_ptr = sys_ptr ; } //************************************************************************************* direct_gpx_render::direct_gpx_render( this_rref_t rhv ) : base_t(std::move(rhv) ) { _trafo_stack = std::move( rhv._trafo_stack ) ; so_move_member_ptr( _gpx_system_ptr, rhv ) ; so_move_member_ptr( _lens_ptr, rhv ) ; _view = rhv._view ; _proj = rhv._proj ; _proj_params = rhv._proj_params ; } //************************************************************************************* direct_gpx_render::~direct_gpx_render( void_t ) {} //************************************************************************************* void_t direct_gpx_render::set_view_matrix( so_math::mat4f_cref_t m ) { _view = m ; } //************************************************************************************* void_t direct_gpx_render::set_proj_matrix( so_math::mat4f_cref_t m ) { _proj = m ; } //************************************************************************************* void_t direct_gpx_render::set_proj_params( so_math::vec4f_cref_t params ) { _proj_params = params ; } //************************************************************************************* void_t direct_gpx_render::set_lens( so_gfx::ilens_ptr_t ptr ) { if( so_core::is_nullptr(ptr) ) return ; _lens_ptr = ptr ; _lens_ptr->get_view_matrix( _view ) ; _lens_ptr->get_proj_matrix( _proj ) ; } //************************************************************************************* void_t direct_gpx_render::use_lens( void_t ) { so_assert( _lens_ptr != nullptr ) ; _lens_ptr->get_view_matrix( _view ) ; _lens_ptr->get_proj_matrix( _proj ) ; } //************************************************************************************* void_t direct_gpx_render::use_varset( size_t const vs ) { _varset = vs ; } //************************************************************************************* so_scene::result direct_gpx_render::visit( so_scene::so_node::transform_3d_ptr_t trafo_ptr ) { so_math::so_3d::trafof_cref_t trafo_in = trafo_ptr->compute_trafo() ; _trafo_stack.push( _trafo_stack.top() * trafo_in ) ; return so_scene::ok ; } //************************************************************************************* so_scene::result direct_gpx_render::post_visit( so_scene::so_node::transform_3d_ptr_t trafo_ptr ) { _trafo_stack.pop() ; return so_scene::ok ; } //************************************************************************************* so_scene::result direct_gpx_render::visit( so_scene::so_node::camera_ptr_t cptr ) { cptr->set_transformation( _trafo_stack.top() ) ; return so_scene::ok ; } //************************************************************************************* so_scene::result direct_gpx_render::visit( so_scene::so_node::renderable_ptr_t nptr ) { if( so_core::is_nullptr(nptr) ) return so_scene::invalid_argument ; if( so_core::is_not_nullptr( _lens_ptr ) ) { _lens_ptr->get_view_matrix( _view ) ; _lens_ptr->get_proj_matrix( _proj ) ; } //nptr->set_object_matrix( so_math::mat4f_t( so_math::so_matrix::with_identity() ) ) ; //nptr->set_world_matrix( so_math::mat4f_t( so_math::so_matrix::with_identity() ) ) ; //nptr->set_view_matrix( so_math::mat4f_t( so_math::so_matrix::with_identity() ) ) ; //nptr->set_proj_matrix( so_math::mat4f_t( so_math::so_matrix::with_identity() ) ) ; nptr->set_world_matrix( _trafo_stack.top().get_transformation() ) ; nptr->set_view_matrix( _view ) ; nptr->set_proj_matrix( _proj ) ; nptr->set_proj_param0( _proj_params ) ; nptr->compute_mvp_matrix() ; size_t const varset = _varset ; _gpx_system_ptr->execute( [this,nptr, varset]( so_gpx::so_driver::driver_async_ptr_t drv_ptr ) { so_gpu::variable_set_ptr_t vs_ptr ; if( nptr->get_varset(varset, vs_ptr ) ) { drv_ptr->load_variable( vs_ptr ) ; drv_ptr->execute( so_gpu::so_driver::render_config_info( nptr->get_config(), varset ) ) ; } } ) ; return so_scene::ok ; } //************************************************************************************* so_scene::result direct_gpx_render::visit( so_scene::so_node::render_state_ptr_t nptr ) { _gpx_system_ptr->execute( [this, nptr]( so_gpx::so_driver::driver_async_ptr_t drv_ptr ) { drv_ptr->push_state( nptr->get_attributes() ) ; drv_ptr->change_states( nptr->get_attributes(), nptr->get_states() ) ; } ) ; return so_scene::ok ; } //************************************************************************************* so_scene::result direct_gpx_render::post_visit( so_scene::so_node::render_state_ptr_t nptr ) { _gpx_system_ptr->execute( [this, nptr]( so_gpx::so_driver::driver_async_ptr_t drv_ptr ) { drv_ptr->pop_state() ; } ) ; return so_scene::ok ; } //************************************************************************************* void_t direct_gpx_render::destroy( void_t ) { this_t::destroy( this ) ; }
fa515841b22846bd67ddde7b3ea62413c8d8da62
20a59a738c1d8521dc95c380190b48d7bc3bb0bb
/pictographs/AknPictograph/src/AknPictographPanic.cpp
dee3b23b7f6777845bdd7fdce934d30e02bdb203
[]
no_license
SymbianSource/oss.FCL.sf.mw.uiresources
376c0cf0bccf470008ae066aeae1e3538f9701c6
b78660bec78835802edd6575b96897d4aba58376
refs/heads/master
2021-01-13T13:17:08.423030
2010-10-19T08:42:43
2010-10-19T08:42:43
72,681,263
2
0
null
null
null
null
UTF-8
C++
false
false
933
cpp
AknPictographPanic.cpp
/* * Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: pictograph panic function * */ // INCLUDE FILES #include <e32std.h> #include "AknPictographPanic.h" // CONSTANTS _LIT( KAknPictographPanicCategory, "AknPictograph" ); // ----------------------------------------------------------------------------- // PictographPanic // ----------------------------------------------------------------------------- // GLDEF_C void PictographPanic( TAknPictographPanic aPanic ) { User::Panic( KAknPictographPanicCategory, aPanic ); } // End of File
3616a64ee29b31332ad33e05745a78b2a19b403e
b9e4f272762d5cf871653e4b4a3aa9ad33b05117
/ACM/cccc天梯赛2017-3-26/L2-020. 功夫传人cbh.cpp
23746ff954fa3ec014c307e5410b7913853b6b28
[]
no_license
haozx1997/C
e799cb25e1fa6c86318721834032c008764066ed
afb7657a58b86bf985c4a44bedfaf1c9cff30cf4
refs/heads/master
2021-07-11T23:54:17.357536
2017-10-12T03:42:23
2017-10-12T03:42:23
106,662,415
0
0
null
null
null
null
UTF-8
C++
false
false
703
cpp
L2-020. 功夫传人cbh.cpp
#include<cstdio> struct node{ int id; int b; }tmp[100005]; int ii=0; int par[100005]; int find(int x,int d) { if(x==par[x]) return d; return find(par[x],d+1); } int main() { int n,k,b,be; double z,r; scanf("%d%lf%lf",&n,&z,&r); for(int i=0;i<n;i++) par[i]= i; for(int i=0;i<n;i++) { scanf("%d",&k); if(k==0) { scanf("%d",&be); tmp[ii].b = be; tmp[ii].id = i; ii++; } else { for(int j=0;j<k;j++) { scanf("%d",&b); par[b] = i; } } } double sum=0.0; for(int i=0;i<ii;i++) { double zz = z; int d = find(tmp[i].id,0); for(int j=0;j<d;j++) { zz-=zz*r/100.0; } sum+=zz*tmp[i].b; } int ssum = sum; printf("%d\n",ssum); return 0; }
8904a26ebebaca88ba3d80935c6ca0b4330fcd8f
338bd4e9ffdb9ab7c260b4f23b20f51d91d4793b
/BattleBoard/vieBBSkillsWidget.cpp
d30c5f32257a08cce93141e002a37249e90cf14d
[]
no_license
Greykoil/BattleBoard
e17357b6566eeee8e2acbda1732b161f188d7d40
3796765ae1c2bf78a5b9a15de77138139c40e2ce
refs/heads/master
2021-05-07T15:27:39.189970
2018-03-08T13:15:01
2018-03-08T13:15:01
109,824,659
0
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
vieBBSkillsWidget.cpp
#include "vieBBSkillsWidget.h" vieBBSkillsWidget::vieBBSkillsWidget(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } vieBBSkillsWidget::~vieBBSkillsWidget() { }
d0b7de2cbcd26234df452de503b359bb5613dba0
b55aef9461d99530339bcdff62796113b34686ad
/Hw4/code/Circle.cpp
8e457c1fd742fdfa4118481d86a23603b5682b37
[]
no_license
Degermandal/Object_Oriented_Programming
8859e2ec89f0af0e5a9edc24dacb3d824173aba8
f68c159ad656b4479a198bf65f66803cfcd3ea3e
refs/heads/master
2020-04-22T00:03:53.162491
2019-02-10T10:29:55
2019-02-10T10:29:55
169,966,342
0
0
null
null
null
null
UTF-8
C++
false
false
2,523
cpp
Circle.cpp
#include "Circle.h" using namespace std; void Circle::setRadius(double r) { if(r > 0.0) radius = r; else cout<<"Incorrect radius input\n"; } void Circle::setX(double x) { if(x >= 0.0) cor_x = x; else cout<<"Incorrect x input\n"; } void Circle::setY(double y) { if(y >= 0.0) cor_y = y; else cout<<"Incorrect y input\n"; } /* void Circle::draw(ofstream &svgFile) { svgFile<<"<circle cx = \"" << radius << "\" cy = \"" << radius << "\" r=\"" << radius << "\" fill=\"red\" stroke = \"black\" stroke-width = \"1\" />\n"; } */ double Circle::cirPerimeter() const { return 2*PI*radius; } double Circle::cirArea() const { return PI*radius*radius; } ostream& operator<< (ostream &out, const Circle &C1) { out<<"<circle cx = \"" << C1.radius << "\" cy = \"" << C1.radius << "\" r=\"" << C1.radius << "\" fill=\"red\" stroke = \"black\" stroke-width = \"1\" />\n"; /* out<< "Radius of Shape: "<<C1.radius<<endl; out<< "X coordinate of Shape : "<<C1.cor_x<<endl; out<< "Y coordinate of Shape : "<<C1.cor_y<<endl; */ return out; } Circle& Circle::operator++()//check YAP!!!!!!!!!!!!!!!! { ++cor_x; ++cor_y; return *this; } Circle& Circle::operator--() { --cor_x; --cor_y; return *this; } Circle Circle::operator++(int) { Circle temp(cor_x, cor_y); ++(*this); return temp; } Circle Circle::operator--(int) { Circle temp(cor_x, cor_y); --(*this); return temp; } Circle Circle::operator+(double plusSize) { return Circle(radius + plusSize); } Circle Circle::operator-(double minusSize) { return Circle(radius - minusSize); } bool operator==(const Circle &c1, const Circle &c2) { return (c1.cirArea() == c2.cirArea()); } bool operator!=(const Circle &c1, const Circle &c2) { return !(c1 == c2); } bool operator>(const Circle &c1, const Circle &c2) { return (c1.cirArea() > c2.cirArea()); } bool operator<(const Circle &c1, const Circle &c2) { return (c1.cirArea() < c2.cirArea()); } bool operator>=(const Circle &c1, const Circle &c2) { return (c1.cirArea() >= c2.cirArea()); } bool operator<=(const Circle &c1, const Circle &c2) { return (c1.cirArea() <= c2.cirArea()); } int Circle::areaCounter = 0; double Circle::totalArea = 0.0; int Circle::perimeterCounter = 0; double Circle::totalPerimeter = 0.0; double Circle::staticCirArea(const Circle &c1) { totalArea += areaCounter * c1.cirArea(); return totalArea; } double Circle::staticCirPerimeter(const Circle &c1) { totalPerimeter += perimeterCounter * c1.cirPerimeter(); return totalPerimeter; }
8220fa596ecad7a5d7e650316619bf41546b03d3
7a49fdcdfe606c3e2d701056d7b752b8a1258265
/Source/seminar2/seminar2GameModeBase.cpp
e8bdf7c4342b35c7f2e639a68e3ecb4473ec2c3d
[]
no_license
JAX3/seminar-2-update-
0f93f4e4ccfd6ddc5a0d6a6a476dfaff738a8f19
572e3190b254be40415e795ac2d2b69e79ac0f45
refs/heads/master
2020-09-13T06:07:52.897357
2019-11-19T11:04:24
2019-11-19T11:04:24
222,676,220
0
0
null
null
null
null
UTF-8
C++
false
false
116
cpp
seminar2GameModeBase.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "seminar2GameModeBase.h"
2361080243a561a0d00e5e3146f1f83a0059367c
65aaba4d24cfbddb05acc0b0ad814632e3b52837
/src/osrm.net/libosrm/osrm-deps/boost/include/boost-1_62/boost/coroutine2/detail/pull_control_block_ecv1.hpp
568be7d4d9c0ecdf8f873e1feb67effcd1ce844a
[ "MIT" ]
permissive
tstaa/osrmnet
3599eb01383ee99dc6207ad39eda13a245e7764f
891e66e0d91e76ee571f69ef52536c1153f91b10
refs/heads/master
2021-01-21T07:03:22.508378
2017-02-26T04:59:50
2017-02-26T04:59:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
pull_control_block_ecv1.hpp
version https://git-lfs.github.com/spec/v1 oid sha256:256a7d9039e44d8f73f228fd7cd61aaa0fc89c654713d55f6913503468393d0c size 3689
72b8e1c6003d23627cec691dd3a7d8eb7609260c
a7d79c535ee42114d80aa6caa2708917321611f9
/src/leader/leader.hpp
b4d487122abfcd3fef75b1bbe364c93245b85061
[ "MIT" ]
permissive
di-unipi-socc/FogMon
422bca2c59ea4faa4d4d7f6811c481a7506e086b
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
refs/heads/master
2022-12-22T21:11:06.008599
2021-04-13T16:42:00
2021-04-13T16:42:00
148,777,271
7
4
MIT
2022-12-08T11:39:11
2018-09-14T11:05:18
C++
UTF-8
C++
false
false
1,291
hpp
leader.hpp
#ifndef LEADER_NODE_HPP_ #define LEADER_NODE_HPP_ class LeaderFactory; #include "leader_connections.hpp" #include "follower.hpp" #include "leader_storage.hpp" #include "server.hpp" #include "leader_factory.hpp" #include "ileader.hpp" #include "selector.hpp" class Leader : virtual public ILeader, public Follower { public: Leader(Message::node node, int nThreads); ~Leader(); bool setParam(std::string name, int value); virtual void initialize(LeaderFactory* factory = NULL); virtual void start(vector<Message::node> mNodes); virtual void stop(); ILeaderConnections* getConnections(); ILeaderStorage* getStorage(); Message::node getMyNode(); virtual bool initSelection(int id); virtual bool calcSelection(Message::node from, int id, bool &res); virtual bool updateSelection(Message::leader_update update); virtual void stopSelection(); virtual void changeRoles(Message::leader_update update); virtual void changeRole(std::vector<Message::node> leaders); protected: void timerFun(); //for the leader selection algorithms Selector selector; std::thread timerFunThread; LeaderConnections *connections; ILeaderStorage* storage; LeaderFactory tFactory; LeaderFactory *factory; }; #endif
d6fb8b4079ee3add7aab5ecd27246f1884d13630
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
/data_structure/binary_tree/test.cpp
08a2b888f2da98019fcb0004c9b095cbb1637da4
[]
no_license
ktosiu/snippets
79c58416117fa646ae06a8fd590193c9dd89f414
08e0655361695ed90e1b901d75f184c52bb72f35
refs/heads/master
2021-01-17T08:13:34.067768
2016-01-29T15:42:14
2016-01-29T15:42:14
53,054,819
1
0
null
2016-03-03T14:06:53
2016-03-03T14:06:53
null
UTF-8
C++
false
false
194
cpp
test.cpp
#include "binary_search_tree.h" int main() { BinarySearchTree<int, int> bst; bst.insert(4, 9); bst.insert(3, 9); bst.insert(9, 9); bst.insert(4, 9); bst.tranverse(); }
84b50f7756cf0327683b8cfc4ce051e5aedfc619
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/KerberosKeyDistributionCenter/UNIX_KerberosKeyDistributionCenter_HPUX.hxx
cdcfe5bfd780e8a289ded39b21109483716bdfa8
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
153
hxx
UNIX_KerberosKeyDistributionCenter_HPUX.hxx
#ifdef PEGASUS_OS_HPUX #ifndef __UNIX_KERBEROSKEYDISTRIBUTIONCENTER_PRIVATE_H #define __UNIX_KERBEROSKEYDISTRIBUTIONCENTER_PRIVATE_H #endif #endif
75f2ecc0f3a5f4b9b7c39dfcf0c115861b71f7eb
8d937ba1412c30a08ffd2a1196d65d836486534c
/Dynamic Programming/322. Coin Change.cpp
14b88ae0730ac56ca596d573aef7b396c1264e88
[]
no_license
ArpitSingla/LeetCode
5988f0a9f43c216ad2d61a847aca8b25ca2330be
4bfe51209e66ce3cee233841de9d4baa97454415
refs/heads/master
2021-03-20T22:14:01.234679
2020-07-30T04:09:04
2020-07-30T04:09:04
247,238,239
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
cpp
322. Coin Change.cpp
class Solution { public: //Using 2D Array int coinChange(vector<int>& coins, int amount) { int n=coins.size(); if(amount==0){ return 0; } vector<vector<unsigned int>> dp(n+1,vector<unsigned int>(amount+1,INT_MAX)); for(int i=0;i<=n;i++){ dp[i][0]=0; } for(int i=1;i<=n;i++){ for(int j=1;j<=amount;j++){ if(j>=coins[i-1]){ dp[i][j]=min(dp[i-1][j],1+dp[i][j-coins[i-1]]); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[n][amount]==INT_MAX?-1:dp[n][amount]; } //Using 1D Array int coinChange(vector<int>& coins, int amount) { int n=coins.size(); if(amount==0){ return 0; } vector<int> dp(amount+1,amount+1); dp[0]=0; for(int j=1;j<=amount;j++){ for(auto i:coins){ if(j>=i){ dp[j]=min(dp[j],1+dp[j-i]); } } } return dp[amount]>amount?-1:dp[amount]; } };
c45f24ee40c791ca0bdba9ae61743a129cd5015b
ac01f1a08fa65ddc25c32eb95db7363766bd1de8
/Exercises/06/Task6/Queue.hpp
d39cd26c15c164857756057897586d8f453b86f6
[]
no_license
gaper94/SD_IS_2017
ceace84733924a6d40c9a88fda77bcddb33e9968
5ca7b1819cc16f38a04ef28d41f40f657434b9b7
refs/heads/master
2021-09-03T15:35:44.269079
2018-01-10T06:44:15
2018-01-10T06:44:15
105,460,471
0
1
null
null
null
null
UTF-8
C++
false
false
1,535
hpp
Queue.hpp
////////////////////////////////////////////////////////////////////////// template<class T> queue<T>::queue(const queue& other) : container(other.container) { } ////////////////////////////////////////////////////////////////////////// template<class T> queue<T>& queue<T>::operator=(const queue& rhs) { if (this != &rhs) { container = rhs.container; } return *this; } ////////////////////////////////////////////////////////////////////////// template<class T> bool queue<T>::is_empty() const { return container.is_empty(); } ////////////////////////////////////////////////////////////////////////// template<class T> void queue<T>::enqueue(const T& data) { container.push_front(data); } ////////////////////////////////////////////////////////////////////////// template<class T> T queue<T>::dequeue() { return container.pop_back(); } ////////////////////////////////////////////////////////////////////////// template<class T> T& queue<T>::peek_first() { return container.peek_back(); } ////////////////////////////////////////////////////////////////////////// template<class T> const T& queue<T>::peek_first() const { return container.peek_back(); } ////////////////////////////////////////////////////////////////////////// template<class T> T& queue<T>::peek_last() { return container.peek_front(); } ////////////////////////////////////////////////////////////////////////// template<class T> const T& queue<T>::peek_last() const { return container.peek_front(); }
4e82ee494ce00be10b33dcb9b25341578314cd32
3abad4016d3500e3a39891531414316df06dfae0
/Observer/Observer/Observer.h
378542bda2703b2167111755439bcc301e6389d9
[]
no_license
helloOK2019/VS
f249b50c1007179231f86b3b88b159bef0c57832
7224e35e29d1c32cee7574525d7c4e17e6269386
refs/heads/master
2022-02-19T14:19:09.973349
2019-09-09T02:55:10
2019-09-09T02:55:10
207,193,849
0
0
null
null
null
null
GB18030
C++
false
false
499
h
Observer.h
#ifndef _OBSERVER_H_ #define _OBSERVER_H_ #include<string> using namespace std; //抽象观察者 class IObserver { public: IObserver(); IObserver(string szName); virtual ~IObserver(); void virtual Update(); private: }; //具体观察者 class CConcreteObserver : public IObserver { public: CConcreteObserver(); CConcreteObserver(string szName); ~CConcreteObserver(); void Update(); void SetName(string szName); string GetName(); private: string m_szName; }; #endif // !_OBSERVER_H_
e1e290fa53cabe35f1b9df6b1da617e482317098
d2871878756ce2b4dbcfc538bcc0ba7a5900c769
/ODE/ode_oop/oscillator/functions.h
e2b94482a542f63c7b41607c68ab5c3870f294d9
[]
no_license
Ziaeemehr/cpp_workshop
75934095eb057d0643d0b59db3712e83fba053d6
5752356aa7aa571c107f2fa042332ebb04ad37f1
refs/heads/master
2022-01-18T18:51:29.398280
2022-01-03T14:10:35
2022-01-03T14:10:35
170,557,736
5
0
null
null
null
null
UTF-8
C++
false
false
582
h
functions.h
#ifndef FUNCTIONS_H #define FUNCTIONS_H #include <fstream> #include <valarray> #include <cmath> #include <iomanip> using StateVec = std::valarray<double>; using DerivFunc = StateVec (*) (const StateVec &); using OutputFunc = void (*) (double , const StateVec &, std::ofstream &); using Integrator = void (*) (StateVec &, DerivFunc, double); void euler_integrator (StateVec &, DerivFunc, double); void runge_kutta4_integrator (StateVec &, DerivFunc, double); void integrate (Integrator, DerivFunc, OutputFunc, std::ofstream &, StateVec, int, double); #endif
57e63a0c6fa658268f5baf98d6ca3b14dbb2333a
4c25432a6d82aaebd82fd48e927317b15a6bf6ab
/data/dataset_2017/dataset_2017_8_formatted/imulan/8294486_5654117850546176_imulan.cpp
f2e37dfc9423a16563caa1bc11a2c4e36c45f63d
[]
no_license
wzj1988tv/code-imitator
dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933
07a461d43e5c440931b6519c8a3f62e771da2fc2
refs/heads/master
2020-12-09T05:33:21.473300
2020-01-09T15:29:24
2020-01-09T15:29:24
231,937,335
1
0
null
2020-01-05T15:28:38
2020-01-05T15:28:37
null
UTF-8
C++
false
false
1,109
cpp
8294486_5654117850546176_imulan.cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i, n) for (int(i) = 0; (i) < (int)(n); ++(i)) #define all(x) (x).begin(), (x).end() #define pb push_back #define fi first #define se second const string ng = "IMPOSSIBLE"; using P = pair<int, char>; bool check(string s) { int S = s.size(); if (s[0] == s[S - 1]) return false; rep(i, S - 1) if (s[i] == s[i + 1]) return false; return true; } string small_solve() { int n, R, O, Y, G, B, V; cin >> n >> R >> O >> Y >> G >> B >> V; int m = max({R, Y, B}); if (2 * m > n) { // printf(" INPUT %d %d %d\n", R,Y,B); return ng; } // return " "; vector<P> p; p.pb(P(R, 'R')); p.pb(P(Y, 'Y')); p.pb(P(B, 'B')); sort(all(p)); string s(n, ' '); rep(i, p[2].fi) s[2 * i] = p[2].se; int st = n - 1; if (n % 2 == 1) --st; rep(i, p[1].fi) s[st - 2 * i] = p[1].se; rep(i, n) if (s[i] == ' ') s[i] = p[0].se; assert(check(s)); return s; } int main() { int T; cin >> T; rep(t, T) { printf("Case #%d: ", t + 1); cout << small_solve() << endl; } return 0; }
940fa6bdeaa2c042ad5ddb7f201ecd8d755c13dd
85fcd407df2eb50ea6e015580986f950882f9fd4
/basics/Strings/StringSubsequence.cpp
79357d1ad0a400f20782cc7c12e9f417d3ce0ac9
[]
no_license
naveen700/CodingPractice
ff26c3901b8721cb0c6de32f8df246b999893471
d4f7c756974a5eee16c79e8d98f86b546260aa6d
refs/heads/master
2021-01-16T02:19:27.387955
2020-04-26T17:41:08
2020-04-26T17:41:08
242,941,499
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
StringSubsequence.cpp
#include <iostream> using namespace std; void printAllSubsequence(char *in , char *out , int i, int j){ // base case if(in[i] == '\0'){ out[j] = '\0'; cout<<out<<endl; return ; } // recursive case // include the curent char out[j] = in[i]; printAllSubsequence(in ,out, i+1,j+1); // exclude the current char printAllSubsequence(in,out, i+1,j); } int main(){ char in[100]; cin>>in; char out[100]; printAllSubsequence(in,out,0,0); return 0; }
cb434883774e6ebdb8fa0b7905b20538b3164d40
a3a7815f2f04bac5844c7144d969a11811d4d188
/gui/MainWindow.cpp
4fbb785f70001155686762a9cc4be37565e3fe45
[]
no_license
Ky3He4iK/InfinityLoopQt
dc909f42961c5a92f5dd12c2c2fb17b064a3a732
9ad7d2e5b2ff21ed83a78a1439a05a4de6e9bbfc
refs/heads/master
2022-03-23T17:08:29.500427
2019-12-12T00:13:29
2019-12-12T00:13:29
198,165,287
0
0
null
null
null
null
UTF-8
C++
false
false
993
cpp
MainWindow.cpp
// // Created by ky3he4ik on 28/07/19. // #include "MainWindow.h" #include "util/IconManager.h" #include <QVBoxLayout> MainWindow::MainWindow(size_t width, size_t height, size_t iconSize, uint8_t solverLevel) { IconManager::getInstance().setIconSize(iconSize); field = new Field(width, height, solverLevel); controlsWidget = new ControlsWidget(Q_NULLPTR, width, height, solverLevel); controlsWidget->adjustSize(); controlsWidget->setWindowTitle("Controls | InfinityLoopQt"); controlsWidget->show(); recreateFieldWidgetSlot(); connect(controlsWidget, &ControlsWidget::resizeSignal, field, &Field::restartSlot); } void MainWindow::recreateFieldWidgetSlot() { delete fieldWidget; fieldWidget = new FieldWidget(Q_NULLPTR, field); fieldWidget->adjustSize(); fieldWidget->setWindowTitle("Field | InfinityLoopQt"); fieldWidget->show(); connect(fieldWidget, &FieldWidget::deleteMeSignal, this, &MainWindow::recreateFieldWidgetSlot); }
90c36bbd1c1af9a3e4442dae52e0710ebba7d9fb
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/llvm/3.5.0/include/llvm/Support/EndianStream.h
89c66d3b84809337abcd198473ae3c71485f65d6
[ "MIT", "LicenseRef-scancode-proprietary-license", "NCSA" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
1,187
h
EndianStream.h
//===- EndianStream.h - Stream ops with endian specific data ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines utilities for operating on streams that have endian // specific data. // //===----------------------------------------------------------------------===// #ifndef _LLVM_SUPPORT_ENDIAN_STREAM_H_ #define _LLVM_SUPPORT_ENDIAN_STREAM_H_ #include <llvm/Support/Endian.h> #include <llvm/Support/raw_ostream.h> namespace llvm { namespace support { namespace endian { /// Adapter to write values to a stream in a particular byte order. template <endianness endian> struct Writer { raw_ostream &OS; Writer(raw_ostream &OS) : OS(OS) {} template <typename value_type> void write(value_type Val) { Val = byte_swap<value_type, endian>(Val); OS.write((const char *)&Val, sizeof(value_type)); } }; } // end namespace endian } // end namespace support } // end namespace llvm #endif // _LLVM_SUPPORT_ENDIAN_STREAM_H_
7e72748e4c274645beb0a0a1f8db7521888bc411
449ccdaba93a620dbffb0fd8b5d48cdd9283a0ca
/dibujarCirculo/dibujarCirculo/Source.cpp
04ef6155c72c74990c8b09bbad488e9594279377
[]
no_license
AndresFDaza/intCompuGrafica
965b3803bc7d9d1372aacace0c84e869466a83f1
8ab7c43ad88b973af137e8de8b67e8b06e6fdaf6
refs/heads/master
2021-01-09T14:57:03.643955
2020-10-30T20:19:06
2020-10-30T20:19:06
242,335,585
0
0
null
null
null
null
UTF-8
C++
false
false
2,668
cpp
Source.cpp
#include <iostream> #include <math.h> #include "glut.h" bool click = false; int a = 0, b = 0, x = 0, y = 0, radio = 0; // global de puntos insertados int xPantalla = 800, yPantalla = 800; //global para cambio tamaño pantalla // Funcion pinta pixel individual void pixel(float xPos, float yPos, float RedColor, float GreenColor, float BlueColor, int tamPoint) { glPointSize(tamPoint); glColor3f(RedColor, GreenColor, BlueColor); glBegin(GL_POINTS); glVertex2f(xPos, yPos); glEnd(); glutSwapBuffers(); } //Funcion pinta ejes x y y void pintaPlano() { //pintar plano, lineas por mitad del tamaño total - color gris for (int i = -xPantalla / 2; i < xPantalla / 2; i++) { pixel(i, 0, 0.5, 0.5, 0.5, 2); } for (int i = -xPantalla / 2; i < xPantalla / 2; i++) { pixel(0, i, 0.5, 0.5, 0.5, 2); } } //Funcion para pintar un circulo void pintaCirculo() { double radio, circX, circY; int grosorCirculo = 3; radio = sqrt(pow(x - a, 2) + pow(y - b, 2)); circX = a; while (circX <= radio) { circY = sqrt(pow(radio, 2) - pow(circX, 2)); //primer cuadrante pixel(circX + a, circY + b, 1, 1, 1, grosorCirculo); pixel(circY + a, circX + b, 1, 1, 1, grosorCirculo); //segundo cuadrante pixel(circX + a, -circY + b, 1, 1, 1, grosorCirculo); pixel(circY + a, -circX + b, 1, 1, 1, grosorCirculo); //tercer cuadrante pixel(-circX + a, -circY + b, 1, 1, 1, grosorCirculo); pixel(-circY + a, -circX + b, 1, 1, 1, grosorCirculo); //cuarto cuadrante pixel(-circX + a, circY + b, 1, 1, 1, grosorCirculo); pixel(-circY + a, circX + b, 1, 1, 1, grosorCirculo); circX = circX + 1; } } //Funcion lee puntos central y de radio void clickeaMouse(int button, int state, int xPos, int yPos) { xPos = xPos - xPantalla / 2; yPos = yPantalla / 2 - yPos; //punto centro if (click == false) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { a = xPos; b = yPos; pixel(a, b, 0, 0, 1, 6); click = true; } } //punto radio else { if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { x = xPos; y = yPos; pixel(x, y, 1, 0, 0, 6); pintaCirculo(); click = false; glFlush(); } } } //Funcion principal (main) int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(xPantalla, yPantalla); glutInitWindowPosition(300, 200); glutCreateWindow("ALGORITMO PARA DIBUJAR UN CIRCULO"); gluOrtho2D(-xPantalla / 2, xPantalla / 2, -yPantalla / 2, yPantalla / 2); //origen "vista- camara" en el centro de la pantalla (tamaño en global) glutDisplayFunc(pintaPlano); glutMouseFunc(clickeaMouse); glutMainLoop(); return 0; }
ec29af74aecffd7ec361369b2fb47d6ae2ef8cbc
fa86389c80009665eb135fc1857c8c83bf442bbb
/CPP01/ex00/randomChump.cpp
ad3cb92aed26d4ac43756235eea5b34d8e812462
[]
no_license
Gtaverne/41-CPP
04a26a3281b311f28bb2fd55fdb3d134aa1ab070
4c7976fe8aa47e07c979430003677a032b8b71bb
refs/heads/master
2023-08-30T03:34:33.566542
2021-10-16T19:53:21
2021-10-16T19:53:21
384,514,595
0
0
null
null
null
null
UTF-8
C++
false
false
107
cpp
randomChump.cpp
#include "Zombie.hpp" void randomChump( std::string name ) { Zombie arsene(name); arsene.announce(); }
b5b25387583a93f8c23140b10481a0f52967ca87
93343c49771b6e6f2952d03df7e62e6a4ea063bb
/HDOJ/5251_autoAC.cpp
87fea91a16648334012faa01150637c5f74ccb51
[]
no_license
Kiritow/OJ-Problems-Source
5aab2c57ab5df01a520073462f5de48ad7cb5b22
1be36799dda7d0e60bd00448f3906b69e7c79b26
refs/heads/master
2022-10-21T08:55:45.581935
2022-09-24T06:13:47
2022-09-24T06:13:47
55,874,477
36
9
null
2018-07-07T00:03:15
2016-04-10T01:06:42
C++
UTF-8
C++
false
false
5,006
cpp
5251_autoAC.cpp
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<math.h> #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; typedef double typev; const double eps = 1e-8; const int N = 50005; int sign(double d){ return d < -eps ? -1 : (d > eps); } struct point{ typev x, y; point operator-(point d){ point dd; dd.x = this->x - d.x; dd.y = this->y - d.y; return dd; } point operator+(point d){ point dd; dd.x = this->x + d.x; dd.y = this->y + d.y; return dd; } }ps[N]; //int n, cn; double dist(point d1, point d2){ return sqrt(pow(d1.x - d2.x, 2.0) + pow(d1.y - d2.y, 2.0)); } double dist2(point d1, point d2){ return pow(d1.x - d2.x, 2.0) + pow(d1.y - d2.y, 2.0); } bool cmp(point d1, point d2){ return d1.y < d2.y || (d1.y == d2.y && d1.x < d2.x); } typev xmul(point st1, point ed1, point st2, point ed2){ return (ed1.x - st1.x) * (ed2.y - st2.y) - (ed1.y - st1.y) * (ed2.x - st2.x); } typev dmul(point st1, point ed1, point st2, point ed2){ return (ed1.x - st1.x) * (ed2.x - st2.x) + (ed1.y - st1.y) * (ed2.y - st2.y); } struct poly{ static const int N = 50005; point ps[N+5]; int pn; poly() { pn = 0; } void push(point tp){ ps[pn++] = tp; } int trim(int k){ return (k+pn)%pn; } void clear(){ pn = 0; } }; poly graham(point* ps, int n){ sort(ps, ps + n, cmp); poly ans; if(n <= 2){ for(int i = 0; i < n; i++){ ans.push(ps[i]); } return ans; } ans.push(ps[0]); ans.push(ps[1]); point* tps = ans.ps; int top = -1; tps[++top] = ps[0]; tps[++top] = ps[1]; for(int i = 2; i < n; i++){ while(top > 0 && xmul(tps[top - 1], tps[top], tps[top - 1], ps[i]) <= 0) top--; tps[++top] = ps[i]; } int tmp = top; for(int i = n - 2; i >= 0; i--){ while(top > tmp && xmul(tps[top - 1], tps[top], tps[top - 1], ps[i]) <= 0) top--; tps[++top] = ps[i]; } ans.pn = top; return ans; } point getRoot(point p, point st, point ed){ point ans; double u=((ed.x-st.x)*(ed.x-st.x)+(ed.y-st.y)*(ed.y-st.y)); u = ((ed.x-st.x)*(ed.x-p.x)+(ed.y-st.y)*(ed.y-p.y))/u; ans.x = u*st.x+(1-u)*ed.x; ans.y = u*st.y+(1-u)*ed.y; return ans; } point change(point st, point ed, point next, double l){ point dd; dd.x = -(ed - st).y; dd.y = (ed - st).x; double len = sqrt(dd.x * dd.x + dd.y * dd.y); dd.x /= len, dd.y /= len; dd.x *= l, dd.y *= l; dd = dd + next; return dd; } double getMinAreaRect(point* ps, int n, point* ds){ int cn, i; double ans; point* con; poly tpoly = graham(ps, n); con = tpoly.ps; cn = tpoly.pn; if(cn <= 2){ ds[0] = con[0]; ds[1] = con[1]; ds[2] = con[1]; ds[3] = con[0]; ans=0; }else{ int l, r, u; double tmp, len; con[cn] = con[0]; ans = 1e40; l = i = 0; while(dmul(con[i], con[i+1], con[i], con[l]) >= dmul(con[i], con[i+1], con[i], con[(l-1+cn)%cn])){ l = (l-1+cn)%cn; } for(r=u=i = 0; i < cn; i++){ while(xmul(con[i], con[i+1], con[i], con[u]) <= xmul(con[i], con[i+1], con[i], con[(u+1)%cn])){ u = (u+1)%cn; } while(dmul(con[i], con[i+1], con[i], con[r]) <= dmul(con[i], con[i+1], con[i], con[(r+1)%cn])){ r = (r+1)%cn; } while(dmul(con[i], con[i+1], con[i], con[l]) >= dmul(con[i], con[i+1], con[i], con[(l+1)%cn])){ l = (l+1)%cn; } tmp = dmul(con[i], con[i+1], con[i], con[r]) - dmul(con[i], con[i+1], con[i], con[l]); tmp *= xmul(con[i], con[i+1], con[i], con[u]); tmp /= dist2(con[i], con[i+1]); len = xmul(con[i], con[i+1], con[i], con[u])/dist(con[i], con[i+1]); if(sign(tmp - ans) < 0){ ans = tmp; ds[0] = getRoot(con[l], con[i], con[i+1]); ds[1] = getRoot(con[r], con[i+1], con[i]); ds[2] = change(con[i], con[i+1], ds[1], len); ds[3] = change(con[i], con[i+1], ds[0], len); } } } return ans+eps; } int main () { int t ,n ,i ,NN ,cas = 1; point ds[10]; scanf("%d" ,&t); while(t--) { scanf("%d" ,&NN); int n = 0; for(i = 1 ;i <= NN ;i ++) { for(int j = 1 ;j <= 4 ;j ++) { scanf("%lf %lf" ,&ps[n].x ,&ps[n].y); n++; } } double ans = getMinAreaRect(ps ,n ,ds); printf("Case #%d:\n" ,cas ++); printf("%.0lf\n" ,ans); } return 0; }
241025cb84782d2ecd1c51bb2dce2160a2e57965
70ad0a06c54b68b7d817131f4b139b76739e2e20
/IO/ClientSocketWriterTask.h
0915ed41c4dcfffb42b5871ccff72d85a1e1795e
[ "MIT" ]
permissive
SherlockThang/sidecar
391b08ffb8a91644cbc86cdcb976993386aca70c
2d09dfaebee3c9b030db4d8503b765862e634068
refs/heads/master
2022-12-09T14:57:08.727181
2020-09-01T10:31:12
2020-09-01T10:31:12
313,326,062
1
0
MIT
2020-11-16T14:21:59
2020-11-16T14:21:58
null
UTF-8
C++
false
false
6,344
h
ClientSocketWriterTask.h
#ifndef SIDECAR_IO_CLIENTSOCKETWRITERTASK_H // -*- C++ -*- #define SIDECAR_IO_CLIENTSOCKETWRITERTASK_H #include "ace/Connector.h" #include "ace/SOCK_Connector.h" #include "ace/Svc_Handler.h" #include "IO/IOTask.h" #include "IO/Writers.h" namespace Logger { class Log; } namespace SideCar { namespace IO { /** An ACE task that keeps alive a connection to a remote server. Incoming messages to its processing queue are written out to the remote server. */ class ClientSocketWriterTask : public IOTask { public: using Ref = boost::shared_ptr<ClientSocketWriterTask>; /** Log device for objects of this type. \return log device */ static Logger::Log& Log(); /** Factory method for creating new ClientSocketWriterTask objects \return reference to new ClientSocketWriterTask object */ static Ref Make(); /** Open a connection to a remote host/port. \param key message type key for data sent out port \param hostName name of the remote host to connect to \param port the port of the remote host to connect to \return true if successful, false otherwise */ bool openAndInit(const std::string& key, const std::string& hostName, uint16_t port); /** Override of ACE_Task method. The service is begin shutdown. Close the socket connection. \param flags if 1, signal service thread to shutdown. \return 0 if successful, -1 otherwise. */ int close(u_long flags = 0); protected: /** Constructor. Does nothing -- like most ACE classes, all initialization is done in the init and open methods. */ ClientSocketWriterTask() : IOTask(), connector_(this) {} private: /** Implementation of Task::deliverDataMessage() method. Places message onto the thread's processing queue. \param data message to deliver \param timeout amount of time to spend trying to deliver message \return true if successful */ bool deliverDataMessage(ACE_Message_Block* data, ACE_Time_Value* timeout); class Connector; /** Helper class that does the writing of data out on a socket connection. There is only one instance of this alive, regardless how many times the connection is reestablished. */ class OutputHandler : public ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_MT_SYNCH> { public: using Super = ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_MT_SYNCH>; /** Log device for objects of this type. \return log device */ static Logger::Log& Log(); /** Constructor. \param task the task whose message queue we pull from */ OutputHandler(ClientSocketWriterTask* task = 0) : Super(0, task->msg_queue(), task->reactor()), connector_(0), writer_() { } /** Override of ACE_Task method. Setup a new connection to the remote host. This routine is called each time a connection is (re)stablished. \param arg Connector object that established the connection \return 0 if successful, -1 otherwise */ int open(void* arg); /** Override of ACE_Task method. Shut the service down. \return 0 if successful, -1 otherwise */ int close(u_long flags = 0); private: /** Override of ACE_Event_Handler method. Notification that the connection to the remote host has closed. Set things up to gracefully attempt a reconnection. \param handle connection that closed \return 0 if successful, -1 otherwise. */ int handle_input(ACE_HANDLE handle); /** Override of ACE_Task method. Continuously pulls messages off of the processing queue and sends them out on an active socket connection. Runs in a separate thread. \return 0 always */ int svc(); Connector* connector_; ///< Connector object that manages connections TCPSocketWriter writer_; ///< Object that does the actual sending }; /** Helper class that does the connecting to a remote host. If unable to connect, will keep trying every second or so. Likewise if the connection drops. */ class Connector : public ACE_Connector<OutputHandler, ACE_SOCK_CONNECTOR> { public: using Super = ACE_Connector<OutputHandler, ACE_SOCK_CONNECTOR>; /** Log device for objects of this type. \return log device */ static Logger::Log& Log(); /** Constructor \param task task from which to pull messages to emit. */ Connector(ClientSocketWriterTask* task) : Super(task->reactor()), outputHandler_(task), remoteAddress_(), timer_(-1), shutdown_(false) { } /** Atttempt to connect to a remote host using the given address. \param remoteAddress address of remote host to connect to \param reactor the ACE_Reactor to register with \return true if successful, false otherwise */ bool openAndInit(const ACE_INET_Addr& remoteAddress, ACE_Reactor* reactor); /** Attempt to reestablish a connection to a remote host. \return true if successful, false otherwise */ bool reconnect(); /** Override of ACE_Task method. Shut down the output handler \param flags ignored \return 0 if successful, -1 otherwise */ int close(); private: /** Notification that our attempt to connect to a remote server has timed out. Try again. \param timeout \param arg \return */ int handle_timeout(const ACE_Time_Value& timeout, const void* arg); /** Attempt to (re)connect to a remote host using the cached connection address. \return true if successful, false otherwise */ bool doconnect(); OutputHandler outputHandler_; ///< Output handler for all connections ACE_INET_Addr remoteAddress_; ///< Address for remote host connection long timer_; bool shutdown_; }; Connector connector_; ///< Object that manages the socket connection }; } // end namespace IO } // end namespace SideCar /** \file */ #endif
d8ce950ee90058d52d879ef1ef13f9731e5ed15e
d489ca093bc0e70fbc653c35a97564aff79963d7
/src/debug_operations.ipp
327ed7d17ec426cb784e053c5c071fe407f9872e
[]
no_license
mocelik/TwoFourTree
04bb6b7595db28f43efce4b6f3345a3dbe7fa1c1
ea5bbcfdaafafe913734a8740381a2e155da953d
refs/heads/master
2023-04-21T06:27:36.156223
2021-05-08T05:57:32
2021-05-08T05:57:32
249,019,969
0
0
null
2021-05-08T05:53:33
2020-03-21T16:52:26
C++
UTF-8
C++
false
false
10,549
ipp
debug_operations.ipp
/* * Filename: debug.ipp * * Created on: Apr. 17, 2020 * Author: orhan * * Description: * Contains debug operation implementations for both the TwoFourTree and the Node class */ #ifndef SRC_DEBUG_OPERATIONS_IPP_ #define SRC_DEBUG_OPERATIONS_IPP_ #include <iomanip> #include <functional> #include <unordered_map> namespace tft { /** * Verify all nodes have the correct child-parent relationship */ template <class K, class C, class A> bool TwoFourTree<K,C,A>::validate() const { return root_->validateRelationships(); } /** * Use a deque<parent, child> to do a breadth-first search over the entire tree to ensure * every child knows who its parent is */ template <class K, class C, class A> bool TwoFourTree<K,C,A>::Node::validateRelationships() const { const Node * node = this; bool rc = true; // parent -> child std::deque<std::pair<const TwoFourTree::Node*, const TwoFourTree::Node*>> allNodes; allNodes.push_back(std::make_pair(nullptr, node)); while (!allNodes.empty()) { auto check = allNodes.front(); allNodes.pop_front(); node = check.second; // Check if the parent/child relationships are consistent if (check.first != check.second->parent_) { rc = false; std::cout << "parent of [" << check.second->getString() << "] doesn't have correct parent.\n"; std::cout << "parent should be: "; if (check.first == nullptr) std::cout << "nullptr\n"; else std::cout << check.first->getString() << "\n"; std::cout << "instead it is: "; if (check.second->parent_ == nullptr) std::cout << "nullptr\n"; else std::cout << check.second->parent_->getString() << "\n"; } // verify the internal contents are sorted for (int i=1; i < node->num_keys_; i++) { if (node->keys_[i-1] > node->keys_[i]) { rc = false; std::cout << "node keys out of order! " << node->keys_[i-1] << " is left of " << node->keys_[i] << std::endl; std::cout << *this << std::endl; } } // Count the number of children in the node // For N keys in a node there should be N+1 children (except for leaf nodes) // Also check to make sure the children contain either bigger or smaller values, // depending on which child it is // While we're traversing we also add each child to the list of nodes to be traversed int num_children = 0; for (int i = 0; i < node->num_keys_; i++) { // First N children should have values smaller than keys_[i] if (node->children_[i]) { const Node *child = node->children_[i].get(); if (child->keys_[child->num_keys_-1] > node->keys_[i]) { rc = false; std::cout << "child to left has key greater than key (" << child->keys_[child->num_keys_ - 1] << " > " << node->keys_[i] << ")\n"; } allNodes.push_back(std::make_pair(node,node->children_[i].get())); ++num_children; } } if (node->children_[node->num_keys_]) { // Last (Nth) child should have value bigger than keys_[max] const Node *child = node->children_[node->num_keys_].get(); if (child->keys_[0] < node->keys_[node->num_keys_-1]){ rc = false; std::cout << "rightmost child has key less than my key (" << child->keys_[0] << " < " << node->keys_[node->num_keys_-1] << ")\n"; } allNodes.push_back(std::make_pair(node,child)); ++num_children; } // verify correct number of children if (!node->isLeaf() && num_children != node->num_keys_ + 1) { std::cout << "number of keys and children mismatch.\n"; std::cout << "Node contents = [" << node->getString() << "], num_keys = " << node->num_keys_ << ", #children (" << num_children <<"): \n"; for (int i = 0; i < num_children; i++) { std::cout << node->children_[i]->getString() << " "; } std::cout << "\n"; rc = false; } } // end loop return rc; } /** * Prints the tree level by level */ template<class K, class C, class A> std::string TwoFourTree<K,C,A>::getString() const{ if (root_) return root_->getStringAll(); else return ""; } template<class K, class C, class A> void TwoFourTree<K,C,A>::print() const{ root_->printAll(); } template<class K, class C, class A> void TwoFourTree<K,C,A>::Node::printAll() const { std::cout << getStringAll(); } template<class K, class C, class A> std::string TwoFourTree<K,C,A>::Node::getStringAll() const { /** * Struct to track the horizontal displacement of the nodes * For leaves, end-begin should be equal to the string length + 1 * For internal nodes, begin will be where the first child begins, * and end will be where the last child ends * * When printing, leaf nodes will print normally. * Internal nodes will print at the average of the begin and end locations */ struct location{ int begin; int end; }; std::deque<const Node*> nodes_to_be_printed; std::unordered_map<const Node*, location> offsets; std::function<void(const Node*, int)> SetBeginLocation = [&offsets, &SetBeginLocation](const Node* node, int begin) { auto it = offsets.find(node); if (it == offsets.end()) { std::cout << "logic error\n"; return; } it->second.begin = begin; if (node->parent_ != nullptr) { auto myidx = node->getMyChildIdx(); if (myidx == 0) { SetBeginLocation(node->parent_, begin); } else { return; } } }; std::function<void(const Node*, int)> SetEndLocation = [&offsets, &SetEndLocation](const Node *node, int end) { auto it = offsets.find(node); if (it == offsets.end()) { std::cout << "logic error\n"; return; } it->second.end = end; if (node->parent_ != nullptr) { auto myidx = node->getMyChildIdx(); if (myidx == node->parent_->num_keys_) { auto whitespace_width = it->second.end - it->second.begin; auto trailing_whitespace_width = whitespace_width / 2 - ((node->getString().length() + 1) / 2); SetEndLocation(node->parent_, end - trailing_whitespace_width); } else { return; } } }; Node end_of_level(nullptr); nodes_to_be_printed.push_back(this); nodes_to_be_printed.push_back(&end_of_level); int current_offset = 0; while (!nodes_to_be_printed.empty()) { const Node *node = nodes_to_be_printed.front(); nodes_to_be_printed.pop_front(); if (node == &end_of_level) { // when we come across this, we know we reached the end of this line nodes_to_be_printed.push_back(&end_of_level); // put it back in so we know for the next iteration current_offset = 0; if (nodes_to_be_printed.front() == &end_of_level) break; // if there isn't another iteration then we've traversed the entire node else continue; } /** * If we are a leaf node then recursively set parent horizontal displacements */ if (node->isLeaf()) { auto start_offset = current_offset; current_offset += node->getString().length() + 1 ; // +1 for space afterwards location l; l.begin = start_offset; l.end = current_offset; offsets.emplace(node, l); SetBeginLocation(node, start_offset); SetEndLocation(node, current_offset); } else { location l {0,0}; offsets.emplace(node, l); } for (int i=0; i < node->kMaxNumChildren; i++) { if (node->children_[i]) { nodes_to_be_printed.push_back(node->children_[i].get()); } } } // end loop // for (const auto& it : offsets) { // std::cout << *it.first << " b: " << it.second.begin << ", e: " << it.second.end << std::endl; // } // std::cout << "---------------------------------------------------------------------------------\n"; // Begin the actual printing std::stringstream ss; { nodes_to_be_printed.clear(); nodes_to_be_printed.push_back(this); nodes_to_be_printed.push_back(&end_of_level); current_offset = 0; while (!nodes_to_be_printed.empty()) { const Node *node = nodes_to_be_printed.front(); nodes_to_be_printed.pop_front(); if (node == &end_of_level) { // when we come across this, we know we reached the end of this line ss << "\n"; // print newline nodes_to_be_printed.push_back(&end_of_level); // put it back in so we know for the next iteration if (nodes_to_be_printed.front() == &end_of_level) // check if there will even be a next iteration break; // if there isn't then we've traversed the entire node else continue; } int printed_length = 0; if (node->isLeaf()) { ss << node->getString() << ' '; printed_length += node->getString().length() + 1; } else { auto str = node->getString() + ' '; auto strlen = str.length(); location l = offsets.find(node)->second; unsigned int given_length = l.end - l.begin; assert(given_length > strlen); ss << std::setw(given_length/2 + strlen/2) << std::right << str << std::setw(given_length/2 - strlen/2) << ' '; printed_length = given_length; } current_offset += printed_length; for (int i = 0; i < node->kMaxNumChildren; i++) { if (node->children_[i]) nodes_to_be_printed.push_back(node->children_[i].get()); } } // end loop ss << std::endl; } return ss.str(); } template <class K, class C, class A> std::string TwoFourTree<K,C,A>::Node::getString() const { std::stringstream ss; if (num_keys_ == 0) return "[]"; ss << "[" << keys_[0]; for (int i=1; i < num_keys_-1; i++) { ss << ", " << keys_[i]; } if (num_keys_ > 1) ss <<", " << keys_[num_keys_-1] << "]"; else ss << "]"; return ss.str(); } // useful when debugging, not used as part of other functions template <class K, class C, class A> void TwoFourTree<K,C,A>::Node::print() const { std::cout << getString() << std::endl; } template <class K, class C, class A> void TwoFourTree<K,C,A>::const_iterator::print() const { std::cout << getString() << std::endl; } template <class K, class C, class A> std::string TwoFourTree<K,C,A>::const_iterator::getString() const { std::stringstream ss; ss << "it: "; if (node_ == nullptr) { ss << "nullptr, idx = " << idx_ ; } else if (idx_ == node_->num_keys_) { ss << "after end iterator (node:" << node_->getString() << "), idx = " << idx_ ; } else if (idx_ == -1) { ss << "before beginning iterator (node:" << node_->getString() << "), idx = " << idx_; } else { ss << "n:" << node_->getString() << " idx_:" << idx_; } return ss.str(); } /** * Goes as high up as it can then prints everything below */ template <class K, class C, class A> void TwoFourTree<K, C, A>::Node::tryPrintAllFromParent(int verbosity) { if (verbosity < 1) return; Node *node = this; while (node->parent_) node = node->parent_; node->printAll(); } } /* namespace tft */ #endif /* SRC_DEBUG_OPERATIONS_IPP_ */
acc9b4d0260111db7ed2db77a4a896110393720e
57b5abdb8ec6c7df3d162d50f57ff051420b710b
/dxHookDLL/GLScreenshoter.cpp
f5865a2bb8aae6287e6d2fc43ec1d7ae11d3b2f5
[]
no_license
IGR2014/ScreenShotTool
3cd40cecc211bbb4799b4dcb059d842f7a663199
423d1d54be3d2b294febd6155023d99fc5f42d23
refs/heads/master
2020-04-22T10:37:16.498888
2019-02-12T12:09:05
2019-02-12T12:09:05
170,311,090
3
4
null
null
null
null
UTF-8
C++
false
false
1,244
cpp
GLScreenshoter.cpp
#include <windows.h> #include <fstream> #include <GL/gl.h> #include "HookFunction.hpp" #include "GLScreenshoter.hpp" // C-tor GLScreenshoter::GLScreenshoter() : endFunction(NULL), endHook(new funcHook()) { wcscpy_s(logPath, MAX_PATH, dllPath); wcscat_s(logPath, MAX_PATH, L"\\Logs\\GLLog.txt"); wcscpy_s(screenPath, MAX_PATH, dllPath); wcscat_s(screenPath, MAX_PATH, L"\\Screenshots\\GLScreenshot.jpg"); globalGLScreenshoter = this; } // Hook DX function BOOL DX9Screenshoter::hook() { HINSTANCE hOpenGL = GetModuleHandle(L"opengl32.dll"); if (hOpenGL == NULL) { return FALSE; } HRESULT h; HMODULE hGL = LoadLibrary(L"opengl32"); if (hGL == NULL) { return FALSE; } #ifdef _WIN64 endFunction = (OPENGLEND)endHook->install(, (LPBYTE)hookedGLEnd, 19); VirtualProtect(endFunction, 19, PAGE_EXECUTE_READWRITE, &previousProtection); #else endFunction = (OPENGLEND)endHook->install(, (LPBYTE)hookedGLEnd, 5); VirtualProtect(endFunction, 5, PAGE_EXECUTE_READWRITE, &previousProtection); #endif FreeModule(hGL); return TRUE; }
6295a8c88f8cd821028c44fd7b97a70ed9df9d42
f66b53e0909f79403a42f9687a837c85f8ffc150
/parse/DimacsParser.cpp
e4117986023ff3942bfcd1c00007eeef037f99c2
[]
no_license
CapacitorSet/graph-coloring
bd325a0cd879fbd7466c6cca3ecb872c66341c65
279077eeb4ffaa19236b8d62437a07bfdc4b50d9
refs/heads/master
2023-08-28T07:24:08.713733
2021-09-27T09:20:32
2021-09-27T09:20:32
382,003,799
1
0
null
null
null
null
UTF-8
C++
false
false
4,431
cpp
DimacsParser.cpp
#include "DimacsParser.h" #include "../utils/PCVector.h" #include "../utils/RangeSplitter.h" #include "Parser.h" #include <algorithm> #include <cmath> #include <sstream> #include <thread> DimacsParser::DimacsParser(std::ifstream &_file, const std::string &filename) : file(std::move(_file)), fastparse_file(filename + ".fast"), num_threads(2) { if (!fastparse_file.is_open()) throw std::runtime_error("Failed to open fastparse file for writing!"); } Graph DimacsParser::parse() { std::string header; std::getline(file, header); // Some files begin with this string for some reason; read the next line if so if (header == "graph_for_greach") std::getline(file, header); num_vertices = std::stoul(header); // Contains the adjacency lists parsed from the file std::vector<adjacency_vec_t> vertices = parse_lines(); // A new vector where to merge vertices, so as not to risk creating the same edges twice std::vector<adjacency_vec_t> merged_vertices = merge_adj_lists(vertices); return Graph(merged_vertices); } std::vector<uint32_t> DimacsParser::parse_numbers(const std::string &line) { std::vector<uint32_t> ret; std::istringstream line_str(line); std::string number_str; // std::getline reads line_str up to the next space and writes it into number_str // Skip the first token (containing the sequential node ID) std::getline(line_str, number_str, ' '); while (std::getline(line_str, number_str, ' ')) { if (number_str == "#") break; uint32_t number = std::stoul(number_str); ret.emplace_back(number); } return ret; } std::vector<adjacency_vec_t> DimacsParser::parse_lines() { // Contains the adjacency lists parsed from the file std::vector<adjacency_vec_t> vertices(num_vertices); // Empirically, the single-thread version performs better by ~30%. if (num_threads == 1) { std::string line; for (uint32_t i = 0; i < num_vertices; i++) { std::getline(file, line); vertices[i] = parse_numbers(line); } } else { using index_line_t = std::pair<std::vector<adjacency_vec_t>::iterator, std::string>; PCVector<index_line_t> line_queue; line_queue.onReceive( num_threads, (void (*)(index_line_t))[](index_line_t pair) { *pair.first = parse_numbers(pair.second); }); std::string line; for (uint32_t i = 0; i < num_vertices; i++) { std::getline(file, line); line_queue.push(std::make_pair(vertices.begin() + i, line)); } line_queue.stop(); line_queue.join(); } return vertices; } std::vector<adjacency_vec_t> DimacsParser::merge_adj_lists(const std::vector<adjacency_vec_t> &vertices) { std::vector<adjacency_vec_t> merged_vertices(vertices); // Because DIMACS-10 only includes edges once (eg. 1->2 and not 2->1), we must merge the adjacency lists. // To do so in parallel, each thread can only write to a range of 1/N elements. // Each thread will iterate over all vertices and merge any relevant nodes. RangeSplitter rs(num_vertices, num_threads); std::vector<std::thread> threads; for (int thread_idx = 0; thread_idx < num_threads; thread_idx++) threads.emplace_back([&, thread_idx, rs]() { // Range of lines that this thread is allowed to write: [range_lower, range_higher) int range_lower = rs.get_min(thread_idx), range_higher = rs.get_max(thread_idx); // If the edge 1->2 appears, we must create 2->1: vertices[destination].push_back(source). for (int source_id = 0; source_id < vertices.size(); source_id++) { auto &neighbors = vertices[source_id]; for (uint32_t destination : neighbors) if (destination >= range_lower && destination < range_higher) merged_vertices[destination].push_back(source_id); } // Sorted vectors allow for efficient algorithms like std::set_intersection for (int pos = range_lower; pos < range_higher; pos++) { adjacency_vec_t &edges = merged_vertices[pos]; std::sort(edges.begin(), edges.end()); } }); for (auto &thread : threads) thread.join(); return merged_vertices; }
fcea9afc08cb567349605332e689ab9b451c4176
846c56f9901daebf8e4abf7509ce606c3100633f
/src/util/geometry.cpp
9a4fc7449bb864ee679fb09484d8af605fdb1324
[]
no_license
mayacoda/cat-safari
5999e21e435dbc874cc1358923594c15ec3f62f3
2c658e3751b1eda6eace05c8431f0655c3736175
refs/heads/master
2020-03-21T12:21:07.764150
2018-09-06T10:34:03
2018-09-06T10:34:03
138,548,446
2
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
geometry.cpp
#include "geometry.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> glm::mat4 Geometry::createTransformationMatrix(const glm::vec3 &translate, const glm::vec3 &rotate, float scale) { // translate an identity matrix to the location glm::mat4 viewTranslate = glm::translate(glm::mat4(1.0f), translate); // rotateBy the translated matrix glm::mat4 viewRotateX = glm::rotate(viewTranslate, glm::radians(rotate.x), glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 viewRotateY = glm::rotate(viewRotateX, glm::radians(rotate.y), glm::vec3(0, 1.0f, 0.0f)); glm::mat4 viewRotateZ = glm::rotate(viewRotateY, glm::radians(rotate.z), glm::vec3(0, 0.0f, 1.0f)); // scale matrix glm::mat4 scaleMatrix = glm::scale(viewRotateZ, glm::vec3(scale)); return scaleMatrix; } glm::mat4 Geometry::createProjectionMatrix(int width, int height) { return glm::perspective(glm::radians(CAMERA_ANGLE), (float) width / (float) height, NEAR, FAR); } glm::mat4 Geometry::createPhotoViewProjectionMatrix(int width, int height) { return glm::perspective(glm::radians(PHOTO_ANGLE), (float) width / (float) height, NEAR, FAR); } glm::mat4 Geometry::createViewMatrix(const Camera &camera) { glm::mat4 rotateX = glm::rotate(glm::mat4(1.0f), glm::radians(camera.getPitch()), glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 rotateY = glm::rotate(rotateX, glm::radians(camera.getYaw()), glm::vec3(0.0f, 1.0f, 0.0f)); glm::vec3 negativeCamPos = -camera.getPos(); glm::mat4 translate = glm::translate(rotateY, negativeCamPos); return translate; }
14a9b212450511da94e269c2eb1c7cbcfcdabe8a
e862f48c627b8effec2a25b37c590ca4f2649fc0
/branches/ming_branches/spectrallibrary/SpectrumLibrary.cpp
cb0856fb25ac13239500a5d8fe5424d3006c520e
[]
no_license
Bandeira/sps
ec82a77c315cf1aff9761c801d1dc63cb5c5e9f0
1809945c9e5a6836a753a434d2c8570941130021
refs/heads/master
2016-09-01T08:18:34.221603
2015-12-10T23:56:52
2015-12-10T23:56:52
47,741,477
0
0
null
null
null
null
UTF-8
C++
false
false
5,258
cpp
SpectrumLibrary.cpp
/* * SpectrumLibrary.cpp * * Created on: Apr 21, 2011 * Author: jsnedecor */ #include "SpectrumLibrary.h" namespace specnets { /* * Generates key for an associated annotation; */ string getKey(string &annotation, int charge) { stringstream key; key << annotation << '_' << charge; return key.str(); } // ------------------------------------------------------------------------- void SpectrumLibrary::buildKeyMap(void) { m_map.clear(); for (int i = 0; i < m_library.size(); i++) { string key = getKey(m_library[i]->m_annotation, m_library[i]->m_charge); m_map[key] = i; } } // ------------------------------------------------------------------------- psmPtr & SpectrumLibrary::operator[](unsigned int i) { return m_library[i]; } // ------------------------------------------------------------------------- const psmPtr & SpectrumLibrary::operator[](unsigned int i) const { return m_library[i]; } // ------------------------------------------------------------------------- SpectrumLibrary & SpectrumLibrary::operator=(SpectrumLibrary &other) { m_library.resize(other.m_library.size()); m_library = other.m_library; buildKeyMap(); } // ------------------------------------------------------------------------- unsigned int SpectrumLibrary::size() { return (unsigned int)m_library.size(); } // ------------------------------------------------------------------------- unsigned int SpectrumLibrary::resize(unsigned int newSize) { m_library.resize(newSize); m_libraryScores.resize(newSize); buildKeyMap(); return m_library.size(); } // ------------------------------------------------------------------------- // Helper function for addToLibrary void SpectrumLibrary::addSpectrumMatch(Spectrum &spectrum, PeptideSpectrumMatch &psm, string &key, float score) { psmPtr currPtr(new PeptideSpectrumMatch); *currPtr = psm; m_library.m_psmSet.push_back(currPtr); m_libraryScores.push_back(score); m_map[key] = m_library.size() - 1; } // ------------------------------------------------------------------------- bool SpectrumLibrary::addToLibrary(Spectrum &spectrum, PeptideSpectrumMatch &psm, float score, bool scoreAscending) { string key = getKey(psm.m_annotation, psm.m_charge); std::tr1::unordered_map<string, unsigned int>::const_iterator it; it = m_map.find(key); if (it != m_map.end()) { psmPtr libMatch = m_library[it->second]; if (scoreAscending) { // if new score is better than old score if (m_libraryScores[it->second] > score) { addSpectrumMatch(spectrum, psm, key, score); return true; } } else if (m_libraryScores[it->second] < score) { // if new score is better than old score addSpectrumMatch(spectrum, psm, key, score); return true; } else { return false; } } else { addSpectrumMatch(spectrum, psm, key, score); return true; } } // ------------------------------------------------------------------------- bool SpectrumLibrary::addToLibrary(Spectrum &spectrum, PeptideSpectrumMatch &psm, float score, string &key, bool scoreAscending) { std::tr1::unordered_map<string, unsigned int>::const_iterator it; it = m_map.find(key); if (it != m_map.end()) { psmPtr libMatch = m_library[it->second]; if (scoreAscending) { // if new score is better than old score if (m_libraryScores[it->second] > score) { addSpectrumMatch(spectrum, psm, key, score); return true; } } else if (m_libraryScores[it->second] < score) { // if new score is better than old score addSpectrumMatch(spectrum, psm, key, score); return true; } else { return false; } } else { addSpectrumMatch(spectrum, psm, key, score); return true; } } // ------------------------------------------------------------------------- bool SpectrumLibrary::getSpectrumLibraryMatch(string &annotation, int charge, psmPtr &outputPsm) { string key = getKey(annotation, charge); DEBUG_MSG(key); std::tr1::unordered_map<string, unsigned int>::const_iterator it; it = m_map.find(key); if (it != m_map.end()) { outputPsm = m_library[it->second]; return true; } else { return false; } } }
acdc00c772cfd19ee2d1282eefc9b31382e9a8ac
b0dd7779c225971e71ae12c1093dc75ed9889921
/boost/spirit/home/phoenix/object/reinterpret_cast.hpp
6f94deaf3bdb8719cb26cfd5fbd3b4a69e0e59c4
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
1,293
hpp
reinterpret_cast.hpp
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef PHOENIX_OBJECT_REINTERPRET_CAST_HPP #define PHOENIX_OBJECT_REINTERPRET_CAST_HPP #include <boost/spirit/home/phoenix/core/compose.hpp> namespace boost { namespace phoenix { namespace impl { template <typename T> struct reinterpret_cast_eval { template <typename Env, typename U> struct result { typedef T type; }; template <typename RT, typename Env, typename U> static RT eval(Env const& env, U& obj) { return reinterpret_cast<RT>(obj.eval(env)); } }; } template <typename T, typename U> inline actor<typename as_composite<impl::reinterpret_cast_eval<T>, U>::type> reinterpret_cast_(U const& obj) { return compose<impl::reinterpret_cast_eval<T> >(obj); } }} #endif
3938b2b9671e08f8b78b00d9ad5637e10eb1a98f
592e72a31d310be8601a29e086a5b5d984bad552
/src/utils.h
23c57b2da27194bf5f90a5c9aa06d643563f89c1
[ "BSD-3-Clause" ]
permissive
Xamla/torch-ros
a8ce5bb45e77df4e185e687b006e400b8b52ff4e
1f42cd4863d68bc4f9134bd1932988c1d5d1e7ca
refs/heads/master
2020-04-10T01:51:04.389566
2018-10-04T16:08:44
2018-10-04T16:08:44
52,296,061
27
10
BSD-3-Clause
2018-09-06T12:51:15
2016-02-22T18:38:02
Lua
UTF-8
C++
false
false
3,873
h
utils.h
#ifndef _utils_h #define _utils_h /* #include <Eigen/Core> #include <Eigen/StdVector> #include <Eigen/Geometry> inline Eigen::Vector4d Tensor2Vec4d(THDoubleTensor *tensor) { if (!tensor || THDoubleTensor_nElement(tensor) < 4) throw MoveItWrapperException("A tensor with at least 4 elements was expected."); THDoubleTensor *tensor_ = THDoubleTensor_newContiguous(tensor); double* data = THDoubleTensor_data(tensor_); Eigen::Vector4d v(data[0], data[1], data[2], data[3]); THDoubleTensor_free(tensor_); return v; } inline Eigen::Vector3d Tensor2Vec3d(THDoubleTensor *tensor) { if (!tensor || THDoubleTensor_nElement(tensor) < 3) throw MoveItWrapperException("A Tensor with at least 3 elements was expected."); THDoubleTensor *tensor_ = THDoubleTensor_newContiguous(tensor); double* data = THDoubleTensor_data(tensor_); Eigen::Vector3d v(data[0], data[1], data[2]); THDoubleTensor_free(tensor_); return v; } template<int rows, int cols> inline Eigen::Matrix<double, rows, cols> Tensor2Mat(THDoubleTensor *tensor) { THArgCheck(tensor != NULL && tensor->nDimension == 2 && tensor->size[0] == rows && tensor->size[1] == cols, 1, "invalid tensor"); tensor = THDoubleTensor_newContiguous(tensor); Eigen::Matrix<double, rows, cols> output(Eigen::Map<Eigen::Matrix<double, rows, cols, Eigen::RowMajor> >(THDoubleTensor_data(tensor))); THDoubleTensor_free(tensor); return output; } template<int rows, int cols, int options> void viewMatrix(Eigen::Matrix<double, rows, cols, options> &m, THDoubleTensor *output) { // create new storage that views into the matrix THDoubleStorage* storage = NULL; if ((Eigen::Matrix<double, rows, cols, options>::Options & Eigen::RowMajor) == Eigen::RowMajor) storage = THDoubleStorage_newWithData(m.data(), (m.rows() * m.rowStride())); else storage = THDoubleStorage_newWithData(m.data(), (m.cols() * m.colStride())); storage->flag = TH_STORAGE_REFCOUNTED; THDoubleTensor_setStorage2d(output, storage, 0, rows, m.rowStride(), cols, m.colStride()); THDoubleStorage_free(storage); // tensor took ownership } inline void viewArray(double* array, size_t length, THDoubleTensor *output) { THDoubleStorage* storage = THDoubleStorage_newWithData(array, length); storage->flag = TH_STORAGE_REFCOUNTED; THDoubleTensor_setStorage1d(output, storage, 0, length, 1); THDoubleStorage_free(storage); // tensor took ownership } template<int rows, int cols> void copyMatrix(const Eigen::Matrix<double, rows, cols> &m, THDoubleTensor *output) { THDoubleTensor_resize2d(output, m.rows(), m.cols()); THDoubleTensor* output_ = THDoubleTensor_newContiguous(output); // there are strange static-asserts in Eigen to disallow specifying RowMajor for vectors... Eigen::Map<Eigen::Matrix<double, rows, cols, (rows == 1 || cols == 1) ? Eigen::ColMajor : Eigen::RowMajor> >(THDoubleTensor_data(output_)) = m; THDoubleTensor_freeCopyTo(output_, output); }*/ #define DECL_vector2Tensor(T, name) inline void vector2Tensor(const std::vector<T> &v, TH##name##Tensor *output) \ { \ TH##name##Tensor_resize1d(output, v.size()); \ TH##name##Tensor *output_ = TH##name##Tensor_newContiguous(output); \ std::copy(v.begin(), v.end(), TH##name##Tensor_data(output_)); \ TH##name##Tensor_freeCopyTo(output_, output); \ } DECL_vector2Tensor(double, Double) DECL_vector2Tensor(float, Float) DECL_vector2Tensor(int, Int) #define DECL_Tensor2vector(T, name) inline void Tensor2vector(TH##name##Tensor *input, std::vector<T> &v) \ { \ long n = TH##name##Tensor_nElement(input); \ v.resize(n); \ input = TH##name##Tensor_newContiguous(input); \ T *begin = TH##name##Tensor_data(input); \ std::copy(begin, begin + n, v.begin()); \ TH##name##Tensor_free(input); \ } DECL_Tensor2vector(double, Double) DECL_Tensor2vector(float, Float) DECL_Tensor2vector(int, Int) #endif //_utils_h
a1118191a36a6743c6effe407b2889d3bee80f5e
7b3856478d8009a2b6bbd7101352e9452e7b1414
/October 14/October 14 Solution.cpp
4f4ce1dad5caf0dfd1f3f9534bb17cee184cd2f8
[]
no_license
Sanjays2402/Leetcode-October-Challenge
40ef29d6dafaa307303f836bb5470e783bc1a8fc
922956d772a91632787f7993d647dc032a8c3f3f
refs/heads/main
2023-01-05T14:25:07.122022
2020-10-28T17:49:26
2020-10-28T17:49:26
300,665,444
0
1
null
null
null
null
UTF-8
C++
false
false
546
cpp
October 14 Solution.cpp
class Solution { public: int helper(vector<int> &nums, int l, int h) { int pre = 0, cur = 0; for (int i = l; i < h; i++) { int temp = max(pre + nums[i], cur); pre = cur; cur = temp; } return cur; } int rob(vector<int>& nums) { if(nums.size() == 0) return 0; if(nums.size() == 1) return nums[0]; return max(helper(nums, 0, nums.size()-1), helper(nums, 1, nums.size())); } };
5725c143aa93ac308f996cdd7a3a2777f2dbb752
03380a2cf46385b0d971e150078d992cd7840980
/Source/Diagnostics/MultiDiagnostics.H
f9907b8bdc626ee75d1d77ab7290f20b0ddde734
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause-LBNL" ]
permissive
ECP-WarpX/WarpX
0cfc85ce306cc5d5caa3108e8e9aefe4fda44cd3
e052c6d1994e4edb66fc27763d72fcf08c3a112a
refs/heads/development
2023-08-19T07:50:12.539926
2023-08-17T20:01:41
2023-08-17T20:01:41
150,626,842
210
147
NOASSERTION
2023-09-13T23:38:13
2018-09-27T17:53:35
C++
UTF-8
C++
false
false
1,911
h
MultiDiagnostics.H
#ifndef WARPX_MULTIDIAGNOSTICS_H_ #define WARPX_MULTIDIAGNOSTICS_H_ #include "Diagnostics.H" #include "MultiDiagnostics_fwd.H" #include <AMReX_Vector.H> #include <memory> #include <string> #include <vector> /** All types of diagnostics. */ enum struct DiagTypes {Full, BackTransformed, BoundaryScraping}; /** * \brief This class contains a vector of all diagnostics in the simulation. */ class MultiDiagnostics { public: MultiDiagnostics (); /** \brief Read Input parameters. Called in constructor. */ void ReadParameters (); /** \brief Loop over diags in alldiags and call their InitDiags */ void InitData (); /** \brief Called at each iteration. Compute diags and flush. */ void FilterComputePackFlush (int step, bool force_flush=false, bool BackTransform=false); /** \brief Called only at the last iteration. Loop over each diag and if m_dump_last_timestep * is true, compute diags and flush with force_flush=true. */ void FilterComputePackFlushLastTimestep (int step); /** \brief Loop over diags in all diags and call their InitializeFieldFunctors. Called when a new partitioning is generated at level, lev. * \param[in] lev level at this the field functors are initialized. */ void InitializeFieldFunctors (int lev); /** Start a new iteration, i.e., dump has not been done yet. */ void NewIteration (); Diagnostics& GetDiag(int idiag) {return *alldiags[idiag]; } int GetTotalDiags() {return ndiags;} DiagTypes diagstypes(int idiag) {return diags_types[idiag];} private: /** Vector of pointers to all diagnostics */ amrex::Vector<std::unique_ptr<Diagnostics> > alldiags; int ndiags = 0; /**< number of different diagnostics */ std::vector<std::string> diags_names; /**Type of each diagnostics*/ std::vector<DiagTypes> diags_types; }; #endif // WARPX_MULTIDIAGNOSTICS_H_
4a546c348870a065c276fd39837963fbe5e05406
3494794986dc3a0a907c42d0897522f562411d1b
/src/tf_broadcaster.cpp
2a06f70f3d220c87ae36a794f7ec9d8edbdad719
[]
no_license
KUKAnauten/iiwa_registration
f8c024d02e402a33a0661e00062fdb08753e881a
f2ee10febb2fa89942b829ebe728afe0971116a4
refs/heads/master
2021-09-07T20:50:46.399785
2018-02-28T22:42:47
2018-02-28T22:42:47
114,258,513
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
tf_broadcaster.cpp
#include <ros/ros.h> #include <tf/transform_broadcaster.h> int main(int argc, char** argv){ ros::init(argc, argv, "robot_tf_publisher"); ros::NodeHandle n; ros::Rate r(10000); tf::TransformBroadcaster broadcaster; while(n.ok()){ broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0.00964753,0.611417, -0.01133,0.791169), tf::Vector3(0.530517,-0.181726,1.16903)), ros::Time::now(),"/world", "/base_pose")); r.sleep(); } }
743c1b511b43ddefce04823607e6a07ed5112440
73fbb7ffa48696a618e1aa0f06b996b442a81017
/src/ScopedReadLock.cpp
b2f143fdcaf6df6107960994d8d5f548e790f8ae
[ "MIT" ]
permissive
mistralol/libclientserver
57632be76830c78829dd0f8a5d68be528ca9ec58
b90837149715d396cf68c2e82c539971e7efeb80
refs/heads/master
2020-04-12T06:34:58.829682
2019-09-08T14:14:40
2019-09-08T14:14:40
12,540,455
4
0
null
null
null
null
UTF-8
C++
false
false
283
cpp
ScopedReadLock.cpp
#include <libclientserver.h> ScopedReadLock::ScopedReadLock(RWLock *lock) { lock->ReadLock(); m_lock = lock; m_locked = true; } ScopedReadLock::~ScopedReadLock() { if (m_locked) m_lock->Unlock(); } void ScopedReadLock::Unlock() { m_lock->Unlock(); m_locked = false; }
88e7a204cd23ac6df8a47bc3c60ab69be5f70a55
2e83ed22512a6292adf10cb1d671730b73f9249a
/BOJ/문제들/b3197_2.cpp
e5bb5943e964dec3346c2c88f6f47dc129f75fa8
[]
no_license
pkiop/ALGORITHM
b7439d693387279866f061408f39dab91ebbb7cf
615f2ac07d61c6b46d18b519949349e4dc3036bb
refs/heads/master
2023-04-28T16:05:10.155585
2022-07-14T14:18:06
2022-07-14T14:18:06
115,351,474
2
1
null
null
null
null
UTF-8
C++
false
false
3,464
cpp
b3197_2.cpp
#include <cstring> #include <iostream> #include <queue> #include <string> using namespace std; int R, C; char input[1501][1501]; bool isCleared[1501][1501]; bool visited[1501][1501]; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; int sx, sy, ex, ey; bool checkRange(int x, int y) { return 0 <= x && x < R && 0 <= y && y < C; } queue<pair<pair<int, int>, int> > iceQueue; void findIce() { memset(isCleared, 0, sizeof(isCleared)); for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { if (input[i][j] == '.') { for (int k = 0; k < 4; ++k) { int nx = i + dx[k]; int ny = j + dy[k]; if (checkRange(nx, ny) && !isCleared[i][j]) { if (input[nx][ny] == 'X') { iceQueue.push(make_pair(make_pair(nx, ny), 1)); isCleared[nx][ny] = true; } } } } } } } void clearIce() { int qLength = iceQueue.size(); while (qLength--) { int nowX = iceQueue.front().first.first; int nowY = iceQueue.front().first.second; int nowDepth = iceQueue.front().second; iceQueue.pop(); for (int k = 0; k < 4; ++k) { int nx = nowX + dx[k]; int ny = nowY + dy[k]; if (checkRange(nx, ny) && !isCleared[nx][ny]) { if (input[nx][ny] == 'X') { iceQueue.push(make_pair(make_pair(nx, ny), nowDepth + 1)); isCleared[nx][ny] = true; } } } input[nowX][nowY] = '.'; } } void printInput(int sx = -1, int sy = -1, int ex = -1, int ey = -1) { for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { if (i == sx && j == sy) { cout << 'S' << ' '; } else if (i == ex && j == ey) { cout << 'E' << ' '; } else { cout << input[i][j] << ' '; } } cout << endl; } cout << endl; } struct mydata { int sx; int sy; int depth; }; bool visit = false; queue<pair<pair<int, int>, int> > nextStart; void dfs(int x, int y, int depth, bool isFirstTry = false) { if (x == ex && y == ey) { visit = true; return; }; for (int k = 0; k < 4; ++k) { int nx = x + dx[k]; int ny = y + dy[k]; if (checkRange(nx, ny) && input[nx][ny] != 'X' && !visited[nx][ny]) { visited[nx][ny] = true; dfs(nx, ny, depth, isFirstTry); } else if (checkRange(nx, ny) && input[nx][ny] == 'X' && !visited[nx][ny]) { nextStart.push(make_pair(make_pair(nx, ny), depth)); visited[nx][ny] = true; } } } int main() { cin >> R >> C; bool isFirst = true; for (int i = 0; i < R; ++i) { string s; cin >> s; for (int j = 0; j < C; ++j) { input[i][j] = s[j]; if (input[i][j] == 'L') { if (isFirst) { sx = i, sy = j; isFirst = false; } else { ex = i, ey = j; } input[i][j] = '.'; } } } nextStart.push(make_pair(make_pair(sx, sy), 0)); findIce(); for (int i = 0; i < max(R, C); ++i) { int nowDepth = nextStart.front().second; // cout << " ice length : " << iceQueue.size() << endl; while (nowDepth == i) { int nx = nextStart.front().first.first; int ny = nextStart.front().first.second; nowDepth = nextStart.front().second; if (input[nx][ny] == 'X') break; nextStart.pop(); dfs(nx, ny, i + 1, i == 0); if (visit) { cout << i << endl; return 0; } } clearIce(); // printInput(); } return 0; };
b4b6d4469e9b857fa6d46c9472d64a89136c47c1
be51f00011496dbcddcd6387a72de81b0e33a13c
/inputCollector.cpp
6831ee48a0ccc22da2263278dffe8ebd940f706c
[]
no_license
prismika/Dijkstra-s-Curse
3a120b324103df1aadc47f39df34269e887da9a7
d8eed03d69872ce18a33097289e32d366bc8b630
refs/heads/master
2021-06-07T19:13:12.695526
2021-05-12T14:49:27
2021-05-12T14:49:27
167,460,500
0
0
null
null
null
null
UTF-8
C++
false
false
3,217
cpp
inputCollector.cpp
#include <ncurses.h> #include <stdio.h> #include "inputCollector.h" int inputState_init(InputState * inState){ raw(); noecho(); keypad(stdscr, true); inState->lastType = input_null; inState->isMovement = false; inState->isStair = false; return 0; } int inputState_update(InputState * inState){ InputType newType = input_null; while(newType == input_null){ int in = getch(); //Is it a movement? switch(in){ case '7': case 'y': newType = input_upleft; break; case '8': case 'k': newType = input_up; break; case '9': case 'u': newType = input_upright; break; case '6': case 'l': newType = input_right; break; case '3': case 'n': newType = input_downright; break; case '2': case 'j': newType = input_down; break; case '1': case 'b': newType = input_downleft; break; case '4': case 'h': newType = input_left; break; case '5': case ' ': case '.': newType = input_rest; break; default:break; } //Did we find a movement? if(newType != input_null){ inState->isMovement = true; inState->isStair = false; inState->lastType = newType; return 0; } //Check for stair commands switch(in){ case '>': newType = input_downstairs; break; case '<': newType = input_upstairs; break; default: break; } //Did we find a stair command? if(newType != input_null){ inState->isStair = true; inState->isMovement = false; inState->lastType = newType; return 0; } //Check for other command types switch(in){ case 'Q': newType = input_quit; break; case 'm': newType = input_mlist; break; case KEY_UP: newType = input_mlist_up; break; case KEY_DOWN: newType = input_mlist_down; break; case 'q': case 27: newType = input_escape; break; case 'T': newType = input_teleport; break; case 'r': newType = input_random; break; case 'f': newType = input_fog; break; case 'w': newType = input_wear; break; case 't': newType = input_t; break; case 'x': newType = input_x; break; case 'I': newType = input_I; break; case 'L': newType = input_L; break; case '0': newType = input_0; break; case 'a': newType = input_a; break; case 'c': newType = input_c; break; case 'd': newType = input_d; break; case 'e': newType = input_e; break; case 'g': newType = input_g; break; case 'i': newType = input_i; break; default://If we reach this point, the input wasn't recognized newType = input_null; break; } inState->isStair = false; inState->isMovement = false; inState->lastType = newType; } return 0; } InputType inputState_get_last(InputState * inState){ return inState->lastType; } bool inputState_is_movement(InputState * inState){ return inState -> isMovement; } bool inputState_is_stair(InputState * inState){ return inState -> isStair; }
71d752888892e4a34a88221fa5db007228c95d6d
73ebcf788041071a87add04bec5b08675573b78f
/tester.cpp
c6362941ae5cd4e55001ed806598da7de6de494e
[]
no_license
rachan5/ECS158HW2
3c721b23f0dcf6830531ca57b75d71ef32b56919
443e21edcb3a3622a2f6ed913ee86d7bf5fdcbe3
refs/heads/master
2020-04-10T00:08:04.302301
2015-03-21T06:51:37
2015-03-21T06:51:37
30,328,120
0
0
null
null
null
null
UTF-8
C++
false
false
300
cpp
tester.cpp
#include <cstdlib> #include <iostream> #include <fstream> using namespace std; int main() { int n = 2000000; int m = 3; ofstream myfile; myfile.open ("seq2Mil.txt"); myfile << n << endl; myfile << m << endl; for (int i=0; i<n; i++) myfile << i << endl; myfile.close(); return 0; }//main
a3fdabeefea9162fee73ed6eae1d2756b8a7e4e8
b651c5e235befc487a7006ee9d7cb27897d9f424
/4111.cpp
7d71048c7af2b315f0064f74a09fdda57b20b952
[]
no_license
utoppia/HDU
c318bbb72ba3d365c0dd203020463a7a17515c31
6eaa36ba142ce57f4bd5b2ff2cd8fc73cef4d9b7
refs/heads/master
2020-05-30T00:40:22.700792
2015-04-06T14:12:27
2015-04-06T14:12:27
18,913,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,010
cpp
4111.cpp
// HDU 4111 // by utoppia // 1 %2=1 // 2 (m+n)%2=0 || #include<cstdio> #include<cstring> int win[60][60000]; // win[i][j] 表示i堆是1,j表示剩余的个数和 int dfs(int u,int v) { if(win[u][v] != -1) { return win[u][v]; } if(u==0)return win[u][v] = (v%2==0?0:1); if(v==1) return win[u][v] = dfs(u+1,0); win[u][v] = 0; if(u) win[u][v] |= !dfs(u-1,v); if(v) win[u][v] |= !dfs(u,v-1); if(u>1 && v==0) win[u][v] |= !dfs(u-2,v+2); if(u>1 && v) win[u][v] |= !dfs(u-2,v+3); if(u && v) win[u][v] |= !dfs(u-1,v+1); return win[u][v]; } int T,n,cas=1; int main() { memset(win,-1,sizeof(win)); win[0][0]=0; scanf("%d",&T); while(T--) { scanf("%d",&n); int u=0,v=0,ans=0; for(int i=0,j;i<n;++i) { scanf("%d",&j); if(j==1) u++; else v+=(j+1); } if(v) --v; ans = dfs(u,v); printf("Case #%d: %s\n",cas++,ans?"Alice":"Bob"); } return 0; }
86000a8666fc8f2de4988e1f6c4abb24aeb2f452
2ea34a7ff11da761313e32914b23ca748e7d3d66
/191227_contoh 1 array_2.cpp
c5436cb051805fc7d9c2642260fed5ca3356a0e0
[]
no_license
andimaliaAMFB/Dasar-Pemrograman-C-
a6c0666f458df1a31c287c3fd7dd80866541ab34
1584a080b955851f304a1dbb9e3108ea56d7714c
refs/heads/main
2023-02-25T20:31:50.498096
2021-01-30T05:57:04
2021-01-30T05:57:04
334,338,569
0
0
null
null
null
null
UTF-8
C++
false
false
224
cpp
191227_contoh 1 array_2.cpp
//contoh 1 array 191227 coba #include<iostream> #include<conio.h> using namespace std; main() { int A[]={2,4,6,4,5}; A[8]=7; cout<<"Tampilkan Semua Data\n"; for(int i=0;i<=8;i++) { cout<<A[i]<<" "; } }