blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f3a4ea2e29217d5e1971eaf83f4cb86b8f37a596
c1e73f3dcd104570ecf363f6a86d843d2b5050e5
/AnimationComponents.h
0fd3da4109e5b34fc8932ebdbfd45bdeeee416ba
[]
no_license
Kol9n9/SimpleGame
46904e95a55e869c21f2f5d20ce3d174fc5ee15f
bcdb0d5879f3aafe3496dd4d7df3bb6350de5905
refs/heads/master
2020-08-28T12:10:47.386022
2019-11-10T17:07:34
2019-11-10T17:07:34
217,696,215
0
0
null
null
null
null
UTF-8
C++
false
false
2,148
h
#pragma once #ifndef ANIMATIONCOMPONENTS_H #define ANIMATIONCOMPONENTS_H #include <iostream> #include <map> #include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <SFML/System.hpp> #include <SFML/Window.hpp> class AnimationComponents { private: class Animation { public: sf::Texture& TextureSheet; sf::Sprite& Sprite; float AnimationTimer; float Timer; int Height; int Width; sf::IntRect StartRect; sf::IntRect EndRect; sf::IntRect CurrentRect; Animation(sf::Sprite &Sprite, sf::Texture& TextureSheet, float AnimationTimer, int StartFrameX, int StartFrameY, int EndFrameX, int EndFrameY, int Width, int Height) : Sprite(Sprite), TextureSheet(TextureSheet), AnimationTimer(AnimationTimer), Width(Width), Height(Height) { this->Timer = 0; this->StartRect = sf::IntRect(StartFrameX*this->Width, StartFrameY*this->Height, this->Width, this->Height); this->EndRect = sf::IntRect(EndFrameX*this->Width, EndFrameY*this->Height, this->Width, this->Height); this->CurrentRect = this->StartRect; this->Sprite.setTexture(this->TextureSheet); this->Sprite.setTextureRect(this->StartRect); } //Function void Play(const float &dt) { this->Timer += 100.f * dt; if (this->Timer >= this->AnimationTimer) { this->Timer = 0; if (this->CurrentRect != this->EndRect) this->CurrentRect.left += this->Width; else this->CurrentRect.left = this->StartRect.left; this->Sprite.setTextureRect(this->CurrentRect); } } void Reset() { this->Timer = this->AnimationTimer; this->CurrentRect = this->StartRect; } }; //VARIABLES std::map<std::string, Animation*> AnimationList; Animation* LastAnimation; sf::Sprite& Sprite; sf::Texture& TextureSheet; //INITIALIZER FUNCTIONS public: AnimationComponents(sf::Sprite& Sprite, sf::Texture& TextureSheet); virtual ~AnimationComponents(); //FUNCTIONS void AddAnimation(const std::string key, float AnimationTimer, int StartFrameX, int StartFrameY, int EndFrameX, int EndFrameY, int Width, int Height); void Play(const std::string key, const float& dt); }; #endif // !ANIMATIONCOMPONENTS_H
[ "slezenkonikolay@mail.ru" ]
slezenkonikolay@mail.ru
b4e1ed7293aadfee796e885c8849da09913d34be
9433cf978aa6b010903c134d77c74719f22efdeb
/src/svl/Mat.cpp
7ad818ded478cf117e5f7ab58ec65a95a5986625
[]
no_license
brandonagr/gpstracktime
4666575cb913db2c9b3b8aa6b40a3ba1a3defb2f
842bfd9698ec48debb6756a9acb2f40fd6041f9c
refs/heads/master
2021-01-20T07:10:58.579764
2008-09-24T05:44:56
2008-09-24T05:44:56
32,090,265
0
0
null
null
null
null
UTF-8
C++
false
false
14,309
cpp
/* File: Mat.cpp Function: Implements Mat.h Author(s): Andrew Willmott Copyright: (c) 1995-2001, Andrew Willmott */ #include "svl/Mat.h" #include <cctype> #include <cstring> #include <cstdarg> #include <iomanip> // --- Mat Constructors & Destructors ----------------------------------------- Mat::Mat(Int rows, Int cols, ZeroOrOne k) : rows(rows), cols(cols) { Assert(rows > 0 && cols > 0, "(Mat) illegal matrix size"); data = new Real[rows * cols]; MakeDiag(k); } Mat::Mat(Int rows, Int cols, Block k) : rows(rows), cols(cols) { Assert(rows > 0 && cols > 0, "(Mat) illegal matrix size"); data = new Real[rows * cols]; MakeBlock(k); } Mat::Mat(Int rows, Int cols, double elt0, ...) : rows(rows), cols(cols) // The double is hardwired here because it is the only type that will work // with var args and C++ real numbers. { Assert(rows > 0 && cols > 0, "(Mat) illegal matrix size"); va_list ap; Int i, j; data = new Real[rows * cols]; va_start(ap, elt0); SetReal(data[0], elt0); for (i = 1; i < cols; i++) SetReal(Elt(0, i), va_arg(ap, double)); for (i = 1; i < rows; i++) for (j = 0; j < cols; j++) SetReal(Elt(i, j), va_arg(ap, double)); va_end(ap); } Mat::Mat(const Mat &m) : cols(m.cols) { Assert(m.data != 0, "(Mat) Can't construct from null matrix"); rows = m.Rows(); UInt elts = rows * cols; data = new Real[elts]; #ifdef VL_USE_MEMCPY memcpy(data, m.data, elts * sizeof(Real)); #else for (UInt i = 0; i < elts; i++) data[i] = m.data[i]; #endif } Mat::Mat(const Mat2 &m) : data(m.Ref()), rows(2 | VL_REF_FLAG), cols(2) { } Mat::Mat(const Mat3 &m) : data(m.Ref()), rows(3 | VL_REF_FLAG), cols(3) { } Mat::Mat(const Mat4 &m) : data(m.Ref()), rows(4 | VL_REF_FLAG), cols(4) { } // --- Mat Assignment Operators ----------------------------------------------- Mat &Mat::operator = (const Mat &m) { if (!IsRef()) SetSize(m.Rows(), m.Cols()); else Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match"); for (Int i = 0; i < Rows(); i++) SELF[i] = m[i]; return(SELF); } Mat &Mat::operator = (const Mat2 &m) { if (!IsRef()) SetSize(m.Rows(), m.Cols()); else Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match"); for (Int i = 0; i < Rows(); i++) SELF[i] = m[i]; return(SELF); } Mat &Mat::operator = (const Mat3 &m) { if (!IsRef()) SetSize(m.Rows(), m.Cols()); else Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match"); for (Int i = 0; i < Rows(); i++) SELF[i] = m[i]; return(SELF); } Mat &Mat::operator = (const Mat4 &m) { if (!IsRef()) SetSize(m.Rows(), m.Cols()); else Assert(Rows() == m.Rows(), "(Mat::=) Matrix rows don't match"); for (Int i = 0; i < Rows(); i++) SELF[i] = m[i]; return(SELF); } Void Mat::SetSize(Int nrows, Int ncols) { UInt elts = nrows * ncols; Assert(nrows > 0 && ncols > 0, "(Mat::SetSize) Illegal matrix size."); UInt oldElts = Rows() * Cols(); if (IsRef()) { // Abort! We don't allow this operation on references. _Error("(Mat::SetSize) Trying to resize a matrix reference"); } rows = nrows; cols = ncols; // Don't reallocate if we already have enough storage if (elts <= oldElts) return; // Otherwise, delete old storage and reallocate delete[] data; data = 0; data = new Real[elts]; // may throw an exception } Void Mat::SetSize(const Mat &m) { SetSize(m.Rows(), m.Cols()); } Void Mat::MakeZero() { #ifdef VL_USE_MEMCPY memset(data, 0, sizeof(Real) * Rows() * Cols()); #else Int i; for (i = 0; i < Rows(); i++) SELF[i] = vl_zero; #endif } Void Mat::MakeDiag(Real k) { Int i, j; for (i = 0; i < Rows(); i++) for (j = 0; j < Cols(); j++) if (i == j) Elt(i,j) = k; else Elt(i,j) = vl_zero; } Void Mat::MakeDiag() { Int i, j; for (i = 0; i < Rows(); i++) for (j = 0; j < Cols(); j++) Elt(i,j) = (i == j) ? vl_one : vl_zero; } Void Mat::MakeBlock(Real k) { Int i; for (i = 0; i < Rows(); i++) SELF[i].MakeBlock(k); } Void Mat::MakeBlock() { Int i, j; for (i = 0; i < Rows(); i++) for (j = 0; j < Cols(); j++) Elt(i,j) = vl_one; } // --- Mat Assignment Operators ----------------------------------------------- Mat &Mat::operator += (const Mat &m) { Assert(Rows() == m.Rows(), "(Mat::+=) matrix rows don't match"); Int i; for (i = 0; i < Rows(); i++) SELF[i] += m[i]; return(SELF); } Mat &Mat::operator -= (const Mat &m) { Assert(Rows() == m.Rows(), "(Mat::-=) matrix rows don't match"); Int i; for (i = 0; i < Rows(); i++) SELF[i] -= m[i]; return(SELF); } Mat &Mat::operator *= (const Mat &m) { Assert(Cols() == m.Cols(), "(Mat::*=) matrix columns don't match"); Int i; for (i = 0; i < Rows(); i++) SELF[i] = SELF[i] * m; return(SELF); } Mat &Mat::operator *= (Real s) { Int i; for (i = 0; i < Rows(); i++) SELF[i] *= s; return(SELF); } Mat &Mat::operator /= (Real s) { Int i; for (i = 0; i < Rows(); i++) SELF[i] /= s; return(SELF); } // --- Mat Comparison Operators ----------------------------------------------- Bool operator == (const Mat &m, const Mat &n) { Assert(n.Rows() == m.Rows(), "(Mat::==) matrix rows don't match"); Int i; for (i = 0; i < m.Rows(); i++) if (m[i] != n[i]) return(0); return(1); } Bool operator != (const Mat &m, const Mat &n) { Assert(n.Rows() == m.Rows(), "(Mat::!=) matrix rows don't match"); Int i; for (i = 0; i < m.Rows(); i++) if (m[i] != n[i]) return(1); return(0); } // --- Mat Arithmetic Operators ----------------------------------------------- Mat operator + (const Mat &m, const Mat &n) { Assert(n.Rows() == m.Rows(), "(Mat::+) matrix rows don't match"); Mat result(m.Rows(), m.Cols()); Int i; for (i = 0; i < m.Rows(); i++) result[i] = m[i] + n[i]; return(result); } Mat operator - (const Mat &m, const Mat &n) { Assert(n.Rows() == m.Rows(), "(Mat::-) matrix rows don't match"); Mat result(m.Rows(), m.Cols()); Int i; for (i = 0; i < m.Rows(); i++) result[i] = m[i] - n[i]; return(result); } Mat operator - (const Mat &m) { Mat result(m.Rows(), m.Cols()); Int i; for (i = 0; i < m.Rows(); i++) result[i] = -m[i]; return(result); } Mat operator * (const Mat &m, const Mat &n) { Assert(m.Cols() == n.Rows(), "(Mat::*m) matrix cols don't match"); Mat result(m.Rows(), n.Cols()); Int i; for (i = 0; i < m.Rows(); i++) result[i] = m[i] * n; return(result); } Vec operator * (const Mat &m, const Vec &v) { Assert(m.Cols() == v.Elts(), "(Mat::*v) matrix and vector sizes don't match"); Int i; Vec result(m.Rows()); for (i = 0; i < m.Rows(); i++) result[i] = dot(v, m[i]); return(result); } Mat operator * (const Mat &m, Real s) { Int i; Mat result(m.Rows(), m.Cols()); for (i = 0; i < m.Rows(); i++) result[i] = m[i] * s; return(result); } Mat operator / (const Mat &m, Real s) { Int i; Mat result(m.Rows(), m.Cols()); for (i = 0; i < m.Rows(); i++) result[i] = m[i] / s; return(result); } // --- Mat Mat-Vec Functions -------------------------------------------------- Vec operator * (const Vec &v, const Mat &m) // v * m { Assert(v.Elts() == m.Rows(), "(Mat::v*m) vector/matrix sizes don't match"); Vec result(m.Cols(), vl_zero); Int i; for (i = 0; i < m.Rows(); i++) result += m[i] * v[i]; return(result); } // --- Mat Special Functions -------------------------------------------------- Mat trans(const Mat &m) { Int i,j; Mat result(m.Cols(), m.Rows()); for (i = 0; i < m.Rows(); i++) for (j = 0; j < m.Cols(); j++) result.Elt(j,i) = m.Elt(i,j); return(result); } Real trace(const Mat &m) { Int i; Real result = vl_0; for (i = 0; i < m.Rows(); i++) result += m.Elt(i,i); return(result); } Mat &Mat::Clamp(Real fuzz) // clamps all values of the matrix with a magnitude // smaller than fuzz to zero. { Int i; for (i = 0; i < Rows(); i++) SELF[i].Clamp(fuzz); return(SELF); } Mat &Mat::Clamp() { return(Clamp(1e-7)); } Mat clamped(const Mat &m, Real fuzz) // clamps all values of the matrix with a magnitude // smaller than fuzz to zero. { Mat result(m); return(result.Clamp(fuzz)); } Mat clamped(const Mat &m) { return(clamped(m, 1e-7)); } Mat oprod(const Vec &a, const Vec &b) // returns outerproduct of a and b: a * trans(b) { Mat result; Int i; result.SetSize(a.Elts(), b.Elts()); for (i = 0; i < a.Elts(); i++) result[i] = a[i] * b; return(result); } // --- Mat Input & Output ----------------------------------------------------- ostream &operator << (ostream &s, const Mat &m) { Int i, w = s.width(); s << '['; for (i = 0; i < m.Rows() - 1; i++) s << setw(w) << m[i] << endl; s << setw(w) << m[i] << ']' << endl; return(s); } inline Void CopyPartialMat(const Mat &m, Mat &n, Int numRows) { for (Int i = 0; i < numRows; i++) n[i] = m[i]; } istream &operator >> (istream &s, Mat &m) { Int size = 1; Char c; Mat inMat; // Expected format: [row0 row1 row2 ...] while (isspace(s.peek())) // chomp white space s.get(c); if (s.peek() == '[') { Vec row; s.get(c); s >> row; inMat.SetSize(2 * row.Elts(), row.Elts()); inMat[0] = row; while (isspace(s.peek())) // chomp white space s.get(c); while (s.peek() != ']') // resize if needed { if (size == inMat.Rows()) { Mat holdMat(inMat); inMat.SetSize(size * 2, inMat.Cols()); CopyPartialMat(holdMat, inMat, size); } s >> row; // read a row inMat[size++] = row; if (!s) { _Warning("Couldn't read matrix row"); return(s); } while (isspace(s.peek())) // chomp white space s.get(c); } s.get(c); } else { s.clear(ios::failbit); _Warning("Error: Expected '[' while reading matrix"); return(s); } m.SetSize(size, inMat.Cols()); CopyPartialMat(inMat, m, size); return(s); } // --- Matrix Inversion ------------------------------------------------------- #if !defined(CL_CHECKING) && !defined(VL_CHECKING) // we #define away pAssertEps if it is not used, to avoid // compiler warnings. #define pAssertEps #endif Mat inv(const Mat &m, Real *determinant, Real pAssertEps) // matrix inversion using Gaussian pivoting { Assert(m.IsSquare(), "(inv) Matrix not square"); Int i, j, k; Int n = m.Rows(); Real t, pivot, det; Real max; Mat A(m); Mat B(n, n, vl_I); // ---------- Forward elimination ---------- ------------------------------ det = vl_1; for (i = 0; i < n; i++) // Eliminate in column i, below diag { max = -1.0; for (k = i; k < n; k++) // Find a pivot for column i if (len(A[k][i]) > max) { max = len(A[k][i]); j = k; } Assert(max > pAssertEps, "(inv) Matrix not invertible"); if (j != i) // Swap rows i and j { for (k = i; k < n; k++) Swap(A.Elt(i, k), A.Elt(j, k)); for (k = 0; k < n; k++) Swap(B.Elt(i, k), B.Elt(j, k)); det = -det; } pivot = A.Elt(i, i); Assert(abs(pivot) > pAssertEps, "(inv) Matrix not invertible"); det *= pivot; for (k = i + 1; k < n; k++) // Only do elements to the right of the pivot A.Elt(i, k) /= pivot; for (k = 0; k < n; k++) B.Elt(i, k) /= pivot; // We know that A(i, i) will be set to 1, so don't bother to do it for (j = i + 1; j < n; j++) { // Eliminate in rows below i t = A.Elt(j, i); // We're gonna zero this guy for (k = i + 1; k < n; k++) // Subtract scaled row i from row j A.Elt(j, k) -= A.Elt(i, k) * t; // (Ignore k <= i, we know they're 0) for (k = 0; k < n; k++) B.Elt(j, k) -= B.Elt(i, k) * t; } } // ---------- Backward elimination ---------- ----------------------------- for (i = n - 1; i > 0; i--) // Eliminate in column i, above diag { for (j = 0; j < i; j++) // Eliminate in rows above i { t = A.Elt(j, i); // We're gonna zero this guy for (k = 0; k < n; k++) // Subtract scaled row i from row j B.Elt(j, k) -= B.Elt(i, k) * t; } } if (determinant) *determinant = det; return(B); }
[ "BrandonAGr@0fd8bb18-9850-0410-888e-21b4c4172e3e" ]
BrandonAGr@0fd8bb18-9850-0410-888e-21b4c4172e3e
06b25adb694a7848655128fb2faeefd5e39e462a
983424bb42cdbef82975287229652d490dd8f521
/Sorting 12.cpp
33c5e158ad907cfa9d93c4d2d72d5a9df02c4817
[]
no_license
namnguyen215/Thuc_hanh_tin
d6802641b73576fdda951f38bb6b5ab31d7d5d7f
c6958a8f9a1ca4a3fc578054cfc289fd9e935bae
refs/heads/main
2023-07-17T07:32:51.408534
2021-08-06T14:29:34
2021-08-06T14:29:34
305,582,293
0
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--){ long n,m; cin>>n>>m; long long a[n+1],b[m+1]; for(long i=0;i<n;i++) cin>>a[i]; for(long i=0;i<m;i++) cin>>b[i]; sort(a,a+n);sort(b,b+n); cout<<a[n-1]*b[0]<<endl; } }
[ "namnguyenphuong215@gmail.com" ]
namnguyenphuong215@gmail.com
08e62cc4c7758481e0654341a25b23ebd593dd1a
7e85951f968dbb36dd8149df26f70ee5ac0f5083
/main.cpp
0e82329feb88062ac8cb4bd339cf009ce83a18e3
[]
no_license
helga1507/coursera_white
ee14de20ad963a196a2da31a926be3f152f3d524
d4db300cadc4f97e0e1b70e99adfd702cc2fe07e
refs/heads/master
2022-12-13T14:53:14.165926
2020-09-07T20:06:12
2020-09-07T20:06:12
283,464,911
0
0
null
null
null
null
UTF-8
C++
false
false
4,627
cpp
#include <iostream> #include <iomanip> #include <sstream> #include <vector> #include <set> #include <map> using namespace std; const char SEPARATOR_DATE = '-'; const string COMMAND_ADD = "Add"; const string COMMAND_DEL = "Del"; const string COMMAND_FIND = "Find"; const string COMMAND_PRINT = "Print"; class Date { public: Date (int new_year, int new_month, int new_day) { if (new_month < 1 || new_month > 12) throw logic_error("Month value is invalid: " + to_string(month)); if (day < 1 || day > 31) throw logic_error("Day value is invalid: " + to_string(day)); this->year = new_year; this->month = new_month; this->day = new_day; } int GetYear() const { return this->year; }; int GetMonth() const { return this->month; }; int GetDay() const { return this->day; }; private: int year, month, day; }; bool operator<(const Date& lhs, const Date& rhs) { if (lhs.GetYear() != rhs.GetYear()) return lhs.GetYear() < rhs.GetYear(); if (lhs.GetMonth() != rhs.GetMonth()) return lhs.GetMonth() < rhs.GetMonth(); return lhs.GetDay() < rhs.GetDay(); }; class Database { public: void AddEvent(const Date& date, const string& event) { this->events[date].insert(event); }; bool DeleteEvent(const Date& date, const string& event) { if (this->events.count(date) == 0) return false; return this->events.at(date).erase(event) != 0; }; int DeleteDate(const Date& date) { if (this->events.count(date) == 0) return 0; int n = this->events.at(date).size(); this->events.erase(date); return n; }; void Find(const Date& date) const { vector<string> v_str; if (this->events.count(date) == 0) return; for (const string& event : this->events.at(date)) cout << event << endl; }; void Print() const { for (const auto& [date, set_values] : this->events) { for (const auto& event : set_values) { cout << setw(4) << setfill('0') << date.GetYear() << "-" << setw(2) << setfill('0') << date.GetMonth() << "-" << setw(2) << setfill('0') << date.GetDay() << " " << event << endl; } } }; private: map<Date, set<string>> events; }; Date parseDate (const string& str_date) { stringstream ss(str_date); string error_str; string trash_text; int year, month, day; char sep, sep2; ss >> year >> sep >> month >> sep2 >> day; if (!ss || sep != SEPARATOR_DATE || sep2 != SEPARATOR_DATE || ss.rdbuf()->in_avail() != 0) throw runtime_error("Wrong date format: " + str_date); return { year, month, day }; } bool CheckCorrectCommand (const string& command) { return command == COMMAND_ADD || command == COMMAND_DEL || command == COMMAND_FIND || command == COMMAND_PRINT; } void FillCommandsData (stringstream& ss, string& command, Date& date, string& event) { string temp; istream& ist = getline(ss, command, ' '); if (ss.eof() || !CheckCorrectCommand(command)) return; getline(ss, temp, ' '); date = parseDate(temp); if (ss.eof()) return; getline(ss, event, ' '); } int main() { Database db; string command_line; while (getline(cin, command_line)) { stringstream ss(command_line); string command; Date date(0, 0, 0); string event; try { FillCommandsData(ss, command, date, event); if (command.empty()) continue; if (command == COMMAND_ADD) { db.AddEvent(date, event); } else if (command == COMMAND_DEL && !event.empty()) { bool is_deleted = db.DeleteEvent(date, event); cout << (is_deleted ? "Deleted successfully" : "Event not found") << endl; } else if (command == COMMAND_DEL) { int n = db.DeleteDate(date); cout << "Deleted " << n << " events" << endl; } else if (command == COMMAND_FIND) { db.Find(date); } else if (command == COMMAND_PRINT) { db.Print(); } else { throw runtime_error("Unknown command: " + command); } } catch (exception& err) { cout << err.what() << endl; } } return 0; }
[ "lashkul@skytracking.ru" ]
lashkul@skytracking.ru
a5b7e8f4e94f435fa62ae71f834958aff72ac9c9
5dd2ec8717248d25c502a7e73182be11dd249fb3
/chrome/browser/share/share_features.cc
51472e6ddebaf4ce87fe3338ea497789ccc731a3
[ "BSD-3-Clause" ]
permissive
sunnyps/chromium
32491c4799a2802fe6ece0c05fb23e00d88020e6
9550e527d46350377a6e84cd6e09e1b32bf2d936
refs/heads/main
2023-08-30T10:34:39.941312
2021-10-09T20:13:18
2021-10-09T20:13:18
217,597,965
0
0
BSD-3-Clause
2021-09-28T18:16:02
2019-10-25T19:01:58
null
UTF-8
C++
false
false
522
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/share/share_features.h" namespace share { const base::Feature kUpcomingSharingFeatures{"UpcomingSharingFeatures", base::FEATURE_DISABLED_BY_DEFAULT}; bool AreUpcomingSharingFeaturesEnabled() { return base::FeatureList::IsEnabled(kUpcomingSharingFeatures); } } // namespace share
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
d2f140350b7e5dfa6d636ba07c0fe9795e987040
f32a24e4cacb917617c017c1da1d1f70024fba65
/cpc/src/chg050.cxx
c688d4b5241297d38e99eed71a46a7faadfdbcab
[]
no_license
yamasdais/iroha-nihoheto
61629750c8028d3f9836e4c5f1793aaf7fb2ae57
033f69bd400d586b0297c8ff97846d01f42ffc55
refs/heads/master
2022-09-24T13:44:34.189177
2022-09-16T12:59:56
2022-09-16T12:59:56
116,883,187
0
0
null
2022-09-12T16:52:47
2018-01-09T23:36:23
C++
UTF-8
C++
false
false
1,017
cxx
#include <regex> #include <algorithm> #include <concepts> #include <ranges> #include "challenge.h" #include "coro_util.h" template <std::ranges::forward_range Range> requires std::convertible_to<std::iter_value_t<Range>, std::string> cpc::generator<std::string, false> filter_dial_country(Range const& range, std::string const& countryCode) { std::regex re(std::string(R"(^\s*\+?)") + countryCode); auto const filter = std::views::filter([&re](auto const& dial) { return std::regex_search(dial, re); }); for (auto const& dial : range | filter) { co_yield dial; } } void test0() { std::vector<std::string> dials{ "+40744909080", "44 7520 112233", "+44 7652 12345", "40 33492442", "7555 23442", "044 23423442", " 44 23423442", }; auto result = filter_dial_country(dials, "44"); for (auto const& dial : result) { std::cout << dial << std::endl; } } int main(int, char**) { test0(); return 0; }
[ "yamasdais@gmail.com" ]
yamasdais@gmail.com
83699bad7b2e08261bbdac52e55a9488d93922a5
701d19cedb341099cafd5602314a0a48ca3e7a50
/RSEngine/RSObjVS.h
56c72deb0e322b6b35c8b4542213b2b51411b99e
[]
no_license
denghc/danmugame
9ab9da54f96b12484689154c2588de7263d775c2
12ec3147a95585709d97eae51f82aa1074a56b91
refs/heads/master
2021-01-01T18:21:54.764551
2012-06-11T06:55:54
2012-06-11T06:55:54
4,621,859
2
0
null
null
null
null
UTF-8
C++
false
false
759
h
#pragma once #include "vertexshaderclass.h" #include "Structures.h" class RSObjVS : public VertexShaderClass { public: RSObjVS(string tag); RSObjVS(void); ~RSObjVS(void); virtual bool Initialize(ID3D11Device*, HWND, WCHAR*, CHAR*); virtual bool InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, CHAR* entryFuncName); virtual bool InitializeConstantBuffer(ID3D11Device*); virtual bool SetRenderParameters(ID3D11DeviceContext* device, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix); virtual void Shutdown(); private: virtual void ShutdownConstantBuffer(); virtual void ShutdownShader(); private: ID3D11VertexShader* m_vertexShader; ID3D11InputLayout* m_layout; ID3D11Buffer* m_rsObjBuffer; };
[ "denghc09@gmail.com" ]
denghc09@gmail.com
b58111b00f0b94eab61982eba3290cadad01b3d9
b85aad75aa5984fb6f276feaad21d9e07040b380
/source/main.cpp
09cd58ebda1efe2671ef6a370d379bbaadbb7ed8
[]
no_license
jason0597/Seedminer-CPP
9e4397d85f47735185f7c6d667adbbe71bab0588
728e02d7e6620ef4132fb4a261ec079f848a4b66
refs/heads/master
2020-03-07T06:47:49.294984
2018-04-04T23:28:18
2018-04-04T23:28:18
127,331,793
1
0
null
null
null
null
UTF-8
C++
false
false
3,081
cpp
#include <iostream> #include <string> #include "common.hpp" #include "data_nodes.hpp" #include "file_handling.hpp" #include "launcher.hpp" int32_t getMsed3Error(uint32_t num, std::vector<std::vector<int32_t>> nodes) { std::vector<int32_t> LFCSes = nodes[0]; std::vector<int32_t> msed3s = nodes[1]; int distance = std::abs((int)(LFCSes[0] - num)); int idx = 0; for (int i = 0; i < LFCSes.size(); i++) { int cdistance = std::abs((int)(LFCSes[i] - num)); if (cdistance < distance) { idx = i; distance = cdistance; } } return msed3s[idx]; } bool stringIsHex(std::string str) { return (str.find_first_not_of("0123456789abcdefABCDEF") == std::string::npos); } int main (int argc, char **argv) { if (argc == 1) { try { movable_part1 mp1; file_handling::readMP1(&mp1); std::vector<std::vector<int32_t>> nodes = data_nodes::readNodes(mp1.isNew3DS); uint32_t lfcs_num = mp1.LFCS[0] | (mp1.LFCS[1] << 8) | (mp1.LFCS[2] << 16) | (mp1.LFCS[3] << 24); std::cout << "lfcs_num: " << std::hex << lfcs_num << std::endl; if (lfcs_num == 0) { throw std::invalid_argument("The LFCS has been left blank!"); } int32_t msed3error = getMsed3Error(lfcs_num >> 12, nodes); std::cout << "msed3error: " << std::dec << msed3error << std::endl; mp1.msed3estimate = ((lfcs_num / 5) + (-1) * msed3error); std::cout << "msed3estimate: " << std::hex << mp1.msed3estimate << std::endl; launcher::doMining(mp1); } catch (std::exception e) { std::cout << "An exception occurred!" << std::endl; std::cout << e.what() << std::endl; system("pause"); return -1; } } else if (argc > 1 && (strcmp(argv[1], "id0") == 0)) { try { if (argc < 3) throw std::invalid_argument("id0 argument specified, but no id0 was provided!"); if (strlen(argv[2]) != 32) throw std::invalid_argument("The provided id0 is not 32 characters!"); if (!stringIsHex(std::string(argv[2]))) throw std::invalid_argument("The provided id0 is not a valid hexadecimal string!"); std::vector<uint8_t> id0(32); memcpy(&id0[0], argv[2], 32); file_handling::writeBytes("movable_part1.sed", 16, id0); std::cout << "Inserted the id0 in the movable_part1.sed" << std::endl; } catch (std::exception e) { std::cout << "An exception occurred!" << std::endl; std::cout << e.what() << std::endl; system("pause"); return -1; } } else { std::cout << "Incorrect usage!" << std::endl; std::cout << "Correct usage:" << std::endl << " - Seedminer" << std::endl << " - Seedminer id0 abcdef012345EXAMPLEdef0123456789" << std::endl; system("pause"); } system("pause"); return 0; }
[ "jason099080@hotmail.com" ]
jason099080@hotmail.com
17fd91a123850b2707faf2bcf468493856e81bed
034de645cc99598e357862fe8f379173edca7021
/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBuffer.h
135d3c2b38744fb65bc31cdb4b6ce2e57cfb9abb
[ "MIT" ]
permissive
leggedrobotics/ogre
1c0efe89a6fe55fe2e505ce55abdcf18603153a1
fe47104b65ffbbf3f4166cc2b11a93109c799537
refs/heads/raisimOgre
2021-07-08T18:46:32.251172
2020-10-05T13:21:09
2020-10-05T13:21:09
195,427,004
2
9
MIT
2020-10-05T13:21:10
2019-07-05T14:56:13
C++
UTF-8
C++
false
false
2,506
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __GL3PlusHARDWAREBUFFER_H__ #define __GL3PlusHARDWAREBUFFER_H__ #include "OgreGL3PlusPrerequisites.h" #include "OgreHardwareBuffer.h" namespace Ogre { class GL3PlusHardwareBuffer { private: GLenum mTarget; size_t mSizeInBytes; uint32 mUsage; GLuint mBufferId; GL3PlusRenderSystem* mRenderSystem; /// Utility function to get the correct GL usage based on HBU's static GLenum getGLUsage(uint32 usage); public: void* lockImpl(size_t offset, size_t length, HardwareBuffer::LockOptions options); void unlockImpl(); GL3PlusHardwareBuffer(GLenum target, size_t sizeInBytes, uint32 usage); ~GL3PlusHardwareBuffer(); void readData(size_t offset, size_t length, void* pDest); void writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer); void copyData(GLuint srcBufferId, size_t srcOffset, size_t dstOffset, size_t length, bool discardWholeBuffer); GLuint getGLBufferId(void) const { return mBufferId; } }; } #endif // __GL3PlusHARDWAREBUFFER_H__
[ "rojtberg@gmail.com" ]
rojtberg@gmail.com
ce418e0b0839d701f9cdb2b443b48c8223c868c1
08d1ed39609beac9ca2604ece44aa10741330e37
/server/main/utils/MD5Util.hpp
ead16a77c5815c9066838114b7bee4d4f567bf50
[]
no_license
wenyiyi/user
e1a310c47b9e526722c0f469054f20a10d12323e
860a1cda51b1024ad21b6f4271f7d613c849b1c6
refs/heads/master
2022-11-10T22:04:34.923705
2020-07-01T05:17:48
2020-07-01T05:17:48
276,225,400
0
0
null
null
null
null
UTF-8
C++
false
false
210
hpp
// // MD5Util.hpp // user // // Created by Vincent on 2020/6/26. // Copyright © 2020 Vincent. All rights reserved. // #ifndef MD5Util_hpp #define MD5Util_hpp #include <stdio.h> #endif /* MD5Util_hpp */
[ "1217047025@qq.com" ]
1217047025@qq.com
d13d46b1241c1fd11c0c52d2d422bf444a860037
5908c584b22d8f152deeb4082ff6003d841deaa9
/Physics_RT/Havok/Source/Physics2012/Dynamics/World/Simulation/Multithreaded/Spu/hkpSpuConfig.h
d05a37af44b8e52e68c345c3660ac015e6d4cb10
[]
no_license
imengyu/Physics_RT
1e7b71912e54b14679e799e7327b7d65531811f5
b8411b4bc483d6ce5c240ae4c004f3872c64d073
refs/heads/main
2023-07-17T20:55:39.303641
2021-08-28T18:25:01
2021-08-28T18:25:01
399,414,182
1
1
null
null
null
null
UTF-8
C++
false
false
9,448
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_SPU_CONFIG_H #define HK_SPU_CONFIG_H #include <Physics2012/Collide/Query/Multithreaded/Spu/hkpSpuConfig.h> #include <Physics2012/Collide/Agent/hkpProcessCollisionData.h> #include <Physics/ConstraintSolver/Solve/hkpSolve.h> // // Note: This file references symbols in other files. // You might have to include another file to use them properly // // Important: after modifying those values, check that you have at least 16k left for the normal stack // Also use the simulator to verify this size // ************************************************************************ // ******* General defines and limits of the engine ****** // ******* These values are Havok tunable + require a full rebuild ****** // ************************************************************************ // The maximum number of contact points which are created between 2 objects #define HK_MAX_NUM_CONTACT_POINTS_IN_CONSTRAINT_ON_SPU HK_MAX_CONTACT_POINT // The size of the cache lines on SPU. Only collision agents using shapes // with a size smaller than this value are processed on the spu; all others are left on PPU. #define HK_SPU_AGENT_SECTOR_JOB_MAX_SHAPE_SIZE HK_SPU_MAXIMUM_SHAPE_SIZE #define HK_SPU_AGENT_SECTOR_JOB_MAX_UNTYPED_CACHE_LINE_SIZE HK_SPU_UNTYPED_CACHE_LINE_SIZE #define HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_LINE_SIZE 512 // The maximum number of jacobians for a normal constraint (excluding contact point constraint) // This maximum is currently reached by a powered ragdoll constraint with friction and limits (hkpRagdollConstraintData::Runtime) #define HK_SPU_CONSTRAINT_RUNTIME_BUFFER_SIZE (16 * 11) // This is the maximum number of hits in a MOPP query, this includes the HK_INVALID_SHAPE_KEY end flag #define HK_MAX_AGENTS_IN_1N_MACHINE HK_MAX_NUM_HITS_PER_AABB_QUERY // ****************************************************** // ******* General flags to tune the performance ****** // ******* client rebuild required ****** // ****************************************************** // // Collision detection buffers // // This is the size of the top level shape cache cache. A cache miss is not really expensive, as the DMA is prefetched. // Must be power of 2, minimum 1k #define HK_SPU_AGENT_SECTOR_JOB_ROOT_SHAPE_CACHE_SIZE 2048 // This is the cache used by the user of shapes with child shapes. A cache miss is stalling and expensive // Must be power of 2, minimum 1k #define HK_SPU_AGENT_SECTOR_JOB_UNTYPED_CACHE_SIZE 4096 // This is the cache used by the MOPP. // Must be power of 2, minimum 2k #define HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_SIZE 8192 #define HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_SIZE_MIN 2048 // ******************************************************* // ******* Internal data, don't touch ****** // ******************************************************* // // Collision detection // // the number of rows, each of them has 4 lines enum { HK_SPU_AGENT_SECTOR_JOB_ROOT_SHAPE_NUM_CACHE_ROWS = HK_SPU_AGENT_SECTOR_JOB_ROOT_SHAPE_CACHE_SIZE / (4*HK_SPU_AGENT_SECTOR_JOB_MAX_SHAPE_SIZE) }; enum { HK_SPU_AGENT_SECTOR_JOB_UNTYPED_NUM_CACHE_ROWS = HK_SPU_AGENT_SECTOR_JOB_UNTYPED_CACHE_SIZE / (4*HK_SPU_AGENT_SECTOR_JOB_MAX_UNTYPED_CACHE_LINE_SIZE) }; enum { HK_SPU_AGENT_SECTOR_JOB_MOPP_NUM_CACHE_ROWS = HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_SIZE / (4*HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_LINE_SIZE) }; enum { HK_SPU_TOTAL_PHYSICS_BUFFER_SIZE = 56000 + HK_SPU_AGENT_SECTOR_JOB_ROOT_SHAPE_CACHE_SIZE + HK_SPU_AGENT_SECTOR_JOB_UNTYPED_CACHE_SIZE + HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_SIZE }; // reduced versions (for static compound ELF) enum { HK_SPU_AGENT_SECTOR_JOB_MOPP_NUM_CACHE_ROWS_MIN = HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_SIZE_MIN / (4*HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_LINE_SIZE) }; enum { HK_SPU_TOTAL_STATIC_COMPOUND_ELF_BUFFER_SIZE = 54000 + HK_SPU_AGENT_SECTOR_JOB_ROOT_SHAPE_CACHE_SIZE + HK_SPU_AGENT_SECTOR_JOB_UNTYPED_CACHE_SIZE + HK_SPU_AGENT_SECTOR_JOB_MOPP_CACHE_SIZE_MIN }; // // Solver // // - for schemas writer, when this buffer is full a DMA write is triggered #define HK_SPU_SCHEMA_WRITER_BASE_BUFFER_SIZE (1024 + 128) // this is the overflow buffer size. // it has to accommodate the entire max contact constraint == some 6000 bytes ?? // it also has to accommodate all the modifiers that my be attached to the constraint enum { HK_SPU_SCHEMA_WRITER_OVERFLOW_BUFFER_SIZE = (128 + (HK_MAX_CONTACT_POINT/2) * hkpJacobianSchemaInfo::PairContact::Sizeof + (HK_MAX_CONTACT_POINT%2) * hkpJacobianSchemaInfo::SingleContact::Sizeof + hkpJacobianSchemaInfo::Friction3D::Sizeof + hkpJacobianSchemaInfo::Header::Sizeof + 2 *(hkpJacobianSchemaInfo::SetMass::Sizeof + hkpJacobianSchemaInfo::AddVelocity::Sizeof + hkpJacobianSchemaInfo::SetCenterOfMass::Sizeof) + 3 * hkpJacobianSchemaInfo::Header::Sizeof), }; #define HK_SPU_SOLVE_SCHEMA_READER_BASE_BUFFER_SIZE (512) #define HK_SPU_SOLVE_SCHEMA_READER_OVERFLOW_BUFFER_SIZE (1024) enum { HK_SPU_SOLVE_MORE_LESS_MAX_SIZE_OF_CONTACT_SCHEMAS_WITHOUT_BUFFER_CHECK = (4 * hkpJacobianSchemaInfo::PairContact::Sizeof + hkpJacobianSchemaInfo::SingleContact::Sizeof + 1 * hkpJacobianSchemaInfo::Header::Sizeof + (hkpJacobianSchemaInfo::SetMass::Sizeof + 2 * hkpJacobianSchemaInfo::AddVelocity::Sizeof + hkpJacobianSchemaInfo::SetCenterOfMass::Sizeof)), }; // this below is 880 enum { HK_SPU_SOLVE_MORE_THAN_MAX_SIZE_OF_CONTACT_SCHEMAS_WITHOUT_BUFFER_CHECK = ( 4 * hkpJacobianSchemaInfo::PairContact::Sizeof + hkpJacobianSchemaInfo::SingleContact::Sizeof + 4 * hkpJacobianSchemaInfo::Header::Sizeof + 2 * (hkpJacobianSchemaInfo::SetMass::Sizeof + hkpJacobianSchemaInfo::AddVelocity::Sizeof + hkpJacobianSchemaInfo::SetCenterOfMass::Sizeof)), }; // solverTempElems for ragdoll: // 3 * (frictionAngular+motorAngular+limitAngular+linear) == 3 * (2+3+1+1) = 21 // solverTempElems for contact point (we have accessor checks every 8th contact point) // ((8+1) * cp + 3d friction) == (8+1) * 1 + 4 = 13 #define HK_SPU_SOLVE_ELEM_TEMP_READER_BASE_BUFFER_SIZE 256 #define HK_SPU_SOLVE_ELEM_TEMP_READER_OVERFLOW_BUFFER_SIZE 128 // Solver export : solver results writer buffer sizes #define HK_SPU_SOLVE_RESULTS_WRITER_BASE_BUFFER_SIZE 512 #define HK_SPU_SOLVE_RESULTS_WRITER_OVERFLOW_BUFFER_SIZE 128 // - for accumulator fetching (sizeof(hkpVelocityAccumulator) == 128, cacheRow = 4*cacheLine, cacheLine = hkpVelocityAccumulator + 2*int) #define HK_SPU_ACCUMULATOR_CACHE_NUM_CACHE_ROWS 16 // - for constraintAtoms #define HK_CONSTRAINTATOM_SIZE_PER_CONTACT_POINT (sizeof(hkContactPoint) + sizeof(hkpContactPointProperties)) #define HK_SPU_CONSTRAINT_ATOM_BUFFER_SIZE ( HK_NEXT_MULTIPLE_OF(16, HK_MAX_NUM_CONTACT_POINTS_IN_CONSTRAINT_ON_SPU * HK_CONSTRAINTATOM_SIZE_PER_CONTACT_POINT) + sizeof(hkpSimpleContactConstraintAtom)) // ********************************** // ******* Internal dma groups ****** // ********************************** // These groups are for reference only. // If you use sub functions to the relevant jobs, // you should avoid conflicts with DMA groups /// DMA groups used by the Jacobians builder. namespace hkSpuBuildJacobiansJobDmaGroups { enum { GET_QUERYIN_DMA_GROUP = 0, GET_DATA_BASE_DMA_GROUP = 1, // we are using double buffering, so we need to reserve 2 DMA groups for this! WRITE_BACK_CONTACT_CONSTRAINT_ATOM_DMA_GROUP = 3, WRITE_BACK_RUNTIME_DMA_GROUP = 4, // next free dma group to use: 5 }; } namespace hkSpuAgentSectorJobDmaGroups { enum { GET_ELEMENT_PTRS_DMA_GROUP = 1, GET_ENTRY_DATA_DMA_GROUP = 2, // we use 5 pipeline stages, so we need to reserve 5 DMA groups GET_BIG_ATOMS_DMA_GROUP = 7, GET_UNTYPED_CACHE_DATA = 8, SHAPE_KEY_TRACK_DMA_GROUP = 9 // Only used in split pipeline. }; } namespace hk1nMachineDmaGroups // these groups should not collide with hkSpuAgentSectorJobDmaGroups { enum { GET_SECTOR_POINTERS_DMA_GROUP = 10, GET_SECTOR_DMA_GROUP = 12, WRITE_SECTOR_DMA_GROUP = 14, }; } #endif // HK_SPU_CONFIG_H /* * Havok SDK - Base file, BUILD(#20131218) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from salesteam@havok.com. * */
[ "1501076885@qq.com" ]
1501076885@qq.com
efdd64ea054270ff7d902a7fd5d3549bb20c704a
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/chrome/browser/ui/views/omnibox/omnibox_result_view_unittest.cc
bc514d77aa398f8df2e08141eba44c3b82c47362
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,215
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/omnibox/omnibox_result_view.h" #include "testing/gtest/include/gtest/gtest.h" TEST(OmniboxResultViewTest, CheckComputeMatchWidths) { int contents_max_width, description_max_width; const int separator_width = 10; // Both contents and description fit fine. OmniboxResultView::ComputeMatchMaxWidths( 100, separator_width, 50, 200, false, true, &contents_max_width, &description_max_width); EXPECT_EQ(-1, contents_max_width); EXPECT_EQ(-1, description_max_width); // Contents should be given as much space as it wants up to 300 pixels. OmniboxResultView::ComputeMatchMaxWidths( 100, separator_width, 50, 100, false, true, &contents_max_width, &description_max_width); EXPECT_EQ(-1, contents_max_width); EXPECT_EQ(0, description_max_width); // Description should be hidden if it's at least 75 pixels wide but doesn't // get 75 pixels of space. OmniboxResultView::ComputeMatchMaxWidths( 300, separator_width, 75, 384, false, true, &contents_max_width, &description_max_width); EXPECT_EQ(-1, contents_max_width); EXPECT_EQ(0, description_max_width); // Both contents and description will be limited. OmniboxResultView::ComputeMatchMaxWidths( 310, separator_width, 150, 400, false, true, &contents_max_width, &description_max_width); EXPECT_EQ(300, contents_max_width); EXPECT_EQ(400 - 300 - separator_width, description_max_width); // Contents takes all available space. OmniboxResultView::ComputeMatchMaxWidths( 400, separator_width, 0, 200, false, true, &contents_max_width, &description_max_width); EXPECT_EQ(-1, contents_max_width); EXPECT_EQ(0, description_max_width); // Half and half. OmniboxResultView::ComputeMatchMaxWidths( 395, separator_width, 395, 700, false, true, &contents_max_width, &description_max_width); EXPECT_EQ((700 - separator_width) / 2, contents_max_width); EXPECT_EQ((700 - separator_width) / 2, description_max_width); // When we disallow shrinking the contents, it should get as much space as // it wants. OmniboxResultView::ComputeMatchMaxWidths( 395, separator_width, 395, 700, false, false, &contents_max_width, &description_max_width); EXPECT_EQ(-1, contents_max_width); EXPECT_EQ(295, description_max_width); // (available_width - separator_width) is odd, so contents gets the extra // pixel. OmniboxResultView::ComputeMatchMaxWidths( 395, separator_width, 395, 699, false, true, &contents_max_width, &description_max_width); EXPECT_EQ((700 - separator_width) / 2, contents_max_width); EXPECT_EQ((700 - separator_width) / 2 - 1, description_max_width); // Not enough space to draw anything. OmniboxResultView::ComputeMatchMaxWidths( 1, 1, 1, 0, false, true, &contents_max_width, &description_max_width); EXPECT_EQ(0, contents_max_width); EXPECT_EQ(0, description_max_width); }
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
6c57c994f37499bf6b67238436e589da7aed452d
20aab3ff4cdf44f9976686a2f161b3a76038e782
/lua/ProjectST/龍神録/project/22章/mydat/source/char.cpp
be176c7a8125a1666f0da320d2a3b1938c34daab
[ "MIT" ]
permissive
amenoyoya/old-project
6eee1e3e27ea402c267fc505b80f31fa89a2116e
640ec696af5d18267d86629098f41451857f8103
refs/heads/master
2020-06-12T20:06:25.828454
2019-07-12T04:09:30
2019-07-12T04:09:30
194,408,956
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,571
cpp
#include "../include/GV.h" void calc_ch(){ if(ch.cnt==0 && ch.flag==2){//今の瞬間死んだら ch.x=FIELD_MAX_X/2;//座標セット ch.y=FIELD_MAX_Y+30; ch.mutekicnt++;//無敵状態へ } if(ch.flag==2){//死んで浮上中なら unsigned int push=CheckStatePad(configpad.left)+CheckStatePad(configpad.right) +CheckStatePad(configpad.up)+CheckStatePad(configpad.down); ch.y-=1.5;//キャラを上に上げる //1秒以上か、キャラがある程度上にいて、何かおされたら if(ch.cnt>60 || (ch.y<FIELD_MAX_Y-20 && push)){ ch.cnt=0; ch.flag=0;//キャラステータスを元に戻す } } if(ch.mutekicnt>0){//無敵カウントが0じゃなければ ch.mutekicnt++; if(ch.mutekicnt>150)//150以上たったら ch.mutekicnt=0;//戻す } ch.cnt++;//キャラクタカウントアップ ch.img=(ch.cnt%24)/6;//現在の画像決定 } void ch_move(){ int i,sayu_flag=0,joge_flag=0; double x,y,mx,my,naname=1; double move_x[4]={-4.0,4.0,0,0},move_y[4]={0,0,4.0,-4.0}; int inputpad[4]; inputpad[0]=CheckStatePad(configpad.left); inputpad[1]=CheckStatePad(configpad.right); inputpad[2]=CheckStatePad(configpad.down); inputpad[3]=CheckStatePad(configpad.up); if(CheckStatePad(configpad.left)>0)//左キーが押されていたら ch.img+=4*2;//画像を左向きに else if(CheckStatePad(configpad.right)>0)//右キーが押されていたら ch.img+=4*1;//画像を右向きに for(i=0;i<2;i++)//左右分 if(inputpad[i]>0)//左右どちらかの入力があれば sayu_flag=1;//左右入力フラグを立てる for(i=2;i<4;i++)//上下分 if(inputpad[i]>0)//上下どちらかの入力があれば joge_flag=1;//上下入力フラグを立てる if(sayu_flag==1 && joge_flag==1)//左右、上下両方の入力があれば斜めだと言う事 naname=sqrt(2.0);//移動スピードを1/ルート2に for(int i=0;i<4;i++){//4方向分ループ if(inputpad[i]>0){//i方向のキーボード、パッドどちらかの入力があれば x=ch.x , y=ch.y;//今の座標をとりあえずx,yに格納 mx=move_x[i]; my=move_y[i];//移動分をmx,myに代入 if(CheckStatePad(configpad.slow)>0){//低速移動なら mx=move_x[i]/3; my=move_y[i]/3;//移動スピードを1/3に } x+=mx/naname , y+=my/naname;//今の座標と移動分を足す if(!(x<10 || x>FIELD_MAX_X || y<5 || y>FIELD_MAX_Y-5)){//計算結果移動可能範囲内なら ch.x=x , ch.y=y;//実際に移動させる } } } }
[ "mtyswe3@gmail.com" ]
mtyswe3@gmail.com
1cbc670dece0f67dbe4908d846cb54bac703d13c
a14bce89ac64eb13ddb80c670624fbc6b0768d8b
/Kaltag/citypath.cpp
24015bb1f952975768ffb2f6d34d783d09d5a199
[]
no_license
tylercchase/cs202
e15ac38d1cdc096d9ba11954af3e42f8402d1d15
ce6d3fe71d52114b3bc4728d009646d933f0a2da
refs/heads/master
2020-12-11T17:48:21.305867
2020-05-01T01:43:03
2020-05-01T01:43:03
233,916,293
0
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
#include "cityPath.hpp" #include <math.h> void CityPath::addCity(CityNode &city){ connections.push_back(city); } int CityPath::totalDistance(){ int total = 0; for(int i = 0; i < connections.size() - 1; i++){ total += sqrt(pow((connections[i+1].getLatitude() - connections[i].getLatitude() ),2) + pow(connections[i+1].getLongitude() - connections[i].getLongitude() ,2)); } return total; }
[ "tylercchase@gmail.com" ]
tylercchase@gmail.com
36a1bc3e5057f9d5b91b56593e679c5e6f187741
497295beab134b883f9b1eb835117aadada06a84
/AI.cpp
08d49e318da3271e54ae692b7cac2dbcf692367d
[]
no_license
Curtainf2f/Gomoku
e51178460362571d348e101f163e4434e46ca084
795cfdc76dde146a6329fce1ec2a8b15abdfef13
refs/heads/master
2020-05-24T00:25:38.761981
2019-05-16T11:53:40
2019-05-16T11:53:40
187,016,376
0
0
null
null
null
null
GB18030
C++
false
false
14,680
cpp
#include "graphics.h" #include "art.h" #include "mystruct.h" #include "AI.h" #include <stack> #include <queue> #include <cstring> #include "rule.h" #include <algorithm> #include <iostream> #include <cstdio> #include <map> #include <set> #include <string> #include <ctime> using namespace std; //#define DEBUG clock_t start_time; const int timelimit = 930; extern int map_wzq[15][15]; extern std::stack<chesspiece*> chess; thinkpiece *tempchess; bool piececlosed(int x,int y) { int next[8][2]= {1,0,-1,0,0,1,0,-1,1,1,-1,-1,1,-1,-1,1}; int tx,ty,sum; for(int i=0; i<4; i++) { for(int j=0; j<2; j++) { sum=1; tx=x; ty=y; while(1) { if(sum>3) break; tx+=next[i*2+j][0]; ty+=next[i*2+j][1]; if(tx<0||ty<0||tx>=15||ty>=15) break; if(map_wzq[tx][ty]==0) sum+=1; else return true; } } } return false; } int analysis(char s[]) { ///长连 if (strstr(s,"OOOOO")!=NULL) return 0; ///活四 else if (strstr(s,"_OOOO_")!=NULL) return 1; else if (strstr(s,"O_OOO_O")!=NULL) return 1; ///冲四 else if (strstr(s,"OOO_O")!=NULL) return 2; else if (strstr(s,"_OOOOH")!=NULL) return 2; else if (strstr(s,"OO_OO")!=NULL) return 2; ///活三 else if (strstr(s,"__OOO_")!=NULL) return 3; else if (strstr(s,"_OO_O_")!=NULL) return 3; ///眠三 else if (strstr(s,"OHHH_O")!=NULL) return 4; else if (strstr(s,"OHH_HO")!=NULL) return 4; else if (strstr(s,"__OOOH")!=NULL) return 4; else if (strstr(s,"_O_OOH")!=NULL) return 4; else if (strstr(s,"_OO_OH")!=NULL) return 4; else if (strstr(s,"O__OO")!=NULL) return 4; else if (strstr(s,"O_O_O")!=NULL) return 4; else if (strstr(s,"H_OOO_H")!=NULL) return 4; ///活二 else if (strstr(s,"__OO__")!=NULL) return 5; else if (strstr(s,"__O_O_")!=NULL) return 5; else if (strstr(s,"_O__O_")!=NULL) return 5; else if (strstr(s,"___OO_")!=NULL) return 5; ///眠二 else if (strstr(s,"___OOH")!=NULL) return 6; else if (strstr(s,"__O_OH")!=NULL) return 6; else if (strstr(s,"_O__OH")!=NULL) return 6; else if (strstr(s,"H_O_O_H")!=NULL) return 6; else if (strstr(s,"H_OO__H")!=NULL) return 6; return 7; } bool vct; int countscore(thinkpiece piece,int c) { int position[15][15] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 }, { 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0 }, { 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0 }, { 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0 }, { 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0 }, { 0, 1, 2, 3, 4, 5, 6, 6, 6, 5, 4, 3, 2, 1, 0 }, { 0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0 }, { 0, 1, 2, 3, 4, 5, 6, 6, 6, 5, 4, 3, 2, 1, 0 }, { 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0 }, { 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0 }, { 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0 }, { 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0 }, { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; int v=0; int tx,ty; char s[4][13]; int len[4]; int situation[8]; int next[8][2]= {1,0,-1,0,0,1,0,-1,1,1,-1,-1,1,-1,-1,1}; v+=position[piece.x][piece.y]; memset(situation,0,sizeof(situation)); for(int i=0; i<4; i++) { for(int j=0; j<2; j++) { len[j]=0; tx=piece.x; ty=piece.y; while(1) { if(len[j]>4) break; tx+=next[i*2+j][0]; ty+=next[i*2+j][1]; if(tx>=0&&ty>=0&&tx<15&&ty<15) { if(map_wzq[tx][ty]==0) s[j][len[j]++]='_'; else if(map_wzq[tx][ty]==c) s[j][len[j]++]='O'; else { s[j][len[j]++]='H'; } } else { s[j][len[j]++]='H'; break; } } s[j][len[j]]='\0'; } len[2]=0; len[3]=0; for(int k=len[0]-1; k>=0; k--) s[2][len[2]++]=s[0][k]; s[2][len[2]++]='O'; for(int k=0; k<len[1]; k++) s[2][len[2]++]=s[1][k]; s[2][len[2]]='\0'; for(int k=len[2]-1; k>=0; k--) s[3][len[3]++]=s[2][k]; s[3][len[3]]='\0'; situation[std::min(analysis(s[2]),analysis(s[3]))]++; } //长连0 活四1 眠四2 活三3 眠三4 活二5 眠二6 if(situation[0]) v+=1000000; else if(situation[1]||situation[2]>=2||(situation[2]&&situation[3])) v+=100000; else if(situation[3]>=2) v+=50000; else if(situation[2] && vct) v+=6000; else if(situation[3] && (situation[4] || situation[5])) v += 5500; else if(situation[2] && (situation[4] || situation[5])) v += 5500; else if(situation[3] || situation[2]) v+=5000; else if(situation[4] >= 2) v+=400*situation[4]; else if(situation[4]) v+=200 + situation[5]*20; else if(situation[5]) v+=80*situation[5]; else if(situation[6]) v+=10*situation[6]; return v; } bool vctf(thinkpiece piece, int range, int c, int depth); int delscore(int c); thinkpiece maxpiece; bool isme; int pdf; #ifdef DEBUG FILE *fp; #endif // DEBUG bool protect(thinkpiece piece, int c, int v, int depth) { clock_t end_time = clock(); if(static_cast<double>(end_time - start_time)/CLOCKS_PER_SEC*1000 >= timelimit) { return true; } int b; if(c==1) b=2; else b=1; queue<thinkpiece> consider; int x = piece.x; int y = piece.y; int next[8][2]= {1,0,-1,0,0,1,0,-1,1,1,-1,-1,1,-1,-1,1}; int tx,ty,sum; for(int i=0; i<4; i++) { for(int j=0; j<2; j++) { sum=1; tx=x; ty=y; while(1) { if(sum>4) break; tx+=next[i*2+j][0]; ty+=next[i*2+j][1]; if(tx<0||ty<0||tx>=15||ty>=15) break; if(map_wzq[tx][ty]==0) { consider.push(thinkpiece(tx, ty)); } sum+=1; } } } while(!consider.empty()) { thinkpiece now = consider.front(); consider.pop(); map_wzq[now.x][now.y] = c; int del = delscore(b); if(del >= 10000) { map_wzq[now.x][now.y] = 0; continue; } else { #ifdef DEBUG fprintf(fp,"%d %d try to protect\n", now.x, now.y); for(int i = 0; i < 15; i ++) { for(int j = 0; j < 15; j ++) { fprintf(fp,"%d ", map_wzq[j][i]); } fprintf(fp,"\n"); } #endif // DEBUG if(!vctf(piece, 4, b, depth - 1)) { map_wzq[now.x][now.y] = 0; return true; } } map_wzq[now.x][now.y] = 0; } return false; } bool vctf(thinkpiece piece, int range, int c, int depth) // range 2 or 14 { clock_t end_time = clock(); if(static_cast<double>(end_time - start_time)/CLOCKS_PER_SEC*1000 >= timelimit) { return false; } if(depth <= 0) return false; int b; if(c==1) b=2; else b=1; int left, right, up, down; if(piece.x - range >= 0) left = piece.x - range; else left = 0; if(piece.x + range < 15) right = piece.x + range; else right = 14; if(piece.y - range >= 0) up = piece.y - range; else up = 0; if(piece.y + range < 15) down = piece.y + range; else down = 14; for(int y=up; y<=down; y++) { for(int x=left; x<=right; x++) { if(!map_wzq[x][y]&&piececlosed(x, y)) { map_wzq[x][y] = c; int v = countscore(thinkpiece(x, y), c); int del; if(v >= 10000) { del = delscore(b); if(v - del >= -10) { #ifdef DEBUG fprintf(fp, "test 10000\n"); for(int i = 0; i < 15; i ++) { for(int j = 0; j < 15; j ++) { fprintf(fp,"%d ", map_wzq[j][i]); } fprintf(fp, "\n"); } #endif // DEBUG map_wzq[x][y] = 0; if(isme) maxpiece = thinkpiece(x,y); return true; } } else if(v >= pdf) { del = delscore(b); if(v - del >= -10) { #ifdef DEBUG fprintf(fp, "test 6000\n"); for(int i = 0; i < 15; i ++) { for(int j = 0; j < 15; j ++) { fprintf(fp,"%d ", map_wzq[j][i]); } fprintf(fp, "\n"); } #endif // DEBUG if(!protect(thinkpiece(x, y), b, v, depth - 3)) { map_wzq[x][y] = 0; if(isme) maxpiece = thinkpiece(x,y); return true; } } } else if(v >= 5000) { del = delscore(b); if(v - del >= -10) { #ifdef DEBUG fprintf(fp, "test 5000\n"); for(int i = 0; i < 15; i ++) { for(int j = 0; j < 15; j ++) { fprintf(fp,"%d ", map_wzq[j][i]); } fprintf(fp, "\n"); } #endif // DEBUG if(!protect(thinkpiece(x, y), b, v, depth - 1)) { map_wzq[x][y] = 0; if(isme) maxpiece = thinkpiece(x,y); return true; } } } map_wzq[x][y] = 0; } } } return false; } int delscore(int c) { queue<thinkpiece> add; thinkpiece piece; int vmax=-9999999, v; for(int y=0; y<15; y++) for(int x=0; x<15; x++) if(!map_wzq[x][y]&&piececlosed(x,y)) { piece.x=x; piece.y=y; add.push(piece); } while(!add.empty()) { map_wzq[add.front().x][add.front().y]=c; v=countscore(add.front(),c); if(v > vmax) { vmax = v; } map_wzq[add.front().x][add.front().y]=0; add.pop(); } return vmax; } void AIthinking(int c) { if(chess.empty()) { putchesspieces(7,7,c); return ; } else if(chess.size() == 1 && !(chess.top()->x ==7 && chess.top()->y == 7)) { if(chess.top()->x>7) { putchesspieces(chess.top()->x-1,chess.top()->y,c); } else { putchesspieces(chess.top()->x+1,chess.top()->y,c); } return ; } int b; if(c==1) b=2; else b=1; thinkpiece piece, vmaxpiece; piece.x = chess.top()->x; piece.y = chess.top()->y; isme = 1; vct = 1; pdf = 6000; #ifdef DEBUG fp = fopen("1.txt", "w"); #endif // DEBUG if(vctf(piece, 14, c, 11)) { #ifdef DEBUG puts("win"); #endif // DEBUG putchesspieces(maxpiece.x,maxpiece.y,c); return ; #ifdef DEBUG fclose(fp); #endif // DEBUG } #ifdef DEBUG fclose(fp); puts("test1"); #endif // DEBUG isme = 0; vct = 0; pdf = 6000; queue<thinkpiece> add; int vmax=-9999999, vvmax = -9999999,v; for(int y=0; y<15; y++) for(int x=0; x<15; x++) if(!map_wzq[x][y]&&piececlosed(x,y)) { piece.x=x; piece.y=y; add.push(piece); } while(!add.empty()) { map_wzq[add.front().x][add.front().y]=c; v=countscore(add.front(),c); int del = delscore(b); v -= del; if(v >= vvmax) { if(v >= -10) { #ifdef DEBUG fp = fopen("23.txt", "a"); #endif // DEBUG vct = 1; if(!vctf(add.front(), 14, b, 11)) { #ifdef DEBUG puts("ok2"); #endif // DEBUG if(v > vvmax) { vvmax = v; vmaxpiece = add.front(); } if(v >= vvmax - 1) { if(rand() & 1) { vmaxpiece = add.front(); } } } vct = 0; #ifdef DEBUG fclose(fp); #endif // DEBUG } else { if(v > vmax){ vmax = v; maxpiece = add.front(); } if(v >= vmax - 1){ if(rand() & 1) { maxpiece = add.front(); } } } } if(vvmax != -9999999) { maxpiece = vmaxpiece; } // printf("[%d %d] +%d -%d =%d\n", add.front().x, add.front().y, addv, del, v); map_wzq[add.front().x][add.front().y]=0; add.pop(); } putchesspieces(maxpiece.x,maxpiece.y,c); return ; }
[ "835074923@qq.com" ]
835074923@qq.com
af73160f7a8b2e8f75da9a7c40a059bed1a5158a
515d4cea84eb2dd70b67b1b1bfc64de14fdd0d3d
/arduino/arduino_onboard/arduino.ino
b91f66ad7a6fdcf9ab03d6d79434547ab0d48a3d
[]
no_license
Pigaco/hosts
cc618566dcedca9442850ce0aeb18286d2b5decb
64a872aeeb179ce38513d553a015c7165956b73e
refs/heads/master
2021-01-22T03:13:58.418832
2016-11-14T12:41:57
2016-11-14T12:41:57
38,927,975
1
0
null
null
null
null
UTF-8
C++
false
false
1,614
ino
#include "serial_connector.h" #include "button.h" #include "led.h" //If you change the baud rate here, you also have //to change it in the makefile. SerialConnector serialConnector(9600); //Workaround for an arduino compiler bug void* __dso_handle; void* __cxa_atexit; //LEDs LED *leds[6]; //Buttons Button *buttons[11]; void setup(void) { //Status-LED pinMode(13, OUTPUT); digitalWrite(13, HIGH); serialConnector.setup(); Button::serialConnector = &serialConnector; //Create LEDs and buttons. //Be cautious with the IDs and pins! // //!!!!!!!!!!! //CHANGE THIS //!!!!!!!!!!! //LEDs use the analog pins. leds[0] = new LED(A0); leds[1] = new LED(A1); leds[2] = new LED(A2); leds[3] = new LED(A3); leds[4] = new LED(A4); leds[5] = new LED(A5); //Buttons use the digital pins. buttons[0] = new Button(10, BUTTON_UP); buttons[1] = new Button(11, BUTTON_DOWN); buttons[2] = new Button(12, BUTTON_LEFT); buttons[3] = new Button(2, BUTTON_RIGHT); buttons[4] = new Button(9, BUTTON_ACTION); buttons[5] = new Button(3, BUTTON_BUTTON1); buttons[6] = new Button(4, BUTTON_BUTTON2); buttons[7] = new Button(5, BUTTON_BUTTON3); buttons[8] = new Button(6, BUTTON_BUTTON4); buttons[9] = new Button(7, BUTTON_BUTTON5); buttons[10] = new Button(8, BUTTON_BUTTON6); serialConnector.leds = leds; } void loop(void) { int i; serialConnector.loop(); for(i = 0; i < 6; ++i) { leds[i]->loop(); } for(i = 0; i < 11; ++i) { buttons[i]->loop(); } }
[ "mail@maximaximal.com" ]
mail@maximaximal.com
24fd8e4ae252079b83a771d1fdf742b566e2fb66
c6881dbb2cb0aea8ac39c809aa5d339c9e15ac09
/Blockchain/txdb.cpp
7beceb3bd01ebb780c277a8af9aa5a2d2c3b2ce9
[]
no_license
HungMingWu/blockchain-demo
d62afbe6caf41f07b7896f312fd9a2a7e27280c7
ebe6e079606fe2fe7bf03783d66300df7a94d5be
refs/heads/master
2020-03-21T22:33:38.664567
2018-10-01T10:12:40
2018-10-01T10:12:40
139,134,108
0
0
null
null
null
null
UTF-8
C++
false
false
12,523
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "chain.h" #include "chainparams.h" #include "hash.h" #include "main.h" #include "pow.h" #include "uint256.h" #include <stdint.h> #include <boost/thread.hpp> using namespace std; static const char DB_COINS = 'c'; static const char DB_BLOCK_FILES = 'f'; static const char DB_TXINDEX = 't'; static const char DB_ADDRESSINDEX = 'a'; static const char DB_ADDRESSUNSPENTINDEX = 'u'; static const char DB_TIMESTAMPINDEX = 's'; static const char DB_SPENTINDEX = 'p'; static const char DB_BLOCK_INDEX = 'b'; static const char DB_BEST_BLOCK = 'B'; static const char DB_FLAG = 'F'; static const char DB_REINDEX_FLAG = 'R'; static const char DB_LAST_BLOCK = 'l'; CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true) { } bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const { return db.Read(make_pair(DB_COINS, txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256 &txid) const { return db.Exists(make_pair(DB_COINS, txid)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read(DB_BEST_BLOCK, hashBestChain)) return uint256(); return hashBestChain; } bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { CDBBatch batch(&db.GetObfuscateKey()); size_t count = 0; size_t changed = 0; for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { if (it->second.coins.IsPruned()) batch.Erase(make_pair(DB_COINS, it->first)); else batch.Write(make_pair(DB_COINS, it->first), it->second.coins); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } if (!hashBlock.IsNull()) batch.Write(DB_BEST_BLOCK, hashBlock); LOG_INFO("Committing {} changed transactions (out of {}) to coin database...", (unsigned int)changed, (unsigned int)count); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(make_pair(DB_BLOCK_FILES, nFile), info); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write(DB_REINDEX_FLAG, '1'); else return Erase(DB_REINDEX_FLAG); } bool CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists(DB_REINDEX_FLAG); return true; } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read(DB_LAST_BLOCK, nFile); } bool CCoinsViewDB::GetStats(CCoinsStats &stats) const { /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ std::unique_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator()); pcursor->Seek(DB_COINS); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, uint256> key; CCoins coins; if (pcursor->GetKey(key) && key.first == DB_COINS) { if (pcursor->GetValue(coins)) { stats.nTransactions++; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + pcursor->GetValueSize(); ss << VARINT(0); } else { LOG_ERROR("CCoinsViewDB::GetStats() : unable to read value"); return false; } } else { break; } pcursor->Next(); } { LOCK(cs_main); stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; } stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : fileInfo) batch.Write(make_pair(DB_BLOCK_FILES, pairs.first), *pairs.second); batch.Write(DB_LAST_BLOCK, nLastFile); for (const auto &info : blockinfo) batch.Write(make_pair(DB_BLOCK_INDEX, info->GetBlockHash()), CDiskBlockIndex(info)); return WriteBatch(batch, true); } bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(make_pair(DB_TXINDEX, txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) batch.Write(make_pair(DB_TXINDEX, pairs.first), pairs.second); return WriteBatch(batch); } bool CBlockTreeDB::ReadSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value) { return Read(make_pair(DB_SPENTINDEX, key), value); } bool CBlockTreeDB::UpdateSpentIndex(const std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) { if (pairs.second.IsNull()) { batch.Erase(make_pair(DB_SPENTINDEX, pairs.first)); } else { batch.Write(make_pair(DB_SPENTINDEX, pairs.first), pairs.second); } } return WriteBatch(batch); } bool CBlockTreeDB::UpdateAddressUnspentIndex(const std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue > >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) { if (pairs.second.IsNull()) { batch.Erase(make_pair(DB_ADDRESSUNSPENTINDEX, pairs.first)); } else { batch.Write(make_pair(DB_ADDRESSUNSPENTINDEX, pairs.first), pairs.second); } } return WriteBatch(batch); } bool CBlockTreeDB::ReadAddressUnspentIndex(uint160 addressHash, int type, std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_ADDRESSUNSPENTINDEX, CAddressIndexIteratorKey(type, addressHash))); while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char,CAddressUnspentKey> key; if (pcursor->GetKey(key) && key.first == DB_ADDRESSUNSPENTINDEX && key.second.hashBytes == addressHash) { CAddressUnspentValue nValue; if (pcursor->GetValue(nValue)) { unspentOutputs.push_back(make_pair(key.second, nValue)); pcursor->Next(); } else { LOG_ERROR("failed to get address unspent value"); return false; } } else { break; } } return true; } bool CBlockTreeDB::WriteAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) batch.Write(make_pair(DB_ADDRESSINDEX, pairs.first), pairs.second); return WriteBatch(batch); } bool CBlockTreeDB::EraseAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) batch.Erase(make_pair(DB_ADDRESSINDEX, pairs.first)); return WriteBatch(batch); } bool CBlockTreeDB::ReadAddressIndex(uint160 addressHash, int type, std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex, int start, int end) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); if (start > 0 && end > 0) { pcursor->Seek(make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorHeightKey(type, addressHash, start))); } else { pcursor->Seek(make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorKey(type, addressHash))); } while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char,CAddressIndexKey> key; if (pcursor->GetKey(key) && key.first == DB_ADDRESSINDEX && key.second.hashBytes == addressHash) { if (end > 0 && key.second.blockHeight > end) { break; } CAmount nValue; if (pcursor->GetValue(nValue)) { addressIndex.push_back(make_pair(key.second, nValue)); pcursor->Next(); } else { LOG_ERROR("failed to get address index value"); return false; } } else { break; } } return true; } bool CBlockTreeDB::WriteTimestampIndex(const CTimestampIndexKey &timestampIndex) { CDBBatch batch(&GetObfuscateKey()); batch.Write(make_pair(DB_TIMESTAMPINDEX, timestampIndex), 0); return WriteBatch(batch); } bool CBlockTreeDB::ReadTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector<uint256> &hashes) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_TIMESTAMPINDEX, CTimestampIndexIteratorKey(low))); while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, CTimestampIndexKey> key; if (pcursor->GetKey(key) && key.first == DB_TIMESTAMPINDEX && key.second.timestamp <= high) { hashes.push_back(key.second.blockHash); pcursor->Next(); } else { break; } } return true; } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair(DB_FLAG, name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::LoadBlockIndexGuts() { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256())); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, uint256> key; if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) { CDiskBlockIndex diskindex; if (pcursor->GetValue(diskindex)) { // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev.reset(InsertBlockIndex(diskindex.hashPrev)); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->hashClaimTrie = diskindex.hashClaimTrie; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; #if 0 if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus())) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); #endif pcursor->Next(); } else { LOG_ERROR("LoadBlockIndex() : failed to read value"); return false; } } else { break; } } return true; }
[ "u9089000@gmail.com" ]
u9089000@gmail.com
d7f035e71582d668881cb61dc4cf243cb15a37f3
75d5e91750db9da92b76b1cf133f1321e5408555
/GRA/Draw.h
2e72dd2a82518cf4c0f65772237da9e62f92f9dd
[]
no_license
piotr4321/grafika
33337eeebe74602caf57bbe3af26116d4d95734d
7cddda25552bec1efa6c4c2061f7c49cd8f2035e
refs/heads/master
2021-01-10T05:34:34.080673
2016-01-22T17:50:25
2016-01-22T17:50:25
50,146,695
0
0
null
null
null
null
UTF-8
C++
false
false
570
h
#pragma once #include <cstdlib> #include "quickcg.h" //klasa reprezentujaca operacje rysowania class Draw { public: //funkcja inicjalizująca okno gry static void initScreen(int width, int height, bool fullscreen, const std::string& text); //funkcja rysująca nową klatkę static void updateScreen(); //funkcja czyszcząca ekran static void clearScreenToBlack(); //funkcja rysująca ściane static void drawVerticalLine(int x, int y1, int y2, const QuickCG::ColorRGB& color); //wybór kolory ściany static QuickCG::ColorRGB setWallColor(int n); };
[ "wefwfwae@gmail.com" ]
wefwfwae@gmail.com
005b56d107a73510760afe9e5140a6be2ba31dee
0a570a49cac8a807d8feceb78663355212b080cb
/Arduino/jarvis/SerialController.hpp
856acc795267d33675151fc3597a9217e64db72b
[ "MIT" ]
permissive
davide-dv/IoTProject
7405c21f2ca611eaf21ea0d691a4e5fdd90795e4
eba3fe2e9bb103f1db971d35a3dd9dc4cd8c5255
refs/heads/master
2021-01-19T00:31:48.384386
2017-05-04T15:10:22
2017-05-04T15:10:22
76,870,978
0
0
null
null
null
null
UTF-8
C++
false
false
538
hpp
#ifndef __SERIALCONTROLLER_HPP__ #define __SERIALCONTROLLER_HPP__ #include "Task.hpp" #include "JarvisHW.hpp" #include "MessageService.hpp" #include <SoftwareSerial.h> #include "PinConfig.hpp" class SerialController : public Task { public: SerialController(JarvisHW* js); ~SerialController(); void init(int period); void tick(); private: int bt[2] = PIN_BT; SoftwareSerial* _bluetooth; MessageService* _btMsg; JarvisHW* _js; long _start; float _temp; enum InternalState {A_WAIT, BT_ADV} _internalState; }; #endif
[ "antoniotagliente@aol.com" ]
antoniotagliente@aol.com
b60d3203764edb1e0783a1d32860419726c350e9
0dde4e977c748fe1dfa5458d9bf790e38ae5b3be
/trunk/analysis/ClasTool/MapTools/TFloatBuffer.h
99c6dfcc362dd9705c9b3daae2af4b059c8a4ea7
[]
no_license
jasonbono/CLAS
e27a48f96b753e11a97803bbe4c782319c4f8534
c899062b8740cdb6ef04916d74f22cebc5d2c5f8
refs/heads/master
2020-05-24T03:56:12.542417
2019-05-16T17:50:31
2019-05-16T17:50:31
187,074,934
0
0
null
null
null
null
UTF-8
C++
false
false
702
h
#ifndef __TFLOATBUFFER__ #define __TFLOATBUFFER__ #include <iostream> #include <cstdlib> #include <unistd.h> #include <iomanip> using std::cout; using std::endl; // ROOT includes #include "TROOT.h" #include "TObject.h" #include "TString.h" class TFloatBuffer{ private: Float_t *lBuffer; Int_t lBuffLength; public: TFloatBuffer(); TFloatBuffer(int gLength); virtual ~TFloatBuffer(); void SetSize(int gSize); Int_t GetSize(); void AllocateBuffer(int gLength); void ResetBuffer(); int BoundCheck(int gPos); void Set(int gPos, float gValue); Float_t Get(int gPos); void Print(); ClassDef(TFloatBuffer,1) // Class for keeping Array of Floats (with bound check) }; #endif
[ "jason.s.bono@gmail.com" ]
jason.s.bono@gmail.com
65561c1c62f688f1c3cb74a90dca3e84e4a108b0
42cb7febe9698c1075f42c61eb8c8f40e082f7b9
/UIRenderingConcepts/UIGraphicsDemo/source/UiDemoApp.cpp
ee3438621190b62fb79b10c318875f99be42f281
[]
no_license
VulkanWorks/QtVulkanSceneGraphUiRenderingConcepts
fb60006e71a7c1c91a3e0238cfee66f83d19cf73
99dc0b744dcd13dd58172b5477d5a728450a1964
refs/heads/master
2020-07-03T22:53:30.406434
2019-07-27T05:52:34
2019-07-27T05:52:34
202,078,122
1
0
null
2019-08-13T06:21:58
2019-08-13T06:21:58
null
UTF-8
C++
false
false
12,925
cpp
#include "UIDemoApp.h" #include "UIDemo.h" #include "UiMetalPaintEngine.h" #include "Circle/Circle.h" #include "Rectangle/Rect.h" #include "../common/SceneGraph/Window.h" #include <QApplication> int main(int argc, char **argv) { QApplication qtApp(argc, argv); UIDemoApp* app = new UIDemoApp(); app->EnableDepthBuffer(true); app->EnableWindowResize(true); app->Initialize(); app->ShowWindow(); qtApp.exec(); delete app; return 0; } UIDemoApp::UIDemoApp() { VulkanHelper::GetInstanceLayerExtensionProperties(); } UIDemoApp::~UIDemoApp() { delete m_Scene; // delete m_ScenePainterEngine; } void UIDemoApp::Configure() { SetApplicationName("Metal performance test"); SetWindowDimension(1200 , 800); #ifdef _WIN32 // Add Validation Layers AddValidationLayer("VK_LAYER_LUNARG_standard_validation"); // Add Vulkan instance extensions AddInstanceExtension(VK_KHR_SURFACE_EXTENSION_NAME); AddInstanceExtension(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); AddInstanceExtension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); #ifdef _WIN64 #else #endif #elif __APPLE__ AddInstanceExtension("VK_KHR_surface"); AddInstanceExtension("VK_MVK_macos_surface"); #endif // // m_SceneVector.push_back(std::make_shared<Scene>(this)); // m_Scene = new Scene(this);//m_SceneVector[0].get(); // m_ScenePainterEngine = new Scene(this);//m_SceneVector[0].get(); // InitMetalEngine(); // //BoundingRegion bgDim(10, 10, 400, 50); // //Node* background = new Rectangl(p_Scene, this, bgDim); // //Node* m_Parent = new Rectangl(m_Scene, NULL, BoundingRegion(), "Node 1", (false ? SHAPE::SHAPE_RECTANGLE_MULTIDRAW : SHAPE::SHAPE_RECTANGLE_INSTANCED)); // m_Scene->SetEarlyDepthTest(true); // Node* m_Parent = new Rectangl(m_Scene, NULL, BoundingRegion(500, 300, 20, 20), "Node 1", SHAPE::SHAPE_RECTANGLE_INSTANCED); // m_Parent->SetColor(glm::vec4(1.0, 0.0, 1.0, 1.0)); // m_Parent->SetDefaultColor(glm::vec4(1.0, 0.0, 0.0, 1.0)); // m_Parent->SetMemPoolIdx(0); // m_Parent->SetZOrder(15); //// Node* m_Parent1 = new Rectangl(m_Scene, NULL, BoundingRegion(150, 150, 200, 200), "Node 2", SHAPE::SHAPE_RECTANGLE_MULTIDRAW); //// m_Parent1->SetColor(glm::vec4(0.0, 1.0, 0.0, 1.0)); //// m_Parent1->SetDefaultColor(glm::vec4(0.0, 1.0, 0.0, 1.0)); //// m_Parent1->SetMemPoolIdx(0); //// m_Parent1->SetZOrder(20); // //m_UIDemo.Grid(m_Scene, m_WindowDimension.x, m_WindowDimension.y); // Grid demo // //m_UIDemo.SliderFunc(m_Scene); // Slider // //m_UIDemo.MixerView(m_Scene, m_WindowDimension.x, m_WindowDimension.y); // Mixer View demo // m_UIDemo.TransformationConformTest(m_Scene); // Transformation test demo } void UIDemoApp::Setup() { m_Scene = new Scene(this); m_Scene->SetSceneRect(0, 0, m_Window->width(), m_Window->height()); m_ScenePainterEngine = new Scene(this); m_ScenePainterEngine->SetSceneRect(0, 0, m_Window->width(), m_Window->height()); InitMetalEngine(); //BoundingRegion bgDim(10, 10, 400, 50); //Node* background = new Rectangl(p_Scene, this, bgDim); //Node* m_Parent = new Rectangl(m_Scene, NULL, BoundingRegion(), "Node 1", (false ? SHAPE::SHAPE_RECTANGLE_MULTIDRAW : SHAPE::SHAPE_RECTANGLE_INSTANCED)); m_Scene->SetEarlyDepthTest(true); Node* m_Parent = new Rectangl(m_Scene, NULL, BoundingRegion(0, 0, 20, 20), "Node 1", SHAPE::SHAPE_RECTANGLE_INSTANCED); m_Parent->SetColor(glm::vec4(1.0, 0.0, 1.0, 1.0)); m_Parent->SetDefaultColor(glm::vec4(1.0, 0.0, 0.0, 1.0)); m_Parent->SetMemPoolIdx(0); m_Parent->SetZOrder(15); // Node* m_Parent1 = new Rectangl(m_Scene, NULL, BoundingRegion(150, 150, 200, 200), "Node 2", SHAPE::SHAPE_RECTANGLE_MULTIDRAW); // m_Parent1->SetColor(glm::vec4(0.0, 1.0, 0.0, 1.0)); // m_Parent1->SetDefaultColor(glm::vec4(0.0, 1.0, 0.0, 1.0)); // m_Parent1->SetMemPoolIdx(0); // m_Parent1->SetZOrder(20); //m_UIDemo.Grid(m_Scene, m_WindowDimension.x, m_WindowDimension.y); // Grid demo //m_UIDemo.SliderFunc(m_Scene); // Slider m_UIDemo.MixerView(m_Scene, m_WindowDimension.x, m_WindowDimension.y); // Mixer View demo //m_UIDemo.TransformationConformTest(m_Scene); // Transformation test demo m_Scene->Setup(); m_ScenePainterEngine->Setup(); RecordRenderPass(1, SG_STATE_SETUP); // Parminder: Double check if this is required // At least update the scene once so that in case UpdateMeAndMyChildren() is being used it has all transformation readily available m_Scene->Update(); m_ScenePainterEngine->Update(); } void UIDemoApp::Update() { m_Scene->Update(); m_ScenePainterEngine->Update(); } bool UIDemoApp::Render() { QRectF rect; m_MetalPaintEngine->drawRects(&rect, 1); RecordRenderPass(1, SG_STATE_RENDER); return VulkanApp::Render(); } void UIDemoApp::MousePressEvent(QMouseEvent* p_Event) { m_Scene->mousePressEvent(p_Event); } void UIDemoApp::MouseReleaseEvent(QMouseEvent* p_Event) { m_Scene->mouseReleaseEvent(p_Event); } void UIDemoApp::MouseMoveEvent(QMouseEvent* p_Event) { m_Scene->mouseMoveEvent(p_Event); } void UIDemoApp::ResizeWindow(int p_Width, int p_Height) { VulkanApp::ResizeWindow(p_Width, p_Height); RecordRenderPass(3, SG_STATE_RESIZE, p_Width, p_Height); } bool UIDemoApp::InitMetalEngine() { if (!m_MetalPaintEngine) { m_MetalPaintEngine.reset(new UiMetalPaintEngine()); return m_MetalPaintEngine->Init(m_ScenePainterEngine); } return true; } void UIDemoApp::RecordRenderPass(int p_Argcount, ...) { // va_list args; // va_start(args, b); // exampleV(b, args); // va_end(args); // va_list list; // va_start(list, p_Argcount); // m_Scene->RecordRenderPass(p_Argcount, list); // va_end(list); //return; va_list list; va_start(list, p_Argcount); SCENE_GRAPH_STATES currentState = SG_STATE_NONE; QSize resizedDimension; for (int i = 0; i < p_Argcount; ++i) { switch (i) { case 0: currentState = static_cast<SCENE_GRAPH_STATES>(va_arg(list, int)); break; case 1: resizedDimension.setWidth(va_arg(list, int)); break; case 2: resizedDimension.setHeight(va_arg(list, int)); break; default: { if (currentState == SG_STATE_NONE) { va_end(list); return; } break; } } } va_end(list); // Specify the clear color value VkClearValue clearColor[2]; clearColor[0].color.float32[0] = 0.0f; clearColor[0].color.float32[1] = 0.0f; clearColor[0].color.float32[2] = 0.0f; clearColor[0].color.float32[3] = 0.0f; // Specify the depth/stencil clear value clearColor[1].depthStencil.depth = 1.0f; clearColor[1].depthStencil.stencil = 0; // Offset to render in the frame buffer VkOffset2D renderOffset = { 0, 0 }; // Width & Height to render in the frame buffer VkExtent2D renderExtent = m_swapChainExtent; // For each command buffers in the command buffer list for (size_t i = 0; i < m_hCommandBufferList.size(); i++) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; // Indicate that the command buffer can be resubmitted to the queue beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; // Begin command buffer vkBeginCommandBuffer(m_hCommandBufferList[i], &beginInfo); VkRenderPassBeginInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = m_hRenderPass; renderPassInfo.framebuffer = m_hFramebuffers[i]; renderPassInfo.renderArea.offset = renderOffset; renderPassInfo.renderArea.extent = renderExtent; renderPassInfo.clearValueCount = 2; renderPassInfo.pClearValues = clearColor; // Begin render pass vkCmdBeginRenderPass(m_hCommandBufferList[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); switch (currentState) { case SG_STATE_SETUP: case SG_STATE_RENDER: m_Scene->Render(static_cast<void*>(m_hCommandBufferList[i])); m_ScenePainterEngine->Render(static_cast<void*>(m_hCommandBufferList[i])); break; case SG_STATE_RESIZE: m_Scene->Resize(resizedDimension.width(), resizedDimension.height()); m_ScenePainterEngine->Resize(resizedDimension.width(), resizedDimension.height()); break; default: break; } // End the Render pass vkCmdEndRenderPass(m_hCommandBufferList[i]); // End the Command buffer VkResult vkResult = vkEndCommandBuffer(m_hCommandBufferList[i]); if (vkResult != VK_SUCCESS) { VulkanHelper::LogError("vkEndCommandBuffer() failed!"); assert(false); } } } //void UIDemoApp::RecordRenderPass(int p_Argcount, ...) //{ // va_list list; // va_start(list, p_Argcount); // SCENE_GRAPH_STATES currentState = SG_STATE_NONE; // QSize resizedDimension; // for (int i = 0; i < p_Argcount; ++i) // { // switch (i) // { // case 0: // currentState = static_cast<SCENE_GRAPH_STATES>(va_arg(list, int)); // break; // case 1: // resizedDimension.setWidth(va_arg(list, int)); // break; // case 2: // resizedDimension.setHeight(va_arg(list, int)); // break; // default: // { // if (currentState == SG_STATE_NONE) // { // va_end(list); // return; // } // break; // } // } // } // va_end(list); // // Specify the clear color value // VkClearValue clearColor[2]; // clearColor[0].color.float32[0] = 0.0f; // clearColor[0].color.float32[1] = 0.0f; // clearColor[0].color.float32[2] = 0.0f; // clearColor[0].color.float32[3] = 0.0f; // // Specify the depth/stencil clear value // clearColor[1].depthStencil.depth = 1.0f; // clearColor[1].depthStencil.stencil = 0; // // Offset to render in the frame buffer // VkOffset2D renderOffset = { 0, 0 }; // // Width & Height to render in the frame buffer // VkExtent2D renderExtent = m_swapChainExtent; // // For each command buffers in the command buffer list // for (size_t i = 0; i < m_hCommandBufferList.size(); i++) // { // VkCommandBufferBeginInfo beginInfo = {}; // beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; // // Indicate that the command buffer can be resubmitted to the queue // beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; // // Begin command buffer // vkBeginCommandBuffer(m_hCommandBufferList[i], &beginInfo); // VkRenderPassBeginInfo renderPassInfo = {}; // renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; // renderPassInfo.renderPass = m_hRenderPass; // renderPassInfo.framebuffer = m_hFramebuffers[i]; // renderPassInfo.renderArea.offset = renderOffset; // renderPassInfo.renderArea.extent = renderExtent; // renderPassInfo.clearValueCount = 2; // renderPassInfo.pClearValues = clearColor; // // Begin render pass // vkCmdBeginRenderPass(m_hCommandBufferList[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); // switch (currentState) // { // case SG_STATE_SETUP: // case SG_STATE_RENDER: // m_Scene->Render(m_hCommandBufferList[i]); // m_ScenePainterEngine->Render(m_hCommandBufferList[i]); // break; // case SG_STATE_RESIZE: // m_Scene->Resize(m_hCommandBufferList[i], resizedDimension.width(), resizedDimension.height()); // m_ScenePainterEngine->Resize(m_hCommandBufferList[i], resizedDimension.width(), resizedDimension.height()); // break; // default: // break; // } // // End the Render pass // vkCmdEndRenderPass(m_hCommandBufferList[i]); // // End the Command buffer // VkResult vkResult = vkEndCommandBuffer(m_hCommandBufferList[i]); // if (vkResult != VK_SUCCESS) // { // VulkanHelper::LogError("vkEndCommandBuffer() failed!"); // assert(false); // } // } //}
[ "engineer.parminder@gmail.com" ]
engineer.parminder@gmail.com
5e47aecb530c8df13b47b4bf197cca0016f9a74e
3438e8c139a5833836a91140af412311aebf9e86
/third_party/WebKit/Source/core/workers/WorkletBackingThreadHolder.h
2f47c61734dda64b74139cabff3bdf08246560a3
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
Exstream-OpenSource/Chromium
345b4336b2fbc1d5609ac5a67dbf361812b84f54
718ca933938a85c6d5548c5fad97ea7ca1128751
refs/heads/master
2022-12-21T20:07:40.786370
2016-10-18T04:53:43
2016-10-18T04:53:43
71,210,435
0
2
BSD-3-Clause
2022-12-18T12:14:22
2016-10-18T04:58:13
null
UTF-8
C++
false
false
816
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WorkletBackingThreadHolder_h #define WorkletBackingThreadHolder_h #include "core/CoreExport.h" #include "wtf/PtrUtil.h" namespace blink { class WorkerBackingThread; class WaitableEvent; class CORE_EXPORT WorkletBackingThreadHolder { public: WorkerBackingThread* thread() { return m_thread.get(); } protected: explicit WorkletBackingThreadHolder(std::unique_ptr<WorkerBackingThread>); virtual void initializeOnThread() = 0; void shutdownAndWait(); void shutdownOnThread(WaitableEvent*); std::unique_ptr<WorkerBackingThread> m_thread; bool m_initialized; }; } // namespace blink #endif // WorkletBackingThreadHolder_h
[ "support@opentext.com" ]
support@opentext.com
b1c6ab4e38fe64bd221c5fc95d236d3617a29ffd
bd697660a48a179aab653ecbc21fdbf4a1c29c80
/BattleTank/Source/BattleTank/TankPlayerController.cpp
1a25fcd5d367289b3360f60af1c3c852718f486c
[]
no_license
celioreyes/UC_Section04_BattleTank
c4c9c99565358420bc1ad7106193a39afa7c9a81
e0640a04db374c597987916c3878384ed9f704cd
refs/heads/master
2020-04-14T19:28:00.377665
2019-02-17T20:59:50
2019-02-17T20:59:50
164,058,590
0
0
null
null
null
null
UTF-8
C++
false
false
231
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TankPlayerController.h" #include "BattleTank.h" ATank* ATankPlayerController::GetControlledTank() const { return Cast<ATank>(GetPawn()); }
[ "celioreyesrr@gmail.com" ]
celioreyesrr@gmail.com
4370de3bfcdc63995690dda85b8b4e74b1109305
8840469d03c5451f589c0e26b72193156c4ee56e
/examples/qntzr/qntzr.ino
a7657b285dfbff1c4c37f03719d2bfaef3567cea
[ "BSD-3-Clause" ]
permissive
saluber/du-ino
f175c8d3b6f8e7820cbf8410ef6c475e55187372
36163e917da9ace7a5b4b131b1fd6086cf7a672d
refs/heads/master
2020-03-26T16:26:47.892257
2018-08-16T22:10:54
2018-08-16T22:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,109
ino
/* * #### #### * #### #### * #### #### ## * #### #### #### * #### ############ ############ #### ########## #### #### * #### #### #### #### #### #### #### ######## * #### #### #### #### #### #### #### ######## * #### #### #### #### #### #### #### #### #### * #### #### #### #### #### #### #### #### #### * #### ############ ############ #### ########## #### #### * #### #### * ################################ #### * __ __ __ __ __ #### * | | | | [__) |_/ (__ |__| | | [__) #### * |/\| |__| | \ | \ .__) | | |__| | ## * * * DU-INO Quantizer Function * Aaron Mavrinac <aaron@logick.ca> */ #include <du-ino_function.h> #include <du-ino_widgets.h> #include <du-ino_scales.h> #include <avr/pgmspace.h> static const unsigned char icons[] PROGMEM = { 0x60, 0x78, 0x78, 0x78, 0x78, 0x78, 0x60, // trigger mode off 0x60, 0x63, 0x0f, 0x0f, 0x0f, 0x63, 0x60 // trigger mode on }; volatile bool triggered; void trig_isr(); void trigger_mode_scroll_callback(int delta); void key_scroll_callback(int delta); void scale_scroll_callback(int delta); void notes_click_callback(uint8_t selected); class DU_Quantizer_Function : public DUINO_Function { public: DU_Quantizer_Function() : DUINO_Function(0b00001100) { } virtual void setup() { // build widget hierarchy container_outer_ = new DUINO_WidgetContainer<2>(DUINO_Widget::DoubleClick); container_top_ = new DUINO_WidgetContainer<3>(DUINO_Widget::Click, 2); container_outer_->attach_child(container_top_, 0); widget_trigger_mode_ = new DUINO_DisplayWidget(76, 0, 9, 9, DUINO_Widget::Full); widget_trigger_mode_->attach_scroll_callback(trigger_mode_scroll_callback); container_top_->attach_child(widget_trigger_mode_, 0); widget_key_ = new DUINO_DisplayWidget(90, 0, 13, 9, DUINO_Widget::Full); widget_key_->attach_scroll_callback(key_scroll_callback); container_top_->attach_child(widget_key_, 1); widget_scale_ = new DUINO_DisplayWidget(108, 0, 19, 9, DUINO_Widget::Full); widget_scale_->attach_scroll_callback(scale_scroll_callback); container_top_->attach_child(widget_scale_, 2); container_notes_ = new DUINO_WidgetContainer<12>(DUINO_Widget::Scroll); container_outer_->attach_child(container_notes_, 1); widgets_notes_[0] = new DUINO_DisplayWidget(6, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[1] = new DUINO_DisplayWidget(15, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[2] = new DUINO_DisplayWidget(24, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[3] = new DUINO_DisplayWidget(33, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[4] = new DUINO_DisplayWidget(42, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[5] = new DUINO_DisplayWidget(60, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[6] = new DUINO_DisplayWidget(69, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[7] = new DUINO_DisplayWidget(78, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[8] = new DUINO_DisplayWidget(87, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[9] = new DUINO_DisplayWidget(96, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[10] = new DUINO_DisplayWidget(105, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[11] = new DUINO_DisplayWidget(114, 54, 7, 7, DUINO_Widget::DottedBox); for(uint8_t i = 0; i < 12; ++i) { container_notes_->attach_child(widgets_notes_[i], i); } container_notes_->attach_click_callback_array(notes_click_callback); trigger_mode = false; key = 0; scale_id = 0; scale = get_scale_by_id(scale_id); output_octave = 0; output_note = 0; current_displayed_note = 0; gt_attach_interrupt(GT3, trig_isr, FALLING); // draw top line Display.draw_du_logo_sm(0, 0, DUINO_SH1106::White); Display.draw_text(16, 0, "QNTZR", DUINO_SH1106::White); // draw kays draw_left_key(1, 11); // C draw_black_key(13, 11); // Db draw_center_key(19, 11); // D draw_black_key(31, 11); // Eb draw_right_key(37, 11); // E draw_left_key(55, 11); // F draw_black_key(67, 11); // Gb draw_center_key(73, 11); // G draw_black_key(85, 11); // Ab draw_center_key(91, 11); // A draw_black_key(103, 11); // Bb draw_right_key(109, 11); // B invert_note(current_displayed_note); widget_setup(container_outer_); Display.display_all(); display_trigger_mode(); display_key(); display_scale(); } virtual void loop() { if(!trigger_mode || triggered) { if(scale == 0) { cv_out(CO1, 0.0); output_octave = 0; output_note = 0; } else { // read input float input = cv_read(CI1); // find a lower bound int below_octave = (int)input - 1; uint8_t below_note = 0; while(!(scale & (1 << below_note))) { below_note++; } // find closest lower and upper values int above_octave = below_octave, octave = below_octave; uint8_t above_note = below_note, note = below_note; while(note_cv(above_octave, key, above_note) < input) { note++; if(note > 11) { note = 0; octave++; } if(scale & (1 << note)) { below_octave = above_octave; below_note = above_note; above_octave = octave; above_note = note; } } // output the nearer of the two values float below = note_cv(below_octave, key, below_note); float above = note_cv(above_octave, key, above_note); if(input - below < above - input) { cv_out(CO1, below); octave = below_octave; note = below_note; } else { cv_out(CO1, above); octave = above_octave; note = above_note; } // send trigger and update display note if note has changed if(octave != output_octave || note != output_note) { gt_out(GT1, true, true); output_octave = octave; output_note = note; } } // reset trigger triggered = false; } widget_loop(); // display current note if(output_note != current_displayed_note) { invert_note(current_displayed_note); invert_note(output_note); current_displayed_note = output_note; } } void widget_trigger_mode_scroll_callback(int delta) { trigger_mode = delta > 0; display_trigger_mode(); } void widget_key_scroll_callback(int delta) { key += delta; key %= 12; if(key < 0) { key += 12; } display_key(); triggered = true; } void widget_scale_scroll_callback(int delta) { scale_id += delta; if(scale_id < -1) { scale_id = -1; } else if(scale_id >= N_SCALES) { scale_id = N_SCALES - 1; } scale = get_scale_by_id(scale_id); display_scale(); triggered = true; } void widgets_notes_click_callback(uint8_t selected) { scale ^= (1 << selected); scale_id = get_id_from_scale(scale); display_scale(); triggered = true; } private: float note_cv(int octave, uint8_t key, uint8_t note) { return (float)octave + (float)key / 12.0 + (float)note / 12.0; } void draw_left_key(int16_t x, int16_t y) { Display.draw_vline(x, y, 52, DUINO_SH1106::White); Display.draw_hline(x + 1, y, 9, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 51, 15, DUINO_SH1106::White); Display.draw_vline(x + 10, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 11, y + 28, 5, DUINO_SH1106::White); Display.draw_vline(x + 16, y + 28, 24, DUINO_SH1106::White); } void draw_center_key(int16_t x, int16_t y) { Display.draw_vline(x, y + 28, 24, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 28, 5, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 51, 15, DUINO_SH1106::White); Display.draw_vline(x + 6, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 7, y, 3, DUINO_SH1106::White); Display.draw_vline(x + 10, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 11, y + 28, 5, DUINO_SH1106::White); Display.draw_vline(x + 16, y + 28, 24, DUINO_SH1106::White); } void draw_right_key(int16_t x, int16_t y) { Display.draw_vline(x, y + 28, 24, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 28, 5, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 51, 15, DUINO_SH1106::White); Display.draw_vline(x + 6, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 7, y, 9, DUINO_SH1106::White); Display.draw_vline(x + 16, y, 52, DUINO_SH1106::White); } void draw_black_key(int16_t x, int16_t y) { Display.draw_vline(x, y, 27, DUINO_SH1106::White); Display.draw_hline(x + 1, y, 9, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 26, 9, DUINO_SH1106::White); Display.draw_vline(x + 10, y, 27, DUINO_SH1106::White); } void display_trigger_mode() { Display.fill_rect(widget_trigger_mode_->x() + 1, widget_trigger_mode_->y() + 1, 7, 7, widget_trigger_mode_->inverted() ? DUINO_SH1106::White : DUINO_SH1106::Black); Display.draw_bitmap_7(widget_trigger_mode_->x() + 1, widget_trigger_mode_->y() + 1, icons, trigger_mode, widget_trigger_mode_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); widget_trigger_mode_->display(); } void display_key() { Display.fill_rect(widget_key_->x() + 1, widget_key_->y() + 1, 11, 7, widget_key_->inverted() ? DUINO_SH1106::White : DUINO_SH1106::Black); bool sharp = false; unsigned char letter; switch(key) { case 1: // C# sharp = true; case 0: // C letter = 'C'; break; case 3: // D# sharp = true; case 2: // D letter = 'D'; break; case 4: // E letter = 'E'; break; case 6: // F# sharp = true; case 5: // F letter = 'F'; break; case 8: // G# sharp = true; case 7: // G letter = 'G'; break; case 10: // A# sharp = true; case 9: // A letter = 'A'; break; case 11: // B letter = 'B'; break; } Display.draw_char(widget_key_->x() + 1, widget_key_->y() + 1, letter, widget_key_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); if(sharp) { Display.draw_char(widget_key_->x() + 7, widget_key_->y() + 1, '#', widget_key_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); } widget_key_->display(); } void display_scale() { Display.fill_rect(widget_scale_->x() + 1, widget_scale_->y() + 1, 17, 7, widget_scale_->inverted() ? DUINO_SH1106::White : DUINO_SH1106::Black); if(scale_id > -1) { for(uint8_t i = 0; i < 3; ++i) { Display.draw_char(widget_scale_->x() + 1 + i * 6, widget_scale_->y() + 1, pgm_read_byte(&scales[scale_id * 5 + 2 + i]), widget_scale_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); } } for(uint8_t note = 0; note < 12; ++note) { bool white = scale & (1 << note); if(note == current_displayed_note) { white = !white; } Display.fill_rect(widgets_notes_[note]->x() + 1, widgets_notes_[note]->y() + 1, 5, 5, white ? DUINO_SH1106::White : DUINO_SH1106::Black); } Display.display_all(); } void invert_note(uint8_t note) { bool refresh_lower = false; switch(note) { case 0: Display.fill_rect(2, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(11, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 1: Display.fill_rect(14, 12, 9, 25, DUINO_SH1106::Inverse); break; case 2: Display.fill_rect(26, 12, 3, 28, DUINO_SH1106::Inverse); Display.fill_rect(20, 40, 15, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 3: Display.fill_rect(32, 12, 9, 25, DUINO_SH1106::Inverse); break; case 4: Display.fill_rect(44, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(38, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 5: Display.fill_rect(56, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(65, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 6: Display.fill_rect(68, 12, 9, 25, DUINO_SH1106::Inverse); break; case 7: Display.fill_rect(80, 12, 3, 28, DUINO_SH1106::Inverse); Display.fill_rect(74, 40, 15, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 8: Display.fill_rect(86, 12, 9, 25, DUINO_SH1106::Inverse); break; case 9: Display.fill_rect(98, 12, 3, 28, DUINO_SH1106::Inverse); Display.fill_rect(92, 40, 15, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 10: Display.fill_rect(104, 12, 9, 25, DUINO_SH1106::Inverse); break; case 11: Display.fill_rect(116, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(110, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; } Display.display(2, 124, 1, refresh_lower ? 7 : 4); } DUINO_WidgetContainer<2> * container_outer_; DUINO_WidgetContainer<3> * container_top_; DUINO_WidgetContainer<12> * container_notes_; DUINO_DisplayWidget * widget_trigger_mode_; DUINO_DisplayWidget * widget_key_; DUINO_DisplayWidget * widget_scale_; DUINO_DisplayWidget * widgets_notes_[12]; bool trigger_mode; int8_t key; int scale_id; uint16_t scale; uint8_t output_note; int output_octave; uint8_t current_displayed_note; }; DU_Quantizer_Function * function; void trig_isr() { triggered = true; } void trigger_mode_scroll_callback(int delta) { function->widget_trigger_mode_scroll_callback(delta); } void key_scroll_callback(int delta) { function->widget_key_scroll_callback(delta); } void scale_scroll_callback(int delta) { function->widget_scale_scroll_callback(delta); } void notes_click_callback(uint8_t selected) { function->widgets_notes_click_callback(selected); } void setup() { function = new DU_Quantizer_Function(); triggered = false; function->begin(); } void loop() { function->loop(); }
[ "mavrinac@gmail.com" ]
mavrinac@gmail.com
f8a2f9878b920864f2f7959eca45175e2601c073
69b650b9d8a72975d0347941977be30e251624d4
/SouraEngine/Platform/Windows/WindowsWindow.h
3ac063e1f12c5b1e2059e5051e05f4af61873cd2
[]
no_license
mohammadkamal/SouraEngine
829b3ec535fc52775523f6c8145fa7389da56fb3
da207e63e66ce004ae44bb61cc896fc472917553
refs/heads/master
2023-06-04T14:04:43.730150
2021-06-29T12:48:31
2021-06-29T12:48:31
271,069,273
1
0
null
null
null
null
UTF-8
C++
false
false
828
h
#pragma once #include "Core/Window.h" #include <memory> #include <glad/glad.h> #include <GLFW/glfw3.h> namespace SouraEngine { class WindowsWindow :public Window { public: WindowsWindow(const WindowProperties& props); virtual ~WindowsWindow(); virtual void OnUpdate() override; virtual uint32_t GetWidth() const override { return m_Data.Width; } virtual uint32_t GetHeight() const override { return m_Data.Height; } //Event Callback Method //VSync virtual void* GetNativeWindow() const { return m_Window; } private: virtual void Init(const WindowProperties& props); virtual void Shutdown(); GLFWwindow* m_Window; std::unique_ptr<GraphicsContext> m_Context; struct WindowData { std::string Title; uint32_t Width, Height; //VSync //Event Callback }; WindowData m_Data; }; }
[ "mohammadkamalshady@gmail.com" ]
mohammadkamalshady@gmail.com
befbc79acc3a9c1f491c77672618342456efeebe
a714d23380e2f75a100c3c98b71e9a878a7c9465
/comp_prog/ioi_archive/2011/ricehub/grader.cpp
00f754fdf17f0f0441dc12f1f0a5f901d456a21d
[]
no_license
harta01/kaizen
61ba6f5b461d2124d6366561c78d535756a1da75
235662e12497ee1eb58bf4f2e37c99746de1f415
refs/heads/master
2020-04-12T22:38:25.934735
2016-10-03T03:04:43
2016-10-03T03:04:43
68,275,745
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
#include "grader.h" #include <stdio.h> #include <stdlib.h> #define MAX_R 1000000 static int R, L; static long long B; static int X[MAX_R]; static int solution; inline void my_assert(int e) {if (!e) abort();} static void read_input() { int i; my_assert(3==scanf("%d %d %lld",&R,&L,&B)); for(i=0; i<R; i++) my_assert(1==scanf("%d",&X[i])); my_assert(1==scanf("%d",&solution)); } int main() { int ans; read_input(); ans = besthub(R,L,X,B); if(ans==solution) printf("Correct.\n"); else printf("Incorrect. Returned %d instead of %d.\n",ans,solution); return 0; }
[ "wijayaha@garena.com" ]
wijayaha@garena.com
c9720145685fd4b975aa66f0483e660dc5a01bb5
67354b590965aef0cfccaf524951e8d799c5dbbf
/gui/ImageStackView.h
f01c35e2bdabbc8c25fecd4c0e79d9204cc191c1
[]
no_license
unidesigner/imageprocessing
31643dcc46ed82f57c1398dc25c74a384dfa35a1
2878a56fff5d59930fe73a8f99200b1ea8fc0607
refs/heads/master
2021-01-15T21:48:56.122674
2013-02-27T11:26:42
2013-02-27T11:26:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
869
h
#ifndef IMAGEPROCESSING_GUI_IMAGE_STACK_VIEW_H__ #define IMAGEPROCESSING_GUI_IMAGE_STACK_VIEW_H__ #include <pipeline/all.h> #include <imageprocessing/ImageStack.h> #include <gui/Keys.h> #include <gui/Signals.h> #include "ImageStackPainter.h" class ImageStackView : public pipeline::SimpleProcessNode<> { public: ImageStackView(unsigned int numImages = 1); private: void updateOutputs(); void onKeyDown(gui::KeyDown& signal); pipeline::Input<ImageStack> _stack; pipeline::Output<ImageStackPainter> _painter; pipeline::Output<Image> _currentImage; signals::Slot<gui::SizeChanged> _sizeChanged; signals::Slot<gui::ContentChanged> _contentChanged; // the section to show int _section; // copy of the currently visible image vigra::MultiArray<2, float> _currentImageData; }; #endif // IMAGEPROCESSING_GUI_IMAGE_STACK_VIEW_H__
[ "funke@ini.ch" ]
funke@ini.ch
56df4e03d1a5923c15de1988c8431d446c6468ff
5bbeacb6613fdaa184a5bda4bdb54b16dc8654e1
/zMuSource/GameServer/MonsterBag.cpp
09f253ca68ce783ea490345dc4864c6cdf122ae9
[]
no_license
yiyilookduy/IGCN-SS12
0e4b6c655c2f15e561ad150e1dd0f047a72ef23b
6a3f8592f4fa9260e56c1d5fee7a62277dc3691d
refs/heads/master
2020-04-04T09:03:13.134134
2018-11-02T03:02:29
2018-11-02T03:02:29
155,804,847
0
4
null
null
null
null
UTF-8
C++
false
false
3,415
cpp
//////////////////////////////////////////////////////////////////////////////// // MonsterBag.cpp #include "stdafx.h" #include "MonsterBag.h" #include "TLog.h" #include "user.h" #include "LuaBag.h" #include "MapClass.h" #include "GameMain.h" CMonsterBag::CMonsterBag() { } CMonsterBag::~CMonsterBag() { } void CMonsterBag::SetBagInfo(int iParam1, int MonsterClass) { this->m_BagMonsterClass = MonsterClass; } bool CMonsterBag::CheckCondition(int aIndex, int MonsterClass, int iParam2) { if (rand() % 10000 >= this->m_BagData.dwBagUseRate) { return false; } if (this->m_BagMonsterClass == MonsterClass) { return true; } return false; } bool CMonsterBag::IsBag(int aIndex, int MonsterClass, int iParam2) { if (this->m_BagMonsterClass == MonsterClass) { return true; } return false; } bool CMonsterBag::UseBag(int aIndex, int iMonsterIndex) { if (gObj[aIndex].Type != OBJ_USER) { return false; } LPOBJ lpObj = &gObj[aIndex]; LPOBJ lpMonsterObj = &gObj[iMonsterIndex]; if (rand() % 10000 >= this->m_BagData.dwItemDropRate) { MapC[gObj[aIndex].MapNumber].MoneyItemDrop(this->m_BagData.dwDropMoney, lpObj->X, lpObj->Y); return true; } if (rand() % 10000 < this->m_BagData.dwGainRuudRate) { int iRuudValue = this->GetValueMinMax(this->m_BagData.dwMinGainRuud, this->m_BagData.dwMaxGainRuud); lpObj->m_PlayerData->Ruud += iRuudValue; GSProtocol.GCSendRuud(aIndex, lpObj->m_PlayerData->Ruud, iRuudValue, true); return true; } BAG_ITEM m_Item; BAG_SECTION_ITEMS m_ItemSection; BAG_SECTION_DROP m_DropSection; int iResult = this->GetDropSection(aIndex, m_DropSection); if (iResult == FALSE) { return false; } iResult = this->GetItemsSection(m_DropSection, m_ItemSection); if (iResult == FALSE) { return false; } if (m_ItemSection.btItemDropCount <= 0) { return false; } if (m_ItemSection.btItemDropCount == 1) { if (rand()%10000 < this->m_BagData.dwRandomSetItemDropRate) { MakeRewardSetItem(aIndex, lpMonsterObj->X, lpMonsterObj->Y, 1, lpObj->MapNumber); return true; } if (this->GetItem(m_ItemSection, m_Item) == FALSE) { return false; } bool bResult = gLuaBag.DropCommonBag(aIndex, lpMonsterObj->MapNumber, lpMonsterObj->X, lpMonsterObj->Y, &m_Item); if (bResult == false) { return false; } return true; } for (int i = 0; i < m_ItemSection.btItemDropCount; i++) { BYTE cDropX = lpMonsterObj->X; BYTE cDropY = lpMonsterObj->Y; if (!gObjGetRandomItemDropLocation(lpMonsterObj->MapNumber, cDropX, cDropY, 4, 4, 10)) { cDropX = lpMonsterObj->X; cDropY = lpMonsterObj->Y; } if (rand()%10000 < this->m_BagData.dwRandomSetItemDropRate) { MakeRewardSetItem(aIndex, cDropX, cDropY, 1, lpObj->MapNumber); continue; } if (this->GetItem(m_ItemSection, m_Item) == FALSE) { return false; } bool bResult = gLuaBag.DropMonsterBag(aIndex, iMonsterIndex, lpMonsterObj->MapNumber, cDropX, cDropY, &m_Item); if (bResult == false) { return false; } } return true; } bool CMonsterBag::UseBag_GremoryCase(int aIndex, int iMonsterIndex, BYTE btStorageType, BYTE btRewardSource, int iExpireDays) { return false; } //////////////////////////////////////////////////////////////////////////////// // vnDev.Games - MuServer S12EP2 IGC v12.0.1.0 - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "duypnse63523@fpt.edu.vn" ]
duypnse63523@fpt.edu.vn
2c9cbb5833abc8bc50a4fbe00343aa7d35ac0a5c
be332b45dc5875246336b3f340f5ccbaa4f299f8
/Conch/source/common/imageLib/JCGifImg.h
adb8cbf4e0af9e60e9788a22322dadc381a24537
[]
no_license
chen1234219/LayaNative2.0
cd1c7cb9f8f8236721a1b0fcfd733565b1d80053
2a210f0a4b988fc3efc824d88cea1ccc54cd0e17
refs/heads/main
2023-08-13T17:44:19.282053
2021-10-11T07:03:50
2021-10-11T07:03:50
null
0
0
null
null
null
null
GB18030
C++
false
false
8,989
h
/** @file JCGifImg.h @brief @author James @version 1.0 @date 2016_7_13 */ #ifndef __JCGifImg_H__ #define __JCGifImg_H__ #include <fstream> #include <iostream> using namespace std; namespace laya { /* * 图像扩展参数 */ typedef struct { bool active; //本结构中的其它参数是否可用 unsigned int disposalMethod; //处理方法(见gif89a.doc,可忽略) bool userInputFlag; //是否期待用户输入 bool trsFlag; //是否有透明色 unsigned short delayTime; //延时时间(单位1/100秒) unsigned int trsColorIndex; //透明色调色板索引 }GCTRLEXT; /* * 一帧图象的参数 */ typedef struct { unsigned short imageLPos; //图象左边沿到逻辑屏幕的距离(单位像素) unsigned short imageTPos; //图象上边沿到逻辑屏幕的距离(单位像素) unsigned short imageWidth; //图象的宽度(单位像素) unsigned short imageHeight; //图象的高度(单位像素) bool lFlag; //是否有局部调色板(决定其他调色板参数是否有效) bool interlaceFlag; //图象数据是否交错 bool sortFlag; //局部调色板数据是否按优先排序 unsigned int lSize; //局部调色板大小(有多少个实际入口) unsigned char* pColorTable; //指向局部调色板的指针(256个入口,每个入口三字节) unsigned char* dataBuf; //调色板格式请参看gif89a.doc GCTRLEXT ctrlExt; //图象数据指针 }FRAME; //图象扩展参数(与透明背景和动画有关) typedef FRAME *LPFRAME; typedef const FRAME *LPCFRAME; /* * GIF文件的全局参数 */ typedef struct { //GIF文件的全局参数 unsigned int frames; //文件中图象帧数 unsigned short scrWidth, scrHeight; //逻辑屏幕的宽度和高度(单位像素) bool gFlag; //是否有全局调色板(决定其他调色板参数是否有效) unsigned int colorRes; //色彩分辨率(不使用) bool gSort; //全局调色板是否按优先排序 unsigned int gSize; //全局调色板大小(有多少个实际入口) unsigned int BKColorIdx; //背景色的调色板索引 unsigned int pixelAspectRatio; //像素长宽比例 unsigned char *gColorTable; //指向全局调色板的指针(256个入口,每个入口三字节) }GLOBAL_INFO; //调色板格式请参看gif89a.doc typedef GLOBAL_INFO *LPGLOBAL_INFO; typedef const GLOBAL_INFO *LPCGLOBAL_INFO; /* * */ typedef struct { unsigned int len; unsigned char* p; }STRING_TABLE_ENTRY; class BufferIOStream { public: BufferIOStream(char* p_sBuffer, int p_nBufferSize) { m_pBuffer = p_sBuffer; m_nSize = p_nBufferSize; m_nCurPos = 0; } ~BufferIOStream() { close(); } bool read(char* p_pRet, int p_nSize) { if ((m_nCurPos + p_nSize) > m_nSize) { return false; } char* pCur = m_pBuffer + m_nCurPos; memcpy(p_pRet, pCur, p_nSize); m_nCurPos += p_nSize; return true; } bool good() { return true; } int tellg() { return m_nCurPos; } void close() { /*直接拿的指针应该在外面释放 if( m_pBuffer != NULL ) { delete[] m_pBuffer; m_pBuffer = NULL; } */ m_nSize = 0; m_nCurPos = 0; } bool eof() { return (m_nCurPos >= m_nSize); } void seekg(int p_nPos) { m_nCurPos = p_nPos; } void seekg(int p_nPos, int p_nMark) { if (p_nMark == 0) { m_nCurPos = 0 + p_nPos; } else if (p_nMark == 1) { m_nCurPos += p_nPos; } else if (p_nMark == 2) { m_nCurPos = m_nSize + p_nPos; } } protected: char* m_pBuffer; int m_nSize; int m_nCurPos; }; /** * Gif类 */ class GifLoader { public: /** @brief * 构造函数 */ GifLoader(void); /** @brief 构造函数 * @param[in] 文件名字 * @param[in] 是否一次性读取完成 * @return */ GifLoader(const char* p_sFileName, bool p_bInMem); GifLoader(unsigned char* p_pBuffer, int p_nBufferSize); /** @brief * 析构函数 */ ~GifLoader(void); /** @brief * 重载错误符号 */ bool operator!(void); /** @brief 打开图片 * @param[in] 图片路径 * @param[in] 是否一次性读取完成 * @return */ bool open(const char* p_sFileName, bool p_bInMem); /** @brief 关闭 * */ void close(void); /** @brief 获得版本 * */ char* getVersion(void); /** @brief 获得下一帧 * */ LPCFRAME getNextFrame(void); /** @brief 获得图片的全局信息 * */ LPCGLOBAL_INFO getGlobalInfo(); /* * */ public: //从内存读取的方法 现在代码比较恶心,回头把ifstream 和 bufferIOStream 封装成一个类 bool open(void); unsigned int checkFrames(BufferIOStream& p_kStrteam); bool getAllFrames(BufferIOStream& p_kIOStream); bool extractData(FRAME* p_pFrame, BufferIOStream& p_kStrteam); private: /* 功能 :检查文件中图象帧数。 参数 :ifs:对文件流的引用。 返回值:文件中图象帧数。 */ unsigned int checkFrames(ifstream& p_kStrteam); /* 功能 :将所有图象帧数据读入内存。 参数 :ifs:对文件流的引用。 返回值:操作是否成功,为真成功,为假失败。 */ bool getAllFrames(ifstream& p_kStrteam); /* 功能 :解压缩一帧图象数据。 参数 :f:指向用于保存图象数据的结构。 ifs:对文件流的引用。 返回值:操作是否成功,为真成功,为假失败。 */ bool extractData(FRAME* p_pFrame, ifstream& p_kStrteam); /* 功能 :初始化字符串表。 参数 :strTable:指向字符串表的指针。 rootSize:初始化的入口数。 返回值:操作是否成功,为真成功,为假失败。 */ bool initStrTable(STRING_TABLE_ENTRY* p_pSTable, unsigned int p_nRootSize); /* 功能 :在字符串表中增加一项。 参数 :strTable:指向字符串表的指针。 addIdx:增加的入口索引。 idx:用于构造要增加的字符串的入口索引。 c:用于构造要增加的字符串的字符。 返回值:操作是否成功,为真成功,为假失败。 */ bool addStrTable(STRING_TABLE_ENTRY* p_pSTable, unsigned int p_nAddInedx, unsigned int p_nIndex, unsigned char p_cBuf); public: FRAME* m_vAllFrames; //指向所有图象帧的指针(inMem为真时用) private: GLOBAL_INFO m_kGInfo; //GIF文件的全局参数 FRAME m_kCurFrame; //当前帧的参数(inMem为假时用) GCTRLEXT m_kCtrlExt; //图象扩展参数(读入数据时临时使用) private: BufferIOStream* m_pBufferIOStream; //用于读取内存的 ifstream m_kIOStream; //用于读文件的文件流 char m_sVersion[4]; //版本字符串 bool m_bError; //类实例变量创建时是否出错的标志 bool m_bOpened; //是否处于打开状态 bool m_bInMem; //图象数据是否一次读入内存 unsigned char m_vGColorTable[256 * 3]; //全局调色板 unsigned char m_vLColorTable[256 * 3]; //局部调色板(inMem为假时用) streampos m_kDataStart; //保存文件流中图象数据开始的地方 unsigned int m_nCurIndex; //当前帧的索引(inMem为真时用) }; } //------------------------------------------------------------------------------ #endif //__JCGifImg_H__ //-----------------------------END FILE--------------------------------
[ "775331175@qq.com" ]
775331175@qq.com
f50c7aecf63e55745f352c46306b0a19098e4874
fe91ffa11707887e4cdddde8f386a8c8e724aa58
/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.cc
945fdcb6ee22706a15da7a82f4ddc77f5ee525c8
[ "BSD-3-Clause" ]
permissive
akshaymarch7/chromium
78baac2b45526031846ccbaeca96c639d1d60ace
d273c844a313b1e527dec0d59ce70c95fd2bd458
refs/heads/master
2023-02-26T23:48:03.686055
2020-04-15T01:20:07
2020-04-15T01:20:07
255,778,651
2
1
BSD-3-Clause
2020-04-15T02:04:56
2020-04-15T02:04:55
null
UTF-8
C++
false
false
22,393
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include <limits> #include <set> #include "base/bind_helpers.h" #include "base/debug/leak_annotations.h" #include "base/hash/hash.h" #include "base/memory/ptr_util.h" #include "base/no_destructor.h" #include "base/process/process.h" #include "base/process/process_handle.h" #include "base/profiler/sampling_profiler_thread_token.h" #include "base/profiler/stack_sampling_profiler.h" #include "base/strings/strcat.h" #include "base/task/thread_pool/thread_pool_instance.h" #include "base/threading/sequence_local_storage_slot.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "services/tracing/public/cpp/perfetto/perfetto_traced_process.h" #include "services/tracing/public/cpp/perfetto/producer_client.h" #include "third_party/perfetto/protos/perfetto/trace/interned_data/interned_data.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/profiling/profile_common.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/profiling/profile_packet.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/track_event/process_descriptor.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/track_event/thread_descriptor.pbzero.h" #if defined(OS_ANDROID) #include "base/android/reached_code_profiler.h" #endif #if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && \ defined(OFFICIAL_BUILD) #include <dlfcn.h> #include "base/trace_event/cfi_backtrace_android.h" #include "services/tracing/public/cpp/stack_sampling/stack_sampler_android.h" #endif using StreamingProfilePacketHandle = protozero::MessageHandle<perfetto::protos::pbzero::StreamingProfilePacket>; namespace tracing { namespace { class TracingSamplerProfilerDataSource : public PerfettoTracedProcess::DataSourceBase { public: static TracingSamplerProfilerDataSource* Get() { static base::NoDestructor<TracingSamplerProfilerDataSource> instance; return instance.get(); } TracingSamplerProfilerDataSource() : DataSourceBase(mojom::kSamplerProfilerSourceName) {} ~TracingSamplerProfilerDataSource() override { NOTREACHED(); } void RegisterProfiler(TracingSamplerProfiler* profiler) { base::AutoLock lock(lock_); if (!profilers_.insert(profiler).second) { return; } if (is_started_) { profiler->StartTracing( producer_->CreateTraceWriter(data_source_config_.target_buffer()), data_source_config_.chrome_config().privacy_filtering_enabled()); } else if (is_startup_tracing_) { profiler->StartTracing(nullptr, /*should_enable_filtering=*/true); } } void UnregisterProfiler(TracingSamplerProfiler* profiler) { base::AutoLock lock(lock_); if (!profilers_.erase(profiler) || !(is_started_ || is_startup_tracing_)) { return; } profiler->StopTracing(); } // PerfettoTracedProcess::DataSourceBase implementation, called by // ProducerClient. void StartTracing( PerfettoProducer* producer, const perfetto::DataSourceConfig& data_source_config) override { base::AutoLock lock(lock_); DCHECK(!is_started_); is_started_ = true; is_startup_tracing_ = false; data_source_config_ = data_source_config; bool should_enable_filtering = data_source_config.chrome_config().privacy_filtering_enabled(); for (auto* profiler : profilers_) { profiler->StartTracing( producer->CreateTraceWriter(data_source_config.target_buffer()), should_enable_filtering); } } void StopTracing(base::OnceClosure stop_complete_callback) override { base::AutoLock lock(lock_); DCHECK(is_started_); is_started_ = false; is_startup_tracing_ = false; producer_ = nullptr; for (auto* profiler : profilers_) { profiler->StopTracing(); } std::move(stop_complete_callback).Run(); } void Flush(base::RepeatingClosure flush_complete_callback) override { flush_complete_callback.Run(); } void SetupStartupTracing(PerfettoProducer* producer, const base::trace_event::TraceConfig& trace_config, bool privacy_filtering_enabled) override { bool enable_sampler_profiler = trace_config.IsCategoryGroupEnabled( TRACE_DISABLED_BY_DEFAULT("cpu_profiler")); if (!enable_sampler_profiler) return; base::AutoLock lock(lock_); if (is_started_) { return; } is_startup_tracing_ = true; for (auto* profiler : profilers_) { // Enable filtering for startup tracing always to be safe. profiler->StartTracing(nullptr, /*should_enable_filtering=*/true); } } void AbortStartupTracing() override { base::AutoLock lock(lock_); if (!is_startup_tracing_) { return; } for (auto* profiler : profilers_) { // Enable filtering for startup tracing always to be safe. profiler->StartTracing(nullptr, /*should_enable_filtering=*/true); } is_startup_tracing_ = false; } void ClearIncrementalState() override { incremental_state_reset_id_.fetch_add(1u, std::memory_order_relaxed); } static uint32_t GetIncrementalStateResetID() { return incremental_state_reset_id_.load(std::memory_order_relaxed); } private: base::Lock lock_; // Protects subsequent members. std::set<TracingSamplerProfiler*> profilers_; bool is_startup_tracing_ = false; bool is_started_ = false; perfetto::DataSourceConfig data_source_config_; static std::atomic<uint32_t> incremental_state_reset_id_; }; // static std::atomic<uint32_t> TracingSamplerProfilerDataSource::incremental_state_reset_id_{0}; base::SequenceLocalStorageSlot<TracingSamplerProfiler>& GetSequenceLocalStorageProfilerSlot() { static base::NoDestructor< base::SequenceLocalStorageSlot<TracingSamplerProfiler>> storage; return *storage; } } // namespace TracingSamplerProfiler::TracingProfileBuilder::BufferedSample::BufferedSample( base::TimeTicks ts, std::vector<base::Frame>&& s) : timestamp(ts), sample(std::move(s)) {} TracingSamplerProfiler::TracingProfileBuilder::BufferedSample:: ~BufferedSample() = default; TracingSamplerProfiler::TracingProfileBuilder::BufferedSample::BufferedSample( TracingSamplerProfiler::TracingProfileBuilder::BufferedSample&& other) : BufferedSample(other.timestamp, std::move(other.sample)) {} TracingSamplerProfiler::TracingProfileBuilder::TracingProfileBuilder( base::PlatformThreadId sampled_thread_id, std::unique_ptr<perfetto::TraceWriter> trace_writer, bool should_enable_filtering, const base::RepeatingClosure& sample_callback_for_testing) : sampled_thread_id_(sampled_thread_id), trace_writer_(std::move(trace_writer)), should_enable_filtering_(should_enable_filtering), sample_callback_for_testing_(sample_callback_for_testing) {} TracingSamplerProfiler::TracingProfileBuilder::~TracingProfileBuilder() { // Deleting a TraceWriter can end up triggering a Mojo call which calls // TaskRunnerHandle::Get() and isn't safe on thread shutdown, which is when // TracingProfileBuilder gets destructed, so we make sure this happens on // a different sequence. if (base::ThreadPoolInstance::Get()) { PerfettoTracedProcess::GetTaskRunner()->GetOrCreateTaskRunner()->DeleteSoon( FROM_HERE, std::move(trace_writer_)); } else { // Intentionally leak; we have no way of safely destroying this at this // point. ANNOTATE_LEAKING_OBJECT_PTR(trace_writer_.get()); trace_writer_.release(); } } base::ModuleCache* TracingSamplerProfiler::TracingProfileBuilder::GetModuleCache() { return &module_cache_; } void TracingSamplerProfiler::TracingProfileBuilder::OnSampleCompleted( std::vector<base::Frame> frames, base::TimeTicks sample_timestamp) { base::AutoLock l(trace_writer_lock_); if (!trace_writer_) { if (buffered_samples_.size() < kMaxBufferedSamples) { buffered_samples_.emplace_back( BufferedSample(sample_timestamp, std::move(frames))); } return; } if (!buffered_samples_.empty()) { for (const auto& sample : buffered_samples_) { WriteSampleToTrace(sample); } buffered_samples_.clear(); } WriteSampleToTrace(BufferedSample(sample_timestamp, std::move(frames))); if (sample_callback_for_testing_) { sample_callback_for_testing_.Run(); } } void TracingSamplerProfiler::TracingProfileBuilder::WriteSampleToTrace( const TracingSamplerProfiler::TracingProfileBuilder::BufferedSample& sample) { const auto& frames = sample.sample; auto reset_id = TracingSamplerProfilerDataSource::GetIncrementalStateResetID(); if (reset_id != last_incremental_state_reset_id_) { reset_incremental_state_ = true; last_incremental_state_reset_id_ = reset_id; } if (reset_incremental_state_) { interned_callstacks_.ResetEmittedState(); interned_frames_.ResetEmittedState(); interned_frame_names_.ResetEmittedState(); interned_module_names_.ResetEmittedState(); interned_module_ids_.ResetEmittedState(); interned_modules_.ResetEmittedState(); auto trace_packet = trace_writer_->NewTracePacket(); trace_packet->set_sequence_flags( perfetto::protos::pbzero::TracePacket::SEQ_INCREMENTAL_STATE_CLEARED); // Note: Make sure ThreadDescriptors we emit here won't cause // metadata events to be emitted from the JSON exporter which conflict // with the metadata events emitted by the regular TrackEventDataSource. auto* thread_descriptor = trace_packet->set_thread_descriptor(); thread_descriptor->set_pid(base::GetCurrentProcId()); thread_descriptor->set_tid(sampled_thread_id_); last_timestamp_ = sample.timestamp; thread_descriptor->set_reference_timestamp_us( last_timestamp_.since_origin().InMicroseconds()); reset_incremental_state_ = false; } int32_t current_process_priority = base::Process::Current().GetPriority(); if (current_process_priority != last_emitted_process_priority_) { last_emitted_process_priority_ = current_process_priority; auto trace_packet = trace_writer_->NewTracePacket(); auto* process_descriptor = trace_packet->set_process_descriptor(); process_descriptor->set_pid(base::GetCurrentProcId()); process_descriptor->set_process_priority(current_process_priority); } auto trace_packet = trace_writer_->NewTracePacket(); // Delta encoded timestamps and interned data require incremental state. trace_packet->set_sequence_flags( perfetto::protos::pbzero::TracePacket::SEQ_NEEDS_INCREMENTAL_STATE); auto callstack_id = GetCallstackIDAndMaybeEmit(frames, &trace_packet); auto* streaming_profile_packet = trace_packet->set_streaming_profile_packet(); streaming_profile_packet->add_callstack_iid(callstack_id); streaming_profile_packet->add_timestamp_delta_us( (sample.timestamp - last_timestamp_).InMicroseconds()); last_timestamp_ = sample.timestamp; } void TracingSamplerProfiler::TracingProfileBuilder::SetTraceWriter( std::unique_ptr<perfetto::TraceWriter> writer) { base::AutoLock l(trace_writer_lock_); trace_writer_ = std::move(writer); } InterningID TracingSamplerProfiler::TracingProfileBuilder::GetCallstackIDAndMaybeEmit( const std::vector<base::Frame>& frames, perfetto::TraceWriter::TracePacketHandle* trace_packet) { size_t ip_hash = 0; for (const auto& frame : frames) { ip_hash = base::HashInts(ip_hash, frame.instruction_pointer); } InterningIndexEntry interned_callstack = interned_callstacks_.LookupOrAdd(ip_hash); if (interned_callstack.was_emitted) return interned_callstack.id; auto* interned_data = (*trace_packet)->set_interned_data(); std::vector<InterningID> frame_ids; for (const auto& frame : frames) { std::string frame_name; std::string module_name; std::string module_id; uintptr_t rel_pc = 0; #if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && \ defined(OFFICIAL_BUILD) Dl_info info = {}; // For chrome address we do not have symbols on the binary. So, just write // the offset address. For addresses on framework libraries, symbolize // and write the function name. if (frame.instruction_pointer == 0) { frame_name = "Scanned"; } else if (base::trace_event::CFIBacktraceAndroid::is_chrome_address( frame.instruction_pointer)) { rel_pc = frame.instruction_pointer - base::trace_event::CFIBacktraceAndroid::executable_start_addr(); } else if (dladdr(reinterpret_cast<void*>(frame.instruction_pointer), &info) != 0) { // TODO(ssid): Add offset and module debug id if symbol was not resolved // in case this might be useful to send report to vendors. if (info.dli_sname) frame_name = info.dli_sname; if (info.dli_fname) module_name = info.dli_fname; } if (frame.module) { module_id = frame.module->GetId(); if (module_name.empty()) module_name = frame.module->GetDebugBasename().MaybeAsASCII(); } // If no module is available, then name it unknown. Adding PC would be // useless anyway. if (module_name.empty()) { DCHECK(!base::trace_event::CFIBacktraceAndroid::is_chrome_address( frame.instruction_pointer)); frame_name = "Unknown"; rel_pc = 0; } #else if (frame.module) { module_name = frame.module->GetDebugBasename().MaybeAsASCII(); module_id = frame.module->GetId(); rel_pc = frame.instruction_pointer - frame.module->GetBaseAddress(); } else { module_name = module_id = ""; frame_name = "Unknown"; } #endif MangleModuleIDIfNeeded(&module_id); // We never emit frame names in privacy filtered mode. bool should_emit_frame_names = !frame_name.empty() && !should_enable_filtering_; if (should_enable_filtering_ && !rel_pc && frame.module) { rel_pc = frame.instruction_pointer - frame.module->GetBaseAddress(); } InterningIndexEntry interned_frame; if (should_emit_frame_names) { interned_frame = interned_frames_.LookupOrAdd(std::make_pair(frame_name, module_id)); } else { interned_frame = interned_frames_.LookupOrAdd(std::make_pair(rel_pc, module_id)); } if (!interned_frame.was_emitted) { InterningIndexEntry interned_frame_name; if (should_emit_frame_names) { interned_frame_name = interned_frame_names_.LookupOrAdd(frame_name); if (!interned_frame_name.was_emitted) { auto* frame_name_entry = interned_data->add_function_names(); frame_name_entry->set_iid(interned_frame_name.id); frame_name_entry->set_str( reinterpret_cast<const uint8_t*>(frame_name.data()), frame_name.length()); } } InterningIndexEntry interned_module; if (frame.module) { interned_module = interned_modules_.LookupOrAdd(frame.module->GetBaseAddress()); if (!interned_module.was_emitted) { InterningIndexEntry interned_module_id = interned_module_ids_.LookupOrAdd(module_id); if (!interned_module_id.was_emitted) { auto* module_id_entry = interned_data->add_build_ids(); module_id_entry->set_iid(interned_module_id.id); module_id_entry->set_str( reinterpret_cast<const uint8_t*>(module_id.data()), module_id.length()); } InterningIndexEntry interned_module_name = interned_module_names_.LookupOrAdd(module_name); if (!interned_module_name.was_emitted) { auto* module_name_entry = interned_data->add_mapping_paths(); module_name_entry->set_iid(interned_module_name.id); module_name_entry->set_str( reinterpret_cast<const uint8_t*>(module_name.data()), module_name.length()); } auto* module_entry = interned_data->add_mappings(); module_entry->set_iid(interned_module.id); module_entry->set_build_id(interned_module_id.id); module_entry->add_path_string_ids(interned_module_name.id); } } auto* frame_entry = interned_data->add_frames(); frame_entry->set_iid(interned_frame.id); if (should_emit_frame_names) { frame_entry->set_function_name_id(interned_frame_name.id); } else { frame_entry->set_rel_pc(rel_pc); } if (frame.module) { frame_entry->set_mapping_id(interned_module.id); } } frame_ids.push_back(interned_frame.id); } auto* callstack_entry = interned_data->add_callstacks(); callstack_entry->set_iid(interned_callstack.id); for (auto& frame_id : frame_ids) callstack_entry->add_frame_ids(frame_id); return interned_callstack.id; } // static void TracingSamplerProfiler::MangleModuleIDIfNeeded(std::string* module_id) { #if defined(OS_ANDROID) || defined(OS_LINUX) // Linux ELF module IDs are 160bit integers, which we need to mangle // down to 128bit integers to match the id that Breakpad outputs. // Example on version '66.0.3359.170' x64: // Build-ID: "7f0715c2 86f8 b16c 10e4ad349cda3b9b 56c7a773 // Debug-ID "C215077F F886 6CB1 10E4AD349CDA3B9B 0" if (module_id->size() >= 32) { *module_id = base::StrCat({module_id->substr(6, 2), module_id->substr(4, 2), module_id->substr(2, 2), module_id->substr(0, 2), module_id->substr(10, 2), module_id->substr(8, 2), module_id->substr(14, 2), module_id->substr(12, 2), module_id->substr(16, 16), "0"}); } #endif } // static std::unique_ptr<TracingSamplerProfiler> TracingSamplerProfiler::CreateOnMainThread() { return std::make_unique<TracingSamplerProfiler>( base::GetSamplingProfilerCurrentThreadToken()); } // static void TracingSamplerProfiler::CreateOnChildThread() { base::SequenceLocalStorageSlot<TracingSamplerProfiler>& slot = GetSequenceLocalStorageProfilerSlot(); if (slot) return; slot.emplace(base::GetSamplingProfilerCurrentThreadToken()); } // static void TracingSamplerProfiler::DeleteOnChildThreadForTesting() { GetSequenceLocalStorageProfilerSlot().reset(); } // static void TracingSamplerProfiler::RegisterDataSource() { PerfettoTracedProcess::Get()->AddDataSource( TracingSamplerProfilerDataSource::Get()); } // static void TracingSamplerProfiler::StartTracingForTesting( PerfettoProducer* producer) { TracingSamplerProfilerDataSource::Get()->StartTracingWithID( 1, producer, perfetto::DataSourceConfig()); } // static void TracingSamplerProfiler::SetupStartupTracingForTesting() { base::trace_event::TraceConfig config( TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), base::trace_event::TraceRecordMode::RECORD_UNTIL_FULL); TracingSamplerProfilerDataSource::Get()->SetupStartupTracing( /*producer=*/nullptr, config, /*privacy_filtering_enabled=*/false); } // static void TracingSamplerProfiler::StopTracingForTesting() { TracingSamplerProfilerDataSource::Get()->StopTracing(base::DoNothing()); } TracingSamplerProfiler::TracingSamplerProfiler( base::SamplingProfilerThreadToken sampled_thread_token) : sampled_thread_token_(sampled_thread_token) { DCHECK_NE(sampled_thread_token_.id, base::kInvalidThreadId); TracingSamplerProfilerDataSource::Get()->RegisterProfiler(this); } TracingSamplerProfiler::~TracingSamplerProfiler() { TracingSamplerProfilerDataSource::Get()->UnregisterProfiler(this); } void TracingSamplerProfiler::SetSampleCallbackForTesting( const base::RepeatingClosure& sample_callback_for_testing) { base::AutoLock lock(lock_); sample_callback_for_testing_ = sample_callback_for_testing; } void TracingSamplerProfiler::StartTracing( std::unique_ptr<perfetto::TraceWriter> trace_writer, bool should_enable_filtering) { base::AutoLock lock(lock_); if (profiler_) { if (trace_writer) { profile_builder_->SetTraceWriter(std::move(trace_writer)); } return; } #if defined(OS_ANDROID) // The sampler profiler would conflict with the reached code profiler if they // run at the same time because they use the same signal to suspend threads. if (base::android::IsReachedCodeProfilerEnabled()) return; #endif base::StackSamplingProfiler::SamplingParams params; params.samples_per_profile = std::numeric_limits<int>::max(); params.sampling_interval = base::TimeDelta::FromMilliseconds(50); // If the sampled thread is stopped for too long for sampling then it is ok to // get next sample at a later point of time. We do not want very accurate // metrics when looking at traces. params.keep_consistent_sampling_interval = false; auto profile_builder = std::make_unique<TracingProfileBuilder>( sampled_thread_token_.id, std::move(trace_writer), should_enable_filtering, sample_callback_for_testing_); profile_builder_ = profile_builder.get(); // Create and start the stack sampling profiler. #if defined(OS_ANDROID) #if BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && defined(OFFICIAL_BUILD) auto* module_cache = profile_builder->GetModuleCache(); profiler_ = std::make_unique<base::StackSamplingProfiler>( params, std::move(profile_builder), std::make_unique<StackSamplerAndroid>(sampled_thread_token_, module_cache)); profiler_->Start(); #endif // BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && defined(OFFICIAL_BUILD) #else // defined(OS_ANDROID) profiler_ = std::make_unique<base::StackSamplingProfiler>( sampled_thread_token_, params, std::move(profile_builder)); profiler_->Start(); #endif // defined(OS_ANDROID) } void TracingSamplerProfiler::StopTracing() { base::AutoLock lock(lock_); if (!profiler_) { return; } // Stop and release the stack sampling profiler. profiler_->Stop(); profile_builder_ = nullptr; profiler_.reset(); } } // namespace tracing
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
3f7bba1662824a937b68e636515ca0c606b2d437
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/multimedia/audio/DuckingCaptureSample/WasapiChat.Cpp
93e269d3755c1808ec1fd55f0ac995ecda52908e
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
UTF-8
C++
false
false
9,810
cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // // // A very simple "Chat" client - reads samples from the default console device and discards the output. // #include "StdAfx.h" #include "WasapiChat.h" CWasapiChat::CWasapiChat(HWND AppWindow) : CChatTransport(AppWindow), _ChatEndpoint(NULL), _AudioClient(NULL), _RenderClient(NULL), _CaptureClient(NULL), _Flow(eRender), _ChatThread(NULL), _ShutdownEvent(NULL), _AudioSamplesReadyEvent(NULL) { } CWasapiChat::~CWasapiChat(void) { SafeRelease(&_ChatEndpoint); SafeRelease(&_AudioClient); SafeRelease(&_RenderClient); SafeRelease(&_CaptureClient); if (_ChatThread) { CloseHandle(_ChatThread); } if (_ShutdownEvent) { CloseHandle(_ShutdownEvent); } if (_AudioSamplesReadyEvent) { CloseHandle(_AudioSamplesReadyEvent); } } // // We can "Chat" if there's more than one capture device. // bool CWasapiChat::Initialize(bool UseInputDevice) { IMMDeviceEnumerator *deviceEnumerator; HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&deviceEnumerator)); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to instantiate device enumerator", L"WASAPI Transport Initialize Failure", MB_OK); return false; } if (UseInputDevice) { _Flow = eCapture; } else { _Flow = eRender; } hr = deviceEnumerator->GetDefaultAudioEndpoint(_Flow, eCommunications, &_ChatEndpoint); deviceEnumerator->Release(); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to retrieve default endpoint", L"WASAPI Transport Initialize Failure", MB_OK); return false; } // // Create our shutdown event - we want an auto reset event that starts in the not-signaled state. // _ShutdownEvent = CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); if (_ShutdownEvent == NULL) { MessageBox(_AppWindow, L"Unable to create shutdown event.", L"WASAPI Transport Initialize Failure", MB_OK); return false; } _AudioSamplesReadyEvent = CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); if (_ShutdownEvent == NULL) { MessageBox(_AppWindow, L"Unable to create samples ready event.", L"WASAPI Transport Initialize Failure", MB_OK); return false; } return true; } // // Shut down the chat code and free all the resources. // void CWasapiChat::Shutdown() { if (_ChatThread) { SetEvent(_ShutdownEvent); WaitForSingleObject(_ChatThread, INFINITE); CloseHandle(_ChatThread); _ChatThread = NULL; } if (_ShutdownEvent) { CloseHandle(_ShutdownEvent); _ShutdownEvent = NULL; } if (_AudioSamplesReadyEvent) { CloseHandle(_AudioSamplesReadyEvent); _AudioSamplesReadyEvent = NULL; } SafeRelease(&_ChatEndpoint); SafeRelease(&_AudioClient); SafeRelease(&_RenderClient); SafeRelease(&_CaptureClient); } // // Start the "Chat" - open the capture device, start capturing. // bool CWasapiChat::StartChat(bool HideFromVolumeMixer) { WAVEFORMATEX *mixFormat = NULL; HRESULT hr = _ChatEndpoint->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, reinterpret_cast<void **>(&_AudioClient)); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to activate audio client.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _AudioClient->GetMixFormat(&mixFormat); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to get mix format on audio client.", L"WASAPI Transport Start Failure", MB_OK); return false; } // // Initialize the chat transport - Initialize WASAPI in event driven mode, associate the audio client with // our samples ready event handle, retrieve a capture/render client for the transport, create the chat thread // and start the audio engine. // GUID chatGuid; hr = CoCreateGuid(&chatGuid); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to create GUID.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _AudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, (HideFromVolumeMixer ? AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE : 0) | AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST, 500000, 0, mixFormat, &chatGuid); CoTaskMemFree(mixFormat); mixFormat = NULL; if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to initialize audio client.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _AudioClient->SetEventHandle(_AudioSamplesReadyEvent); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to set ready event.", L"WASAPI Transport Start Failure", MB_OK); return false; } if (_Flow == eRender) { hr = _AudioClient->GetService(IID_PPV_ARGS(&_RenderClient)); } else { hr = _AudioClient->GetService(IID_PPV_ARGS(&_CaptureClient)); } if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to get Capture/Render client.", L"WASAPI Transport Start Failure", MB_OK); return false; } // // Now create the thread which is going to drive the "Chat". // _ChatThread = CreateThread(NULL, 0, WasapiChatThread, this, 0, NULL); if (_ChatThread == NULL) { MessageBox(_AppWindow, L"Unable to create transport thread.", L"WASAPI Transport Start Failure", MB_OK); return false; } // // For render, we want to pre-roll a frames worth of silence into the pipeline. That way the audio engine won't glitch on startup. // if (_Flow == eRender) { BYTE *pData; UINT32 framesAvailable; hr = _AudioClient->GetBufferSize(&framesAvailable); if (FAILED(hr)) { MessageBox(_AppWindow, L"Failed to get client buffer size.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _RenderClient->GetBuffer(framesAvailable, &pData); if (FAILED(hr)) { MessageBox(_AppWindow, L"Failed to get buffer.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _RenderClient->ReleaseBuffer(framesAvailable, AUDCLNT_BUFFERFLAGS_SILENT); if (FAILED(hr)) { MessageBox(_AppWindow, L"Failed to release buffer.", L"WASAPI Transport Start Failure", MB_OK); return false; } } // // We're ready to go, start the chat! // hr = _AudioClient->Start(); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to start chat client.", L"WASAPI Transport Start Failure", MB_OK); return false; } return true; } // // Stop the "Chat" - Stop the capture thread and release the buffers. // void CWasapiChat::StopChat() { // // Tell the chat thread to shut down, wait for the thread to complete then clean up all the stuff we // allocated in StartChat(). // if (_ShutdownEvent) { SetEvent(_ShutdownEvent); } if (_ChatThread) { WaitForSingleObject(_ChatThread, INFINITE); CloseHandle(_ChatThread); _ChatThread = NULL; } SafeRelease(&_RenderClient); SafeRelease(&_CaptureClient); SafeRelease(&_AudioClient); } DWORD CWasapiChat::WasapiChatThread(LPVOID Context) { bool stillPlaying = true; CWasapiChat *chat = static_cast<CWasapiChat *>(Context); HANDLE waitArray[2] = {chat->_ShutdownEvent, chat->_AudioSamplesReadyEvent}; while (stillPlaying) { HRESULT hr; DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, INFINITE); switch (waitResult) { case WAIT_OBJECT_0 + 0: stillPlaying = false; // We're done, exit the loop. break; case WAIT_OBJECT_0 + 1: // // Either stream silence to the audio client or ignore the audio samples. // // Note that we don't check for errors here. This is because // (a) there's no way of reporting the failure // (b) once the streaming engine has started there's really no way for it to fail. // if (chat->_Flow == eRender) { BYTE *pData; UINT32 framesAvailable; hr = chat->_AudioClient->GetCurrentPadding(&framesAvailable); hr = chat->_RenderClient->GetBuffer(framesAvailable, &pData); hr = chat->_RenderClient->ReleaseBuffer(framesAvailable, AUDCLNT_BUFFERFLAGS_SILENT); } else { BYTE *pData; UINT32 framesAvailable; DWORD flags; hr = chat->_AudioClient->GetCurrentPadding(&framesAvailable); hr = chat->_CaptureClient->GetBuffer(&pData, &framesAvailable, &flags, NULL, NULL); hr = chat->_CaptureClient->ReleaseBuffer(framesAvailable); } } } return 0; } // // Returns "true" for the window messages we handle in our transport. // bool CWasapiChat::HandlesMessage(HWND /*hWnd*/, UINT /*message*/) { return false; } // // Don't process Wave messages. // INT_PTR CWasapiChat::MessageHandler(HWND /*hWnd*/, UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/) { return FALSE; }
[ "chrisg@microsoft.com" ]
chrisg@microsoft.com
bb1e5e0ad7d3c14a859e3e886aa34e15d40558d9
ea727ced064f305a844d54343ee0534e00571e24
/Graph/PrintAdjList/PrintAdjList.h
05f9ff9e0eb826bd1c71b90005e4c30ab2a321fb
[]
no_license
iukjgo/practice_easy
dce60754329dd63f15dfdf9ee7a77fea7229fee0
dfd19e7c28b8f967d4079f6d6870492723cdfefa
refs/heads/master
2020-04-06T08:03:09.227027
2018-11-21T03:11:54
2018-11-21T03:11:54
157,293,395
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
#ifndef PrintAdjList_h #define PrintAdjList_h #include <iostream> #include <vector> class Graph { public: Graph(int vertices, int edges) : mVertices(vertices), mEdges(edges), mAdj(vertices) { }; void addEdge(int u, int v); const std::vector<int>* getAdjList(int u) const; const int getVerticesCount() const { return mVertices; } private: std::vector<std::vector<int>> mAdj; int mVertices; int mEdges; }; class PrintAdjList { public: PrintAdjList() {}; static void print(const Graph& g); private: }; #endif /* PrintAdjList_h */
[ "iukjgo@gmail.com" ]
iukjgo@gmail.com
e06aa2ce7e88d706576ff9d6ff2ee2585f29a3b9
9ef5662fa65ca9793577d5151fcf4a7b82ef300f
/P5/SDLProject/Entity.h
d3861a3eaa62f8d6920c4ab2a0703d7f5f2a1539
[]
no_license
lsemenuk/CS3113
ab9a5261b7f2f261350b170fa0d8b576d65d2de8
ef46502117638622bb96957ccf9994a4010f70ba
refs/heads/master
2022-12-02T23:15:14.105027
2020-08-14T21:31:37
2020-08-14T21:31:37
267,184,503
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
h
#pragma once #define GL_SILENCE_DEPRECATION #ifdef _WINDOWS #include <GL/glew.h> #endif #define GL_GLEXT_PROTOTYPES 1 #include <SDL.h> #include <SDL_opengl.h> #include "glm/mat4x4.hpp" #include "glm/gtc/matrix_transform.hpp" #include "ShaderProgram.h" #include "Map.h" enum EntityType { PLAYER, PLATFORM, ENEMY }; enum AIType { STAGE1, STAGE2, STAGE3 }; enum AIState { IDLE, WALKING, ATTACKING, CHARGING, }; class Entity { public: EntityType entityType; AIType aiType; AIState aiState; Entity *lastCollided = NULL; glm::vec3 position; glm::vec3 movement; glm::vec3 acceleration; glm::vec3 velocity; float width = .8; float height = .8; bool jump = false; float jumpPower = 0; float speed; GLuint textureID; glm::mat4 modelMatrix; int *animRight = NULL; int *animLeft = NULL; int *animUp = NULL; int *animDown = NULL; int *animIndices = NULL; int animFrames = 0; int animIndex = 0; float animTime = 0; int animCols = 0; int animRows = 0; bool isActive = true; bool collidedTop = false; bool collidedBottom = false; bool collidedLeft = false; bool collidedRight = false; bool collidedEnemyBottom = false; bool lostLife = false; bool gameOver = false; bool gameWin = false; Entity(); bool CheckCollision(Entity *other); void CheckCollisionsY(Entity *objects, int objectCount); void CheckCollisionsX(Entity *objects, int objectCount); void CheckCollisionsX(Map *map); void CheckCollisionsY(Map *map); void Update(float deltaTime, Entity *player, Entity *objects, int objectCount, Map *map, int *lives); void Render(ShaderProgram *program); void DrawSpriteFromTextureAtlas(ShaderProgram *program, GLuint textureID, int index); void AI(Entity *player); void AIWalker(); void AIWaitAndCharge(Entity *player); void AIJumpAndFollow(Entity *player); void AIPatrol(Entity *player); void AIPatrolLevel3(Entity *player); };
[ "ls4508@nyu.edu" ]
ls4508@nyu.edu
744c48380fbc321db608409ae435136b82cc90b6
4d7ae3ca4674267c72385fa1ba67496e3abd55ff
/libRayTracing/RayTracing/aabb.h
f52df8b074fa8ed181af90015358b6fd35c6187c
[ "MIT" ]
permissive
tanganke/RayTracing
1e5c1e066b74f26ef215f1075e43cd8db8eb7259
876180439cbc2a6241735d18de6e0eb9e2f11e96
refs/heads/master
2023-08-25T02:56:58.126412
2021-10-13T11:52:07
2021-10-13T11:52:07
404,777,544
0
0
null
null
null
null
UTF-8
C++
false
false
2,421
h
#pragma once #include "ray.h" #include "float.h" #include <iostream> namespace ray_tracing { class aabb { public: vec3 lower_bound, higher_bound; public: aabb() : lower_bound{FLT_MAX, FLT_MAX, FLT_MAX}, higher_bound{FLT_MIN, FLT_MIN, FLT_MIN} {}; aabb(const vec3 &lower_bound_, const vec3 &higher_bound_) : lower_bound{lower_bound_}, higher_bound{higher_bound_} {} aabb(const aabb &a, const aabb &b) { vec3 lower{std::min(a.lower_bound[0], b.lower_bound[0]), std::min(a.lower_bound[1], b.lower_bound[1]), std::min(a.lower_bound[2], b.lower_bound[2])}; vec3 higher{std::max(a.higher_bound[0], b.higher_bound[0]), std::max(a.higher_bound[1], b.higher_bound[1]), std::max(a.higher_bound[2], b.higher_bound[2])}; lower_bound = lower; higher_bound = higher; } inline vec3 &min() { return lower_bound; } inline vec3 &max() { return higher_bound; } inline const vec3 &min() const { return lower_bound; } inline const vec3 &max() const { return higher_bound; } aabb &push_back(const vec3 &p) { for (int i = 0; i < 3; ++i) { lower_bound[i] = std::min(lower_bound[i], p[i]); higher_bound[i] = std::max(higher_bound[i], p[i]); } return *this; } bool hit(const ray &r, float t_min, float t_max) const { for (int i = 0; i < 3; ++i) { float t[2] = {(lower_bound[i] - r.start_point[i]) / r.direction[i], (higher_bound[i] - r.start_point[i]) / r.direction[i]}; float interval[2] = {std::min(t[0], t[1]), std::max(t[0], t[1])}; t_min = std::max(interval[0], t_min); t_max = std::min(interval[1], t_max); if (t_max <= t_min) return false; } return true; } inline void translate(const vec3 &displacement) { lower_bound += displacement; higher_bound += displacement; } inline void clear() { *this = aabb(); } }; inline std::ostream &operator<<(std::ostream &os, const aabb &bbox) { os << "aabb(" << bbox.lower_bound << ',' << bbox.higher_bound << ')'; return os; } }
[ "tang.anke@foxmail.com" ]
tang.anke@foxmail.com
4854448793f4dbf22a51e067b83293ffee1db3d0
fef58dcd0c1434724a0a0a82e4c84ae906200289
/usages/0x7033EEFD9B28088E.cpp
7437a3e5ec31d297b26c583585689f28aff74211
[]
no_license
DottieDot/gta5-additional-nativedb-data
a8945d29a60c04dc202f180e947cbdb3e0842ace
aea92b8b66833f063f391cb86cbcf4d58e1d7da3
refs/heads/main
2023-06-14T08:09:24.230253
2021-07-11T20:43:48
2021-07-11T20:43:48
380,364,689
1
0
null
null
null
null
UTF-8
C++
false
false
879
cpp
// freemode.ysc @ L146260 void func_1667(int iParam0, bool bParam1) { struct<14> Var0; struct<13> Var1; if (NETWORK::NETWORK_IS_GAME_IN_PROGRESS()) { if (!func_1669()) { if (iParam0 != -1) { if (NETWORK::NETWORK_IS_PLAYER_ACTIVE(iParam0)) { NETWORK::_0xA7C511FA1C5BDA38(iParam0, 1); func_101(&(Global_1676406[iParam0 /*5*/].f_2), 0, 0); if (bParam1) { func_1619("GRIEF_TICK_VIC", iParam0, 0, 0, 0, 1, 1, 0); } Var0.f_10 = PLAYER::PLAYER_ID(); Var0.f_2 = -1256884122; func_1668(Var0, func_17850(iParam0)); if (MISC::IS_BIT_SET(Global_1573899, 3)) { MISC::SET_BIT(&Global_1573899, 7); } Var1 = { func_38(iParam0) }; STATS::_0x7033EEFD9B28088E(&Var1); } } } } }
[ "tvangroenigen@outlook.com" ]
tvangroenigen@outlook.com
d3efa762dbb898e39d13bd12646aca5d867154d3
ae0dbf9739042461b1b55dd79aad3beff25ba3b0
/bfs2.cpp
68a8f66dea2ec611bfe9e4a6df431a2b77f96d38
[]
no_license
saquib77/Code
b058d587438c5e029a1b422b2facb80924c69f91
006faa69f35d3cbfd9aca261ed696cab78ff7fb0
refs/heads/main
2023-07-14T01:05:22.466452
2021-08-20T06:55:13
2021-08-20T06:55:13
341,225,695
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
#include<bits/stdc++.h> using namespace std; queue<int>q; bool visited[7]; int dist[7]; vector<pair<int,int>>gp[7]; void bfs(int n){ visited[n]=true; dist[n]=0; q.push(n); while(!q.empty()){ int s=q.front(); q.pop(); cout<<s<<" "; for(auto v:gp[s]){ if(visited[v.first]) continue; visited[v.first]=true; dist[v.first]=dist[s]+1; q.push(v.first); } } } int main(){ gp[1].push_back(make_pair(5,1)); gp[2].push_back(make_pair(3,2)); gp[2].push_back(make_pair(1,5)); gp[3].push_back(make_pair(4,7)); gp[3].push_back(make_pair(2,2)); gp[4].push_back(make_pair(1,3)); gp[5].push_back(make_pair(4,2)); //bfs(1); bfs(2); cout<<"\n"; return 0; }
[ "chand567khan@gmail.com" ]
chand567khan@gmail.com
39a5c59db82d2e73c7893bcc582794792e2fa6c0
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/cdc/include/tencentcloud/cdc/v20201214/model/ModifyDedicatedClusterInfoResponse.h
e5f1ce5239fd2e4ed8cde99b4cdd799f2b453acf
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
1,686
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CDC_V20201214_MODEL_MODIFYDEDICATEDCLUSTERINFORESPONSE_H_ #define TENCENTCLOUD_CDC_V20201214_MODEL_MODIFYDEDICATEDCLUSTERINFORESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Cdc { namespace V20201214 { namespace Model { /** * ModifyDedicatedClusterInfo返回参数结构体 */ class ModifyDedicatedClusterInfoResponse : public AbstractModel { public: ModifyDedicatedClusterInfoResponse(); ~ModifyDedicatedClusterInfoResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; private: }; } } } } #endif // !TENCENTCLOUD_CDC_V20201214_MODEL_MODIFYDEDICATEDCLUSTERINFORESPONSE_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
129b28ea2e4c5cf8f36aaac73632c2560d45192b
785df77400157c058a934069298568e47950e40b
/TnbMesh/TnbLib/SizeMapControl/3d/Mesh3d_SizeMapControlFwd.hxx
1969f93adb96a6c04dcbef044688aefd24d1edbd
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
343
hxx
#pragma once #ifndef _Mesh3d_SizeMapControlFwd_Header #define _Mesh3d_SizeMapControlFwd_Header namespace tnbLib { // Forward Declarations [6/22/2022 Amir] class Cad_TModel; template<class GeomType> class Mesh_SizeMapControl; typedef Mesh_SizeMapControl<Cad_TModel> Mesh3d_SizeMapControl; } #endif // !_Mesh3d_SizeMapControlFwd_Header
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
109c6cf5b2f8d28dd9b9255d055de409901993b4
fb72a39f5da510ba346db3073d33c6387760fb93
/ficha.h
ecb6eead10ccdf8555e8b80c3c80000089c9cd76
[ "MIT" ]
permissive
jion/tetrabrick
bcd724e572c907f7fc8c4fb7219ea4decc7e88c7
0946c2528a1e8b13ad7c1835b93934138404c025
refs/heads/master
2021-01-17T12:15:42.512451
2020-03-10T14:35:29
2020-03-10T14:35:29
33,821,988
1
0
null
null
null
null
UTF-8
C++
false
false
706
h
#ifndef ficha_h #define ficha_h #include <SDL/SDL.h> #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; class Ficha { public: int valor; int posicion; bool data[4][4][4]; Ficha( class Galeria *galeria ); ~Ficha(); void imprimir (SDL_Surface *dst, int x = 0, int y = 0); void nueva_ficha(int ficha = 0); void rotar(int lado); // 0 + // 1 - private: class Image *bloques; SDL_Surface *pieza; void actualizar(void); void carga_valores(void); typedef Uint8 data_[4][4]; typedef data_ pieza_[4]; pieza_ fichas[7]; }; #endif
[ "el.manu@gmail.com" ]
el.manu@gmail.com
89df47c8a1ee872b4f921051dc543be6aece782d
08278b638a0c44e7a3951f2a5f5d72d33f610682
/MummyDiner/state/LevelScreen.h
aa03e238494085e8311f86f3b5a5cd9d6aa99ca6
[]
no_license
muhdmirzamz/MummyDiner
f486446c74290c959fd3bae8dbaeed96f0a475df
ce55023acc138638dc1cb3fc8360e4fad9b7bc18
refs/heads/master
2021-01-01T16:00:25.059462
2015-12-15T12:04:07
2015-12-15T12:04:07
31,579,910
1
0
null
2015-04-25T12:05:44
2015-03-03T04:48:03
C++
UTF-8
C++
false
false
1,405
h
// // LevelScreen.h // MummyDiner // // Created by Muhd Mirza on 5/1/15. // Copyright (c) 2015 Muhd Mirza. All rights reserved. // #ifndef __MummyDiner__LevelScreen__ #define __MummyDiner__LevelScreen__ #include "GameState.h" #include "GameOverScreen.h" class LevelScreen: public GameState { public: static bool normalMode; LevelScreen(); void handleEvent(); void spawnCustomer(); void moveCharacter(); void checkCollision(); void update(); void render(); void cleanupLevelScreen(int state); private: SpriteClass *_waitress; Waitress _waitressObj; SpriteClass *_customer; Customer _customerObj; SpriteClass *_topWalkingCustomer; Customer _topWalkingCustomerObj; SpriteClass *_bottomWalkingCustomer; Customer _bottomWalkingCustomerObj; SpriteClass *_chef; Chef _chefObj; SpriteClass _topLeftTable; SpriteClass _topRightTable; SpriteClass _bottomLeftTable; SpriteClass _bottomRightTable; SpriteClass _counter; SpriteClass _stove; BackgroundClass _backgroundArr[5]; BackgroundClass _topLeftBackground; BackgroundClass _topRightBackground; BackgroundClass _bottomLeftBackground; BackgroundClass _bottomRightBackground; BackgroundClass _foodPickupBackground; ButtonClass _lsBackToMenuButton; MenuSystem _menuSystem; int _mouseClickX; int _mouseClickY; }; #endif /* defined(__MummyDiner__LevelScreen__) */
[ "muhdmirzamz@gmail.com" ]
muhdmirzamz@gmail.com
71ab6c9395fd926ab847a0d3c2f50e7518ed573f
6dedc5c204ac18abee11159ffe0bcc300be61c5a
/signalAndSlot/student.cpp
75264368d46f11cb6d0083d9eff7e58b8321e503
[]
no_license
MrDalili/qtStudy
ad364cd8b91212a8bb7f3916b1abf7653888d5c0
febd2cfbbb04f0b99038ccac78a48c4247ea5451
refs/heads/master
2020-08-04T04:32:13.014803
2019-11-17T04:09:15
2019-11-17T04:09:15
212,006,597
0
0
null
null
null
null
UTF-8
C++
false
false
255
cpp
#include "student.h" #include <QDebug> Student::Student(QObject *parent) : QObject(parent) { } void Student::treat(){ qDebug() << "请老师吃饭"; } void Student::treat(QString food){ qDebug() << "请老师吃饭" << food.toUtf8().data(); }
[ "275482839@qq.com" ]
275482839@qq.com
61aa9de08c5ecf8ca4bb8c8e2806be2d1f89a0f1
888ff1ff4f76c61e0a2cff281f3fae2c9a4dcb7b
/C/C200/C230/C236/1.cpp
5fd04a813965d37db35728ca035a9cee196df843
[]
no_license
sanjusss/leetcode-cpp
59e243fa41cd5a1e59fc1f0c6ec13161fae9a85b
8bdf45a26f343b221caaf5be9d052c9819f29258
refs/heads/master
2023-08-18T01:02:47.798498
2023-08-15T00:30:51
2023-08-15T00:30:51
179,413,256
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
/* * @Author: sanjusss * @Date: 2021-04-11 10:31:51 * @LastEditors: sanjusss * @LastEditTime: 2021-04-11 10:33:19 * @FilePath: \C\C200\C230\C236\1.cpp */ #include "leetcode.h" class Solution { public: int arraySign(vector<int>& nums) { int sign = 1; for (int i : nums) { if (i == 0) { return 0; } else if (i < 0) { sign *= -1; } } return sign; } };
[ "sanjusss@qq.com" ]
sanjusss@qq.com
7b659d4b8492dfd26232988ddfd5359a133d6c45
77a091c62781f6aefeebdfd6efd4bab9caa51465
/Done/main/mon.cpp
abd7c73ba2761e597109d329fe43eff048d1ec2a
[]
no_license
breno-helf/Maratona
55ab11264f115592e1bcfd6056779a3cf27e44dc
c6970bc554621746cdb9ce53815b8276a4571bb3
refs/heads/master
2021-01-23T21:31:05.267974
2020-05-05T23:25:23
2020-05-05T23:25:23
57,412,343
1
2
null
2017-01-25T14:58:46
2016-04-29T20:54:08
C++
UTF-8
C++
false
false
702
cpp
#include <bits/stdc++.h> using namespace std; #define debug(args...) fprintf(stderr,args) #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const int MAX = 1e6 + 2; const int INF = 0x3f3f3f3f; const ll MOD = 1000000007; int n, k; char s[MAX]; map<ll, int> M; int main () { scanf("%d%d", &n, &k); scanf(" %s", s); ll sum = 0; int resp = 0; for (int i = 0; i < n; i++) { if (s[i] == 'O') sum++; else sum -= k; if (!sum) resp = i + 1; else if (M.find(sum) != M.end()) { resp = (i - M[sum] > resp) ? i - M[sum] : resp; } else { M[sum] = i; } } printf("%d\n", resp); return 0; }
[ "breno.moura@hotmail.com" ]
breno.moura@hotmail.com
bddec873c29a08479271504dab4d0c1b692050ae
e46b909cdf0361f6c336f532507573c2f592cdf4
/contrib/libs/protobuf/util/internal/protostream_objectsource.h
66ea5bc4884533a8c3176e3cbc75bdf2fa084cf9
[ "Apache-2.0" ]
permissive
exprmntr/test
d25b50881089640e8d94bc6817e9194fda452e85
170138c9ab62756f75882d59fb87447fc8b0f524
refs/heads/master
2022-11-01T16:47:25.276943
2018-03-31T20:56:25
2018-03-31T20:56:25
95,452,782
0
3
Apache-2.0
2022-10-30T22:45:27
2017-06-26T14:04:21
C++
UTF-8
C++
false
false
13,643
h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__ #define GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__ #include <functional> #include "stubs/hash.h" #include "stubs/common.h" #include "type.pb.h" #include "util/internal/object_source.h" #include "util/internal/object_writer.h" #include "util/internal/type_info.h" #include "util/type_resolver.h" #include <contrib/libs/protobuf/stubs/stringpiece.h> #include "stubs/status.h" #include "stubs/statusor.h" namespace google { namespace protobuf { class Field; class Type; } // namespace protobuf namespace protobuf { namespace util { namespace converter { class TypeInfo; // An ObjectSource that can parse a stream of bytes as a protocol buffer. // Its WriteTo() method can be given an ObjectWriter. // This implementation uses a google.protobuf.Type for tag and name lookup. // The field names are converted into lower camel-case when writing to the // ObjectWriter. // // Sample usage: (suppose input is: string proto) // ArrayInputStream arr_stream(proto.data(), proto.size()); // CodedInputStream in_stream(&arr_stream); // ProtoStreamObjectSource os(&in_stream, /*ServiceTypeInfo*/ typeinfo, // <your message google::protobuf::Type>); // // Status status = os.WriteTo(<some ObjectWriter>); class /* LIBPROTOBUF_EXPORT */ ProtoStreamObjectSource : public ObjectSource { public: ProtoStreamObjectSource(google::protobuf::io::CodedInputStream* stream, TypeResolver* type_resolver, const google::protobuf::Type& type); virtual ~ProtoStreamObjectSource(); virtual util::Status NamedWriteTo(StringPiece name, ObjectWriter* ow) const; // Sets whether or not to use lowerCamelCase casing for enum values. If set to // false, enum values are output without any case conversions. // // For example, if we have an enum: // enum Type { // ACTION_AND_ADVENTURE = 1; // } // Type type = 20; // // And this option is set to true. Then the rendered "type" field will have // the string "actionAndAdventure". // { // ... // "type": "actionAndAdventure", // ... // } // // If set to false, the rendered "type" field will have the string // "ACTION_AND_ADVENTURE". // { // ... // "type": "ACTION_AND_ADVENTURE", // ... // } void set_use_lower_camel_for_enums(bool value) { use_lower_camel_for_enums_ = value; } // Sets the max recursion depth of proto message to be deserialized. Proto // messages over this depth will fail to be deserialized. // Default value is 64. void set_max_recursion_depth(int max_depth) { max_recursion_depth_ = max_depth; } protected: // Writes a proto2 Message to the ObjectWriter. When the given end_tag is // found this method will complete, allowing it to be used for parsing both // nested messages (end with 0) and nested groups (end with group end tag). // The include_start_and_end parameter allows this method to be called when // already inside of an object, and skip calling StartObject and EndObject. virtual util::Status WriteMessage(const google::protobuf::Type& descriptor, StringPiece name, const uint32 end_tag, bool include_start_and_end, ObjectWriter* ow) const; private: ProtoStreamObjectSource(google::protobuf::io::CodedInputStream* stream, const TypeInfo* typeinfo, const google::protobuf::Type& type); // Function that renders a well known type with a modified behavior. typedef util::Status (*TypeRenderer)(const ProtoStreamObjectSource*, const google::protobuf::Type&, StringPiece, ObjectWriter*); // Looks up a field and verify its consistency with wire type in tag. const google::protobuf::Field* FindAndVerifyField( const google::protobuf::Type& type, uint32 tag) const; // TODO(skarvaje): Mark these methods as non-const as they modify internal // state (stream_). // // Renders a repeating field (packed or unpacked). // Returns the next tag after reading all sequential repeating elements. The // caller should use this tag before reading more tags from the stream. util::StatusOr<uint32> RenderList(const google::protobuf::Field* field, StringPiece name, uint32 list_tag, ObjectWriter* ow) const; // Renders a NWP map. // Returns the next tag after reading all map entries. The caller should use // this tag before reading more tags from the stream. util::StatusOr<uint32> RenderMap(const google::protobuf::Field* field, StringPiece name, uint32 list_tag, ObjectWriter* ow) const; // Renders a packed repeating field. A packed field is stored as: // {tag length item1 item2 item3} instead of the less efficient // {tag item1 tag item2 tag item3}. util::Status RenderPacked(const google::protobuf::Field* field, ObjectWriter* ow) const; // Renders a google.protobuf.Timestamp value to ObjectWriter static util::Status RenderTimestamp(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Renders a google.protobuf.Duration value to ObjectWriter static util::Status RenderDuration(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Following RenderTYPE functions render well known types in // google/protobuf/wrappers.proto corresponding to TYPE. static util::Status RenderDouble(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderFloat(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderInt64(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderUInt64(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderInt32(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderUInt32(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderBool(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderString(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderBytes(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Renders a google.protobuf.Struct to ObjectWriter. static util::Status RenderStruct(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Helper to render google.protobuf.Struct's Value fields to ObjectWriter. static util::Status RenderStructValue(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Helper to render google.protobuf.Struct's ListValue fields to ObjectWriter. static util::Status RenderStructListValue( const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Render the "Any" type. static util::Status RenderAny(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Render the "FieldMask" type. static util::Status RenderFieldMask(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static hash_map<string, TypeRenderer>* renderers_; static void InitRendererMap(); static void DeleteRendererMap(); static TypeRenderer* FindTypeRenderer(const string& type_url); // Renders a field value to the ObjectWriter. util::Status RenderField(const google::protobuf::Field* field, StringPiece field_name, ObjectWriter* ow) const; // Same as above but renders all non-message field types. Callers don't call // this function directly. They just use RenderField. util::Status RenderNonMessageField(const google::protobuf::Field* field, StringPiece field_name, ObjectWriter* ow) const; // Reads field value according to Field spec in 'field' and returns the read // value as string. This only works for primitive datatypes (no message // types). const string ReadFieldValueAsString( const google::protobuf::Field& field) const; // Utility function to detect proto maps. The 'field' MUST be repeated. bool IsMap(const google::protobuf::Field& field) const; // Utility to read int64 and int32 values from a message type in stream_. // Used for reading google.protobuf.Timestamp and Duration messages. std::pair<int64, int32> ReadSecondsAndNanos( const google::protobuf::Type& type) const; // Helper function to check recursion depth and increment it. It will return // Status::OK if the current depth is allowed. Otherwise an error is returned. // type_name and field_name are used for error reporting. util::Status IncrementRecursionDepth(StringPiece type_name, StringPiece field_name) const; // Input stream to read from. Ownership rests with the caller. google::protobuf::io::CodedInputStream* stream_; // Type information for all the types used in the descriptor. Used to find // google::protobuf::Type of nested messages/enums. const TypeInfo* typeinfo_; // Whether this class owns the typeinfo_ object. If true the typeinfo_ object // should be deleted in the destructor. bool own_typeinfo_; // google::protobuf::Type of the message source. const google::protobuf::Type& type_; // Whether to render enums using lowerCamelCase. Defaults to false. bool use_lower_camel_for_enums_; // Tracks current recursion depth. mutable int recursion_depth_; // Maximum allowed recursion depth. int max_recursion_depth_; // Whether to render unknown fields. bool render_unknown_fields_; GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(ProtoStreamObjectSource); }; } // namespace converter } // namespace util } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
[ "exprmntr@yandex-team.ru" ]
exprmntr@yandex-team.ru
24ff7f5b273714ec781324349f641ea696872520
19531eb1f498ad7273bcec961b34e9de79fd9381
/cservan/MWERalign-master/src/Evaluator_unsegmentedWER.hh
2e7b79bf6dee8e6248cca65a64a9aa8a2b76367a
[]
no_license
Trialp/Ressources_GETALP
106e8616cef17510037bfd8af5a15511779842f7
e728f4ece5ac344ad57c1cc7eddc8bf9cfa4bcd2
refs/heads/master
2020-03-07T05:16:01.590588
2018-04-04T14:18:47
2018-04-04T14:18:47
127,291,077
0
0
null
null
null
null
UTF-8
C++
false
false
3,124
hh
/*-------------------------------------------------------------- Copyright 2006 (c) by RWTH Aachen - Lehrstuhl fuer Informatik 6 Richard Zens, Evgeny Matusov, Gregor Leusch --------------------------------------------------------------- This header file is part of the MwerAlign C++ Library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef EVALUATOR_UNSEGMENTEDWER_HH_ #define EVALUATOR_UNSEGMENTEDWER_HH_ #include "Evaluator.hh" #include <map> #include <set> using namespace std; class Evaluator_unsegmentedWER : public Evaluator { public: typedef Evaluator::hyptype hyptype; typedef Evaluator::HypContainer HypContainer; typedef struct DP_ { unsigned int cost; unsigned int bp; } DP; typedef std::vector<std::vector<DP> > Matrix; Evaluator_unsegmentedWER(); Evaluator_unsegmentedWER(const std::string& refFile); ~Evaluator_unsegmentedWER() {} double _evaluate2(const HypContainer& hyps, std::ostream& out) const; double _evaluate2(const HypContainer& hyps, const HypContainer& hypsBi, std::ostream& out) const; double _evaluate(const HypContainer& hyps) const { return _evaluate2(hyps, std::cout); } double _evaluate_abs(const HypContainer&) const { return 0.0; }; std::string name() const; void setInsertionCosts(double x) {ins_=x;} void setDeletionCosts(double x) {del_=x;} virtual bool initrefs() { return true; } void setOptions(const double maxER, const bool human) { maxER_ = maxER; human_ = human; } protected: double computeSpecialWER(const std::vector<std::vector<unsigned int> >& A, const std::vector<unsigned int>& B, unsigned int nSegments) const; unsigned int getVocIndex(const std::string& word) const; unsigned int getSubstitutionCosts(const uint a, const uint b) const; unsigned int getInsertionCosts(const uint w) const; unsigned int additionalInsertionCosts(const uint w, const uint w2=0) const; unsigned int getDeletionCosts(const uint w) const; double ins_,del_; void fillPunctuationSet(); private: unsigned int segmentationWord; double maxER_; bool human_; mutable unsigned int refLength_; mutable unsigned int vocCounter_; mutable std::map<std::string,unsigned int> vocMap_; mutable std::set<unsigned int> punctuationSet_; mutable std::vector<unsigned int> boundary; mutable std::vector<unsigned int> sentCosts; }; #endif
[ "initial@athena5.imag.fr" ]
initial@athena5.imag.fr
b1dc38d0e606b4c9bdd5d24af987982ff86e1862
aa4b90e539ab43c64b54b9f2516a3446c9380a01
/main.cpp
dcc32d9c3a57150ee91fa8d3759ef8f4aa26755c
[]
no_license
eggplanty/CPPAlgorithmLearning
27197a0fbf7bdb124b77d443d34326ae875bf4fd
1870fef242631f26d1bb0922084fb49f66439e76
refs/heads/master
2022-12-06T00:36:18.244126
2020-08-28T03:07:33
2020-08-28T03:07:33
272,315,654
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
#include <iostream> #include <vector> #include <cstring> using namespace std; class Solution { public: string reverseLeftWords(string s, int n) { auto reverse = [] (string &str, int i , int j) { while(i < j) swap(str[i++], str[j--]); }; reverse(s, 0, n-1); reverse(s, n, s.size() - 1); reverse(s, 0, s.size()); return s; } }; int main() { Solution().reverseLeftWords("123456", 3); }
[ "794261358@qq.com" ]
794261358@qq.com
4461b5f1ac1074311ee33a16e2d870117977669c
9b9b0fd49be3d29b1367e7882c4b69ca4e3118ed
/Source/System/Math/Primitive/Others/Ray.cpp
e622ba288e2fec28980a8f2e64def04fb7612c70
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
arian153/Physics-Project
01e949bc4edf2a5ea3436fe2e85c20c566eae923
4571eab70d0a079358905db8c33230545ffb66b9
refs/heads/main
2023-04-22T13:13:12.557697
2021-04-30T11:48:39
2021-04-30T11:48:39
320,809,601
1
0
null
null
null
null
UTF-8
C++
false
false
13,285
cpp
#include "Ray.hpp" #include "../../Utility/Utility.hpp" #include "Line.hpp" namespace PhysicsProject { Ray::Ray(const Vector3& position, const Vector3& direction) : position(position), direction(direction) { } Ray::Ray(const Ray& rhs) : position(rhs.position), direction(rhs.direction) { } Ray::~Ray() { } Vector3 Ray::ParamToPoint(Real t) const { if (t < 0.0f) { return position; } return position + direction * t; } Real Ray::PointToParam(const Vector3& point_on_ray) const { Vector3 t_dir = point_on_ray - position; Vector3 inv_dir = direction; inv_dir.SetInverse(); Vector3 t_vector = t_dir.HadamardProduct(inv_dir); if (Math::IsValid(t_vector.x) == true) { return t_vector.x; } if (Math::IsValid(t_vector.y) == true) { return t_vector.y; } if (Math::IsValid(t_vector.z) == true) { return t_vector.z; } return 0.0f; } Ray Ray::GetReflectedRay(const Vector3& normal, const Vector3& new_position) const { Vector3 n = normal.Normalize(); Vector3 reflect_direction = -2.0f * DotProduct(direction, n) * n + direction; return Ray(new_position, reflect_direction.Normalize()); } Vector3 Ray::SymmetricPoint(const Vector3& point) const { Vector3 closest = ClosestPoint(point); return closest + closest - point; } Vector3 Ray::ClosestPoint(const Vector3& point) const { Vector3 w = point - position; Real proj = w.DotProduct(direction); // endpoint 0 is closest point if (proj <= 0.0f) { return position; } // somewhere else in ray Real ddd = direction.DotProduct(direction); return position + (proj / ddd) * direction; } Real Ray::Distance(const Vector3& point, Real& t) const { return sqrtf(DistanceSquared(point, t)); } Real Ray::DistanceSquared(const Vector3& point, Real& t) const { Vector3 w = point - position; Real proj = w.DotProduct(direction); // origin is closest point if (proj <= 0) { t = 0.0f; return w.DotProduct(w); } // else use normal line check Real ddd = direction.DotProduct(direction); t = proj / ddd; return w.DotProduct(w) - t * proj; } Vector3Pair Ray::ClosestPoint(const Ray& ray) const { Vector3 w0 = position - ray.position; Real r0d_dot_r0d = direction.DotProduct(direction); Real r0d_dot_r1d = direction.DotProduct(ray.direction); Real r1d_dot_r1d = ray.direction.DotProduct(ray.direction); Real r0d_dot_w = direction.DotProduct(w0); Real r1d_dot_w = ray.direction.DotProduct(w0); Real denominator = r0d_dot_r0d * r1d_dot_r1d - r0d_dot_r1d * r0d_dot_r1d; // parameters to compute s_c, t_c Real s_c, t_c; Real sn, sd, tn, td; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { sd = td = r1d_dot_r1d; sn = 0.0f; tn = r1d_dot_w; } else { // start by clamping s_c sd = td = denominator; sn = r0d_dot_r1d * r1d_dot_w - r1d_dot_r1d * r0d_dot_w; tn = r0d_dot_r0d * r1d_dot_w - r0d_dot_r1d * r0d_dot_w; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = r1d_dot_w; td = r1d_dot_r1d; } } // clamp t_c within [0,+inf] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if (-r0d_dot_w < 0.0f) { s_c = 0.0f; } else { s_c = -r0d_dot_w / r0d_dot_r0d; } } else { t_c = tn / td; s_c = sn / sd; } // compute closest points return Vector3Pair(position + s_c * direction, ray.position + t_c * ray.direction); } Ray& Ray::operator=(const Ray& rhs) { if (this != &rhs) { position = rhs.position; direction = rhs.direction; direction.SetNormalize(); } return *this; } bool Ray::operator==(const Ray& rhs) const { return rhs.position == position && rhs.direction == direction; } bool Ray::operator!=(const Ray& rhs) const { return rhs.position != position || rhs.direction != direction; } Real Distance(const Ray& ray0, const Ray& ray1, Real& s, Real& t) { return sqrtf(DistanceSquared(ray0, ray1, s, t)); } Real Distance(const Ray& ray, const Vector3& point, Real& t) { return sqrtf(DistanceSquared(ray, point, t)); } Real Distance(const Ray& ray, const Line& line, Real& s, Real& t) { return sqrtf(DistanceSquared(ray, line, s, t)); } Real Distance(const Line& line, const Ray& ray, Real& s, Real& t) { return sqrtf(DistanceSquared(line, ray, s, t)); } Real DistanceSquared(const Ray& ray0, const Ray& ray1, Real& s, Real& t) { Vector3 w0 = ray0.position - ray1.position; Real r0d_dot_r0d = ray0.direction.DotProduct(ray0.direction); Real r0d_dot_r1d = ray0.direction.DotProduct(ray1.direction); Real r1d_dot_r1d = ray1.direction.DotProduct(ray1.direction); Real r0d_dot_w = ray0.direction.DotProduct(w0); Real r1d_dot_w = ray1.direction.DotProduct(w0); Real denominator = r0d_dot_r0d * r1d_dot_r1d - r0d_dot_r1d * r0d_dot_r1d; Real sn, sd, tn, td; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator) == true) { // clamp s_c to 0 sd = td = r1d_dot_r1d; sn = 0.0f; tn = r1d_dot_w; } else { // clamp s_c within [0,+inf] sd = td = denominator; sn = r0d_dot_r1d * r1d_dot_w - r1d_dot_r1d * r0d_dot_w; tn = r0d_dot_r0d * r1d_dot_w - r0d_dot_r1d * r0d_dot_w; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = r1d_dot_w; td = r1d_dot_r1d; } } // clamp t within [0,+inf] // clamp t to 0 if (tn < 0.0f) { t = 0.0f; // clamp s_c to 0 if (-r0d_dot_w < 0.0f) { s = 0.0f; } else { s = -r0d_dot_w / r0d_dot_r0d; } } else { t = tn / td; s = sn / sd; } // compute difference vector and distance squared Vector3 wc = w0 + (ray0.direction * s) - (ray1.direction * t); return wc.DotProduct(wc); } Real DistanceSquared(const Ray& ray, const Vector3& point, Real& t) { Vector3 w = point - ray.position; Real proj = w.DotProduct(ray.direction); // origin is closest point if (proj <= 0) { t = 0.0f; return w.DotProduct(w); } // else use normal line check Real vsq = ray.direction.DotProduct(ray.direction); t = proj / vsq; return w.DotProduct(w) - (proj * t); } Real DistanceSquared(const Ray& ray, const Line& line, Real& s, Real& t) { Vector3 w0 = ray.position - line.position; Real rd_dot_rd = ray.direction.DotProduct(ray.direction); Real rd_dot_ld = ray.direction.DotProduct(line.direction); Real ld_dot_ld = line.direction.DotProduct(line.direction); Real rd_dot_w = ray.direction.DotProduct(w0); Real ld_dot_w = line.direction.DotProduct(w0); Real denominator = rd_dot_rd * ld_dot_ld - rd_dot_ld * rd_dot_ld; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { s = 0.0f; t = ld_dot_w / ld_dot_ld; // compute difference vector and distance squared Vector3 wc = w0 - t * line.direction; return wc.DotProduct(wc); } // clamp s_c within [0,1] Real sn = rd_dot_ld * ld_dot_w - ld_dot_ld * rd_dot_w; // clamp s_c to 0 if (sn < 0.0f) { s = 0.0f; t = ld_dot_w / ld_dot_ld; } // clamp s_c to 1 else if (sn > denominator) { s = 1.0f; t = (ld_dot_w + rd_dot_ld) / ld_dot_ld; } else { s = sn / denominator; t = (rd_dot_rd * ld_dot_w - rd_dot_ld * rd_dot_w) / denominator; } // compute difference vector and distance squared Vector3 wc = w0 + s * ray.direction - t * line.direction; return wc.DotProduct(wc); } Real DistanceSquared(const Line& line, const Ray& ray, Real& s, Real& t) { return DistanceSquared(ray, line, s, t); } Vector3Pair ClosestPoint(const Ray& ray0, const Ray& ray1) { Vector3 w0 = ray0.position - ray1.position; Real r0d_dot_r0d = ray0.direction.DotProduct(ray0.direction); Real r0d_dot_r1d = ray0.direction.DotProduct(ray1.direction); Real r1d_dot_r1d = ray1.direction.DotProduct(ray1.direction); Real r0d_dot_w = ray0.direction.DotProduct(w0); Real r1d_dot_w = ray1.direction.DotProduct(w0); Real denominator = r0d_dot_r0d * r1d_dot_r1d - r0d_dot_r1d * r0d_dot_r1d; // parameters to compute s_c, t_c Real s_c, t_c; Real sn, sd, tn, td; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { sd = td = r1d_dot_r1d; sn = 0.0f; tn = r1d_dot_w; } else { // start by clamping s_c sd = td = denominator; sn = r0d_dot_r1d * r1d_dot_w - r1d_dot_r1d * r0d_dot_w; tn = r0d_dot_r0d * r1d_dot_w - r0d_dot_r1d * r0d_dot_w; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = r1d_dot_w; td = r1d_dot_r1d; } } // clamp t_c within [0,+inf] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if (-r0d_dot_w < 0.0f) { s_c = 0.0f; } else { s_c = -r0d_dot_w / r0d_dot_r0d; } } else { t_c = tn / td; s_c = sn / sd; } // compute closest points return Vector3Pair(ray0.position + s_c * ray0.direction, ray1.position + t_c * ray1.direction); } Vector3Pair ClosestPoint(const Ray& ray, const Line& line) { // compute intermediate parameters Vector3Pair result; Vector3 w0 = ray.position - line.position; Real rd_dot_rd = ray.direction.DotProduct(ray.direction); Real rd_dot_ld = ray.direction.DotProduct(line.direction); Real ld_dot_ld = line.direction.DotProduct(line.direction); Real rd_dot_w = ray.direction.DotProduct(w0); Real ld_dot_w = line.direction.DotProduct(w0); Real denominator = rd_dot_rd * ld_dot_ld - rd_dot_ld * rd_dot_ld; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { // compute closest points result.a = ray.position; result.b = line.position + (ld_dot_w / ld_dot_ld) * line.direction; } else { // parameters to compute s_c, t_c Real s_c, t_c; // clamp s_c within [0,1] Real sn = rd_dot_ld * ld_dot_w - ld_dot_ld * rd_dot_w; // clamp s_c to 0 if (sn < 0.0f) { s_c = 0.0f; t_c = ld_dot_w / ld_dot_ld; } // clamp s_c to 1 else if (sn > denominator) { s_c = 1.0f; t_c = (ld_dot_w + rd_dot_ld) / ld_dot_ld; } else { s_c = sn / denominator; t_c = (rd_dot_rd * ld_dot_w - rd_dot_ld * rd_dot_w) / denominator; } // compute closest points result.a = ray.position + s_c * ray.direction; result.b = line.position + t_c * line.direction; } return result; } }
[ "p084111@gmail.com" ]
p084111@gmail.com
935b7906fa0d013ab04fbad50b0109663462b879
3dca688178c70e5f1469763682f344d2aa2a3a89
/HihoCoder/1014.cpp
cad32503b43cb85f0a5b058e50560b20037c5d78
[]
no_license
Jokeren/OnlineJudge
cbfa422dd62c18f29c7f240c7936891a5ba8c8de
6759791b2cff3872b8dbefc064d543ed18df8296
refs/heads/master
2020-05-20T13:48:45.245018
2015-04-19T05:44:34
2015-04-19T05:44:34
32,642,030
0
0
null
null
null
null
UTF-8
C++
false
false
2,561
cpp
#define _USE_MATH_DEFINES #ifdef ONLINE_JUDGE #define FINPUT(file) 0 #define FOUTPUT(file) 0 #else #define FINPUT(file) freopen(file,"r",stdin) #define FOUTPUT(file) freopen(file,"w",stdout) #endif #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <ctime> #include <set> #include <stack> #include <string> #include <map> #include <vector> #include <queue> #include <algorithm> #include <functional> #include <bitset> typedef long long ll; typedef long double ld; static const int N = 1000100; static const int M = 19; static const int LEN = 50; static const int MAX = 0x7fffffff; static const int GMAX = 0x3f3f3f3f; static const ll LGMAX = 0x3f3f3f3f3f3f3f3f; static const int MIN = ~MAX; static const double EPS = 1e-9; static const ll BASE = 1000000007; static const int CH = 27; struct Trie { //N代表节点个数,通常为字符串长度*字符串个数 //数据量太大时要用new int ch[N][CH]; int value[N][CH]; int sz; Trie():sz(1) { memset(ch[0], 0, sizeof(ch[0])); memset(value[0], 0, sizeof(value[0])); } void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); memset(value[0], 0, sizeof(value[0])); } void insert(char *s, int v) { int u = 0, n = strlen(s); for (int i = 0; i < n; i++) { int c = s[i] - 'a' + 1; if (!ch[u][c]) { //大量节省时间 memset(ch[sz], 0, sizeof(ch[sz])); memset(value[sz], 0, sizeof(value[sz])); ch[u][c] = sz++; } ++value[u][c]; u = ch[u][c]; } } int search(char *s) { int u = 0, n = strlen(s); int ret; int c; for (int i = 0; i < n; i++) { c = s[i] - 'a' + 1; if (ch[u][c] != 0) { ret = value[u][c]; u = ch[u][c]; } else { return 0; } } return ret; } }; int main() { FINPUT("in.txt"); FOUTPUT("out.txt"); int n, m; //数据量太大时要用new struct Trie *trie = new Trie(); while (scanf("%d", &n) != EOF) { char str[12]; for (int i = 0; i < n; ++i) { scanf("%s", str); trie->insert(str, i); } scanf("%d", &m); for (int i = 0; i < m; ++i) { scanf("%s", str); printf("%d\n", trie->search(str)); } trie->init(); } return 0; }
[ "KerenZhou@outlook.com" ]
KerenZhou@outlook.com
458deacd30242136f570046f24a40c96a781eec5
5e3d71944ea698f673276eb9ccd5cf099f3d422c
/src/libIterativeRobot/abstractBaseClasses/PositionTracker.cpp
2a67d5ec06d69b25e2ba30127ba6c09163470cce
[]
no_license
1138programming/2018-2019-VEX-1138C-Redemption
7e1533d1f5fb0cf394d734d6e8b3f0f0f551a0e8
bea4f343786092472031a79ffc03b784eef7fc2a
refs/heads/master
2020-04-06T21:11:45.215021
2019-02-24T18:50:58
2019-02-24T18:50:58
157,795,757
1
0
null
null
null
null
UTF-8
C++
false
false
3,009
cpp
#include "abstractBaseClasses/PositionTracker.h" PositionTracker::PositionTracker(Motor* leftMotor, Motor* rightMotor, pros::ADIEncoder* backEncoder, float leftDist, float rightDist, float backDist, float wheelRadius, int ticksPerRev) { this->leftMotor = leftMotor; this->rightMotor = rightMotor; this->backEncoder = backEncoder; this->leftDist = leftDist; this->rightDist = rightDist; this->backDist = backDist; this->wheelRadius = wheelRadius; this->ticksPerRev = ticksPerRev; currentLeftEncoderValue = 0; currentRightEncoderValue = 0; currentBackEncoderValue = 0; previousLeftEncoderValue = 0; previousRightEncoderValue = 0; previousBackEncoderValue = 0; deltaLeftEncoderValue = 0; deltaRightEncoderValue = 0; deltaBackEncoderValue = 0; initialAngle = 0; absoluteAngle = 0; previousAngle = 0; deltaAngle = 0; averageAngle = 0; localXOffset = 0; localYOffset = 0; globalXOffset = 0; globalYOffset = 0; previousXOffset = 0; previousYOffset = 0; currentX = 0; currentY = 0; } float PositionTracker::ticksToInches(int ticks) { float c = M_PI * wheelRadius * wheelRadius; return c * (ticks / ticksPerRev); } void PositionTracker::update() { currentLeftEncoderValue = leftMotor->getEncoderValue(); currentRightEncoderValue = rightMotor->getEncoderValue(); currentBackEncoderValue = backEncoder->get_value(); deltaLeftEncoderValue = currentLeftEncoderValue - previousLeftEncoderValue; deltaRightEncoderValue = currentLeftEncoderValue - previousRightEncoderValue; deltaBackEncoderValue = currentBackEncoderValue - previousBackEncoderValue; previousLeftEncoderValue = currentLeftEncoderValue; previousRightEncoderValue = currentRightEncoderValue; previousBackEncoderValue = currentBackEncoderValue; absoluteAngle = initialAngle + (ticksToInches(deltaLeftEncoderValue) - ticksToInches(deltaRightEncoderValue)) / (leftDist + rightDist); deltaAngle = absoluteAngle - previousAngle; previousAngle = absoluteAngle; if (deltaAngle == 0) { localXOffset = deltaBackEncoderValue; localYOffset = deltaRightEncoderValue; } else { localXOffset = 2 * sin(deltaAngle / 2) * ((deltaBackEncoderValue / deltaAngle) + backDist); localYOffset = 2 * sin(deltaAngle / 2) * ((deltaRightEncoderValue / deltaAngle) + rightDist); } averageAngle = absoluteAngle + deltaAngle / 2; float radius = sqrt((localXOffset * localXOffset) + (localYOffset * localYOffset)); float angle = atan(localYOffset / localXOffset); float newAngle = angle - averageAngle; globalXOffset = radius * cos(newAngle); globalYOffset = radius * sin(newAngle); currentX = globalXOffset + previousXOffset; currentY = globalYOffset + previousYOffset; previousXOffset = globalXOffset; previousYOffset = globalYOffset; } float PositionTracker::getCurrentXPosition() { return currentX; } float PositionTracker::getCurrentYPosition() { return currentY; } float PositionTracker::getCurrentAngle() { return absoluteAngle; }
[ "CDCheek22@chaminet.org" ]
CDCheek22@chaminet.org
ffeb1e40bda9195a71b9e93f296a6f8ade9c312a
d6b742de2c20c67e2afcb36fa8f4b0b5deb78c77
/plotscript.cpp
07d8365e01863697400e3164ecc3803d802bfa1b
[]
no_license
hqt286/Plot-Script
a58e4a97261d903bddbdd6577599111c24b75200
cb8babc0f644bb1b3e17163e5cd14fd1991918de
refs/heads/master
2020-04-12T04:48:54.427447
2018-12-18T16:22:22
2018-12-18T16:22:22
162,306,552
1
0
null
null
null
null
UTF-8
C++
false
false
4,251
cpp
#include <string> #include <sstream> #include <iostream> #include <fstream> #include <thread> #include "startup_config.hpp" #include "interpreter.hpp" #include "semantic_error.hpp" #include "cntlc_tracer.hpp" typedef message_queue<std::string> MessageQueueStr; void repl(Interpreter interp); void prompt() { std::cout << "\nplotscript> "; } std::string readline() { std::string line; std::getline(std::cin, line); return line; } void error(const std::string & err_str) { std::cerr << "Error: " << err_str << std::endl; } void info(const std::string & err_str) { std::cout << "Info: " << err_str << std::endl; } int eval_from_stream(std::istream & stream, std::string filename) { Interpreter interp; if (!interp.parseStream(stream)) { error("Invalid Program. Could not parse."); return EXIT_FAILURE; } else { try { Expression exp = interp.evaluate(); std::cout << exp << std::endl; } catch (const SemanticError & ex) { std::cerr << ex.what() << std::endl; return EXIT_FAILURE; } } if (filename == STARTUP_FILE) repl(interp); return EXIT_SUCCESS; } int eval_from_file(std::string filename) { std::ifstream ifs(filename); if (!ifs) { error("Could not open file for reading."); return EXIT_FAILURE; } return eval_from_stream(ifs, filename); } int eval_from_command(std::string argexp) { std::istringstream expression(argexp); return eval_from_stream(expression, "no_file"); } void ProcessData(MessageQueueStr * msgIn, MessageQueueStr * msgOut, Interpreter * interp) { while (1) { std::string popMessage; msgIn->wait_and_pop(popMessage); if (popMessage == "%stop") break; std::istringstream expMsg(popMessage); std::ostringstream textOutput; if (!interp->parseStream(expMsg)) { msgOut->push("Invalid Expression. Could not parse."); } else { try { Expression exp = interp->evaluate(); textOutput << exp; msgOut->push(textOutput.str()); } catch (const SemanticError & ex) { textOutput << ex.what(); msgOut->push(textOutput.str()); } } } } // A REPL is a repeated read-eval-print loop void repl(Interpreter interp) { bool reset = false; install_handler(); while (1) { global_status_flag = 0; Interpreter InscopeInterp(interp); MessageQueueStr * msgIn = new MessageQueueStr(); MessageQueueStr * msgOut = new MessageQueueStr(); bool KernalRunning = true; std::thread * worker; worker = new std::thread(ProcessData, msgIn, msgOut, &InscopeInterp); std::string textOutput; while (!std::cin.eof()) { if (reset) { reset = false; break; } prompt(); std::string line = readline(); if (line.empty()) continue; if (line == "%exit") { msgIn->push("%stop"); worker->join(); return; } if (line == "%stop" && KernalRunning == true) { msgIn->push(line); worker->join(); KernalRunning = false; } else if (line == "%start" && KernalRunning == false) { worker = new std::thread(ProcessData, msgIn, msgOut, &InscopeInterp); KernalRunning = true; } else if (line == "%reset") { if (KernalRunning == true) { msgIn->push("%stop"); worker->join(); } reset = true; } else if (KernalRunning == false) { std::cout << "Error: interpreter kernel not running"; continue; } else { msgIn->push(line); while (!msgOut->try_pop(textOutput)) { if (global_status_flag > 0) { global_status_flag = 0; std::cout << "Error: interpreter kernel interrupted"; msgIn->push("%stop"); worker->detach(); worker->~thread(); msgIn = new MessageQueueStr(); msgOut = new MessageQueueStr(); InscopeInterp = interp; worker = new std::thread(ProcessData, msgIn, msgOut, &InscopeInterp); break; } if (msgOut->try_pop(textOutput)) break; } std::cout << textOutput; } } } } int main(int argc, char *argv[]) { if (argc == 2) { return eval_from_file(argv[1]); } else if (argc == 3) { if (std::string(argv[1]) == "-e") { return eval_from_command(argv[2]); } else { error("Incorrect number of command line arguments."); } } else { eval_from_file(STARTUP_FILE); } return EXIT_SUCCESS; }
[ "hqt286@vt.edu" ]
hqt286@vt.edu
31e6f12a2149c21297c193403f899b0ad7472938
e56923b83be1f888f1a36877c904efc5e92341d6
/BreathDetectionSystem/src/forandroid/CommBase/jni/include/TCPConnector.h
c1acc506618e636e40c05d11344d8f6522c398fc
[]
no_license
IFrestart/Breath
12671279452d2c69298b5f8682013424b5a6f9ae
d93701f1caf228fe39a1c53651ee59705390736f
refs/heads/master
2020-06-19T23:36:43.916392
2019-07-16T02:01:17
2019-07-16T02:01:17
196,914,017
0
0
null
null
null
null
GB18030
C++
false
false
5,962
h
/** * Copyright (c) 2004, HangZhou Webcon Corporation. * 被动TCP类,提供被动TCP的建立,关闭,发送数据等操作 * @file TCPConnector.h * @short 被动TCP类 * @author zhoujj <zhoujj@webcon.com.cn> * @class CTCPConnector * @short 被动TCP类 **/ #ifndef __TCPCONNECTOR_H__ #define __TCPCONNECTOR_H__ #include "Timer.h" #include "BaseACObject.h" #include "ACCommMainObject.h" //#include "HighCommCon.h" class IACMainObject; //class CACPackHead; class CSockHeader; // 包装MyAcDll中UDP和TCP连接套接字 class CTCPConnector { public: /** 构造函数 */ CTCPConnector(ISockEventCallBack* pCallBack=0); /** 析构函数 */ ~CTCPConnector(void); /** * 创建一个TCP socket * @param ipstr socket要连接到的IP,字符串 * @param port socket要连接到的端口号 * @param pSockEventCallBack 处理TCP事件的回调接口 * @return 成功则返回0 */ int create(const char* ipstr, unsigned short port, ISockEventCallBack* pSockEventCallBack= 0); /** * 创建一个TCP socket * @param ip socket要连接到的IP * @param port socket要连接到的端口号 * @param pSockEventCallBack 处理TCP事件的回调接口 * @return 成功则返回0 */ int create(unsigned long ip, unsigned short port, ISockEventCallBack* pSockEventCallBack= 0); /** * 关闭TCP socket * @return 成功则返回0 */ int close(); /** * 通过TCP socket发送数据 * @param pdutype socket要发送数据的PDU类型 * @param data socket要发送的数据 * @param len socket要发送数据的长度 * @return 成功则返回0 */ int sendPacket(unsigned short pdutype, const void* data, unsigned long len); /** * 返回TCP socket底层的FD * @return 不成功则返回-1 */ ACE_HANDLE getSock() const; #if 0 /** 启动通信对象(不使用代理) * @param wProtoType 通信对象类型(SOCK_STREAM-TCP, SOCK_DGRAM-UDP) * @param lpLocalHost 本机IP * @param nLocalPort 本机端口 * @param lpszSvrAddr 服务器IP * @param nSvrPort 服务器端口 * @param bUseHttp 是否使用HTTP协议(当用HTTP代理或HTTP协议登陆后, 建立点对点连接时,如双方在同一局域网,则为FALSE,其它情况为TRUE) * @param bMulPoint 是否组播 * @return 0-成功, <0失败 */ int Start(WORD wProtoType, LPCTSTR lpLocalHost, USHORT nLocalPort, LPCTSTR lpszSvrAddr, USHORT nSvrPort, BOOL bUseHttp,BOOL bMulPoint=FALSE); /** 启动通信对象(使用SOCK5代理) * @param wProtoType 通信对象类型(SOCK_STREAM-TCP, SOCK_DGRAM-UDP) * @param lpLocalHost 本机IP * @param nLocalPort 本机端口 * @param lpszSvrAddr 服务器IP * @param nSvrPort 服务器端口 * @param lpProxyAddr 代理服务器IP * @param nProxyPort 代理服务器端口 * @param lpProxyUserName 代理用户名 * @param lpProxyPassword 代理密码 * @return 0-成功, <0失败 */ int StartSock5(WORD wProtoType, LPCTSTR lpLocalHost, USHORT nLocalPort, LPCTSTR lpszSvrAddr, USHORT nSvrPort, LPCTSTR lpProxyAddr, USHORT nProxyPort, LPCTSTR lpProxyUserName, LPCTSTR lpProxyPassword); /** 启动通信对象(使用HTTP代理) * @param wProtoType 通信对象类型(SOCK_STREAM-TCP, SOCK_DGRAM-UDP) * @param lpLocalHost 本机IP * @param nLocalPort 本机端口 * @param lpszSvrAddr 服务器IP * @param nSvrPort 服务器端口 * @param lpProxyAddr 代理服务器IP * @param nProxyPort 代理服务器端口 * @param lpProxyUserName 代理用户名 * @param lpProxyPassword 代理密码 * @return 0-成功, <0失败 */ int StartHttp(WORD wProtoType, LPCTSTR lpLocalHost, USHORT nLocalPort, LPCTSTR lpszSvrAddr, USHORT nSvrPort, LPCTSTR lpProxyAddr, USHORT nProxyPort, LPCTSTR lpProxyUserName, LPCTSTR lpProxyPassword); /** UDP通信对象发送数据 * @param wPduType 数据包的PDU类别 * @param lpData 要发送的数据 * @param dwSize 数据长度 * @param bSync 是否同步发送(目前只支持同步发送) * @param lpRemoteHost 接收方的IP * @param nRemotePort 接收方的端口 * @param wExtParam 扩展参数(用于程序调试) * @param bSock5Flag 如果用SOCK5登陆到服务器,点对点连接间发送数据是否加 SOCK5头(当双方在同一局域网时,应为FALSE) */ int SendCommUDPData(WORD wPduType, const BYTE* lpData, DWORD dwSize, BOOL bSync, LPCTSTR lpRemoteHost, USHORT nRemotePort, WORD wExtParam, BOOL bSock5Flag); /** TCP通信对象发送数据 * @param wPduType 数据包的PDU类别 * @param lpData 要发送的数据 * @param dwSize 数据长度 * @param bSync 是否同步发送(目前只支持同步发送) * @param hSocket 本参数不使用 */ int SendCommTCPData(WORD wPduType, const BYTE* lpData, DWORD dwSize, BOOL bSync, SOCKET hSocket= INVALID_SOCKET); #endif /** 停止通信对象 */ void Stop(int nType=0); ///** 获取本机IP //*/ //LPCTSTR GetLocalHost(void) const; ///** 获取本机子网掩码 //*/ //LPCTSTR GetLocalMask(void) const; ///** 获取本地端口 //*/ //USHORT GetLocalPort(void); ///** 获取通信对象的套接字句柄 //*/ //SOCKET GetSocket(void); /*关闭Socket * */ // void CloseConnect(); //void CloseConnect(SOCKET hSocket); void setHeadFlag(bool flag) {m_bHeadFlag = flag;}//add 2012-10-18 int GetExitType(); private: /** 删除通信对象(不用线程删除) */ void FreeObject(void); /** 停止通信对象实现线程 */ #ifdef _WIN32 static DWORD WINAPI StopThreadHelper(LPVOID lpParam); static DWORD WINAPI StopMyselfThreadHelper(LPVOID lpParam); #else static void* StopThreadHelper(LPVOID lpParam); static void* StopMyselfThreadHelper(LPVOID lpParam); #endif IACMainObject* m_pAcCommObj; ///< MyAcDll通信对象接口 ISockEventCallBack* m_pCallBack; ///< 数据回调接口实现对象 //CACPackHead* m_pHeadInfo; ///< 数据包头处理对象 CSockHeader* m_pHeadInfo; ///< 数据包头处理对象 int m_nExitType; bool m_bHeadFlag; //add 2012-10-18 }; #endif /*__TCPCONNECTOR_H__*/
[ "782117205@qq.com" ]
782117205@qq.com
511df78768ddfc0863ff29e00ad0c5763f02fc74
942e6d29b3e6193c8541b31140ea9aef5554379b
/Sources/Inputs/ButtonMouse.cpp
ad84f4e0b33bf9bda0750a06d9f7db20f00de37e
[ "MIT" ]
permissive
hhYanGG/Acid
e7da2457bdd5820f7cba38b1602762f426dbd849
f5543e9290aee5e25c6ecdafe8a3051054b203c0
refs/heads/master
2020-03-27T13:11:56.488574
2018-08-28T17:47:35
2018-08-28T18:10:46
146,595,670
1
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#include "ButtonMouse.hpp" namespace acid { ButtonMouse::ButtonMouse(const std::vector<MouseButton> &buttons) : IButton(), m_buttons(buttons), m_wasDown(false) { } ButtonMouse::~ButtonMouse() { } bool ButtonMouse::IsDown() const { if (Mouse::Get() == nullptr) { return false; } for (auto &button : m_buttons) { if (Mouse::Get()->GetButton(button)) { return true; } } return false; } bool ButtonMouse::WasDown() { bool stillDown = m_wasDown && IsDown(); m_wasDown = IsDown(); return m_wasDown == !stillDown; } }
[ "mattparks5855@gmail.com" ]
mattparks5855@gmail.com
094d0f0a877564aeac36fa8e32505a80f4934f43
b6790e0d113b82bf0064220d0b469cfe77d21d78
/Source/tasks/VideoUpdate.cpp
85fb6afbb45068532025ed169d3ba71835f765bd
[]
no_license
spykedood/Oh-My-Buddha
e2c2a4d0ae5a39958cca8e3f0de2b31438b5c2e7
20c632c55afda0482267c7d4528f88c387c2098d
refs/heads/master
2021-01-17T12:19:23.311953
2012-10-17T20:16:14
2012-10-17T20:16:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,610
cpp
#include <SDL.h> #include <SDL_ttf.h> #include <GL/glew.h> #include "VideoUpdate.h" #include "../game.h" #include "../utilities/VarManager.h" #include "../utilities/xml.h" #include "../utilities/types.h" int VideoUpdate::scrWidth; int VideoUpdate::scrHeight; int VideoUpdate::scrBPP; int VideoUpdate::fullScrn; bool VideoUpdate::scrResized; VideoUpdate::VideoUpdate() { } VideoUpdate::~VideoUpdate() { } bool VideoUpdate::Start() { SINGLETON_GET(VarManager, var) XMLFile file; GET_PATH("\\Data\\", path) if (file.load(path + "Settings\\omb.cfg")) { file.setElement("graphics"); scrWidth = file.readInt("graphics", "width"); scrHeight = file.readInt("graphics", "height"); scrBPP = file.readInt("graphics", "bpp"); fullScrn = (file.readString("graphics", "fullscreen") == "true") ? true : false; } else { const SDL_VideoInfo* video = SDL_GetVideoInfo(); scrWidth = 800; scrHeight = 600; scrBPP = 32;// video->vfmt->BitsPerPixel; fullScrn = false; } screenWidth = scrWidth; var.set("win_width", scrWidth); screenHeight=scrHeight; var.set("win_height", scrHeight); screenBPP=scrBPP; fullScreen=fullScrn; var.set("win_fullScreen", fullScrn); scrResized = false; if(-1==SDL_InitSubSystem(SDL_INIT_VIDEO)) { printf("Error: %c", SDL_GetError()); return false; } SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // Set title to build stamp and set icon SDL_WM_SetCaption("Oh My Buddha!", "OMB"); std::string myIcon = path + "OMG.ico"; SDL_Surface* Icon = SDL_LoadBMP(myIcon.c_str()); SDL_WM_SetIcon(Icon, NULL); if(fullScrn != true){ flags = SDL_OPENGL | SDL_RESIZABLE | SDL_ASYNCBLIT | SDL_HWSURFACE; SDL_putenv("SDL_VIDEO_CENTERED=center"); //Center the game Window }else{ flags = SDL_OPENGL | SDL_ANYFORMAT | SDL_FULLSCREEN | SDL_HWSURFACE; } if( ( SDL_SetVideoMode(scrWidth, scrHeight, scrBPP, flags) ) == false ) { printf("Error: SDL_SetVideoMode(%i, %i, %i) : %s", scrWidth, scrHeight, scrBPP, SDL_GetError()); return false; } // Hide the mouse cursor SDL_ShowCursor(var.getb("mouseEnabled")); // Enable fonts if (TTF_Init() == -1) printf("ERROR: TTF_Init() : %s", TTF_GetError()); // Enable GLEW for Shaders GLenum err = glewInit(); if (GLEW_OK != err) printf("ERROR: TTF_Init() : %s", glewGetErrorString(err)); return true; } void VideoUpdate::Update() { SINGLETON_GET(VarManager, var) // Check for window events SDL_Event test_event; while(SDL_PollEvent(&test_event)) { switch (test_event.type) { case SDL_ACTIVEEVENT: if( ( test_event.active.state & SDL_APPACTIVE ) || ( test_event.active.state & SDL_APPINPUTFOCUS ) ) // ICONIFIED or restored { if( test_event.active.gain == 0 ) { var.set("hasFocus", false); var.set("mouseEnabled", true); } else { var.set("hasFocus", true); var.set("mouseEnabled", false); } } break; case SDL_VIDEORESIZE: // Adjusted screen size. scrWidth = test_event.resize.w; var.set("win_width", scrWidth); scrHeight = test_event.resize.h; var.set("win_height", scrHeight); scrResized = true; break; case SDL_QUIT: // Pressed 'x'. exit(0); break; } } // Show or hide mouse SDL_ShowCursor(var.getb("mouseEnabled")); SDL_GL_SwapBuffers(); } void VideoUpdate::Stop() { SDL_QuitSubSystem(SDL_INIT_VIDEO); //TODO: FIX ON EXIT ERROR TTF_Quit(); }
[ "msleith@cngames.co.uk" ]
msleith@cngames.co.uk
19fe69fae6ecd207e5804b903b11d656270b8135
4ed0e03a070b86faa1b031ff88ad488f032dd91e
/dart_microtask_queue.h
bcb0427af8d37ef34d0679f9d059c237e8069734
[ "BSD-3-Clause" ]
permissive
canluhuang/tonic
a83df0666225e66b01501e454b6db8d65a32c821
7bdb116b60aebc4200823147d6986037faab43f0
refs/heads/main
2023-03-16T16:53:04.455969
2021-03-03T13:03:46
2021-03-03T13:03:46
344,128,393
0
0
null
null
null
null
UTF-8
C++
false
false
992
h
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_TONIC_DART_MICROTASK_QUEUE_H_ #define LIB_TONIC_DART_MICROTASK_QUEUE_H_ #include <vector> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/dart_persistent_value.h" #include "tonic/logging/dart_error.h" namespace tonic { class DartMicrotaskQueue { public: DartMicrotaskQueue(); ~DartMicrotaskQueue(); static void StartForCurrentThread(); static DartMicrotaskQueue* GetForCurrentThread(); void ScheduleMicrotask(Dart_Handle callback); void RunMicrotasks(); void Destroy(); bool HasMicrotasks() const { return !queue_.empty(); } DartErrorHandleType GetLastError(); private: typedef std::vector<DartPersistentValue> MicrotaskQueue; DartErrorHandleType last_error_; MicrotaskQueue queue_; }; } // namespace tonic #endif // LIB_TONIC_DART_MICROTASK_QUEUE_H_
[ "lukehuang@tencent.com" ]
lukehuang@tencent.com
239d1e454cf30f5a03d73cc40ff71e8dc4c85353
2dfbb17960cc1ad86163abdba8ab380554ca635a
/src/utiltime.h
eded248c4af480eb228d19dcccabe9d4c7f28f00
[ "MIT" ]
permissive
liray-unendlich/ZENZO-Core
1bdba73696f63ccec16d04bf4189f55b07c9de78
b6d449447a675e1307f0c02e36daaf5c1afb67ae
refs/heads/master
2020-04-13T16:08:23.460161
2018-10-13T19:25:07
2018-10-13T19:25:07
163,313,550
0
0
MIT
2018-12-27T16:08:07
2018-12-27T16:08:07
null
UTF-8
C++
false
false
705
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The PIVX developers // Copyright (c) 2017 The Zenzo developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTILTIME_H #define BITCOIN_UTILTIME_H #include <stdint.h> #include <string> int64_t GetTime(); int64_t GetTimeMillis(); int64_t GetTimeMicros(); void SetMockTime(int64_t nMockTimeIn); void MilliSleep(int64_t n); std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); std::string DurationToDHMS(int64_t nDurationTime); #endif // BITCOIN_UTILTIME_H
[ "info@zenzo.io" ]
info@zenzo.io
f83556b84f13c6a8e889a825d49e472a39d8b749
987fa85ca5b7db9806e698f6947714de6be9f7a6
/Personal/backup4/gameBackup/src/ShaderProgram.cpp
6f5e84b0823843534b5f4b148fa5a79442fb22be
[]
no_license
mynameisjohn/code
89a711c554766a354f7268d714ddbda183e9dd6c
14f0fd704e13939e71d2bdd17862573eff32ef9d
refs/heads/master
2021-01-15T12:19:10.912281
2014-09-02T23:10:55
2014-09-02T23:10:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,395
cpp
//also ripped off of lazy foo #include "ShaderProgram.h" ShaderProgram::ShaderProgram(){ mProgramID = (GLuint)NULL; } ShaderProgram::~ShaderProgram(){ freeProgram(); } void ShaderProgram::freeProgram(){ glDeleteProgram(mProgramID); } bool ShaderProgram::bind(){ glUseProgram(mProgramID); GLenum err = glGetError(); if (err != GL_NO_ERROR){ printf( "Error binding shader! %s\n", gluErrorString(err)); printProgramLog(mProgramID); return false; } return true; } void ShaderProgram::unbind(){ glUseProgram((GLuint)NULL); } GLuint ShaderProgram::getProgramID(){ return mProgramID; } void ShaderProgram::printProgramLog(GLuint program){ if (glIsProgram(program)){ int infoLogLength=0, maxLength=0; char * infoLog; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); infoLog = new char[maxLength]; glGetProgramInfoLog(program,maxLength,&infoLogLength,infoLog); if (infoLogLength>0) printf("%s\n", infoLog); delete[] infoLog; } else printf("%d did not reference a program. \n",program); return; } void ShaderProgram::printShaderLog(GLuint shader){ if (glIsShader(shader)){ int infoLogLength=0, maxLength=0; char * infoLog; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); infoLog = new char[maxLength]; glGetShaderInfoLog(shader,maxLength,&infoLogLength,infoLog); if (infoLogLength>0) printf("%s\n", infoLog); delete[] infoLog; } else printf("%d did not reference a shader. \n",shader); return; } GLuint ShaderProgram::loadShaderFromFile(std::string path, GLenum shaderType){ GLuint shaderID=0; std::string shaderString; std::ifstream sourceFile(path.c_str()); if (sourceFile){ shaderString.assign((std::istreambuf_iterator<char>(sourceFile)), std::istreambuf_iterator<char>()); shaderID = glCreateShader(shaderType); const GLchar * shaderSource = shaderString.c_str(); glShaderSource(shaderID, 1, (const GLchar**)&shaderSource, NULL); glCompileShader(shaderID); GLint shaderCompiled = GL_FALSE; glGetShaderiv(shaderID, GL_COMPILE_STATUS, &shaderCompiled); if (shaderCompiled != GL_TRUE){ printf("Unable to compile shader %d!\n\nSource:\n%s\n", shaderID, shaderSource); printShaderLog(shaderID); glDeleteShader(shaderID); shaderID = 0; } } else printf( "Unable to open file %s\n", path.c_str() ); return shaderID; }
[ "mynameisjohnj@gmail.com" ]
mynameisjohnj@gmail.com
2509fdbb377a57a44bcac8d0922f53bd8b612f32
96730d79a4f1e874944869458cf76c38d5926bbf
/src/qt/miningpage.cpp
c1d9c02b0689134dff80d0594f9c50098df3cf9f
[ "MIT" ]
permissive
HorseCoinProject/Horsecoin
ae40225796570af2211da20d4af07adab101f46f
057bdf236c1d71d5986be469e1f197f345d3bc0c
refs/heads/master
2016-08-06T16:58:33.284292
2014-03-08T14:57:55
2014-03-08T14:57:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,679
cpp
#include "miningpage.h" #include "ui_miningpage.h" MiningPage::MiningPage(QWidget *parent) : QWidget(parent), ui(new Ui::MiningPage) { ui->setupUi(this); setFixedSize(400, 420); minerActive = false; minerProcess = new QProcess(this); minerProcess->setProcessChannelMode(QProcess::MergedChannels); readTimer = new QTimer(this); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; initThreads = 0; connect(readTimer, SIGNAL(timeout()), this, SLOT(readProcessOutput())); connect(ui->startButton, SIGNAL(pressed()), this, SLOT(startPressed())); connect(ui->typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeChanged(int))); connect(ui->debugCheckBox, SIGNAL(toggled(bool)), this, SLOT(debugToggled(bool))); connect(minerProcess, SIGNAL(started()), this, SLOT(minerStarted())); connect(minerProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(minerError(QProcess::ProcessError))); connect(minerProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(minerFinished())); connect(minerProcess, SIGNAL(readyRead()), this, SLOT(readProcessOutput())); } MiningPage::~MiningPage() { minerProcess->kill(); delete ui; } void MiningPage::setModel(ClientModel *model) { this->model = model; loadSettings(); bool pool = model->getMiningType() == ClientModel::PoolMining; ui->threadsBox->setValue(model->getMiningThreads()); ui->typeBox->setCurrentIndex(pool ? 1 : 0); // if (model->getMiningStarted()) // startPressed(); } void MiningPage::startPressed() { initThreads = ui->threadsBox->value(); if (minerActive == false) { saveSettings(); if (getMiningType() == ClientModel::SoloMining) minerStarted(); else startPoolMining(); } else { if (getMiningType() == ClientModel::SoloMining) minerFinished(); else stopPoolMining(); } } void MiningPage::startPoolMining() { QStringList args; QString url = ui->serverLine->text(); if (!url.contains("http://")) url.prepend("http://"); QString urlLine = QString("%1:%2").arg(url, ui->portLine->text()); QString userpassLine = QString("%1:%2").arg(ui->usernameLine->text(), ui->passwordLine->text()); args << "--algo" << "scrypt"; args << "--scantime" << ui->scantimeBox->text().toAscii(); args << "--url" << urlLine.toAscii(); args << "--userpass" << userpassLine.toAscii(); args << "--threads" << ui->threadsBox->text().toAscii(); args << "--retries" << "-1"; // Retry forever. args << "-P"; // This is needed for this to work correctly on Windows. Extra protocol dump helps flush the buffer quicker. threadSpeed.clear(); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; // If minerd is in current path, then use that. Otherwise, assume minerd is in the path somewhere. QString program = QDir::current().filePath("minerd"); if (!QFile::exists(program)) program = "minerd"; if (ui->debugCheckBox->isChecked()) ui->list->addItem(args.join(" ").prepend(" ").prepend(program)); ui->mineSpeedLabel->setText("Speed: N/A"); ui->shareCount->setText("Accepted: 0 - Rejected: 0"); minerProcess->start(program,args); minerProcess->waitForStarted(-1); readTimer->start(500); } void MiningPage::stopPoolMining() { ui->mineSpeedLabel->setText(""); minerProcess->kill(); readTimer->stop(); } void MiningPage::saveSettings() { model->setMiningDebug(ui->debugCheckBox->isChecked()); model->setMiningScanTime(ui->scantimeBox->value()); model->setMiningServer(ui->serverLine->text()); model->setMiningPort(ui->portLine->text()); model->setMiningUsername(ui->usernameLine->text()); model->setMiningPassword(ui->passwordLine->text()); } void MiningPage::loadSettings() { ui->debugCheckBox->setChecked(model->getMiningDebug()); ui->scantimeBox->setValue(model->getMiningScanTime()); ui->serverLine->setText(model->getMiningServer()); ui->portLine->setText(model->getMiningPort()); ui->usernameLine->setText(model->getMiningUsername()); ui->passwordLine->setText(model->getMiningPassword()); } void MiningPage::readProcessOutput() { QByteArray output; minerProcess->reset(); output = minerProcess->readAll(); QString outputString(output); if (!outputString.isEmpty()) { QStringList list = outputString.split("\n", QString::SkipEmptyParts); int i; for (i=0; i<list.size(); i++) { QString line = list.at(i); // Ignore protocol dump if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr")) continue; if (ui->debugCheckBox->isChecked()) { ui->list->addItem(line.trimmed()); ui->list->scrollToBottom(); } if (line.contains("(yay!!!)")) reportToList("Share accepted", SHARE_SUCCESS, getTime(line)); else if (line.contains("(booooo)")) reportToList("Share rejected", SHARE_FAIL, getTime(line)); else if (line.contains("LONGPOLL detected new block")) reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line)); else if (line.contains("Supported options:")) reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL); else if (line.contains("The requested URL returned error: 403")) reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL); else if (line.contains("HTTP request failed")) reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL); else if (line.contains("JSON-RPC call failed")) reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL); else if (line.contains("thread ") && line.contains("khash/s")) { QString threadIDstr = line.at(line.indexOf("thread ")+7); int threadID = threadIDstr.toInt(); int threadSpeedindx = line.indexOf(","); QString threadSpeedstr = line.mid(threadSpeedindx); threadSpeedstr.chop(8); threadSpeedstr.remove(", "); threadSpeedstr.remove(" "); threadSpeedstr.remove('\n'); double speed=0; speed = threadSpeedstr.toDouble(); threadSpeed[threadID] = speed; updateSpeed(); } } } } void MiningPage::minerError(QProcess::ProcessError error) { if (error == QProcess::FailedToStart) { reportToList("Miner failed to start. Make sure you have the minerd executable and libraries in the same directory as HorseCoin-Qt.", ERROR, NULL); } } void MiningPage::minerFinished() { if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining stopped.", ERROR, NULL); else reportToList("Miner exited.", ERROR, NULL); ui->list->addItem(""); minerActive = false; resetMiningButton(); model->setMining(getMiningType(), false, initThreads, 0); } void MiningPage::minerStarted() { if (!minerActive) if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining started.", ERROR, NULL); else reportToList("Miner started. You might not see any output for a few minutes.", STARTED, NULL); minerActive = true; resetMiningButton(); model->setMining(getMiningType(), true, initThreads, 0); } void MiningPage::updateSpeed() { double totalSpeed=0; int totalThreads=0; QMapIterator<int, double> iter(threadSpeed); while(iter.hasNext()) { iter.next(); totalSpeed += iter.value(); totalThreads++; } // If all threads haven't reported the hash speed yet, make an assumption if (totalThreads != initThreads) { totalSpeed = (totalSpeed/totalThreads)*initThreads; } QString speedString = QString("%1").arg(totalSpeed); QString threadsString = QString("%1").arg(initThreads); QString acceptedString = QString("%1").arg(acceptedShares); QString rejectedString = QString("%1").arg(rejectedShares); QString roundAcceptedString = QString("%1").arg(roundAcceptedShares); QString roundRejectedString = QString("%1").arg(roundRejectedShares); if (totalThreads == initThreads) ui->mineSpeedLabel->setText(QString("Speed: %1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); else ui->mineSpeedLabel->setText(QString("Speed: ~%1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); ui->shareCount->setText(QString("Accepted: %1 (%3) - Rejected: %2 (%4)").arg(acceptedString, rejectedString, roundAcceptedString, roundRejectedString)); model->setMining(getMiningType(), true, initThreads, totalSpeed*1000); } void MiningPage::reportToList(QString msg, int type, QString time) { QString message; if (time == NULL) message = QString("[%1] - %2").arg(QTime::currentTime().toString(), msg); else message = QString("[%1] - %2").arg(time, msg); switch(type) { case SHARE_SUCCESS: acceptedShares++; roundAcceptedShares++; updateSpeed(); break; case SHARE_FAIL: rejectedShares++; roundRejectedShares++; updateSpeed(); break; case LONGPOLL: roundAcceptedShares = 0; roundRejectedShares = 0; break; default: break; } ui->list->addItem(message); ui->list->scrollToBottom(); } // Function for fetching the time QString MiningPage::getTime(QString time) { if (time.contains("[")) { time.resize(21); time.remove("["); time.remove("]"); time.remove(0,11); return time; } else return NULL; } void MiningPage::enableMiningControls(bool enable) { ui->typeBox->setEnabled(enable); ui->threadsBox->setEnabled(enable); ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } void MiningPage::enablePoolMiningControls(bool enable) { ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } ClientModel::MiningType MiningPage::getMiningType() { if (ui->typeBox->currentIndex() == 0) // Solo Mining { return ClientModel::SoloMining; } else if (ui->typeBox->currentIndex() == 1) // Pool Mining { return ClientModel::PoolMining; } return ClientModel::SoloMining; } void MiningPage::typeChanged(int index) { if (index == 0) // Solo Mining { enablePoolMiningControls(false); } else if (index == 1) // Pool Mining { enablePoolMiningControls(true); } } void MiningPage::debugToggled(bool checked) { model->setMiningDebug(checked); } void MiningPage::resetMiningButton() { ui->startButton->setText(minerActive ? "Stop Mining" : "Start Mining"); enableMiningControls(!minerActive); }
[ "jack@jack-desktop.(none)" ]
jack@jack-desktop.(none)
c00565dd227c6261c032f7218e7ebc2856af1143
1da7dac0da7bbfab25ffd47b6ef898e42365af25
/src/fpLineSpectrum.h
669fd58e58b6361b41a82fe98411f13a5d7b82fc
[ "Apache-2.0" ]
permissive
pixlise/piquant
a32e9a6dab8115bc6a601bac4b6efa4bebe2395a
a534d67ee84734fff746e6bdce0df8a1c3f72926
refs/heads/main
2023-04-13T21:21:07.518073
2023-03-24T11:02:43
2023-03-24T11:02:43
520,582,671
3
0
Apache-2.0
2023-03-24T11:02:45
2022-08-02T17:04:14
C
UTF-8
C++
false
false
2,647
h
// Copyright (c) 2018-2022 California Institute of Technology (“Caltech”) and // University of Washington. U.S. Government sponsorship acknowledged. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Caltech nor its operating division, the Jet Propulsion // Laboratory, nor the names of its contributors may be used to endorse or // promote products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef fpLineSpectrum_h #define fpLineSpectrum_h #include <vector> #include "XrayLines.h" #include "XraySpectrum.h" #include "XrayDetector.h" // Info for consolidated emission lines, used for tails, shelf, and pileup effects struct LineGroup { float energy = 0; float intensity = 0; int number = 0; float tail_sum = 0; string symbol; }; // Generates calculated spectrum from Xray Lines object that has been loaded with intensity factor // Calculation is Gaussian with fwhm as input, integral matches line intensity // Calculated spectrum is counts in each channel // Added check for zero or negative energy at low channels Dec. 12, 2011 void fpLineSpectrum( const XrayLines &lines_in, const XrayDetector detector, const float threshold_in, const XrayEnergyCal &cal_in, const float eMin, std::vector <LineGroup> &pileup_list, SpectrumComponent &component_out ); #endif
[ "tom@spicule.co.uk" ]
tom@spicule.co.uk
e945f13a1afce69eeb7b9a12bbb573c0ebb22739
df3e1338171befbad80267a24c6866e97bd5f378
/Dfslab.cpp
bb12b231b0cc6ab5f4e41f810e15b381fd6a9f90
[]
no_license
Shaykat/Algorithms
1e6cf3ab7421478d7c293c340438917fa6064eb9
66960a9cc1aab35cf703ea220f9b0706e9e32afb
refs/heads/master
2021-08-20T01:02:53.538420
2017-11-27T21:54:29
2017-11-27T21:54:29
107,311,887
0
0
null
null
null
null
UTF-8
C++
false
false
1,576
cpp
#include<iostream> #include<cstdlib> #include<vector> #include<cstring> using namespace std; int matrix[100][100]; vector<int>graph[100]; int time[2][100],color[100]; int node,edge; int t=0; void dfs(int u) { color[u] = 1; time[0][u] = ++t; for(int i=0;i<node;i++) { if(matrix[u][i] == 1 && color[i] == 0) { dfs(i); } } color[u] = 2; time[1][u] = ++t; } int main() { int x,y,v; cin >> node >> edge; memset(color,0,sizeof(color)); for(int i=0;i<edge;i++) { cin >> x >> y; graph[x].push_back(y); graph[y].push_back(x); matrix[x][y] = 1; matrix[y][x] = 1; } /*for(int i=0;i<node;i++) { cout << i << " : "; for(int j=0;j<graph[i].size();j++) { cout << matrix[i][j] << " "; } cout << endl; }*/ // adjecensi matrix; /*for(int i=0;i<node;i++) { for(int j=0;j<node;j++) { if(matrix[i][j]== 1) { cout << matrix[i][j] << " " ; } cout << endl; } }*/ int component = 0; int ft,tm,n; for(int i =0;i<node;i++) { tm = t; if(color[i] == 0) { dfs(i); component ++; } ft = t - tm; cout << "number of node in component " << component << ": " << ft/2 << endl; } cout << "component :" << component << endl; //getch(); return 0; } /* 10 11 0 6 0 9 6 1 6 7 7 3 0 1 1 9 1 3 9 4 3 4 8 2 */
[ "shaykat2057@gmail.com" ]
shaykat2057@gmail.com
48e85d3fcc55a6709568cd82a8079d00b1441f80
503a8aac2364361325a9adcdbb7d27c2982c8624
/Drinks/Wine.cpp
a9cb92ecfd59b6f0ad23ef6110a72e91df2a74a6
[]
no_license
GuyOded/Driniking_Bar
19a4769c82fc1a5447b48d9501bfb24a13f6f0b4
8c778156c90126691c03c8cb25f47633c76d58e0
refs/heads/master
2021-01-10T17:44:15.265995
2016-03-01T18:19:02
2016-03-01T18:19:02
52,898,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
/* * Wine.cpp * * Created on: Feb 12, 2016 * Author: guy */ #include "Wine.h" #include <sstream> /** * * @param name-the name of the wine * @param temp-the temperature * @param year-the year the wine was made in(or aged since I think) */ Wine::Wine(std::string name, int temp, int year) :Drink(name), m_temp(temp), m_year(year) { //basically converts to string std::string temp_string; std::stringstream ss; ss << temp; ss >> temp_string; m_preparation = "Keep it in " + temp_string + " degrees celsius and serve"; } /** * copy constructor * @param other */ Wine::Wine(const Wine& other) :Drink(other.m_name, other.m_preparation), m_temp(other.m_temp), m_year(other.m_year) {} Wine::~Wine() { } /** * * @return the name plus the year in brackets */ std::string Wine::getName() { std::string year; std::stringstream ss; ss << m_year; ss >> year; return m_name + " (year " + year + ")"; } std::string Wine::prepare() { return m_preparation; } Wine* Wine::clone() const { return new Wine(*this); }
[ "itayoded1@gmail.com" ]
itayoded1@gmail.com
c7f7d149ec86bbd6623b4d4dedc8ba476590d403
9c98ce485432ed36171800011fcdce2b5ca8a04d
/employee.h
c3e2e76e81c293910c6f20eb5fca4b2d613d3839
[ "Apache-2.0" ]
permissive
MasterMaxLi/EmployeeManager
621560baadf333d3d985c5550177962543933998
a6121a53012086691de393f939853a0119e509db
refs/heads/main
2023-04-06T10:24:46.027062
2021-04-16T13:11:30
2021-04-16T13:11:30
357,537,511
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
238
h
#pragma once #include<iostream> #include"worker.h" using namespace std; class Employee :public Worker { public: //¹¹Ô캯Êý Employee(int id, string name, int dId); virtual void showInfo(); virtual string getDeptName(); };
[ "riwinkids@gmail.com" ]
riwinkids@gmail.com
fdeadfd0a2b861f2b996166eefc29efb6adf203e
6a6e8dbc2b200b730cbafbee4b075384a9fb5a11
/source/test/intltest/textfile.cpp
4bb6965ab58a9f0eaae1e23922c59511525525c2
[ "BSD-3-Clause", "ICU", "LicenseRef-scancode-unicode", "NAIST-2003", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
njlr/icu4c-2
74fc360be3c75663e6e0e2dc1fc5ddbd13d0efe2
caef63a217fd526bdcf221de949374b4c1b275cc
refs/heads/master
2021-01-20T11:09:30.606859
2017-03-30T17:26:53
2017-03-30T17:26:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,231
cpp
// Copyright (C) 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ********************************************************************** * Copyright (c) 2004,2011 International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Author: Alan Liu * Created: March 19 2004 * Since: ICU 3.0 ********************************************************************** */ #include "textfile.h" #include "cmemory.h" #include "cstring.h" #include "intltest.h" #include "util.h" // If the symbol CCP is defined, then the 'name' and 'encoding' // constructor parameters are copied. Otherwise they are aliased. // #define CCP TextFile::TextFile(const char* _name, const char* _encoding, UErrorCode& ec) : file(0), name(0), encoding(0), buffer(0), capacity(0), lineNo(0) { if (U_FAILURE(ec) || _name == 0 || _encoding == 0) { if (U_SUCCESS(ec)) { ec = U_ILLEGAL_ARGUMENT_ERROR; } return; } #ifdef CCP name = uprv_malloc(uprv_strlen(_name) + 1); encoding = uprv_malloc(uprv_strlen(_encoding) + 1); if (name == 0 || encoding == 0) { ec = U_MEMORY_ALLOCATION_ERROR; return; } uprv_strcpy(name, _name); uprv_strcpy(encoding, _encoding); #else name = (char*) _name; encoding = (char*) _encoding; #endif const char* testDir = IntlTest::getSourceTestData(ec); if (U_FAILURE(ec)) { return; } if (!ensureCapacity((int32_t)(uprv_strlen(testDir) + uprv_strlen(name) + 1))) { ec = U_MEMORY_ALLOCATION_ERROR; return; } uprv_strcpy(buffer, testDir); uprv_strcat(buffer, name); file = T_FileStream_open(buffer, "rb"); if (file == 0) { ec = U_ILLEGAL_ARGUMENT_ERROR; return; } } TextFile::~TextFile() { if (file != 0) T_FileStream_close(file); if (buffer != 0) uprv_free(buffer); #ifdef CCP uprv_free(name); uprv_free(encoding); #endif } UBool TextFile::readLine(UnicodeString& line, UErrorCode& ec) { if (T_FileStream_eof(file)) { return FALSE; } // Note: 'buffer' may change after ensureCapacity() is called, // so don't use // p=buffer; *p++=c; // but rather // i=; buffer[i++]=c; int32_t n = 0; for (;;) { int c = T_FileStream_getc(file); // sic: int, not int32_t if (c < 0 || c == 0xD || c == 0xA) { // consume 0xA following 0xD if (c == 0xD) { c = T_FileStream_getc(file); if (c != 0xA && c >= 0) { T_FileStream_ungetc(c, file); } } break; } if (!setBuffer(n++, c, ec)) return FALSE; } if (!setBuffer(n++, 0, ec)) return FALSE; UnicodeString str(buffer, encoding); // Remove BOM in first line, if present if (lineNo == 0 && str[0] == 0xFEFF) { str.remove(0, 1); } ++lineNo; line = str.unescape(); return TRUE; } UBool TextFile::readLineSkippingComments(UnicodeString& line, UErrorCode& ec, UBool trim) { for (;;) { if (!readLine(line, ec)) return FALSE; // Skip over white space int32_t pos = 0; ICU_Utility::skipWhitespace(line, pos, TRUE); // Ignore blank lines and comment lines if (pos == line.length() || line.charAt(pos) == 0x23/*'#'*/) { continue; } // Process line if (trim) line.remove(0, pos); return TRUE; } } /** * Set buffer[index] to c, growing buffer if necessary. Return TRUE if * successful. */ UBool TextFile::setBuffer(int32_t index, char c, UErrorCode& ec) { if (capacity <= index) { if (!ensureCapacity(index+1)) { ec = U_MEMORY_ALLOCATION_ERROR; return FALSE; } } buffer[index] = c; return TRUE; } /** * Make sure that 'buffer' has at least 'mincapacity' bytes. * Return TRUE upon success. Upon return, 'buffer' may change * value. In any case, previous contents are preserved. */ #define LOWEST_MIN_CAPACITY 64 UBool TextFile::ensureCapacity(int32_t mincapacity) { if (capacity >= mincapacity) { return TRUE; } // Grow by factor of 2 to prevent frequent allocation // Note: 'capacity' may be 0 int32_t i = (capacity < LOWEST_MIN_CAPACITY)? LOWEST_MIN_CAPACITY: capacity; while (i < mincapacity) { i <<= 1; if (i < 0) { i = 0x7FFFFFFF; break; } } mincapacity = i; // Simple realloc() no good; contents not preserved // Note: 'buffer' may be 0 char* newbuffer = (char*) uprv_malloc(mincapacity); if (newbuffer == 0) { return FALSE; } if (buffer != 0) { uprv_strncpy(newbuffer, buffer, capacity); uprv_free(buffer); } buffer = newbuffer; capacity = mincapacity; return TRUE; }
[ "njlr@users.noreply.github.com" ]
njlr@users.noreply.github.com
2cf42f2729cbc21d310cfcd6ee5ee3444c4b946b
e276303d11773362c146c4a6adbdc92d6dee9b3f
/Classes/Native/mscorlib_System_Collections_Generic_GenericEqualit1636656366.h
c6a4f79bb3713f3072861a65887c4f0f8f3b077f
[ "Apache-2.0" ]
permissive
AkishinoShiame/Virtual-Elderly-Chatbot-IOS-Project-IOS-12
45d1358bfc7c8b5c5b107b9d50a90b3357dedfe1
a834966bdb705a2e71db67f9d6db55e7e60065aa
refs/heads/master
2020-06-14T02:22:06.622907
2019-07-02T13:45:08
2019-07-02T13:45:08
194,865,711
0
0
null
null
null
null
UTF-8
C++
false
false
642
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Collections_Generic_EqualityCompar1226409501.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.GenericEqualityComparer`1<UnityEngine.UI.ColorBlock> struct GenericEqualityComparer_1_t1636656366 : public EqualityComparer_1_t1226409501 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "akishinoshiame@icloud.com" ]
akishinoshiame@icloud.com
5603a11b546db76f172f6d86aae3f835e9f8f62d
584ca4da32b0e70a2702b5b16222d3d9475cd63a
/src/test/bswap_tests.cpp
5d903859a8146c8d16e92fcb9fd60c2c7d9ac045
[ "MIT" ]
permissive
IluminumProject/iluminum
d87e14cbeb0873fc7b1e42968cb039ecf2b4e03d
9685edf64161c66205c89ee72d711b0144733735
refs/heads/master
2020-03-10T08:55:36.095447
2018-04-21T15:56:18
2018-04-21T15:56:18
128,815,453
0
0
MIT
2018-04-12T07:00:53
2018-04-09T18:19:59
C++
UTF-8
C++
false
false
737
cpp
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "compat/byteswap.h" #include "test/test_iluminum.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(bswap_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(bswap_tests) { // Sibling in bitcoin/src/qt/test/compattests.cpp uint16_t u1 = 0x1234; uint32_t u2 = 0x56789abc; uint64_t u3 = 0xdef0123456789abc; uint16_t e1 = 0x3412; uint32_t e2 = 0xbc9a7856; uint64_t e3 = 0xbc9a78563412f0de; BOOST_CHECK(bswap_16(u1) == e1); BOOST_CHECK(bswap_32(u2) == e2); BOOST_CHECK(bswap_64(u3) == e3); } BOOST_AUTO_TEST_SUITE_END()
[ "4mindsmine@gmail.com" ]
4mindsmine@gmail.com
cb985a48458f063a4d6edc8fd94768ae1155d1af
fcffc4a91dcc4c2ec3ed814f6a949e9d7e8a83fa
/SDL_OpenGL_app.cpp
1a65e950683effc77cda4868336911840b8bd1f5
[]
no_license
IAmCorbin/SDL_OpenGL_app
721394445563083d0559eb3848f82c8d8729416e
7b289b7695fb0df1604e402e0ca0c3587ea401e9
refs/heads/master
2020-05-19T09:05:38.145314
2010-02-23T09:26:44
2010-02-23T09:26:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,234
cpp
// SDL_OpenGL_app.cpp // Class for creating a new SDL and OpenGL Application #include "SDL_OpenGL_app.h" //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// //:::::::::::::SDL_OpenGL_app CLASS METHODS::::::::::::::::::// SDL_OpenGL_app::SDL_OpenGL_app() : fov(45.0f), zNear(0.1f), zFar(500.0f), incAngle(0.1f), incZoom(0.01f), xMove(0.0f), yMove(0.0f), zoom(-30.0f), angleX(-45.0f), angleY(0.0f), angleZ(15.0f), mousemove(false), gameover(false) { } void SDL_OpenGL_app::init(const char* titleTxt, const char* iconTxt, int width=800, int height=600, bool full=false) { fullscreen = full; //START SDL and error check if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)==-1) { //error initializing SDL fprintf(stderr,"Could not initialize SDL!\n"); exit(1); } else { //SDL initialized fprintf(stdout,"SDL initialized!\n"); atexit(SDL_Quit); } //Initialize Joystick if present if(SDL_NumJoysticks()>0) { //grab the first joystick joystick =SDL_JoystickOpen(0); //get the number of buttons joystickButtons = SDL_JoystickNumButtons(joystick); //enable joystick events SDL_JoystickEventState(SDL_ENABLE); } //Set Window Title SDL_WM_SetCaption(titleTxt,iconTxt); //initialize OpenGL SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 ); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 ); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); resize(width,height); } void SDL_OpenGL_app::run() { //SDL Event Structure SDL_Event event; while(!this->isGameover()) { //draw the current frame this->drawFrame(); //swap OpenGL Buffers SDL_GL_SwapBuffers(); //EVENTS if(SDL_PollEvent(&event)) { this->handleEvents(event); } else { this->handleKeys(); } } } void SDL_OpenGL_app::resize(int width, int height) { //Resize WIDTH = width; HEIGHT = height; //load window and error check if(fullscreen) MainWindow = SDL_SetVideoMode(WIDTH,HEIGHT,32,SDL_OPENGL | SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN); else MainWindow = SDL_SetVideoMode(WIDTH,HEIGHT,0,SDL_OPENGL | SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE); if(!MainWindow) { fprintf(stderr,"Error with SDL_SetVideoMove!\n"); exit(1); }else { fprintf(stderr,"SDL_SetVideoMode Successfull!\n"); } glViewport(0, 0, WIDTH, HEIGHT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (height <= 0) height = 1; int aspectratio = WIDTH / HEIGHT; gluPerspective(fov, aspectratio, zNear, zFar); glMatrixMode(GL_MODELVIEW); //enable culling for performance and proper display glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); //enable depth testing for proper display glEnable(GL_DEPTH_TEST); glLoadIdentity(); } Uint8* SDL_OpenGL_app::getKeystate() { keystate = SDL_GetKeyState(NULL); return keystate; } //Mouse, Quit and Resize events void SDL_OpenGL_app::handleEvents(SDL_Event event) { switch(event.type) { //hangle resize //handle mouse movements case SDL_MOUSEBUTTONDOWN: if(event.button.button == SDL_BUTTON_LEFT) { if(!mousemove) mousemove = true; } else if(event.button.button == SDL_BUTTON_WHEELUP ) { if(abs(zoom)>zNear) zoom += 1.0f; } else if(event.button.button == SDL_BUTTON_WHEELDOWN ) { if(abs(zoom)<zFar) zoom -= 1.0f; } break; case SDL_MOUSEBUTTONUP: if(event.button.button == SDL_BUTTON_LEFT) if(mousemove) mousemove = false; break; case SDL_MOUSEMOTION: if(mousemove) { if(event.motion.xrel > 0 ) angleY += 1.0f; if(event.motion.xrel < 0 ) angleY -= 1.0f; if(event.motion.yrel > 0 ) angleX += 1.0f; if(event.motion.yrel < 0 ) angleX -= 1.0f; } break; case SDL_VIDEORESIZE: resize(event.resize.w, event.resize.h); break; //handle quit case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: gameover = true; break; default: break; } break; case SDL_QUIT: gameover = true; break; default: break; } } void SDL_OpenGL_app::handleKeys() { //grab keyboard state SDL_OpenGL_app::getKeystate(); //process key data //TRANSLATE //zoom in if (keystate[SDLK_i] ) { if(abs(zoom)>zNear) { zoom += incZoom; } }//zoom out if (keystate[SDLK_o] ) { if(abs(zoom)<zFar) { zoom -= incZoom; } }//translate world camera X if (keystate[SDLK_LEFT] ) { xMove += .01; } if (keystate[SDLK_RIGHT] ) { xMove -= .01; } //translate world camera Y if (keystate[SDLK_DOWN] ) { yMove += .01; } if (keystate[SDLK_UP] ) { yMove -= .01; } //ROTATE //rotate world around X if (keystate[SDLK_KP8] ) { angleX += incAngle; } if (keystate[SDLK_KP2] ) { angleX -= incAngle; } //rotate world around Y if (keystate[SDLK_KP4] ) { angleY += incAngle; if(angleY == 360) angleY = 0; } if (keystate[SDLK_KP6] ) { angleY -= incAngle; if(angleY == 0) angleY = 360; } //rotate world around Z if (keystate[SDLK_KP1] ) { angleZ += incAngle; } if (keystate[SDLK_KP3] ) { angleZ -= incAngle; } } void SDL_OpenGL_app::drawFrame() { SDL_OpenGL_app::drawFrame_Open(); } void SDL_OpenGL_app::drawFrame_Open() { //CLEAR glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //DRAW glLoadIdentity(); //apply camera location and zoom glTranslatef(xMove,yMove,zoom); //apply X Rotation glRotatef(angleX, 1.0f, 0.0f, 0.0f); //apply Y Rotation glRotatef(angleY, 0.0f, 1.0f, 0.0f); //apply Z Rotation glRotatef(angleZ, 0.0f, 0.0f, 1.0f); //Let OpenGL know about Vertex and Color array glEnableClientState(GL_VERTEX_ARRAY); //We want a vertex array glEnableClientState(GL_COLOR_ARRAY); //and a color array } void SDL_OpenGL_app::drawFrame_Close() { glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); } //gluPerspective //fovy // Specifies the field of view angle, in degrees, in the y direction. //aspect // Specifies the aspect ratio that determines // the field of view in the x direction. // The aspect ratio is the ratio of x (width) to y (height). //zNear // Specifies the distance from the viewer to the near clipping plane (always positive). //zFar // Specifies the distance from the viewer to the far clipping plane (always positive). void SDL_OpenGL_app::gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) { GLdouble xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * M_PI / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); } void SDL_OpenGL_app::setGameover() { gameover = true; } bool SDL_OpenGL_app::isGameover() { return gameover; } //:::::::::::::SDL_OpenGL_app CLASS METHODS::::::::::::::::::// //:::::END:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::END::::::://
[ "Corbin@IAmCorbin.net" ]
Corbin@IAmCorbin.net
7770d97190d004aab3d589728c5316574fafe963
dc4e28a8f33435c15271211049dff3cbcf65a4e3
/RA6963/RA6963.ino
fc920659177ea16e396da00ed83d0971b35ddb1a
[]
no_license
Hrastovc/RA6963-LCD-driver
3d466d4f8bed007882d6a1ef066da0a98cac19fc
cadc5db6c35e638516baa707e5f92232c6607f23
refs/heads/master
2022-06-27T06:35:16.026490
2020-05-09T18:18:17
2020-05-09T18:18:17
262,631,849
2
0
null
null
null
null
UTF-8
C++
false
false
13,417
ino
#include "pinsDef.h" #include "RA6963defines.h" #define FALSE (0) #define TRUE (1) #define DATA (0) #define AUTO (0) #define CMD (1) #define STATUS (1) #define READ (0) #define WRITE (1) #define FILL (0) #define BITMAP (1) void setup() { /* set output pins */ WR_DDR |= (1 << WR); RD_DDR |= (1 << RD); CE_DDR |= (1 << CE); CD_DDR |= (1 << CD); RST_DDR |= (1 << RST); FS1_DDR |= (1 << FS1); /* set pins to HIGH */ RD_PORT |= (1 << RD); WR_PORT |= (1 << WR); CE_PORT |= (1 << CE); CD_PORT |= (1 << CD); /* set pins to LOW */ FS1_PORT &= ~(1 << FS1); /* Reset LCD IC */ RST_PORT &= ~(1 << RST); delay(50); RST_PORT |= (1 << RST); delay(50); /* LCD init */ R6963(WRITE, CMD, 0x00, 0x00, SetControlWord | GraphicHomeAddress, 2); R6963(WRITE, CMD, 0x1E, 0x00, SetControlWord | GraphicArea, 2); R6963(WRITE, CMD, 0x00, 0x00, ModeSet, 0); R6963(WRITE, CMD, 0x00, 0x00, DisplayMode | GraphicOn, 0); R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); R6963(WRITE, DATA, FILL, 0x00, DataAutoReadWrite, 3840); } void loop() { R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); for(uint16_t i = 0; i < 3840; i++) { R6963(WRITE, CMD, 0x00, (0x01 << (7-((i/30)%8))), DataReadWrite | WriteIncrementADP, 1); } delay(1000); R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); for(uint16_t i = 0; i < 3840; i++) { R6963(WRITE, CMD, 0x00, (0x80 << (7-((i/30)%8))), DataReadWrite | WriteIncrementADP, 1); } delay(1000); //R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); //R6963(WRITE, DATA, FILL, 0xFF, DataAutoReadWrite, 3840); //R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); //R6963(WRITE, DATA, FILL, 0x00, DataAutoReadWrite, 3840); } /************************************************************************************//** ** \brief R6963 ** \param rdWr Indicates reading or writing, WRITE or READ. ** \param cmdData Indicates data or command operatiom. ** \param data0 First data byte. ** \param data1 Second data byte. ** \param cmd Command to send. ** \param dataCount Number of bytes to send. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963(uint8_t rdWr, uint8_t cmdData, uint8_t data0, uint16_t data1, uint8_t cmd, uint16_t dataCount) { uint8_t command[3]; /* Write command to RA6963. */ if(rdWr == WRITE & cmdData == CMD) { /* Fill array with first data byte */ command[0] = data0; /* In case only one data byte is to be writen put it in the command[0]. */ if(dataCount) command[dataCount - 1] = data1; /* Fill array with command */ command[dataCount] = cmd; /* Call R6963sendCmd and return status */ return R6963sendCmd(command, dataCount); } /* Write data to RA6963 */ else if(cmdData == DATA) { /* Call R6963auto and return status */ return R6963auto(rdWr, data0, (uint8_t *)data1, dataCount); } /* Parameters invalid */ return FALSE; } /*** end of R6963 ***/ /************************************************************************************//** ** \brief R6963auto ** \param rdWr Indicates reading or writing, WRITE or READ. ** \param p Indicates if data parameter is pointer or not. ** \param data Pointer to the start of bitmap. ** \param byteCount Number ob bytes to send. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963auto(uint8_t rdWr, uint8_t p, uint8_t *data, uint16_t byteCount) { uint8_t cmd; /* wait for status */ if(!R6963waitStatus(STA1 | STA0, 1000)) return FALSE; /* write data */ if(rdWr == WRITE) { /* write command */ cmd = DataAutoReadWrite | DataAutoWrite; if(!R6963rdWrData(WRITE, CMD, &cmd)) return FALSE; /* wait for status */ if(!R6963waitStatus(STA3, 1000)) return FALSE; } /* read data */ else if(rdWr == READ) { /* write command */ cmd = DataAutoReadWrite | DataAutoRead; if(!R6963rdWrData(WRITE, CMD, &cmd)) return FALSE; /* wait for status */ if(!R6963waitStatus(STA2, 1000)) return FALSE; } else { /* Mode not supported. */ return FALSE; } /* counter */ uint16_t i = 0; /* write/read all the data bytes */ do { /* write data */ if(rdWr == WRITE) { if(p == FILL) { /* write data */ uint8_t color = (uint16_t)data; if(!R6963rdWrData(WRITE, DATA, &color)) return FALSE; i++; } else if(p == BITMAP) { /* write data */ if(!R6963rdWrData(WRITE, DATA, (data + (i++)))) return FALSE; } else { /* Mode not supported. */ return FALSE; } /* wait for status */ if(!R6963waitStatus(STA3, 1000)) return FALSE; } /* read data */ else if(rdWr == READ) { /* read data */ if(!R6963rdWrData(READ, DATA, (data + (i++)))) return FALSE; /* wait for status */ if(!R6963waitStatus(STA2, 1000)) return FALSE; } else { /* Mode not supported. */ return FALSE; } } while(i < byteCount); /* write command */ cmd = DataAutoReadWrite | AutoReset; if(!R6963rdWrData(WRITE, CMD, &cmd)) return FALSE; /* return true */ return TRUE; } /*** end of R6963auto ***/ /************************************************************************************//** ** \brief R6963sendCmd ** \param data Pointer to the variable with data to send. ** \param byteCount Number of byte to send. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963sendCmd(uint8_t *data, uint8_t byteCount) { /* constrain byteCount */ if(byteCount > 2) return FALSE; /* write all the data bytes */ for(uint8_t i = 0; i < byteCount; i++) { /* wait for status */ if(!R6963waitStatus(STA1 | STA0, 1000)) return FALSE; /* write data */ if(!R6963rdWrData(WRITE, DATA, (data + i))) return FALSE; } /* wait for status */ if(!R6963waitStatus(STA1 | STA0, 1000)) return FALSE; /* write command */ if(!R6963rdWrData(WRITE, CMD, (data + byteCount))) return FALSE; /* return true */ return TRUE; } /*** end of R6963sendCmd ***/ /************************************************************************************//** ** \brief R6963waitStatus ** \param mask Status register mask. ** \param timeout Time to wait for status in ms. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963waitStatus(uint8_t mask, uint16_t timeout) { uint8_t statReg; /* convert time to count */ //TODO /* poll status */ do { /* read status register */ if(!R6963rdWrData(READ, STATUS, &statReg)) return FALSE; /* wait a bit */ //TODO } while(!((statReg & mask) == mask)); /* return status */ if(!((statReg & mask) == mask)) return FALSE; /* return TRUE */ return TRUE; } /*** end of R6963waitStatus ***/ /************************************************************************************//** ** \brief R6963rdWrData ** \param rdWr Indicates reading or writing, WRITE or READ. ** \param cdState State of a CD pin. ** \param data Pointer to the data variable to read or write. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963rdWrData(uint8_t rdWr, uint8_t cdState, uint8_t *data) { /* write data */ if(rdWr == WRITE) { /* Data bus direction */ if(!R6963dataBusDir(OUTPUT)) return FALSE; /* set data bus */ if(!R6963setDataBus(*data)) return FALSE; } /* read data */ else if(rdWr == READ) { /* Data bus direction */ if(!R6963dataBusDir(INPUT)) return FALSE; } else { /* Mode not supported. */ return FALSE; } /* Register select; Command/Data write */ if(!R6963cd(cdState)) return FALSE; /* WR or RD take low */ if(!R6963wr(~rdWr)) return FALSE; if(!R6963rd( rdWr)) return FALSE; /* CE pulsed low for greater than 150ns */ if(!R6963ce(LOW)) return FALSE; /* wait a least 150ns */ //asm("nop"); //asm("nop"); //asm("nop"); if(rdWr == READ) { /* read data bus */ if(!R6963readDataBus(data)) return FALSE; } /* CE take high */ if(!R6963ce(HIGH)) return FALSE; /* return TRUE */ return TRUE; } /*** end of R6963rdWrData ***/ /************************************************************************************//** ** \brief R6963cd ** \param state State of the CD pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963cd(uint8_t state) { /* set pin to the state. */ CD_PORT = (CD_PORT & ~(1 << CD)) | ((state & 0x01) << CD); /* return TRUE */ return TRUE; } /*** end of R6963cd ***/ /************************************************************************************//** ** \brief R6963wr ** \param state State of the WR pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963wr(uint8_t state) { /* set pin to the state. */ WR_PORT = (WR_PORT & ~(1 << WR)) | ((state & 0x01) << WR); /* return TRUE */ return TRUE; } /*** end of R6963wr ***/ /************************************************************************************//** ** \brief R6963rd ** \param state State of the RD pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963rd(uint8_t state) { /* set pin to the state. */ RD_PORT = (RD_PORT & ~(1 << RD)) | ((state & 0x01) << RD); /* return TRUE */ return TRUE; } /*** end of R6963rd ***/ /************************************************************************************//** ** \brief R6963ce ** \param state State of the CE pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963ce(uint8_t state) { /* set pin to the state. */ CE_PORT = (CE_PORT & ~(1 << CE)) | ((state & 0x01) << CE); /* return TRUE */ return TRUE; } /*** end of R6963ce ***/ /************************************************************************************//** ** \brief R6963setDataBus ** \param data Data to set the bus to ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963setDataBus(uint8_t data) { /* set data bus */ D0_PORT = (D0_PORT & ~(1 << D0)) | (((data >> 0) & 0x01) << D0); D1_PORT = (D1_PORT & ~(1 << D1)) | (((data >> 1) & 0x01) << D1); D2_PORT = (D2_PORT & ~(1 << D2)) | (((data >> 2) & 0x01) << D2); D3_PORT = (D3_PORT & ~(1 << D3)) | (((data >> 3) & 0x01) << D3); D4_PORT = (D4_PORT & ~(1 << D4)) | (((data >> 4) & 0x01) << D4); D5_PORT = (D5_PORT & ~(1 << D5)) | (((data >> 5) & 0x01) << D5); D6_PORT = (D6_PORT & ~(1 << D6)) | (((data >> 6) & 0x01) << D6); D7_PORT = (D7_PORT & ~(1 << D7)) | (((data >> 7) & 0x01) << D7); /* return TRUE */ return TRUE; } /*** end of R6963setDataBus ***/ /************************************************************************************//** ** \brief R6963readDataBus ** \param data Pointer to the bus variable ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963readDataBus(uint8_t *data) { *data = 0; /* read data bus */ *data |= (((D0_PIN >> D0) & 0x01) << 0); *data |= (((D1_PIN >> D1) & 0x01) << 1); *data |= (((D2_PIN >> D2) & 0x01) << 2); *data |= (((D3_PIN >> D3) & 0x01) << 3); *data |= (((D4_PIN >> D4) & 0x01) << 4); *data |= (((D5_PIN >> D5) & 0x01) << 5); *data |= (((D6_PIN >> D6) & 0x01) << 6); *data |= (((D7_PIN >> D7) & 0x01) << 7); /* return TRUE */ return TRUE; } /*** end of R6963readDataBus ***/ /************************************************************************************//** ** \brief R6963dataBusDir ** \param dir Data bus direction, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963dataBusDir(uint8_t dir) { /* set pins direction */ D0_DDR = (D0_DDR & ~(1 << D0)) | ((dir & 0x01) << D0); D1_DDR = (D1_DDR & ~(1 << D1)) | ((dir & 0x01) << D1); D2_DDR = (D2_DDR & ~(1 << D2)) | ((dir & 0x01) << D2); D3_DDR = (D3_DDR & ~(1 << D3)) | ((dir & 0x01) << D3); D4_DDR = (D4_DDR & ~(1 << D4)) | ((dir & 0x01) << D4); D5_DDR = (D5_DDR & ~(1 << D5)) | ((dir & 0x01) << D5); D6_DDR = (D6_DDR & ~(1 << D6)) | ((dir & 0x01) << D6); D7_DDR = (D7_DDR & ~(1 << D7)) | ((dir & 0x01) << D7); /* return TRUE */ return TRUE; } /*** end of R6963dataBusDir ***/
[ "luka.hrastovec@gmail.com" ]
luka.hrastovec@gmail.com
5f8413f6dee2c381bdb9f9b2410d359d34a28fa2
ff3f093552bd4bd4a1ce172afc18c5e473844b02
/xwa_hook_d3dinfos_textures/hook_d3dinfos_textures/d3dinfos.cpp
5377f4b1317b6c80fcb69e0ba9080a036919f4d6
[]
no_license
hixio-mh/xwa_hooks
d31172d2249c60bf12aaff60301d8814fe9f3ec7
c97e4634c0e084665d007f7bc053b69ca7370522
refs/heads/master
2022-11-18T19:28:56.170099
2020-07-23T16:20:50
2020-07-23T16:20:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,295
cpp
#include "targetver.h" #include "d3dinfos.h" #include "config.h" #pragma pack(push, 1) struct XwaD3DInfo { char m00[0x53]; XwaD3DInfo* pNext; XwaD3DInfo* pPrevious; }; static_assert(sizeof(XwaD3DInfo) == 91, "size of XwaD3DInfo must be 91"); #pragma pack(pop) class D3DInfoArray { public: D3DInfoArray() { auto lines = GetFileLines("hooks.ini", "hook_d3dinfos_textures"); if (lines.empty()) { lines = GetFileLines("hook_d3dinfos_textures.cfg"); } int count = abs(GetFileKeyValueInt(lines, "Size")); if (count == 0) { count = 10000; } this->_d3dinfos.reserve(count); } int Size() { return this->_d3dinfos.capacity(); } XwaD3DInfo* Data() { return this->_d3dinfos.data(); } private: std::vector<XwaD3DInfo> _d3dinfos; }; D3DInfoArray g_XwaD3DInfos; int InitD3DInfosHook(int* params) { auto& XwaD3DInfosFirstEmpty = *(XwaD3DInfo**)0x00686B24; auto& XwaD3DInfosFirstUsed = *(XwaD3DInfo**)0x00686B28; auto& XwaD3DInfosCount = *(int*)0x00686B2C; int size = g_XwaD3DInfos.Size(); XwaD3DInfo* data = g_XwaD3DInfos.Data(); for (int i = 0; i < size - 1; i++) { data[i] = {}; data[i].pNext = &data[i + 1]; } data[size - 1] = {}; XwaD3DInfosFirstEmpty = &data[0]; XwaD3DInfosFirstUsed = nullptr; XwaD3DInfosCount = 0; return 0; }
[ "JeremyAnsel@users.noreply.github.com" ]
JeremyAnsel@users.noreply.github.com
586642535890a4705ad4cd65de24dd23fe6a281f
db04ecf258aef8a187823b8e47f4a1ae908e5897
/Cplus/FlattenBinaryTreetoLinkedList.cpp
812f1e994941e6615964e6dd3fe4f4f7a055f2b7
[ "MIT" ]
permissive
JumHorn/leetcode
9612a26e531ceae7f25e2a749600632da6882075
abf145686dcfac860b0f6b26a04e3edd133b238c
refs/heads/master
2023-08-03T21:12:13.945602
2023-07-30T07:00:50
2023-07-30T07:00:50
74,735,489
0
0
null
null
null
null
UTF-8
C++
false
false
670
cpp
//Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: void flatten(TreeNode *root) { TreeNode dummy, *d = &dummy; preorder(root, d); } void preorder(TreeNode *root, TreeNode *&pre) { if (root == nullptr) return; TreeNode *left = root->left, *right = root->right; root->left = nullptr; pre->right = root; pre = root; preorder(left, pre); preorder(right, pre); } };
[ "JumHorn@gmail.com" ]
JumHorn@gmail.com
22c41bf05ed2bbad30e2e0d479443c56a31a6266
cac6b164b1946be1f64fe47f50239dd4e61392ae
/src/qt/optionsdialog.cpp
12fcd1b82f59ca464be925c639dd662149238488
[ "MIT" ]
permissive
shacker6868/signatumclassicd
ccddbf0213613ec7b5eccb6d4eade9a3a88c3aa6
fb2d969a7853a140088396687beb56153e2b6abd
refs/heads/master
2021-01-19T12:51:08.591971
2017-08-25T04:32:25
2017-08-25T04:32:25
100,336,108
1
0
null
null
null
null
UTF-8
C++
false
false
7,792
cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); mapper->addMapping(ui->useBlackTheme, OptionsModel::UseBlackTheme); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Signatumclassic."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Signatumclassic."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
[ "signatum-classic@protonmail.com" ]
signatum-classic@protonmail.com
97585d88601930cd6102b5085f3d50c721b9def5
57d123a5f68b1e8095d5239eb7c3af28784e0799
/OJ——work/work_three/一元多项式相加.cpp
df415b93e16c492ba3cc22d768b2d525f6f52eba
[]
no_license
Floweryu/DataStructuresAlgorithms
dda159afe3b8327deecfa3a8f72a62cf16d1d538
e61a424dcca1913c0e5ef4fae15b5945dbd04d9b
refs/heads/master
2022-03-26T04:22:07.849883
2019-12-18T07:52:11
2019-12-18T07:52:11
null
0
0
null
null
null
null
GB18030
C++
false
false
2,926
cpp
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct term{ int cof; int inx; struct term *next; }term,*LinkList; typedef LinkList polynomial; //初始化链表 int InitList(LinkList &L) { L=(LinkList)malloc(sizeof(term)); if(!L) return 0; L->next=NULL; return 1; } //判断链表是否为空;空就返回1 int Empty_L(term *L) { /*当只有一个头结点的时候,该链表就为空*/ if((L->next)==NULL) //头结点与NULL相连 return 1; else return 0; } //打印多项式链表 void printfPolynomial(polynomial &P) { LinkList q=P->next; while(q) { printf("%d %d ",q->cof,q->inx); q=q->next; } printf("\n"); } //创建输入多项式 int CreatePoly(polynomial &L) { LinkList p,q; L=(LinkList)malloc(sizeof(term)); q=L; int c,e; while(scanf("%d %d",&c,&e)!=EOF&&e>=0) { p=(LinkList)malloc(sizeof(term)); p->cof=c; p->inx=e; q->next=p; q=q->next; } q->next=NULL; } //多项式加法 int addPolyn(polynomial pa,polynomial pb) { LinkList qa=pa->next; LinkList qb=pb->next; LinkList L,qc,s,pc; L=pc=(LinkList)malloc(sizeof(term)); L->next=NULL; while(qa!=NULL&&qb!=NULL) { qc=(LinkList)malloc(sizeof(term)); //测试点printf("%d %d\n",qa->inx,qb->inx); if(qa->inx < qb->inx) //pa中的指数大于pb { qc->cof=qb->cof; //将小的一项赋给qc qc->inx=qb->inx; qb=qb->next; //指向下一个 } else if(qa->inx > qb->inx) { qc->cof=qa->cof; //将小的一项赋给qc qc->inx=qa->inx; qa=qa->next; } else //如果相等 { qc->cof=qa->cof+qb->cof; //系数相加保存到qc qc->inx=qa->inx; //指数不变 qa=qa->next; qb=qb->next; } if((qc->cof)!=0) //如果该项系数不为0 { qc->next=pc->next; //将qc插入到新链表 pc中 pc->next=qc; pc=qc; //新申请指针向下移 } else free(qc); } while(qa!=NULL) { qc=(LinkList)malloc(sizeof(term)); qc->cof=qa->cof; qc->inx=qa->inx; qa=qa->next; qc->next=pc->next; pc->next=qc; pc=qc; } while(qb!=NULL) { qc=(LinkList)malloc(sizeof(term)); qc->cof=qb->cof; qc->inx=qb->inx; qb=qb->next; qc->next=pc->next; pc->next=qc; pc=qc; } if(Empty_L(L)) printf("0\n"); printfPolynomial(L); } int main() { LinkList pa,pb; CreatePoly(pa); //测试点printfPolynomial(pa); CreatePoly(pb); //测试点printfPolynomial(pb); addPolyn(pa,pb); }
[ "869830837@qq.com" ]
869830837@qq.com
be58a95473b63f9443359e39de7994e4e349ec9c
72251ba180a723f3e653231b265efaedf6f31f8f
/tests/src/helper_func.cpp
64d68fd5e2d8cfb3c007583cb043fc238e8daf6e
[ "MIT" ]
permissive
fundies/Crash2D
b9e6bc1fe55d1957ea1f1320a7019e797ea0a322
40b14d4259d7cedeea27d46f7206b80a07a3327c
refs/heads/master
2023-03-30T02:01:19.942794
2017-09-11T10:50:33
2017-09-11T10:50:33
63,020,131
1
4
MIT
2021-04-02T08:00:21
2016-07-10T21:59:32
C++
UTF-8
C++
false
false
897
cpp
#include "helper.hpp" #include <gtest/gtest.h> Segment mSegment(Segment s, Vector2 displacement) { return Segment(s.GetPoint(0) + displacement, s.GetPoint(1) + displacement); } Circle mCircle(Circle c, Vector2 displacement) { return Circle(c.GetCenter() + displacement, c.GetRadius()); } Polygon mPolygon(Polygon p, Vector2 displacement) { Polygon pD; pD.SetPointCount(p.GetPointCount()); for (unsigned i = 0; i < p.GetPointCount(); ++i) { pD.SetPoint(i, p.GetPoint(i) + displacement); } pD.ReCalc(); return pD; } bool vectorContains(std::vector<Vector2> &coords, Vector2 pt) { auto it = std::find(std::begin(coords), std::end(coords), pt); return (it != std::end(coords)); } bool vectorEQ(std::vector<Vector2> &a, std::vector<Vector2> &b) { if (a.size() != b.size()) return false; for (auto i : a) { if (!vectorContains(b, i)) return false; } return true; }
[ "cheeseboy16@gmail.com" ]
cheeseboy16@gmail.com
ad107d784307f66de034af1e20db2eed41149780
f14626611951a4f11a84cd71f5a2161cd144a53a
/武侠世界/代码/客户端/SceneEdit/src/AddLightObjectPlugin.cpp
c1d589aa2de8e9f485e5222c642335db4d3eff35
[]
no_license
Deadmanovi4/mmo-resourse
045616f9be76f3b9cd4a39605accd2afa8099297
1c310e15147ae775a59626aa5b5587c6895014de
refs/heads/master
2021-05-29T06:14:28.650762
2015-06-18T01:16:43
2015-06-18T01:16:43
null
0
0
null
null
null
null
GB18030
C++
false
false
12,230
cpp
#include "AddLightObjectPlugin.h" #include "SceneManipulator.h" #include "Core/WXLightObject.h" #include "Core/WXObjectProxy.h" #include "Core/WXSceneInfo.h" #include "Core/TerrainData.h" #include <OgreEntity.h> #include <OgreSceneNode.h> #include <OgreSceneManager.h> #include <OgreCamera.h> namespace WX { class AddLightObjectPlugin::Indicator { public: Indicator(const ObjectPtr &object, Ogre::SceneManager *sceneMgr, WX::SceneManipulator *sceneManipulator) : mProxy(NULL), mOldPos(Ogre::Vector3::ZERO) { assert(sceneMgr && sceneManipulator); mProxy = new ObjectProxy(object); mSceneManipulator = sceneManipulator; mCurrentLightEntity = NULL; // 根据光源位置来定节点位置 Ogre::Vector3 pos = VariantCast<Ogre::Vector3>(object->getProperty("position")); mIndicatorSceneNode = sceneManipulator->getIndicatorRootSceneNode()->createChildSceneNode(pos); // mIndicatorSceneNode->scale(2.0,15.0,2.0); // 创建三个entity分别来代表三种光源的模型 mPointLightEntity = sceneMgr->createEntity(mIndicatorSceneNode->getName()+"point","pointLight.mesh"); mDirectionalLightEntity = sceneMgr->createEntity(mIndicatorSceneNode->getName()+"directional","directionalLight.mesh"); mDirectionalLightEntity->setQueryFlags(0); mSpotLightEntity = sceneMgr->createEntity(mIndicatorSceneNode->getName()+"spotlight","spotLight.mesh"); mPointLightEntity->setUserObject(mProxy); mDirectionalLightEntity->setUserObject(mProxy); mSpotLightEntity->setUserObject(mProxy); // 根据光源类型来挂接模型 setIndicatorModel(mProxy->getObject()->getPropertyAsString("type")); // 根据光源方向来决定scenenode方向 Ogre::Vector3 &dir = VariantCast<Ogre::Vector3>(object->getProperty("direction")); setDirection(dir); showIndicator(false); } ~Indicator() { if (mIndicatorSceneNode) { mIndicatorSceneNode->destroy(); } if (mPointLightEntity) { mPointLightEntity->destroy(); } if (mDirectionalLightEntity) { mDirectionalLightEntity->destroy(); } if (mSpotLightEntity) { mSpotLightEntity->destroy(); } if (mProxy) { delete mProxy; mProxy = NULL; } } void showIndicator( bool show ) { assert(mIndicatorSceneNode); assert( mCurrentLightEntity && mDirectionalLightEntity ); // 如果是方向光 if ( mCurrentLightEntity == mDirectionalLightEntity ) { mIndicatorSceneNode->setVisible(show); mIndicatorSceneNode->showBoundingBox(false); // 获取到摄像机与地形的交点 Ogre::Vector3 pos; Ogre::Ray cameraRay( mSceneManipulator->getCamera()->getPosition(), mSceneManipulator->getCamera()->getDirection() ); bool hit = mSceneManipulator->getTerrainIntersects(cameraRay, pos); if (hit) { // 在地形上的一米处出现光源指示器 float height = mSceneManipulator->getTerrainData()->getHeightAt(pos.x, pos.z) + 100.0f; mIndicatorSceneNode->setPosition(pos.x, height, pos.z); } } else { mIndicatorSceneNode->showBoundingBox(show); } } void setPosition( const Ogre::Vector3 &pos ) { assert(mIndicatorSceneNode); mOldPos = pos; if ( mCurrentLightEntity != mDirectionalLightEntity ) mIndicatorSceneNode->setPosition(pos); } void setDirection( const Ogre::Vector3 &dir ) { assert(mIndicatorSceneNode); // 分别计算出节点三个轴上的方向 Ogre::Vector3 yAdjustVec = -dir; yAdjustVec.normalise(); Ogre::Vector3 xVec = mIndicatorSceneNode->getOrientation().zAxis().crossProduct( yAdjustVec ); xVec.normalise(); Ogre::Vector3 zVec = xVec.crossProduct( yAdjustVec ); zVec.normalise(); mIndicatorSceneNode->setOrientation(Ogre::Quaternion( xVec, yAdjustVec, zVec )); } void setIndicatorModel( const Ogre::String &lightType ) { assert( !lightType.empty() ); assert ( mIndicatorSceneNode ); assert ( mPointLightEntity ); assert ( mDirectionalLightEntity ); assert ( mSpotLightEntity ); mIndicatorSceneNode->detachAllObjects(); if ( lightType == "point" ) { // mIndicatorSceneNode->attachObject(mPointLightEntity); mCurrentLightEntity = mPointLightEntity; if ( mOldPos != Ogre::Vector3::ZERO ) mIndicatorSceneNode->setPosition(mOldPos); } else if ( lightType == "directional") { // mIndicatorSceneNode->attachObject(mDirectionalLightEntity); // 因为方向光本身没有位置属性,不过指示器会出现在地形中心,会改变scene node的位置 // 所以这里先把旧位置保存下来 mOldPos = mIndicatorSceneNode->getPosition(); mCurrentLightEntity = mDirectionalLightEntity; // mIndicatorSceneNode->setPosition(0, 0 ,0); // 获取到地形中心点的高度 float height = mSceneManipulator->getTerrainData()->getHeightAt(0,0); mIndicatorSceneNode->setPosition(0, height ,0); } else if ( lightType == "spotlight" ) { // mIndicatorSceneNode->attachObject(mSpotLightEntity); mCurrentLightEntity = mSpotLightEntity; if ( mOldPos != Ogre::Vector3::ZERO ) mIndicatorSceneNode->setPosition(mOldPos); } mIndicatorSceneNode->attachObject(mCurrentLightEntity); } protected: Ogre::Entity *mPointLightEntity; Ogre::Entity *mDirectionalLightEntity; Ogre::Entity *mSpotLightEntity; Ogre::Entity *mCurrentLightEntity; Ogre::SceneNode *mIndicatorSceneNode; WX::SceneManipulator *mSceneManipulator; ObjectProxy* mProxy; Ogre::Vector3 mOldPos; }; AddLightObjectPlugin::AddLightObjectPlugin(WX::SceneManipulator* sceneManipulator) { assert(sceneManipulator); mSceneManipulator = sceneManipulator; mSceneManipulator->addSceneListener(this); } AddLightObjectPlugin::~AddLightObjectPlugin() { mSceneManipulator->removeSceneListener(this); clearIndicators(); } ////////////////////////////////////////////////////////////////////////// void AddLightObjectPlugin::onSceneReset(void) { clearIndicators(); typedef WX::SceneInfo::Objects Objects; const WX::SceneInfo* sceneInfo = mSceneManipulator->getSceneInfo(); const Objects& objects = sceneInfo->getObjects(); for (Objects::const_iterator it = objects.begin(); it != objects.end(); ++it) { Ogre::String type = (*it)->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { LightObject *lightObject = static_cast<LightObject *> ((*it).get()); Indicator *indicator = new Indicator( *it, mSceneManipulator->getSceneManager(), mSceneManipulator ); std::pair<Indicators::iterator, bool> inserted = mIndicators.insert(Indicators::value_type(*it, indicator)); assert(inserted.second); } } } void AddLightObjectPlugin::onAddObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { LightObject *lightObject = static_cast<LightObject *> (object.get()); Indicator *indicator = new Indicator(object,mSceneManipulator->getSceneManager(), mSceneManipulator ); std::pair<Indicators::iterator, bool> inserted = mIndicators.insert(Indicators::value_type(object, indicator)); assert(inserted.second); } } void AddLightObjectPlugin::onRemoveObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { delete i->second; i->second = NULL; mIndicators.erase(i); } } } /* void AddLightObjectPlugin::onRenameObject(const ObjectPtr& object, const String& oldName) { }*/ void AddLightObjectPlugin::onSelectObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { i->second->showIndicator(true); } } } void AddLightObjectPlugin::onDeselectObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { i->second->showIndicator(false); } } } void AddLightObjectPlugin::onDeselectAllObjects(void) { for (Indicators::iterator i = mIndicators.begin(); i != mIndicators.end(); ++i ) { if ( i->second ) { i->second->showIndicator(false); } } } void AddLightObjectPlugin::onObjectPropertyChanged(const ObjectPtr& object, const String& name) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { if ( name == "position" ) i->second->setPosition( VariantCast<Ogre::Vector3>(object->getProperty("position")) ); else if ( name == "type" ) { Ogre::String lightType = object->getPropertyAsString("type"); i->second->setIndicatorModel(lightType); } else if ( name == "direction" ) { i->second->setDirection( VariantCast<Ogre::Vector3>(object->getProperty("direction")) ); } } } } void AddLightObjectPlugin::clearIndicators(void) { for (Indicators::iterator i = mIndicators.begin(); i != mIndicators.end(); ++i ) { if ( i->second ) { delete i->second; i->second = NULL; } } mIndicators.clear(); } }
[ "ichenq@gmail.com" ]
ichenq@gmail.com
7b9a585fa86ad340d46ca2614e14fae8621b6a44
b06d2b7a619db62dafbd1b5df065d961994cd008
/ip.cpp
6401be0268d4d49179d658eda557152d745477b3
[]
no_license
ehddud758/arp_spoofing
ca6db7654175f24a59d0d358801fd07fe4244e3f
c955f7974057cfa3d92958269756400be31b1e52
refs/heads/master
2020-03-26T06:04:11.734667
2018-08-13T16:00:40
2018-08-13T16:00:40
144,588,010
0
0
null
null
null
null
UTF-8
C++
false
false
1,920
cpp
#ifndef __IPV4_ADDR_CPP__ #define __IPV4_ADDR_CPP__ #include "ip.h" #include <arpa/inet.h> #include <iostream> #include <string> #include <cstdio> #include <cstring> using namespace std; IPv4_addr& IPv4_addr::operator = (const char* rhs) { int ret = inet_pton(AF_INET, rhs, &_ip); switch(ret) { case 0: cout << "inet_pton return zero ip='" << rhs << "'" << endl; break; case 1: _ip = ntohl(_ip); break; default: cout << "inet_pton return " << ret << endl; } return *this; } IPv4_addr& IPv4_addr::operator = (const string& rhs) { const char *c = rhs.c_str(); *this = c; return *this; } void IPv4_addr::hex_dump() { uint8_t hex[4]; uint32_t __ip = htonl(_ip); memcpy(hex, &__ip, 4); printf("%02hhX.%02hhX.%02hhX.%02hhX", hex[0], hex[1], hex[2], hex[3]); } void IPv4_addr::ascii_dump() { uint8_t hex[4]; uint32_t __ip = htonl(_ip); memcpy(hex, &__ip, 4); printf("%hhu.%hhu.%hhu.%hhu", hex[0], hex[1], hex[2], hex[3]); } void IPv4_addr::write_mem(uint8_t *mem) { uint32_t __ip = htonl(_ip); memcpy(mem, &__ip, 4); } void IPv4_addr::parse_mem(uint8_t *mem) { memcpy(&_ip, mem, 4); _ip = ntohl(_ip); } void IPv4_addr::parse_mem(char *mem) { memcpy(&_ip, mem, 4); _ip = ntohl(_ip); } bool IPv4_addr::is_equal(uint32_t val) { return _ip == val; } bool IPv4_addr::is_equal(IPv4_addr addr) { return _ip == addr._ip; } string IPv4_addr::to_string() { char buf[32]; uint32_t __ip = htonl(_ip); const char* ret = inet_ntop(AF_INET, &__ip, buf, sizeof(buf)); if (ret == NULL) { fprintf(stderr, "IPv4_addr to_string error\n"); return string(""); } string str(buf); return str; } IPv4_addr::operator struct in_addr() { struct in_addr ret; ret.s_addr = _ip; return ret; } char* IPv4_addr::to_string(char* mem, int buf_size) { uint32_t __ip = htonl(_ip); const char* ret = inet_ntop(AF_INET, &__ip, mem, buf_size); return (char*)ret; } #endif
[ "aaa7663@naver.com" ]
aaa7663@naver.com
5fca83dadbcbc189da9c3e40178a9113c7772fc1
5f9b26a41102c38da28b8f757a5586f9bc7cf71a
/crates/zig_build_bin_windows_x86_64/zig-windows-x86_64-0.5.0+80ff549e2/lib/zig/libcxx/include/compare
48564c8ef860a0164c34767202ceccc931766a43
[ "MIT", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
jeremyBanks/zig_with_cargo
f8e65f14adf17ed8d477f0856257422c2158c63f
f8ee46b891bbcdca7ff20f5cad64aa94c5a1d2d1
refs/heads/master
2021-02-06T10:26:17.614138
2020-03-09T04:46:26
2020-03-09T04:46:26
243,905,553
4
1
null
null
null
null
UTF-8
C++
false
false
27,204
// -*- C++ -*- //===-------------------------- compare -----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_COMPARE #define _LIBCPP_COMPARE /* compare synopsis namespace std { // [cmp.categories], comparison category types class weak_equality; class strong_equality; class partial_ordering; class weak_ordering; class strong_ordering; // named comparison functions constexpr bool is_eq (weak_equality cmp) noexcept { return cmp == 0; } constexpr bool is_neq (weak_equality cmp) noexcept { return cmp != 0; } constexpr bool is_lt (partial_ordering cmp) noexcept { return cmp < 0; } constexpr bool is_lteq(partial_ordering cmp) noexcept { return cmp <= 0; } constexpr bool is_gt (partial_ordering cmp) noexcept { return cmp > 0; } constexpr bool is_gteq(partial_ordering cmp) noexcept { return cmp >= 0; } // [cmp.common], common comparison category type template<class... Ts> struct common_comparison_category { using type = see below; }; template<class... Ts> using common_comparison_category_t = typename common_comparison_category<Ts...>::type; // [cmp.alg], comparison algorithms template<class T> constexpr strong_ordering strong_order(const T& a, const T& b); template<class T> constexpr weak_ordering weak_order(const T& a, const T& b); template<class T> constexpr partial_ordering partial_order(const T& a, const T& b); template<class T> constexpr strong_equality strong_equal(const T& a, const T& b); template<class T> constexpr weak_equality weak_equal(const T& a, const T& b); } */ #include <__config> #include <type_traits> #include <array> #ifndef _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER #pragma GCC system_header #endif _LIBCPP_BEGIN_NAMESPACE_STD #if _LIBCPP_STD_VER > 17 // exposition only enum class _LIBCPP_ENUM_VIS _EqResult : unsigned char { __zero = 0, __equal = __zero, __equiv = __equal, __nonequal = 1, __nonequiv = __nonequal }; enum class _LIBCPP_ENUM_VIS _OrdResult : signed char { __less = -1, __greater = 1 }; enum class _LIBCPP_ENUM_VIS _NCmpResult : signed char { __unordered = -127 }; struct _CmpUnspecifiedType; using _CmpUnspecifiedParam = void (_CmpUnspecifiedType::*)(); class weak_equality { _LIBCPP_INLINE_VISIBILITY constexpr explicit weak_equality(_EqResult __val) noexcept : __value_(__val) {} public: static const weak_equality equivalent; static const weak_equality nonequivalent; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, weak_equality __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(weak_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, weak_equality __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr weak_equality operator<=>(weak_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr weak_equality operator<=>(_CmpUnspecifiedParam, weak_equality __v) noexcept; #endif private: _EqResult __value_; }; _LIBCPP_INLINE_VAR constexpr weak_equality weak_equality::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr weak_equality weak_equality::nonequivalent(_EqResult::__nonequiv); _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator==(weak_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator==(_CmpUnspecifiedParam, weak_equality __v) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator!=(weak_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator!=(_CmpUnspecifiedParam, weak_equality __v) noexcept { return __v.__value_ != _EqResult::__zero; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY inline constexpr weak_equality operator<=>(weak_equality __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY inline constexpr weak_equality operator<=>(_CmpUnspecifiedParam, weak_equality __v) noexcept { return __v; } #endif class strong_equality { _LIBCPP_INLINE_VISIBILITY explicit constexpr strong_equality(_EqResult __val) noexcept : __value_(__val) {} public: static const strong_equality equal; static const strong_equality nonequal; static const strong_equality equivalent; static const strong_equality nonequivalent; // conversion _LIBCPP_INLINE_VISIBILITY constexpr operator weak_equality() const noexcept { return __value_ == _EqResult::__zero ? weak_equality::equivalent : weak_equality::nonequivalent; } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(strong_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, strong_equality __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, strong_equality __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr strong_equality operator<=>(strong_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr strong_equality operator<=>(_CmpUnspecifiedParam, strong_equality __v) noexcept; #endif private: _EqResult __value_; }; _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::equal(_EqResult::__equal); _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::nonequal(_EqResult::__nonequal); _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::nonequivalent(_EqResult::__nonequiv); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(strong_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, strong_equality __v) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(strong_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, strong_equality __v) noexcept { return __v.__value_ != _EqResult::__zero; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr strong_equality operator<=>(strong_equality __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr strong_equality operator<=>(_CmpUnspecifiedParam, strong_equality __v) noexcept { return __v; } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR class partial_ordering { using _ValueT = signed char; _LIBCPP_INLINE_VISIBILITY explicit constexpr partial_ordering(_EqResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr partial_ordering(_OrdResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr partial_ordering(_NCmpResult __v) noexcept : __value_(_ValueT(__v)) {} constexpr bool __is_ordered() const noexcept { return __value_ != _ValueT(_NCmpResult::__unordered); } public: // valid values static const partial_ordering less; static const partial_ordering equivalent; static const partial_ordering greater; static const partial_ordering unordered; // conversion constexpr operator weak_equality() const noexcept { return __value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent; } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, partial_ordering __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(_CmpUnspecifiedParam, partial_ordering __v) noexcept; #endif private: _ValueT __value_; }; _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::less(_OrdResult::__less); _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::greater(_OrdResult::__greater); _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::unordered(_NCmpResult ::__unordered); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ >= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 == __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 < __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 <= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 > __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 >= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return !__v.__is_ordered() || __v.__value_ != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return !__v.__is_ordered() || __v.__value_ != 0; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr partial_ordering operator<=>(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr partial_ordering operator<=>(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v < 0 ? partial_ordering::greater : (__v > 0 ? partial_ordering::less : __v); } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR class weak_ordering { using _ValueT = signed char; _LIBCPP_INLINE_VISIBILITY explicit constexpr weak_ordering(_EqResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr weak_ordering(_OrdResult __v) noexcept : __value_(_ValueT(__v)) {} public: static const weak_ordering less; static const weak_ordering equivalent; static const weak_ordering greater; // conversions _LIBCPP_INLINE_VISIBILITY constexpr operator weak_equality() const noexcept { return __value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent; } _LIBCPP_INLINE_VISIBILITY constexpr operator partial_ordering() const noexcept { return __value_ == 0 ? partial_ordering::equivalent : (__value_ < 0 ? partial_ordering::less : partial_ordering::greater); } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, weak_ordering __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(_CmpUnspecifiedParam, weak_ordering __v) noexcept; #endif private: _ValueT __value_; }; _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::less(_OrdResult::__less); _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::greater(_OrdResult::__greater); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ >= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 == __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 != __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 < __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 <= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 > __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 >= __v.__value_; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr weak_ordering operator<=>(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr weak_ordering operator<=>(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return __v < 0 ? weak_ordering::greater : (__v > 0 ? weak_ordering::less : __v); } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR class strong_ordering { using _ValueT = signed char; _LIBCPP_INLINE_VISIBILITY explicit constexpr strong_ordering(_EqResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr strong_ordering(_OrdResult __v) noexcept : __value_(_ValueT(__v)) {} public: static const strong_ordering less; static const strong_ordering equal; static const strong_ordering equivalent; static const strong_ordering greater; // conversions _LIBCPP_INLINE_VISIBILITY constexpr operator weak_equality() const noexcept { return __value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent; } _LIBCPP_INLINE_VISIBILITY constexpr operator strong_equality() const noexcept { return __value_ == 0 ? strong_equality::equal : strong_equality::nonequal; } _LIBCPP_INLINE_VISIBILITY constexpr operator partial_ordering() const noexcept { return __value_ == 0 ? partial_ordering::equivalent : (__value_ < 0 ? partial_ordering::less : partial_ordering::greater); } _LIBCPP_INLINE_VISIBILITY constexpr operator weak_ordering() const noexcept { return __value_ == 0 ? weak_ordering::equivalent : (__value_ < 0 ? weak_ordering::less : weak_ordering::greater); } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, strong_ordering __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(_CmpUnspecifiedParam, strong_ordering __v) noexcept; #endif private: _ValueT __value_; }; _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::less(_OrdResult::__less); _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::equal(_EqResult::__equal); _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::greater(_OrdResult::__greater); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ >= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 == __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 != __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 < __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 <= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 > __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 >= __v.__value_; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr strong_ordering operator<=>(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr strong_ordering operator<=>(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return __v < 0 ? strong_ordering::greater : (__v > 0 ? strong_ordering::less : __v); } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR // named comparison functions _LIBCPP_INLINE_VISIBILITY constexpr bool is_eq(weak_equality __cmp) noexcept { return __cmp == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_neq(weak_equality __cmp) noexcept { return __cmp != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_lt(partial_ordering __cmp) noexcept { return __cmp < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_lteq(partial_ordering __cmp) noexcept { return __cmp <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_gt(partial_ordering __cmp) noexcept { return __cmp > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_gteq(partial_ordering __cmp) noexcept { return __cmp >= 0; } namespace __comp_detail { enum _ClassifyCompCategory : unsigned{ _None, _WeakEq, _StrongEq, _PartialOrd, _WeakOrd, _StrongOrd, _CCC_Size }; template <class _Tp> _LIBCPP_INLINE_VISIBILITY constexpr _ClassifyCompCategory __type_to_enum() noexcept { if (is_same_v<_Tp, weak_equality>) return _WeakEq; if (is_same_v<_Tp, strong_equality>) return _StrongEq; if (is_same_v<_Tp, partial_ordering>) return _PartialOrd; if (is_same_v<_Tp, weak_ordering>) return _WeakOrd; if (is_same_v<_Tp, strong_ordering>) return _StrongOrd; return _None; } template <size_t _Size> constexpr _ClassifyCompCategory __compute_comp_type(std::array<_ClassifyCompCategory, _Size> __types) { std::array<int, _CCC_Size> __seen = {}; for (auto __type : __types) ++__seen[__type]; if (__seen[_None]) return _None; if (__seen[_WeakEq]) return _WeakEq; if (__seen[_StrongEq] && (__seen[_PartialOrd] || __seen[_WeakOrd])) return _WeakEq; if (__seen[_StrongEq]) return _StrongEq; if (__seen[_PartialOrd]) return _PartialOrd; if (__seen[_WeakOrd]) return _WeakOrd; return _StrongOrd; } template <class ..._Ts> constexpr auto __get_comp_type() { using _CCC = _ClassifyCompCategory; constexpr array<_CCC, sizeof...(_Ts)> __type_kinds{{__comp_detail::__type_to_enum<_Ts>()...}}; constexpr _CCC _Cat = sizeof...(_Ts) == 0 ? _StrongOrd : __compute_comp_type(__type_kinds); if constexpr (_Cat == _None) return void(); else if constexpr (_Cat == _WeakEq) return weak_equality::equivalent; else if constexpr (_Cat == _StrongEq) return strong_equality::equivalent; else if constexpr (_Cat == _PartialOrd) return partial_ordering::equivalent; else if constexpr (_Cat == _WeakOrd) return weak_ordering::equivalent; else if constexpr (_Cat == _StrongOrd) return strong_ordering::equivalent; else static_assert(_Cat != _Cat, "unhandled case"); } } // namespace __comp_detail // [cmp.common], common comparison category type template<class... _Ts> struct _LIBCPP_TEMPLATE_VIS common_comparison_category { using type = decltype(__comp_detail::__get_comp_type<_Ts...>()); }; template<class... _Ts> using common_comparison_category_t = typename common_comparison_category<_Ts...>::type; // [cmp.alg], comparison algorithms // TODO: unimplemented template<class _Tp> constexpr strong_ordering strong_order(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr weak_ordering weak_order(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr partial_ordering partial_order(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr strong_equality strong_equal(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr weak_equality weak_equal(const _Tp& __lhs, const _Tp& __rhs); #endif // _LIBCPP_STD_VER > 17 _LIBCPP_END_NAMESPACE_STD #endif // _LIBCPP_COMPARE
[ "_@jeremy.ca" ]
_@jeremy.ca
e69f41719effeae0e6a8e6ffbc59dfc75ebd7662
bad4cb7ec18961d4cedcf827f687198886bd744e
/500-599/547-friend-circles.cpp
c4330a566b41da04dec8a20eeeec44c35b54bf30
[]
no_license
lamborghini1993/LeetCode
505fb3fef734deb9a04e342058f4cedc6ffdc8d2
818833ca87e8dbf964c0743d8381408964d37c71
refs/heads/master
2021-12-26T19:54:09.451175
2021-08-15T15:27:20
2021-08-15T15:27:20
160,816,839
0
0
null
null
null
null
UTF-8
C++
false
false
951
cpp
#include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <string> #include <queue> #include <climits> #include <algorithm> #include <unordered_map> using namespace std; class Solution { public: int row, col; int findCircleNum(vector<vector<int>> &M) { row = M.size(); if (row < 1) return 0; col = M[0].size(); vector<bool> vis(row); int result = 0; for (int i = 0; i < row; i++) { if (vis[i]) continue; vis[i] = true; DFS(vis, M, i); result++; } return result; } void DFS(vector<bool> &vis, vector<vector<int>> &grid, int x) { for (int i = 0; i < col; i++) { if (x == i || vis[i] || grid[x][i] == 0) continue; vis[i] = true; DFS(vis, grid, i); } } };
[ "1323242382@qq.com" ]
1323242382@qq.com
1bda00844dd3dc2c4af66df38867da60c7e71481
89db00ac521f82738df606dff95403ae0cf9a52f
/SDL_Demo/Source files/GameWindow.cpp
d98d55d8cf4614cde6f3e274a6dccef6ae07950e
[]
no_license
n1yazbek/Helicopter-Game-final-project-
6f6cc85fb3d3704414085df32f775abb31145833
dc578b99b1e5a226bf0eea7ee5674aadde122aec
refs/heads/master
2023-04-29T08:08:22.033610
2021-05-12T22:22:40
2021-05-12T22:22:40
353,833,169
0
0
null
null
null
null
UTF-8
C++
false
false
2,934
cpp
#include "GameWindow.h" GameWindow::GameWindow(const char* title) :window(NULL), renderer(NULL){ window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, GetWidth(), GetHeight(), SDL_WINDOW_SHOWN); if (window == NULL) { cerr << "There was an error while creating the window" << endl << SDL_GetError() << endl; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); } SDL_Texture* GameWindow::loadTexture(const char* filename) { SDL_Texture* texture = NULL; texture = IMG_LoadTexture(renderer, filename); if (texture == NULL) cout << "Failed to load texture: " << SDL_GetError() << endl; return texture; } void GameWindow::clear() { SDL_RenderClear(renderer); } void GameWindow::render(const Sprite& sprite) { SDL_Rect src; if (sprite.getRows() != 1 || sprite.getCols()!=1) { int cls = 1; int frameW = sprite.getFrameW(), frameH = sprite.getFrameH(); SDL_QueryTexture(sprite.GetTex(), NULL, NULL, &frameW, &frameH); int time_r = (SDL_GetTicks() / sprite.getAnimSpeed()) % (sprite.getRows() ); int time_c = (SDL_GetTicks() / sprite.getAnimSpeed()) % (sprite.getCols()); src.y = sprite.getFrameH() * time_r; src.x = sprite.getFrameW() * time_c; src.w = sprite.getRect().w; src.h = sprite.getRect().h; } else{ src.x = sprite.getRect().x; src.y = sprite.getRect().y; src.w = sprite.getRect().w; src.h = sprite.getRect().h; } SDL_Rect dst; dst.x = sprite.GetX(); dst.y = sprite.GetY(); dst.w = sprite.getRect().w; dst.h = sprite.getRect().h; SDL_Texture* txt = sprite.GetTex(); SDL_RenderCopy(renderer, txt, &src, &dst); } void GameWindow::renderScore( Helicopter& helic) { SDL_QueryTexture(helic.scoreText, NULL, NULL, &helic.texW, &helic.texH); SDL_RenderCopy(renderer, helic.scoreText, NULL, &helic.scoreRect); } void GameWindow::textCreator(TTF_Font* font, SDL_Color color, const char* text, Helicopter&helic) { SDL_Surface* textSurface = TTF_RenderText_Solid(font, text, color); helic.scoreText = SDL_CreateTextureFromSurface(renderer, textSurface); } void GameWindow::render_BestScore(Helicopter& helic) { SDL_QueryTexture(helic.BestScoreText, NULL, NULL, &helic.BestTexW, &helic.BestTexH); SDL_RenderCopy(renderer, helic.BestScoreText, NULL, &helic.BestScoreRect); } void GameWindow::BestScore_Creator(TTF_Font* font, SDL_Color color, const char* text, Helicopter& helic) { SDL_Surface* textSurface = TTF_RenderText_Solid(font, text, color); helic.BestScoreText = SDL_CreateTextureFromSurface(renderer, textSurface); } void GameWindow::display() { SDL_RenderPresent(renderer); } int GameWindow::GetWidth()const{ return width; } int GameWindow::GetHeight() const{ return height; } SDL_Renderer* GameWindow::getRenderer() const { return this->renderer; } GameWindow::~GameWindow() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); }
[ "niiazbek.mamasaliev@edu.bme.hu" ]
niiazbek.mamasaliev@edu.bme.hu
8c00a5ed93401e7ae58ad9eeb4dd4e9fe3fc883c
90517ce1375e290f539748716fb8ef02aa60823b
/solved/f-h/hotel-booking/hotel.cpp
336470bc837871c3046f543eb00e62693fd3978c
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
Code4fun4ever/pc-code
23e4b677cffa57c758deeb655fd4f71b36807281
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
refs/heads/master
2021-01-15T08:15:00.681534
2014-09-08T05:28:39
2014-09-08T05:28:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,637
cpp
#include <cstdio> #include <cstring> #include <list> #include <set> #include <vector> using namespace std; #define MAXN 10000 const int INF = 600 * 100000 + 10; #define Zero(v) memset(v, 0, sizeof(v)) #define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); ++v) typedef vector<int> IV; typedef vector<IV> IVV; // Graphs typedef int w_t; struct Graph { struct Edge { int v; w_t w; Edge(int V, w_t W) : v(V), w(W) {} }; typedef list<Edge> EL; typedef vector<EL> ELV; ELV adj; int n; void init(int N) { n=N; adj.clear(); adj.resize(n); } void add(int u, int v, w_t w) { adj[u].push_back(Edge(v, w)); } struct Node { int s; // number of hotel stops made int t; // accumulated travel time from last stop int v; // city Node(int S, int T, int V) : s(S), t(T), v(V) {} bool operator<(const Node &x) const { if (s != x.s) return s < x.s; if (t != x.t) return t < x.t; return v < x.v; } }; typedef set<Node> NS; int dijkstra(bool hs[], int H) { NS q; // dis[v][s] is the best known distance to reach v after s stops IVV dis = IVV(n, IV(H + 1, INF)); dis[0][0] = 0; q.insert(Node(0, 0, 0)); while (! q.empty()) { Node nd = *(q.begin()); q.erase(q.begin()); if (nd.v == n - 1) return nd.s; if (dis[nd.v][nd.s] < nd.t) continue; cFor (EL, e, adj[nd.v]) { int d = nd.t + e->w; if (d <= 600 && d < dis[e->v][nd.s]) { dis[e->v][nd.s] = d; q.insert(Node(nd.s, d, e->v)); } if (! hs[nd.v] || nd.s == H) continue; d = e->w; if (d <= 600 && d < dis[e->v][nd.s + 1]) { dis[e->v][nd.s + 1] = d; q.insert(Node(nd.s + 1, d, e->v)); } } } return -1; } }; int n, h, m; bool hotels[MAXN]; Graph g; int main() { while (true) { scanf("%d", &n); if (n == 0) break; Zero(hotels); scanf("%d", &h); for (int i = 0; i < h; ++i) { int c; scanf("%d", &c); hotels[c - 1] = true; } g.init(n); scanf("%d", &m); while (m--) { int u, v, w; scanf("%d%d%d", &u, &v, &w); --u, --v; g.add(u, v, w); g.add(v, u, w); } printf("%d\n", g.dijkstra(hotels, h)); } return 0; }
[ "leonardo@diptongonante.com" ]
leonardo@diptongonante.com
cf0528f61aeeefef1a010ce692318643ae80ea68
a3d61b8e29f489cba3c2ff2393af488d5c3df40b
/DeformableObject.hpp
fc8fd13168daa19b4e723276f125c925849eb976
[]
no_license
PeterZhouSZ/adaptiveDeformables
343208e4269bfd1dc1e7a60388cf6c7762f27b07
652599d10c1fae4062c6e001c4751b7ab24baa35
refs/heads/master
2021-09-18T20:46:40.541413
2018-07-19T21:34:21
2018-07-19T21:34:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,124
hpp
#pragma once #include <vector> #include <iostream> #include <json/json.h> #include "Particle.hpp" struct DeformableObject{ DeformableObject(const Json::Value& jv); void dump(const std::string& filename) const; void dumpWithColor(const std::string& filename) const; //void writeHierarchy(const std::string& filename) const; //initialization stuff void computeNeighbors(); void computeBasisAndVolume(); //void computeHierarchy(); //timestepping methods void applyGravity(double dt); void applyElasticForces(double dt); //void applyElasticForcesAdaptive(double dt); void applyElasticForcesNoOvershoot(double dt); void updatePositions(double dt); void bounceOffGround(); void damp(double dt); void springDamping(double dt); Mat3 computeDeformationGradient(int pIndex) const; Mat3 computeDeformationGradientRBF(int pIndex) const; void RBFInit(); //data std::vector<Particle> particles; double lambda, mu, density, dampingFactor; double rbfDelta; //double scalingVarianceThreshold, angularVarianceThreshold; //int hierarchyLevels, parentsPerParticle, int neighborsPerParticle; double particleSize; //static constants confuse me //int desiredNumNeighbors() const { return 24; } std::vector<RenderInfo> renderInfos; void assertFinite() const{ for(const auto& p : particles){ if(!p.position.allFinite()){ std::cout << "bad position! " << std::endl; exit(1); } if(!p.velocity.allFinite()){ std::cout << "bad velocity!" << std::endl; exit(1); } } std::cout << "all finite!" << std::endl; } private: //use to accumulate forces. Stored as a member to avoid allocationg it each timestep std::vector<Vec3> forces; std::vector<Vec3> dampedVelocities; //same for damping //hierarchy 0 is the smallest //std::vector<std::vector<int>> hierarchy; }; //return the points corresponding to cluster centers //from among those specified in indices //n is the number of clusters //returned vector IS SORTED std::vector<int> kMeans(const DeformableObject& d, const std::vector<int>& indices, int n);
[ "ben.james.jones@gmail.com" ]
ben.james.jones@gmail.com
0fa5d9f11a60f90ff00db7bc4392de83cf57565a
d4433d8c51e9dc6e0c2904def0a524c9125555de
/hero/HeroExpItem.h
1afe92fef3c1facd8bb025b64abfd18eb82459cf
[]
no_license
54993306/Classes
3458d9e86d1f0e2caa791cde87aff383b2a228bb
d4d1ec5ca100162bd64156deba3748ce1410151d
refs/heads/master
2020-04-12T06:23:49.273040
2016-11-17T04:00:19
2016-11-17T04:00:19
58,427,218
1
3
null
null
null
null
UTF-8
C++
false
false
825
h
 #ifndef __HEROEXPITEM_ #define __HEROEXPITEM_ #include "AppUI.h" #include "scene/layer/LayerManager.h" #include "mainCity/CityData.h" #include "hero/HeroData.h" class CHeroExpItem: public BaseLayer { public: CREATE_LAYER(CHeroExpItem); virtual bool init(); void onEnter(); void onEvolveBtn(CCObject* pSender); void onExit(); void showMoveDirection(CHero* hero); void evolveTask(const CEvolInfo& evInfo ); void showItem(CItem* item); bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); protected: CCObject* tableviewDataSource(CCObject* pConvertCell, unsigned int uIdx); void addTableCell(unsigned int uIdx, CTableViewCell * pCell); void onRecvTask(CCObject* pSender); private: CLayout *m_ui; CHero *m_hero; CLayout *m_cell; CTableView *m_tableView; CEvolInfo m_evolInfo; }; #endif
[ "54993306@qq.com" ]
54993306@qq.com
2fedd3cbdf4915ca3749281e325f34633495e4b7
21ab8235a1deadbd3914c15645226ca45978b1ad
/simmigoogle1.cpp
1785b66a76e766bb9ef4286809c37072fb6781be
[]
no_license
surarijit/DSA_ALGO
8a9079c71444928f88995679d16dafb50df8be5b
1e1a1e189c9cd11b222150df2aa89952cb15de8d
refs/heads/master
2023-01-29T04:36:49.892183
2020-12-07T07:01:47
2020-12-07T07:01:47
281,638,964
0
4
null
2021-10-01T10:58:11
2020-07-22T09:50:53
C++
UTF-8
C++
false
false
1,407
cpp
/* ARIJIT SUR @duke_knight @surcode @comeback IIT ISM */ #include<bits/stdc++.h> #define SIZE 200 #define mod (ll)(1e9+7) #define INF 0x3f3f3f3f #define max(a,b) (a>b?a:b) #define min(a,b) (a<b?a:b) #define abs(a) (a>0?a:-a) #define all(a) a.begin(),a.end() #define maxelem(a) *max_element(all(a)) #define minelem(a) *min_element(all(a)) #define pb push_back #define pi pair<int,int> #define sort(a) sort(all(a)) #define reverse(a) reverse(all(a)) #define input(a) {for(int i1=0;i1<a.size();i1++) cin>>a[i1];} #define display(a) {for(int i1=0;i1<a.size();i1++) cout<<a[i1]<<" "; cout<<endl;} #define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; typedef long long ll; int dp[SIZE][SIZE][SIZE]; int solve(string X, string Y, int l, int r, int k) { if (!k) return 0; if (l < 0 | r < 0) return 1e9; if (dp[l][r][k] != -1) return dp[l][r][k]; int cost = abs((X[l] - 'a') - (Y[r] - 'a')); return dp[l][r][k] = min(cost + solve(X, Y, l - 1, r - 1, k - 1), min( solve(X, Y, l - 1, r, k), solve(X, Y, l, r - 1, k))); } void solve(){ int n,m,k; string a,b; cin>>n>>m>>k>>a>>b; memset(dp, -1, sizeof (dp)); int ans = solve(a,b,n-1,m-1,k); if(ans==1e9) cout<<-1<<endl; else cout<<ans<<endl; } int main() { IOS int t=1; cin>>t; while(t--){ solve(); } return 0; }
[ "arijit.sur1998@gmail.com" ]
arijit.sur1998@gmail.com
950a9f6167ab15c462bd28748effa1cd092d6849
cec0ca2a70535e17488b3bb6b23d678d7e2dadbb
/BirdGame/CGridNums.h
94e8c4ed86d57517d1b669a28892a81cd8e7f16e
[]
no_license
hb2008hahaha/NumberRecognitionGame
0327938624c43f1cd6ca6995f83a3c9f54010135
4d6193f94e53476a20d58e2d596a0134525e3f5a
refs/heads/master
2021-01-22T14:39:48.517902
2014-08-29T02:41:19
2014-08-29T02:41:19
null
0
0
null
null
null
null
GB18030
C++
false
false
2,013
h
#ifndef CGRIDNUMS_H #define CGRIDNUMS_H ////网格数字 #define BlockNums 10 //不超过32 #define ColNum 5 //每列5个方块 #include "global.h" class CGridNums{ public: CGridNums() { #ifdef QImage ImgBlock.load("://res/pig.png"); #endif } int Nums; char BlockFlag[BlockNums]; void InitGame() { int TmpNum=(2<<BlockNums)-1; int Value=rand()%(TmpNum-1)+1; for(int i=0;i<BlockNums;i++) BlockFlag[i]=(Value&1<<i)!=0; Nums=0; for(int i=0;i<BlockNums;i++) { Nums+= BlockFlag[i]; } } void DrawBoard(QPainter *painter) { for(int i=0;i<BlockNums;i++) DrawBlock(painter,i); } private: #ifdef QTImage QPixmap ImgBlock; #endif void DrawBlock(QPainter *painter,int pos) // { if(pos<0||pos>=BlockNums)return ; int x=pos%ColNum; int y=pos/ColNum; int m=x*BlockSize+1+LocX; //坐标变换 int n=y*BlockSize+1+LocY; #ifdef QTImage if(ImgBlock.isNull()!=true) { if(BlockFlag[pos]!=0)painter->drawPixmap(m,n,BlockSize,BlockSize,ImgBlock); } else { QColor penColor = Qt::green; penColor.setAlpha(80);//将颜色的透明度减小,使方框边界和填充色直接能区分开 if(BlockFlag[pos]==0)//如果被选中的话则变色 painter->setBrush(Qt::NoBrush); else painter->setBrush(Qt::blue); painter->setPen(penColor);//色绘制画笔 painter->drawRect(m,n,BlockSize-1,BlockSize-1);//输入参数依次为左上角坐标,长,宽 } #else QColor penColor = Qt::green; //penColor.setAlpha(80);//将颜色的透明度减小,使方框边界和填充色直接能区分开 if(BlockFlag[pos]==0)//如果被选中的话则变色 painter->setBrush(Qt::NoBrush); else painter->setBrush(Qt::blue); painter->setPen(penColor);//色绘制画笔 painter->drawRect(m,n,BlockSize-1,BlockSize-1);//输入参数依次为左上角坐标,长,宽 #endif } }; #endif // CGRIDNUMS_H
[ "hb2008hahaha@163.com" ]
hb2008hahaha@163.com
a974103cf067e446aa86e3db1dcef1e8e394a06d
8b9b1249163ca61a43f4175873594be79d0a9c03
/deps/boost_1_66_0/libs/test/test/writing-test-ts/assertion-construction-test.cpp
303e6c157564327fe8f6f0dfa463da739b1d6e88
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
maugf214/LiquidCore
f6632537dfb4686f4302e871d997992e6289eb65
80a9cce27ceaeeb3c8002c17ce638ed45410d3e6
refs/heads/master
2022-12-02T01:18:26.132951
2020-08-17T10:27:36
2020-08-17T10:27:36
288,151,167
0
1
MIT
2020-08-17T10:32:05
2020-08-17T10:32:04
null
UTF-8
C++
false
false
21,624
cpp
// (C) Copyright Gennadiy Rozental 2011-2015. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 62023 $ // // Description : unit test for new assertion construction based on input expression // *************************************************************************** // Boost.Test #define BOOST_TEST_MODULE Boost.Test assertion consruction test #include <boost/test/unit_test.hpp> #include <boost/test/tools/assertion.hpp> #include <boost/test/utils/is_forward_iterable.hpp> #include <boost/noncopyable.hpp> #include <map> #include <set> namespace utf = boost::unit_test; //____________________________________________________________________________// #define EXPR_TYPE( expr ) ( assertion::seed() ->* expr ) #if !defined(BOOST_TEST_FWD_ITERABLE_CXX03) // some broken compilers do not implement properly decltype on expressions // partial implementation of is_forward_iterable when decltype not available struct not_fwd_iterable_1 { typedef int const_iterator; typedef int value_type; bool size(); }; struct not_fwd_iterable_2 { typedef int const_iterator; typedef int value_type; bool begin(); }; struct not_fwd_iterable_3 { typedef int value_type; bool begin(); bool size(); }; BOOST_AUTO_TEST_CASE( test_forward_iterable_concept ) { { typedef std::vector<int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { // should also work for references, but from is_forward_iterable typedef std::vector<int>& type; BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef std::list<int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef std::map<int, int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef std::set<int, int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef float type; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef not_fwd_iterable_1 type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef not_fwd_iterable_2 type; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef not_fwd_iterable_3 type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef char type; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { // C-tables are in the forward_iterable concept, but are not containers typedef int type[10]; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { // basic_cstring should be forward iterable and container typedef boost::unit_test::basic_cstring<char> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); typedef boost::unit_test::basic_cstring<const char> type2; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type2>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type2>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type2>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type2 >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type2 >::value, "is_container_forward_iterable failed"); } } //is_container_forward_iterable_impl #endif BOOST_AUTO_TEST_CASE( test_basic_value_expression_construction ) { using namespace boost::test_tools; { predicate_result const& res = EXPR_TYPE( 1 ).evaluate(); BOOST_TEST( res ); BOOST_TEST( res.message().is_empty() ); } { predicate_result const& res = EXPR_TYPE( 0 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); } { predicate_result const& res = EXPR_TYPE( true ).evaluate(); BOOST_TEST( res ); BOOST_TEST( res.message().is_empty() ); } { predicate_result const& res = EXPR_TYPE( 1.5 ).evaluate(); BOOST_TEST( res ); } { predicate_result const& res = EXPR_TYPE( "abc" ).evaluate(); BOOST_TEST( res ); } { predicate_result const& res = EXPR_TYPE( 1>2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [1 <= 2]" ); } } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_comparison_expression ) { using namespace boost::test_tools; { predicate_result const& res = EXPR_TYPE( 1>2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [1 <= 2]" ); } { predicate_result const& res = EXPR_TYPE( 100 < 50 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [100 >= 50]" ); } { predicate_result const& res = EXPR_TYPE( 5 <= 4 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [5 > 4]" ); } { predicate_result const& res = EXPR_TYPE( 10>=20 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [10 < 20]" ); } { int i = 10; predicate_result const& res = EXPR_TYPE( i != 10 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [10 == 10]" ); } { int i = 5; predicate_result const& res = EXPR_TYPE( i == 3 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [5 != 3]" ); } } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_arithmetic_ops ) { using namespace boost::test_tools; { int i = 3; int j = 5; predicate_result const& res = EXPR_TYPE( i+j !=8 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [3 + 5 == 8]" ); } { int i = 3; int j = 5; predicate_result const& res = EXPR_TYPE( 2*i-j > 1 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [2 * 3 - 5 <= 1]" ); } { int j = 5; predicate_result const& res = EXPR_TYPE( 2<<j < 30 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [2 << 5 >= 30]" ); } { int i = 2; int j = 5; predicate_result const& res = EXPR_TYPE( i&j ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [2 & 5]" ); } { int i = 3; int j = 5; predicate_result const& res = EXPR_TYPE( i^j^6 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [3 ^ 5 ^ 6]" ); } // do not support // EXPR_TYPE( 99/2 == 48 || 101/2 > 50 ); // EXPR_TYPE( a ? 100 < 50 : 25*2 == 50 ); // EXPR_TYPE( true,false ); } //____________________________________________________________________________// struct Testee { static int s_copy_counter; Testee() : m_value( false ) {} Testee( Testee const& ) : m_value(false) { s_copy_counter++; } Testee( Testee&& ) : m_value(false) {} Testee( Testee const&& ) : m_value(false) {} bool foo() { return m_value; } operator bool() const { return m_value; } friend std::ostream& operator<<( std::ostream& ostr, Testee const& ) { return ostr << "Testee"; } bool m_value; }; int Testee::s_copy_counter = 0; Testee get_obj() { return Testee(); } Testee const get_const_obj() { return Testee(); } class NC : boost::noncopyable { public: NC() {} bool operator==(NC const&) const { return false; } friend std::ostream& operator<<(std::ostream& ostr, NC const&) { return ostr << "NC"; } }; BOOST_AUTO_TEST_CASE( test_objects ) { using namespace boost::test_tools; int expected_copy_count = 0; { Testee obj; Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( obj ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee const obj; Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( obj ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( get_obj() ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( get_const_obj() ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee::s_copy_counter = 0; Testee t1; Testee t2; predicate_result const& res = EXPR_TYPE( t1 != t2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [Testee == Testee]" ); BOOST_TEST( Testee::s_copy_counter == 0 ); } { NC nc1; NC nc2; predicate_result const& res = EXPR_TYPE( nc1 == nc2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [NC != NC]" ); } } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_pointers ) { using namespace boost::test_tools; { Testee* ptr = 0; predicate_result const& res = EXPR_TYPE( ptr ).evaluate(); BOOST_TEST( !res ); } { Testee obj1; Testee obj2; predicate_result const& res = EXPR_TYPE( &obj1 == &obj2 ).evaluate(); BOOST_TEST( !res ); } { Testee obj; Testee* ptr =&obj; predicate_result const& res = EXPR_TYPE( *ptr ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); } { Testee obj; Testee* ptr =&obj; bool Testee::* mem_ptr =&Testee::m_value; predicate_result const& res = EXPR_TYPE( ptr->*mem_ptr ).evaluate(); BOOST_TEST( !res ); } // do not support // Testee obj; // bool Testee::* mem_ptr =&Testee::m_value; // EXPR_TYPE( obj.*mem_ptr ); } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_mutating_ops ) { using namespace boost::test_tools; { int j = 5; predicate_result const& res = EXPR_TYPE( j = 0 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j -= 5 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j *= 0 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j /= 10 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 4; predicate_result const& res = EXPR_TYPE( j %= 2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j ^= j ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } } BOOST_AUTO_TEST_CASE( test_specialized_comparator_string ) { using namespace boost::test_tools; { std::string s("abc"); predicate_result const& res = EXPR_TYPE( s == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); BOOST_TEST( s == "abc" ); } { predicate_result const& res = EXPR_TYPE( std::string("abc") == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); } { predicate_result const& res = EXPR_TYPE( "abc" == std::string("a") ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); } { predicate_result const& res = EXPR_TYPE( std::string("abc") == std::string("a") ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); } } BOOST_AUTO_TEST_CASE( test_comparison_with_arrays ) { using namespace boost::test_tools; { char c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( c_string_array == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); BOOST_TEST( c_string_array == "abc" ); } { char c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( "a" == c_string_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [a != abc]" ); BOOST_TEST( "abc" == c_string_array ); } { char const c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( c_string_array == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); BOOST_TEST( c_string_array == "abc" ); } { char const c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( "a" == c_string_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [a != abc]" ); BOOST_TEST( "abc" == c_string_array ); } { long int c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( c_long_array == v_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 4 != 7. \nMismatch at position 2: 7 != 4. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } { long int c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( v_long_array == c_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 7 != 4. \nMismatch at position 2: 4 != 7. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } { long int const c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( c_long_array == v_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 4 != 7. \nMismatch at position 2: 7 != 4. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } { long int const c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( v_long_array == c_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 7 != 4. \nMismatch at position 2: 4 != 7. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } } // EOF
[ "eric@flicket.tv" ]
eric@flicket.tv
0ba27240f97b9236796448232c12bc11ec7747a2
23d096a2c207eff63f0c604825d4b2ea1a5474d9
/CRUZET/DataTest/plugins/deltaR.h
9ac3b1690876b52509002c816f1bbafb3475c7f9
[]
no_license
martinamalberti/BicoccaUserCode
40d8272c31dfb4ecd5a5d7ba1b1d4baf90cc8939
35a89ba88412fb05f31996bd269d44b1c6dd42d3
refs/heads/master
2021-01-18T09:15:13.790891
2013-08-07T17:08:48
2013-08-07T17:08:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,197
h
// -*- C++ -*- // // Package: deltaR // Class: deltaR // /**\class deltaR deltaR.h Description: <one line class summary> Implementation: <Notes on implementation> */ // $Id: deltaR.h,v 1.3 2008/11/13 17:33:37 govoni Exp $ // // system include files #include <memory> #include <vector> #include <map> #include <set> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/EcalRawData/interface/EcalRawDataCollections.h" #include "DataFormats/EgammaReco/interface/BasicCluster.h" #include "DataFormats/EgammaReco/interface/BasicClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "CaloOnlineTools/EcalTools/interface/EcalTrackLengthMeasurement.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "PhysicsTools/UtilAlgos/interface/TFileService.h" #include "TFile.h" #include "TH1F.h" #include "TH2F.h" #include "TH3F.h" #include "TGraph.h" #include "TTree.h" #include <vector> // *** for TrackAssociation #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/Common/interface/Handle.h" #include "TrackingTools/TrackAssociator/interface/TrackDetectorAssociator.h" #include "TrackingTools/TrackAssociator/interface/TrackAssociatorParameters.h" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" // *** //for track length #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" #include "Geometry/EcalAlgo/interface/EcalBarrelGeometry.h" #include "RecoCaloTools/Navigation/interface/CaloNavigator.h" #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" // class deltaR : public edm::EDAnalyzer { public: explicit deltaR (const edm::ParameterSet&) ; ~deltaR () ; private: virtual void beginJob (const edm::EventSetup&) {} ; virtual void analyze (const edm::Event&, const edm::EventSetup&) ; virtual void endJob () ; void initHists (int) ; private: edm::InputTag barrelSuperClusterCollection_ ; edm::InputTag endcapSuperClusterCollection_ ; edm::InputTag muonTracksCollection_ ; TrackDetectorAssociator trackAssociator_ ; TrackAssociatorParameters trackParameters_ ; TH1F * m_deltaRSCMu ; TH1F * m_deltaPhiSCMu ; TH1F * m_deltaEtaSCMu ; int m_totalMuons ; } ;
[ "" ]
9ef92fbe19b376a1dba70fdcd3367368348df6b0
3f5fbaeaaf62da1e4f9bfb7b349cf7a3a6e4efcb
/DSA/Linked List/mid of LL (2 methods).cpp
e303c5bdc8890fdb5a003895263dcbba8f306ea3
[]
no_license
dipesh-m/Data-Structures-and-Algorithms
f91cd3e3a71c46dc6ffe22dac6be22d454d01ec3
f3dfd6f1e0f9c0124d589ecdb60e7e0e26eb28fc
refs/heads/master
2023-05-26T05:14:19.258994
2021-05-26T16:41:11
2021-05-26T16:41:11
276,396,488
1
1
null
null
null
null
UTF-8
C++
false
false
1,536
cpp
#include<iostream> using namespace std; #include "class Node.h" #include "taking input and printing LL.h" void printAt(Node* head, int i) { int j=0; while(j<i && head!=NULL) { head=head->next; j++; } if(head!=NULL) { cout<<head->data<<endl; } } int sizeIteratively(Node* head) { if(head==NULL) { return 0; } int c=0; while(head!=NULL) { c++; head=head->next; } return c; } int midOfLLUsingSize(Node* head) { if(head==NULL) { return INT_MIN; } int get_size=sizeIteratively(head); int mid=(get_size-1)/2; return mid; } int midOfLLUsing2Ptrs(Node* head) { if(head==NULL) { return INT_MIN; } Node* slow=head; Node* fast=head->next; int mid=0; while(fast!=NULL) { if(fast->next!=NULL) { fast=fast->next->next; mid+=1; } else { fast=fast->next; } slow=slow->next; } return mid; } int main() { cout<<"INSERT THE LL DATA:-"<<endl; Node* head=takeInput(); //for even sized LL, the index 1 less than (size of LL)/2 is treated as mid int mid1=midOfLLUsingSize(head); if(mid1!=INT_MIN) { cout<<"Mid of LL Using Size: "; printAt(head, mid1); } cout<<endl; int mid2=midOfLLUsing2Ptrs(head); if(mid2!=INT_MIN) { cout<<"Mid of LL Using 2 Pointers: "; printAt(head, mid2); } }
[ "62656237+dipesh-m@users.noreply.github.com" ]
62656237+dipesh-m@users.noreply.github.com
ad8f5239146d53b7968fc59f16e00ae1e0ff200e
3606ebb854d102a67ab65f5f37ad981244a2f9e1
/cpp/design_patterns/singleton.cpp
1d3bcf8e6c92f959e60f97e073f47d032817d720
[]
no_license
pashnidgunde/Code
ebbe0d8fac65bc840a00baf281cf0d6bfcdfd1db
418e68406738ba10b25433b5c4173dc28e2e037a
refs/heads/master
2023-02-25T03:08:50.252370
2022-08-21T20:59:16
2022-08-21T20:59:16
56,103,688
1
0
null
2022-08-13T10:28:22
2016-04-12T22:59:30
C++
UTF-8
C++
false
false
578
cpp
#include <cassert> #include <iostream> #include <mutex> #include <thread> class Singleton { private: Singleton() = default; ~Singleton() = default; static Singleton *instance; std::mutex _m; public: static Singleton *getInstance() { if (nullptr == instance) { std::lock_guard<mutex>(m); if (nullptr == instance) instance = new Singleton(); } return instance; } }; Singleton *Singleton::instance = nullptr; int main() { Singleton *s = Singleton::getInstance(); Singleton *s1 = Singleton::getInstance(); assert(s == s1); }
[ "pashnidgunde@gmail.com" ]
pashnidgunde@gmail.com
38a4707f7a24d9fd1c0ce72c15c2bc7149a2bff9
3b3b9e16fbc253d599783e1e36c7509bb7ceb273
/lg/도로건설3_다익스트라.cpp
d06c381c4afe39c931e659e08dcebd6f0e805734
[]
no_license
ttt977/algorithm
91e7357d4972a10b0b9af9a895249d8952a9d869
828a96b7d3ea6bf99830957d2626f2cd2c8722e0
refs/heads/master
2021-09-11T09:03:51.193340
2021-09-06T09:07:06
2021-09-06T09:07:06
191,852,243
0
0
null
null
null
null
UHC
C++
false
false
1,696
cpp
//다익스트라 알고리즘 활용 최단비용계산 #include <iostream> #include <queue> #include <algorithm> using namespace std; typedef pair<int,pair<int,int> > pii; //현재까지 거리,x,y 위치 저장 int N;//지도 크기 char map[110][110];//지도 정보 int visited[110][110];//방문여부체크 void Input_Data(){ cin >> N; for (int i = 0; i < N; i++){ cin >> map[i]; } } int bfs(int y, int x) //y,x 위치에서 N-1,N-1 위치까지의 최단 경로를 반환 { int arri[4] = {0,-1,0,1}; //좌/상/우/하 방문 int arrj[4] = {-1,0,1,0}; priority_queue<pii> q; //현재 위치에서 상/하/좌/우중 비용이 적은 것을 우선으로 탐색하기 위함 q.push(make_pair(0,make_pair(y,x))); //초기 거리,위치 q에 push visited[y][x] = 1; while(!q.empty()) { int cur_d = q.top().first; int cur_i = q.top().second.first; int cur_j = q.top().second.second; cur_d *= -1; //들어갈 때 (-) 했으므로 뺄때도 (-) 필요 if(cur_i == N-1 && cur_j == N-1) return cur_d; q.pop(); for(int k=0;k<4;k++) { int ni = cur_i + arri[k]; int nj = cur_j + arrj[k]; int nd = 0; if(ni < 0 || nj < 0 || ni > N-1 || nj > N-1) //범위초과냐? continue; if(visited[ni][nj] != 0) //기존방문했냐? continue; visited[ni][nj] = 1; //방문체크 nd = cur_d + (map[ni][nj] - '0'); //이전에방문했던 노드까지 거리 + 내 위치의 값 더하기 nd *= -1; //작은 값 기준으로 우선순위큐에서 뽑아내기 위함 q.push(make_pair(nd,make_pair(ni,nj))); } } } int main(){ int ans = -1; Input_Data(); ans = bfs(0,0); cout << ans << endl; return 0; }
[ "hslim@lginnotek.com" ]
hslim@lginnotek.com
a2d68aa98db6f4b9fa2b72255547dcbe84c0764c
63ae3dbfae3e4273e9d6d98d945341512a4b2177
/Andrew_Sandbox/Version_14/Resources.h
2922155b8f7d0a462119a00d60514b134368d15b
[]
no_license
akm0012/Comp5360_Project1
a89686ee5f56ab00227334363869323a4940245c
3c1fe98c3455d3673276cf80ae71caf8b6470cd1
refs/heads/master
2020-05-17T19:42:58.042454
2015-04-12T19:50:32
2015-04-12T19:50:32
31,297,604
0
0
null
null
null
null
UTF-8
C++
false
false
4,492
h
/* * Comp5360: Project 1 * * File: Resources.h * Created by Andrew K. Marshall on 2/23/15 * Refactored by Evan Hall on 3/12/15 * Repatterened by Andrew Marshall on 3/13/15 * Due Date: 3/18/15 * Version: 1.0 * Version Notes: Final Version. */ #ifndef RESOURCES_H #define RESOURCES_H #define MAX_MESSAGE_LEN 4096 #define MAX_PACKET_LEN 4096 #define NUM_THREADS 1 #define LEFT_LANE 5 #define RIGHT_LANE 0 #define PASSING_SPEED_INCREASE 5 // 5 m/s #define PASSING_BUFFER 20 #define PLATOON_SPACE_BUFFER 15 // The space in between cars #define TRUCK_LENGTH 10 #define CAR_LENGTH 5 #define DANGER_CLOSE 20 #define MAX_NUM_OF_NODES 11 // Packet Types #define INIT_LOCATION_PACKET 7 // Indicates this is a new node joining the sim #define LOCATION_PACKET 8 // Indicates this packet has updated location info #define REQUEST_PACKET 16 // Indicates this packet is a request #define PLATOON_JOIN_INFO_PACKET 32 // Indicates this packet has platoon info for a joining car #define PLATOON_WAIT_TO_JOIN_PACKET 33 // Indicates the car should wait to join #define CAR_JOIN_STATUS 64 // Used to give the all clear // Pre-defined Messages #define ALL_CLEAR 20 #define REQUEST_DENIED 100 #define REQUEST_GRANTED 101 #define REQUEST_ENTER_PLATOON 50 // A request to enter the car train #define REQUEST_LEAVE_PLATOON 51 // A request to leave the platoon #define MAX_HOSTNAME_LENGTH 50 #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <iomanip> #include <iostream> #include <cstdlib> #include <unistd.h> #include <fstream> #include <pthread.h> #include <deque> #include <time.h> using std::string; using std::cout; using std::endl; using std::ifstream; using std::ofstream; using std::deque; using std::to_string; using std::setprecision; typedef double Timestamp; // Used for timing and statistics typedef struct { time_t sec; long nsec; } utime; // This is the struct that represents our packet struct packet_to_send { // Header unsigned int sequence_num; // 4 bytes unsigned int source_address; // 4 bytes unsigned int previous_hop; // 4 bytes (address of last hop) int port_num; // 4 bytes, the port number of the source int previous_hop_node_num; // Node number of last hop unsigned int destination_address; // 4 bytes (All 1's means broadcast) double time_sent; // 8 bytes int node_number_source; // 4 bytes // Only used for status packets bool was_sent; // Used to keep track of if this was "sent in the simulator" // Payload unsigned short packet_type; // 2 bytes (Defines if update location packet or request packet) float x_position; // 4 bytes int y_position; // 4 bytes float x_speed; // 4 bytes bool platoon_member; // 1 byte (Indicates if this node is in a platoon) int number_of_platoon_members; unsigned short message; // 2 bytes int size_of_packet_except_hostname; // Size of everything in this packet, except the hostname char hostname[MAX_HOSTNAME_LENGTH]; } __attribute__(( __packed__ )); typedef struct packet_to_send tx_packet; struct node_info { int node_number; string node_hostname; string node_port_number; float node_x_coordinate; int node_y_coordinate; //int number_of_links; int connected_nodes[MAX_NUM_OF_NODES + 1]; // string connected_hostnames[MAX_NUM_OF_NODES]; // string connected_ports[MAX_NUM_OF_NODES]; }; struct cache_table { unsigned int source_address[MAX_NUM_OF_NODES]; int highest_sequence_num[MAX_NUM_OF_NODES]; int number_of_broadcasts[MAX_NUM_OF_NODES]; // # Times we have bradcasted highest seq.# packet }; // Prototypes extern void send_packet(string hostname_to_send, string port_to_send, packet_to_send packet_out); static int get_number_of_digits(int number) { int result; if (number < 0) { number *= -1; result++; } else if (number == 0) { return 1; } do { number /= 10; result++; } while (number != 0); return result; } static int get_number_of_digits(float number) { int result; if (signbit(number)) { number *= -1; result++; } else if (number == 0.0) { return 1; } double intpart, fractpart; fractpart = modf(number, &intpart); while (intpart != 0.0) { intpart /= 10; result++; } while (fractpart != 0.0) { fractpart *= 10; fractpart = modf(fractpart, &intpart); result++; } return result; } #endif
[ "akm0012@auburn.edu" ]
akm0012@auburn.edu
673715f129f87fad8ffe4db256a34fedfb7bd541
a5909aaec6e4aab8a779ca8bacc4af8f6c1295f3
/samples/12_InitFrameBuffers/12_InitFrameBuffers.cpp
2340e042797046893db3ed9fb3599b9b5d06dbd4
[ "Apache-2.0" ]
permissive
cdotstout/Vulkan-Hpp
538e97e209d18fee139f7482093095ed90644797
eaf09ee61e6cb964cf72e0023cd30777f8e3f9fe
refs/heads/master
2020-07-02T00:00:41.267108
2019-07-25T12:26:03
2019-07-25T12:26:03
201,353,822
0
1
Apache-2.0
2020-01-11T00:44:33
2019-08-08T23:44:48
C++
UTF-8
C++
false
false
3,434
cpp
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // VulkanHpp Samples : 12_InitFrameBuffers // Initialize framebuffers #include "../utils/utils.hpp" #include "vulkan/vulkan.hpp" #include <iostream> static char const* AppName = "12_InitFrameBuffers"; static char const* EngineName = "Vulkan.hpp"; int main(int /*argc*/, char ** /*argv*/) { try { vk::UniqueInstance instance = vk::su::createInstance(AppName, EngineName, {}, vk::su::getInstanceExtensions()); #if !defined(NDEBUG) vk::UniqueDebugReportCallbackEXT debugReportCallback = vk::su::createDebugReportCallback(instance); #endif vk::PhysicalDevice physicalDevice = instance->enumeratePhysicalDevices().front(); vk::su::SurfaceData surfaceData(instance, AppName, AppName, vk::Extent2D(64, 64)); std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex = vk::su::findGraphicsAndPresentQueueFamilyIndex(physicalDevice, *surfaceData.surface); vk::UniqueDevice device = vk::su::createDevice(physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions()); vk::su::SwapChainData swapChainData(physicalDevice, device, *surfaceData.surface, surfaceData.extent, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, vk::UniqueSwapchainKHR(), graphicsAndPresentQueueFamilyIndex.first, graphicsAndPresentQueueFamilyIndex.second); vk::su::DepthBufferData depthBufferData(physicalDevice, device, vk::Format::eD16Unorm, surfaceData.extent); vk::UniqueRenderPass renderPass = vk::su::createRenderPass(device, swapChainData.colorFormat, depthBufferData.format); /* VULKAN_KEY_START */ vk::ImageView attachments[2]; attachments[1] = depthBufferData.imageView.get(); std::vector<vk::UniqueFramebuffer> framebuffers; framebuffers.reserve(swapChainData.imageViews.size()); for (auto const& view : swapChainData.imageViews) { attachments[0] = view.get(); framebuffers.push_back(device->createFramebufferUnique(vk::FramebufferCreateInfo(vk::FramebufferCreateFlags(), renderPass.get(), 2, attachments, surfaceData.extent.width, surfaceData.extent.height, 1))); } // Note: No need to explicitly destroy the Framebuffers, as the destroy functions are called by the destructor of the UniqueFramebuffer on leaving this scope. /* VULKAN_KEY_END */ #if defined(VK_USE_PLATFORM_WIN32_KHR) DestroyWindow(surfaceData.window); #else #pragma error "unhandled platform" #endif } catch (vk::SystemError err) { std::cout << "vk::SystemError: " << err.what() << std::endl; exit(-1); } catch (std::runtime_error err) { std::cout << "std::runtime_error: " << err.what() << std::endl; exit(-1); } catch (...) { std::cout << "unknown error\n"; exit(-1); } return 0; }
[ "mtavenrath@users.noreply.github.com" ]
mtavenrath@users.noreply.github.com
d5bd7de2d25a51669dc06f714bb96c608d0bd850
6a310ae5f8e5fb460a3869ea0fcab25b133dea3e
/src/defin.cpp
b40db238ef913bbf752d73899f5003b146c0112f
[]
no_license
NZT48/nztKernel
4ef0c2a6be12007d0b749efa5795eae64e8fe35b
e043ba48ad0045b7db76df8e7711ec6438faf4a7
refs/heads/master
2022-04-09T22:59:32.391207
2020-03-15T17:14:59
2020-03-15T17:14:59
187,092,514
0
0
null
null
null
null
UTF-8
C++
false
false
52
cpp
#include "defin.h" unsigned volatile lockFlag = 0;
[ "nikolaztodorovic26@gmail.com" ]
nikolaztodorovic26@gmail.com
9e7fd22557f5dc3b3e3d2dfd39481b4fc121be5c
46d7d80c1315a8c3f3f242445559b1b29f7ce782
/Gladiator/main.cpp
2c753923a645cb62297f822b0b7ae1280b663669
[]
no_license
lafferc/Gladiator
eb78943d21350a2fff9b58dea3532c35b004c516
0e5957d8f94ba8a92e87f0b18c88693ae36f8740
refs/heads/master
2022-11-08T09:49:40.246535
2020-06-16T22:52:50
2020-06-16T22:52:50
272,063,353
0
0
null
null
null
null
UTF-8
C++
false
false
2,938
cpp
#include<iostream> #include"gladiator.h" #include<string> #include<ctime> #include<Windows.h> using namespace std; void level1(Gladiator& player); void main() { srand((unsigned)time(0)); string name = ""; Gladiator player; SetConsoleTitle(L"Gladiator v0.0.2"); cout << "What is your name ?..."; cin >> name; cout << "Welcome to Rome " << name << ", you have been condemned to die in the arena\n"; cout << "Here are your stats\n"; player = Gladiator(name, 100, 1, 1, 1, 0, "condemned"); player.print(); cout << "If your health reaches 0 you will die\n starting level 1\n"; system("Pause"); level1(player); system("Pause"); } void battle(Gladiator& player, Unit& oponent) { char command; bool success; oponent.print(); while (player.alive == true && oponent.alive == true) { cout << "use 'a' for normal attack or 's' for strong attack (ignores targets defence rolls). "; cin >> command; if (command == 's') { if ((success = player.strongattack(oponent)) == false) cout << "You cannot perform that attack\n"; } else { if ((success = player.attack(oponent)) == false) cout << "Your attack failed\n"; } if (success == true) { oponent.print(); } if (oponent.alive == true) { if (oponent.attack(player) == true) player.print(); else cout << oponent.name << "'s attack failed\n"; } } if (player.alive == true) { player.print(); } } void level1(Gladiator& player) { Gladiator* boss; cout << "You must defeat the 5 others that have also been condemned\n"; for (int i = 0; i < 5; i++) { Unit* unit; if (player.alive == false) { cout << "You were killed by unit" << i << endl; cout << "You died in the arena\n"; return; } unit = Gladiator::create_condemned("unit" + to_string(i + 1)); battle(player, *unit); delete unit; } player.heal(25); player.s_a_remaining += 2; player.print(); cout << "You are alone in the arena, surrounded by your fallen foe\n"; cout << "You barely have time to catch your breath, when a gate opens and another gladiator enters.\n This is not going to be easy\n"; system("Pause"); boss = Gladiator::factory("gladiator1"); battle(player, *boss); if(boss->alive==false) { cout << "\nGood work you kill the gladiator\n"; cout << "\ngold taken from " << boss->name << ": " << boss->money << endl; player.money += boss->money; player.skill += 2; player.print(); } else if(player.alive==false){ cout<<"You died in the arena\n"; } delete boss; }
[ "lafferc@tcd.ie" ]
lafferc@tcd.ie
b37fb86311fbee709cb703096f8fe047728cda12
df6481f4023d47cfcbfa87318ceae38d870d14a6
/heimdall/source/FlashAction.h
b4e1b6baa070f6e41b931667ce4cf72ac927bbd0
[ "MIT" ]
permissive
nka11/Heimdall
152bd30e8bd9faef5f7a4136cddf5888056a8dea
efedda846db56b6ba9c0b8e337210843f084345a
refs/heads/master
2021-01-17T22:56:34.881802
2013-01-18T17:26:57
2013-01-18T17:26:57
6,088,699
1
0
null
null
null
null
UTF-8
C++
false
false
1,276
h
/* Copyright (c) 2010-2012 Benjamin Dobell, Glass Echidna Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef FLASHACTION_H #define FLASHACTION_H namespace Heimdall { namespace FlashAction { extern const char *usage; int Execute(int argc, char **argv); }; } #endif
[ "benjamin.dobell+git@glassechidna.com.au" ]
benjamin.dobell+git@glassechidna.com.au
a4b38bbb324c72b52723a2918eaf2480ef910dec
bb287b07de411c95595ec364bebbaf44eaca4fc6
/src/work/test/WorkTests.cpp
a38e36e432512d0cc61f9a505ee1050656e2e9c6
[ "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT", "BSD-2-Clause" ]
permissive
viichain/vii-core
09eb613344630bc80fee60aeac434bfb62eab46e
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
refs/heads/master
2020-06-28T06:33:58.908981
2019-08-14T02:02:13
2019-08-14T02:02:13
200,164,931
0
0
null
null
null
null
UTF-8
C++
false
false
22,806
cpp
#include "lib/catch.hpp" #include "lib/util/format.h" #include "main/Application.h" #include "main/Config.h" #include "process/ProcessManager.h" #include "test/TestUtils.h" #include "test/test.h" #include "work/WorkScheduler.h" #include "historywork/RunCommandWork.h" #include "work/BatchWork.h" #include <cstdio> #include <fstream> #include <random> #include <xdrpp/autocheck.h> using namespace viichain; class TestBasicWork : public BasicWork { bool mShouldFail; public: int const mNumSteps; int mCount; int mRunningCount{0}; int mSuccessCount{0}; int mFailureCount{0}; int mRetryCount{0}; int mAbortCount{0}; TestBasicWork(Application& app, std::string name, bool fail = false, int steps = 3, size_t retries = RETRY_ONCE) : BasicWork(app, std::move(name), retries) , mShouldFail(fail) , mNumSteps(steps) , mCount(steps) { } void forceWakeUp() { wakeUp(); } protected: BasicWork::State onRun() override { CLOG(DEBUG, "Work") << "Running " << getName(); mRunningCount++; if (--mCount > 0) { return State::WORK_RUNNING; } return mShouldFail ? State::WORK_FAILURE : State::WORK_SUCCESS; } bool onAbort() override { CLOG(DEBUG, "Work") << "Aborting " << getName(); ++mAbortCount; return true; } void onSuccess() override { ++mSuccessCount; } void onFailureRaise() override { ++mFailureCount; } void onFailureRetry() override { ++mRetryCount; } void onReset() override { mCount = mNumSteps; } }; class TestWaitingWork : public TestBasicWork { VirtualTimer mTimer; public: int mWaitingCount{0}; int mWakeUpCount{0}; TestWaitingWork(Application& app, std::string name) : TestBasicWork(app, name), mTimer(app.getClock()) { } protected: BasicWork::State onRun() override { ++mRunningCount; if (--mCount > 0) { std::weak_ptr<TestWaitingWork> weak( std::static_pointer_cast<TestWaitingWork>(shared_from_this())); auto handler = [weak](asio::error_code const& ec) { auto self = weak.lock(); if (self) { ++(self->mWakeUpCount); self->wakeUp(); } }; mTimer.expires_from_now(std::chrono::milliseconds(1)); mTimer.async_wait(handler); ++mWaitingCount; return BasicWork::State::WORK_WAITING; } return BasicWork::State::WORK_SUCCESS; } }; TEST_CASE("BasicWork test", "[work][basicwork]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); auto checkSuccess = [](TestBasicWork const& w) { REQUIRE(w.getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w.mRunningCount == w.mNumSteps); REQUIRE(w.mSuccessCount == 1); REQUIRE(w.mFailureCount == 0); REQUIRE(w.mRetryCount == 0); }; SECTION("one work") { auto w = wm.scheduleWork<TestBasicWork>("test-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w); } SECTION("2 works round robin") { auto w1 = wm.scheduleWork<TestBasicWork>("test-work1"); auto w2 = wm.scheduleWork<TestBasicWork>("test-work2"); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w1); checkSuccess(*w2); } SECTION("work waiting") { auto w = wm.scheduleWork<TestWaitingWork>("waiting-test-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w); REQUIRE(w->mWaitingCount == w->mWakeUpCount); REQUIRE(w->mWaitingCount == w->mNumSteps - 1); } SECTION("new work added midway") { auto w1 = wm.scheduleWork<TestBasicWork>("test-work1"); auto w2 = wm.scheduleWork<TestBasicWork>("test-work2"); std::shared_ptr<TestBasicWork> w3; while (!wm.allChildrenSuccessful()) { clock.crank(); if (!w3) { w3 = wm.scheduleWork<TestBasicWork>("test-work3"); }; } checkSuccess(*w1); checkSuccess(*w2); checkSuccess(*w3); } SECTION("new work wakes up scheduler") { while (wm.getState() != TestBasicWork::State::WORK_WAITING) { clock.crank(); } auto w = wm.scheduleWork<TestBasicWork>("test-work"); REQUIRE(wm.getState() == TestBasicWork::State::WORK_RUNNING); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w); } SECTION("work retries and fails") { auto w = wm.scheduleWork<TestBasicWork>("test-work", true); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(w->mRunningCount == w->mNumSteps * (BasicWork::RETRY_ONCE + 1)); REQUIRE(w->mSuccessCount == 0); REQUIRE(w->mFailureCount == 1); REQUIRE(w->mRetryCount == BasicWork::RETRY_ONCE); } SECTION("work shutdown") { auto w = wm.scheduleWork<TestBasicWork>("test-work", false, 100); while (!wm.allChildrenDone()) { clock.crank(); w->shutdown(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(w->mAbortCount == 1); REQUIRE(w->mCount == w->mNumSteps); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } } class TestWork : public Work { public: int mRunningCount{0}; int mSuccessCount{0}; int mFailureCount{0}; int mRetryCount{0}; TestWork(Application& app, std::string name) : Work(app, std::move(name), RETRY_NEVER) { } BasicWork::State doWork() override { ++mRunningCount; return WorkUtils::checkChildrenStatus(*this); } template <typename T, typename... Args> std::shared_ptr<T> addTestWork(Args&&... args) { return addWork<T>(std::forward<Args>(args)...); } void onSuccess() override { mSuccessCount++; } void onFailureRaise() override { mFailureCount++; } void onFailureRetry() override { mRetryCount++; } }; TEST_CASE("work with children", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); auto w1 = wm.scheduleWork<TestWork>("test-work1"); auto w2 = wm.scheduleWork<TestWork>("test-work2"); auto l1 = w1->addTestWork<TestBasicWork>("leaf-work"); auto l2 = w1->addTestWork<TestBasicWork>("leaf-work-2"); SECTION("success") { while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(l1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(l2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } SECTION("child failed") { auto l3 = w2->addTestWork<TestBasicWork>("leaf-work3", true); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(l1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(l2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w2->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(l3->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } SECTION("child failed so parent aborts other child") { auto l3 = w2->addTestWork<TestBasicWork>("leaf-work3", true, 3, TestBasicWork::RETRY_NEVER); auto l4 = w2->addTestWork<TestBasicWork>("leaf-work4", false, 100); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(l1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(l2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w2->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(l3->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(l4->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } SECTION("work scheduler shutdown") { wm.shutdown(); REQUIRE(wm.isAborting()); REQUIRE(w1->isAborting()); REQUIRE(w2->isAborting()); REQUIRE(l1->isAborting()); REQUIRE(l2->isAborting()); REQUIRE_NOTHROW(l1->forceWakeUp()); REQUIRE_NOTHROW(l2->forceWakeUp()); REQUIRE(l1->isAborting()); REQUIRE(l2->isAborting()); REQUIRE_THROWS_AS(w1->addTestWork<TestBasicWork>("leaf-work-3"), std::runtime_error); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(wm.getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(w1->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(w2->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(l1->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(l2->getState() == TestBasicWork::State::WORK_ABORTED); } } TEST_CASE("work scheduling and run count", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); auto mainWork = wm.scheduleWork<TestWork>("main-work"); SECTION("multi-level tree") { auto w1 = mainWork->addTestWork<TestBasicWork>("3-step-work"); auto w2 = mainWork->addTestWork<TestWork>("wait-for-children-work"); auto c1 = w2->addTestWork<TestBasicWork>("child-3-step-work"); auto c2 = w2->addTestWork<TestBasicWork>("other-child-3-step-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w1->mRunningCount == w1->mNumSteps); REQUIRE(w2->mRunningCount == c1->mNumSteps); REQUIRE(c1->mRunningCount == c1->mNumSteps); REQUIRE(c2->mRunningCount == c2->mNumSteps); REQUIRE(mainWork->mRunningCount == (c1->mRunningCount * 2 + w2->mRunningCount)); } SECTION("multi-level tree more leaves do not affect scheduling") { auto w1 = mainWork->addTestWork<TestWork>("test-work-1"); auto w2 = mainWork->addTestWork<TestWork>("test-work-2"); auto c1 = w1->addTestWork<TestBasicWork>("child-3-step-work"); auto c2 = w1->addTestWork<TestBasicWork>("other-child-3-step-work"); auto c3 = w2->addTestWork<TestBasicWork>("2-child-3-step-work"); auto c4 = w2->addTestWork<TestBasicWork>("2-other-child-3-step-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w2->mRunningCount == c1->mNumSteps); REQUIRE(c1->mRunningCount == c1->mNumSteps); REQUIRE(c2->mRunningCount == c2->mNumSteps); REQUIRE(mainWork->mRunningCount == (c2->mRunningCount * 2 + w2->mRunningCount)); } } TEST_CASE("work scheduling compare trees", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); SECTION("linked list structure") { auto w1 = wm.scheduleWork<TestWork>("work-1"); auto w2 = w1->addTestWork<TestWork>("work-2"); auto w3 = w2->addTestWork<TestBasicWork>("work-3"); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w3->mRunningCount == w3->mNumSteps); REQUIRE(w2->mRunningCount == w3->mRunningCount); REQUIRE(w1->mRunningCount == w2->mRunningCount + w3->mRunningCount); } SECTION("flat work sequence") { auto w1 = std::make_shared<TestWork>(*appPtr, "work-1"); auto w2 = std::make_shared<TestWork>(*appPtr, "work-2"); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w3, w2, w1}; auto sw = wm.scheduleWork<WorkSequence>("test-work-sequence", seq); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w3->mRunningCount == w3->mNumSteps); REQUIRE(w2->mRunningCount == 1); REQUIRE(w1->mRunningCount == 1); } } class TestRunCommandWork : public RunCommandWork { std::string mCommand; public: TestRunCommandWork(Application& app, std::string name, std::string command) : RunCommandWork(app, std::move(name)), mCommand(std::move(command)) { } ~TestRunCommandWork() override = default; CommandInfo getCommand() override { return CommandInfo{mCommand, std::string()}; } BasicWork::State onRun() override { return RunCommandWork::onRun(); } }; TEST_CASE("RunCommandWork test", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); SECTION("one run command work") { wm.scheduleWork<TestRunCommandWork>("test-run-command", "date"); while (!wm.allChildrenSuccessful()) { clock.crank(); } } SECTION("round robin with other work") { wm.scheduleWork<TestRunCommandWork>("test-run-command", "date"); wm.scheduleWork<TestBasicWork>("test-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } } SECTION("invalid run command") { auto w = wm.scheduleWork<TestRunCommandWork>("test-run-command", "_invalid_"); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_FAILURE); } SECTION("run command aborted") { #ifdef _WIN32 std::string command = "waitfor /T 10 pause"; #else std::string command = "sleep 10"; #endif auto w = wm.scheduleWork<TestRunCommandWork>("test-run-command", command); while (w->getState() != TestBasicWork::State::WORK_WAITING) { clock.crank(); } REQUIRE(appPtr->getProcessManager().getNumRunningProcesses()); wm.shutdown(); while (wm.getState() != TestBasicWork::State::WORK_ABORTED) { clock.crank(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(appPtr->getProcessManager().getNumRunningProcesses() == 0); } } TEST_CASE("WorkSequence test", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); SECTION("basic") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1"); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2"); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.scheduleWork<WorkSequence>("test-work-sequence", seq); while (!wm.allChildrenSuccessful()) { if (!w1->mSuccessCount) { REQUIRE(!w2->mRunningCount); REQUIRE(!w3->mRunningCount); } else if (!w2->mSuccessCount) { REQUIRE(w1->mSuccessCount); REQUIRE(!w3->mRunningCount); } else { REQUIRE(w1->mSuccessCount); REQUIRE(w2->mSuccessCount); } clock.crank(); } } SECTION("WorkSequence is empty") { std::vector<std::shared_ptr<BasicWork>> seq{}; auto work2 = wm.scheduleWork<WorkSequence>("test-work-sequence-2", seq); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(work2->getState() == TestBasicWork::State::WORK_SUCCESS); } SECTION("first work fails") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1", true); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2"); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.executeWork<WorkSequence>("test-work-sequence", seq); auto w1RunCount = w1->mNumSteps * (BasicWork::RETRY_ONCE + 1); REQUIRE(w1->mRunningCount == w1RunCount * (BasicWork::RETRY_A_FEW + 1)); REQUIRE(w1->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE_FALSE(w2->mRunningCount); REQUIRE_FALSE(w2->mSuccessCount); REQUIRE_FALSE(w2->mFailureCount); REQUIRE_FALSE(w2->mRetryCount); REQUIRE_FALSE(w3->mRunningCount); REQUIRE_FALSE(w3->mSuccessCount); REQUIRE_FALSE(w3->mFailureCount); REQUIRE_FALSE(w3->mRetryCount); REQUIRE(work->getState() == TestBasicWork::State::WORK_FAILURE); } SECTION("fails midway") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1"); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2", true); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.executeWork<WorkSequence>("test-work-sequence", seq); auto w2RunCount = w2->mNumSteps * (BasicWork::RETRY_ONCE + 1); REQUIRE(w2->mRunningCount == w2RunCount * (BasicWork::RETRY_A_FEW + 1)); REQUIRE(w2->getState() == BasicWork::State::WORK_FAILURE); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->mRunningCount); REQUIRE(w1->mSuccessCount); REQUIRE_FALSE(w1->mFailureCount); REQUIRE_FALSE(w1->mRetryCount); REQUIRE_FALSE(w3->mRunningCount); REQUIRE_FALSE(w3->mSuccessCount); REQUIRE_FALSE(w3->mFailureCount); REQUIRE_FALSE(w3->mRetryCount); REQUIRE(work->getState() == TestBasicWork::State::WORK_FAILURE); } SECTION("work scheduler shutdown") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1", false, 100); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2", false, 100); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3", false, 100); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.scheduleWork<WorkSequence>("test-work-sequence", seq); clock.crank(); CHECK(!wm.allChildrenDone()); wm.shutdown(); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(work->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(wm.getState() == TestBasicWork::State::WORK_ABORTED); } } class TestBatchWork : public BatchWork { bool mShouldFail; int mTotalWorks; public: int mCount{0}; std::vector<std::shared_ptr<TestBasicWork>> mBatchedWorks; TestBatchWork(Application& app, std::string const& name, bool fail = false) : BatchWork(app, name) , mShouldFail(fail) , mTotalWorks(app.getConfig().MAX_CONCURRENT_SUBPROCESSES * 2) { } protected: bool hasNext() const override { return mCount < mTotalWorks; } void resetIter() override { mCount = 0; } std::shared_ptr<BasicWork> yieldMoreWork() override { bool fail = mCount == mTotalWorks - 1 && mShouldFail; auto w = std::make_shared<TestBasicWork>( mApp, fmt::format("child-{:d}", mCount++), fail); if (!fail) { mBatchedWorks.push_back(w); } return w; } }; TEST_CASE("Work batching", "[batching][work]") { VirtualClock clock; Application::pointer app = createTestApplication(clock, getTestConfig()); auto& wm = app->getWorkScheduler(); SECTION("success") { auto testBatch = wm.scheduleWork<TestBatchWork>("test-batch"); while (!clock.getIOContext().stopped() && !wm.allChildrenDone()) { clock.crank(true); REQUIRE(testBatch->getNumWorksInBatch() <= app->getConfig().MAX_CONCURRENT_SUBPROCESSES); } REQUIRE(testBatch->getState() == TestBasicWork::State::WORK_SUCCESS); } SECTION("shutdown") { auto testBatch = wm.scheduleWork<TestBatchWork>("test-batch", true); while (!clock.getIOContext().stopped() && !wm.allChildrenDone()) { clock.crank(true); wm.shutdown(); } REQUIRE(testBatch->getState() == TestBasicWork::State::WORK_ABORTED); for (auto const& w : testBatch->mBatchedWorks) { auto validState = w->getState() == TestBasicWork::State::WORK_SUCCESS || w->getState() == TestBasicWork::State::WORK_ABORTED; REQUIRE(validState); } } }
[ "viichain" ]
viichain
d27fcb69ef8452171f1fb4e3912465e111142484
276bf5f1534176d7ecdd28f49b5167fc141d7e33
/systemc-tutorial-examples/tlm/buffer/main.cpp
5d727b32c4e4dba4b26e9d45c977622f62d0c4c5
[]
no_license
vj-sananda/systemc
dfa56b8e1131e86ac1322be885fad3528fc24e74
492fa6effb304e18ec66918dd10f17b1fe86b4d8
refs/heads/master
2021-01-05T01:15:41.328636
2020-02-16T03:41:26
2020-02-16T03:41:26
240,826,440
0
0
null
null
null
null
UTF-8
C++
false
false
570
cpp
#include "systemc.h" #include "flatbuffer.cpp" #include "complexbuffer.cpp" #include "bufwriter.cpp" /* simulation main function */ int sc_main(int argc, char *argv[]) { // instantiate a FlatBuffer and a Bufwriter FlatBuffer buf1("Buffer1"); Bufwriter writer("BufWriter1"); /* alternative: instantiate a ComplexBuffer */ ComplexBuffer buf2("Buffer2"); // link the buffer to the writer writer.buf(buf2); // also try: //writer.buf(buf2); // feeding writer the complex buffer // start the simulation sc_start(); }
[ "vsananda@macbook-pro-9.lan" ]
vsananda@macbook-pro-9.lan
b4cbdf6bdcd0b97e3471e6ff9fd34a260efc9a8e
2efbd55f9c7f39bddc1348f3a9d38a8f05d0644a
/plugins/eeui/WeexSDK/ios/weex_core/Source/include/wtf/dtoa.h
83f092bb214f6216d118c222b2ff6114bf1232d4
[ "MIT" ]
permissive
bonniesl/yktapp
23b05cc53214269bf1d792dcf41993b425bfe470
3f96b7aad945e9aa110f0643d9a57e28d0645ab6
refs/heads/master
2023-03-27T04:27:14.921221
2021-03-25T06:29:16
2021-03-25T06:33:12
351,330,677
0
0
null
null
null
null
UTF-8
C++
false
false
3,704
h
/* * Copyright (C) 2003, 2008, 2012 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef WTF_dtoa_h #define WTF_dtoa_h #include <unicode/utypes.h> #include <wtf/ASCIICType.h> #include <wtf/dtoa/double-conversion.h> #include <wtf/text/StringView.h> namespace WTF { typedef char DtoaBuffer[80]; WTF_EXPORT_PRIVATE void dtoa(DtoaBuffer result, double dd, bool& sign, int& exponent, unsigned& precision); WTF_EXPORT_PRIVATE void dtoaRoundSF(DtoaBuffer result, double dd, int ndigits, bool& sign, int& exponent, unsigned& precision); WTF_EXPORT_PRIVATE void dtoaRoundDP(DtoaBuffer result, double dd, int ndigits, bool& sign, int& exponent, unsigned& precision); // Size = 80 for sizeof(DtoaBuffer) + some sign bits, decimal point, 'e', exponent digits. const unsigned NumberToStringBufferLength = 96; typedef char NumberToStringBuffer[NumberToStringBufferLength]; typedef LChar NumberToLStringBuffer[NumberToStringBufferLength]; WTF_EXPORT_PRIVATE const char* numberToString(double, NumberToStringBuffer); WTF_EXPORT_PRIVATE const char* numberToFixedPrecisionString(double, unsigned significantFigures, NumberToStringBuffer, bool truncateTrailingZeros = false); WTF_EXPORT_PRIVATE const char* numberToFixedWidthString(double, unsigned decimalPlaces, NumberToStringBuffer); double parseDouble(const LChar* string, size_t length, size_t& parsedLength); double parseDouble(const UChar* string, size_t length, size_t& parsedLength); double parseDouble(StringView, size_t& parsedLength); namespace Internal { WTF_EXPORT_PRIVATE double parseDoubleFromLongString(const UChar* string, size_t length, size_t& parsedLength); } inline double parseDouble(const LChar* string, size_t length, size_t& parsedLength) { return double_conversion::StringToDoubleConverter::StringToDouble(reinterpret_cast<const char*>(string), length, &parsedLength); } inline double parseDouble(const UChar* string, size_t length, size_t& parsedLength) { const size_t conversionBufferSize = 64; if (length > conversionBufferSize) return Internal::parseDoubleFromLongString(string, length, parsedLength); LChar conversionBuffer[conversionBufferSize]; for (int i = 0; i < static_cast<int>(length); ++i) conversionBuffer[i] = isASCII(string[i]) ? string[i] : 0; return parseDouble(conversionBuffer, length, parsedLength); } inline double parseDouble(StringView string, size_t& parsedLength) { if (string.is8Bit()) return parseDouble(string.characters8(), string.length(), parsedLength); return parseDouble(string.characters16(), string.length(), parsedLength); } } // namespace WTF using WTF::NumberToStringBuffer; using WTF::NumberToLStringBuffer; using WTF::numberToString; using WTF::numberToFixedPrecisionString; using WTF::numberToFixedWidthString; using WTF::parseDouble; #endif // WTF_dtoa_h
[ "1336429771@qq.com" ]
1336429771@qq.com
12ad3191dc3e63ddff4a944b9700f009a7a79028
762d0c7c44687373bf643624c8ac616cb08cd227
/Espresso Shot/src/Espresso/main.cpp
56050ded678e29d7e6daa7fe8b711b9ddc9e7e7f
[ "MIT" ]
permissive
Promethaes/Espresso-Shot-Engine
eba955c95cbbce03cb22051bd055ae89a499d984
6dffcbd5e69708af2f8251b701b7052207162e9b
refs/heads/master
2020-07-17T03:27:23.751072
2019-09-10T02:56:06
2019-09-10T02:56:06
205,931,611
0
0
null
null
null
null
UTF-8
C++
false
false
5,235
cpp
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <Fmod/fmod.h> #include <Fmod/fmod_common.h> #include <Fmod/fmod.hpp> #include <Fmod/fmod_errors.h> #include <iostream> #include <vector> #include <time.h> #include "Espresso/Camera.h" #include "Espresso/ShaderProgram.h" #include "Espresso/XinputManager.h" #include "Espresso/Scene Manager.h" #include "Espresso/Test Scene.h" #include "Espresso/f16.h" #define _CRT_SECURE_NO_WARNINGS #define Scenes Espresso::Scene::scenes #define GameObjects Espresso::GameObject::gameObjects #define ESPRESSOSHOTPATH std::string(std::getenv("EspressoShotPath")) void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(Espresso::Camera& defaultCamera, float dt, GLFWwindow* window); void mouse_callback(GLFWwindow* window, double xpos, double ypos); //settings, might change from globals to something else float lastX = 400, lastY = 300; float yaw = -90.0f; float pitch = 0.0f; bool firstMouse = true; Espresso::Camera* defaultCamera = new Espresso::Camera(); float dt = 0.0f; // Time between current frame and last frame float lastFrame = 0.0f; // Time of last frame int main() { srand(time(0)); //initialize glfw #pragma region InitialzeGLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(800 * 2, 600 * 2, "Espresso Test", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << "\n"; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << "\n"; return -1; } //end initialization #pragma endregion #pragma region InitializeFmod ///This code is NOT mine, it is from <https://www.fmod.com/resources/documentation-api?version=2.0&page=white-papers-getting-started.html> FMOD_RESULT result; FMOD::System* system = NULL; result = FMOD::System_Create(&system); // Create the main system object. if (result != FMOD_OK) { printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result)); exit(-1); } result = system->init(512, FMOD_INIT_NORMAL, 0); // Initialize FMOD. if (result != FMOD_OK) { printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result)); exit(-1); } #pragma endregion ///FMOD::Sound** sound = nullptr; ///FMOD::ChannelGroup** group1; ///std::string soundPath = ESPRESSOSHOTPATH + "Assets/Sound/testSound.mp3"; ///auto soundHandle = system->createSound(soundPath.c_str(),FMOD_2D ,new FMOD_CREATESOUNDEXINFO(),sound); ///auto channelGHandle = system->createChannelGroup("group1", group1); ///FMOD::Channel** channel = nullptr; /// ///system->playSound(*sound, *group1, false, channel); Espresso::Shader lightingShader(ESPRESSOSHOTPATH + "Assets/Shaders/lightingShader.vert", ESPRESSOSHOTPATH + "Assets/Shaders/lightingShader.frag"); Sedna::XinputManager* manager = new Sedna::XinputManager(); Sedna::XinputController* controller = manager->getController(0); bool f16Test = false; bool sceneTest = true; if (f16Test == true) sceneTest = true; //if (f16Test) // Espresso::F16 f16(Espresso::Mesh(ESPRESSOSHOTPATH + "Assets/Mesh/f16.obj"), lightingShader, manager, 0); //run this scene if (sceneTest) Espresso::TestScene* s = new Espresso::TestScene(true); glEnable(GL_DEPTH_TEST); //render loop while (!glfwWindowShouldClose(window)) { float currentFrame = glfwGetTime(); dt = currentFrame - lastFrame; lastFrame = currentFrame; processInput(*defaultCamera, dt, window); glClearColor(0.33f, 0.33f, 0.33f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //manager->update(); for (unsigned i = 0; i < Scenes.size(); i++) { if (!Scenes[i]->isInit()) Scenes[i]->init(); if (Scenes[i]->isInit()) Scenes[i]->baseUpdate(dt, *defaultCamera); } for (auto x : GameObjects) x->baseUpdate(dt); glfwSwapBuffers(window); glfwPollEvents(); } //end of program glfwTerminate(); return 0; } void processInput(Espresso::Camera& defaultCamera, float dt, GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); defaultCamera.move(window, 2.5f * dt); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; lastX = xpos; lastY = ypos; defaultCamera->doMouseMovement(xoffset, yoffset); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); }
[ "anth19800@hotmail.com" ]
anth19800@hotmail.com
9a0f0484baf335c54b14c235ec39e910a255c40b
d32424b20ae663a143464a9277f8090bd017a7f6
/arsenal/datastructure/BinaryTree/Traversal.cpp
13b2ccf10e67bc8c895ab158b41e8b11b1a02f1e
[]
no_license
Vesion/Misirlou
a8df716c17a3072e5cf84b5e279c06e2eac9e6a7
95274c8ccb3b457d5e884bf26948b03967b40b32
refs/heads/master
2023-05-01T10:05:40.709033
2023-04-22T18:41:29
2023-04-22T18:43:05
51,061,447
1
0
null
null
null
null
UTF-8
C++
false
false
3,296
cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <stack> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left, *right; TreeNode(int v) : val(v), left(NULL), right(NULL) {} }; // preorder / inorder / postorder / level order // recursively + iteratively // preorder traverse, recursively class Solution_pre_re { public: void preorder(TreeNode* root) { if (root) { cout << root->val << " "; preorder(root->left); preorder(root->right); } } }; // preorder traverse, stack class Solution_pre_it { public: void preorder(TreeNode* root) { if (!root) return; stack<TreeNode*> st; st.push(root); while (!st.empty()) { TreeNode* p = st.top(); st.pop(); cout << p->val << " "; if (p->right) st.push(p->right); if (p->left) st.push(p->left); } } }; // inorder traverse, recursively class Solution_in_re { public: void inorder(TreeNode* root) { if (root) { inorder(root->left); cout << root->val << " "; inorder(root->right); } } }; // inorder traverse, stack class Solution_in_it { public: void inorder(TreeNode* root) { if (!root) return; stack<TreeNode*> st; TreeNode* p = root; while (!st.empty() || p) { if (p) { st.push(p); p = p->left; } else { p = st.top(); st.pop(); cout << p->val; p = p->right; } } } }; // postorder traverse, recursively class Solution_post_re { public: void postorder(TreeNode* root) { if (root) { postorder(root->left); postorder(root->right); cout << root->val << " "; } } }; // postorder traverse, stack class Solution_post_it { public: void postorder(TreeNode* root) { if (!root) return; TreeNode* pre = NULL; // the last poped node TreeNode* cur = root; stack<TreeNode*> st; while (cur || !st.empty()) { if (cur) { st.push(cur); cur = cur->left; } else { TreeNode* t = st.top(); if (t->right && t->right != pre) cur = t->right; else { cout << t->val << " "; pre = t; st.pop(); } } } } }; // level traverse, queue class Solution_level { public: void levelorder(TreeNode* root) { if (!root) return; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* p = q.front(); q.pop(); cout << p->val << " "; if (p->left) q.push(p->left); if (p->right) q.push(p->right); } } }; int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); root->right->left = new TreeNode(6); root->right->right = new TreeNode(7); return 0; }
[ "xuxiang19930924@126.com" ]
xuxiang19930924@126.com
16f6f4bced0c50a79add47dbaf3e582d5479c6e2
f8517de40106c2fc190f0a8c46128e8b67f7c169
/AllJoyn/Samples/OICAdapter/iotivity-1.0.0/resource/oc_logger/include/oc_logger.hpp
2d0df21448b4f239ccd3ffe1de0233fc8b1825cb
[ "MIT", "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
ferreiramarcelo/samples
eb77df10fe39567b7ebf72b75dc8800e2470108a
4691f529dae5c440a5df71deda40c57976ee4928
refs/heads/develop
2023-06-21T00:31:52.939554
2021-01-23T16:26:59
2021-01-23T16:26:59
66,746,116
0
0
MIT
2023-06-19T20:52:43
2016-08-28T02:48:20
C
UTF-8
C++
false
false
1,046
hpp
//****************************************************************** // // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #ifndef __OC_LOG_HPP_20140910 #define __OC_LOG_HPP_20140910 #include "oc_logger.h" #include "oc_log_stream.hpp" #include "targets/oc_console_logger.h" #include "targets/oc_ostream_logger.h" #endif
[ "artemz@microsoft.com" ]
artemz@microsoft.com
1928bc5ac7bac74d0c2e35cfe70584ef08d51768
acd990e4b571c6be0508bc8e5a6b54efaf656bde
/src/caffe/layers/coral_loss_layer.cpp
9116e7daca53467cbeb19498a653c350ef159bca
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
permissive
baochens/Caffe-Deep_CORAL
f119c60d71282600c4d4f98641bb906a28dfede4
c0921c1131227a2d1d48adea7c0727a6aae62dfc
refs/heads/master
2021-01-13T07:51:19.778102
2017-06-20T20:33:54
2017-06-20T20:33:54
94,930,877
4
1
null
null
null
null
UTF-8
C++
false
false
5,611
cpp
#include <vector> #include "caffe/layers/coral_loss_layer.hpp" #include "caffe/util/math_functions.hpp" #include <algorithm> namespace caffe { template <typename Dtype> void CORALLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); // CHECK_EQ might not be necessary as the size of the covariance matrices of //source and target are always the same even if the batch size is different. CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1)) << "Inputs must have the same dimension."; const int count = bottom[0]->count(); const int num = bottom[0]->num(); const int dim = count / num; diff_.Reshape(dim, dim, 1, 1); cov_s.Reshape(dim, dim, 1, 1); cov_t.Reshape(dim, dim, 1, 1); mean_s.Reshape(dim, 1, 1, 1); mean_t.Reshape(dim, 1, 1, 1); square_mean_s.Reshape(dim, dim, 1, 1); square_mean_t.Reshape(dim, dim, 1, 1); diff_data_s.Reshape(num, dim, 1, 1); diff_data_t.Reshape(num, dim, 1, 1); identity.Reshape(num, 1, 1, 1); bp_mean_s.Reshape(dim, num, 1, 1); bp_mean_t.Reshape(dim, num, 1, 1); bp_der_s.Reshape(dim, num, 1, 1); bp_der_t.Reshape(dim, num, 1, 1); } template <typename Dtype> void CORALLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const int count = bottom[0]->count(); const int num = bottom[0]->num(); const int dim = count / num; const int size_cov = dim * dim; // calculating D'D for source and target caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans, dim, dim, num, 1., bottom[0]->cpu_data(), bottom[0]->cpu_data(), 0., cov_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans, dim, dim, num, 1., bottom[1]->cpu_data(), bottom[1]->cpu_data(), 0., cov_t.mutable_cpu_data()); // divide D'D by (num-1) caffe_scal<Dtype>(size_cov, Dtype(1./(num-1)), cov_s.mutable_cpu_data()); caffe_scal<Dtype>(size_cov, Dtype(1./(num-1)), cov_t.mutable_cpu_data()); // identity is a row vector of 1s caffe_set(num, Dtype(1.), identity.mutable_cpu_data()); // calculate the mean of D per column caffe_cpu_gemv<Dtype>(CblasTrans, dim, 1, 1., bottom[0]->cpu_data(), identity.cpu_data(), 0., mean_s.mutable_cpu_data()); caffe_cpu_gemv<Dtype>(CblasTrans, dim, 1, 1., bottom[1]->cpu_data(), identity.cpu_data(), 0., mean_t.mutable_cpu_data()); // calculate the squared mean caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, dim, dim, 1, 1., mean_s.cpu_data(), mean_s.cpu_data() , 0., square_mean_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, dim, dim, 1, 1., mean_t.cpu_data(), mean_t.cpu_data() , 0., square_mean_t.mutable_cpu_data()); // divide squared mean by (num*(num-1)) caffe_scal(size_cov, Dtype(1./(num*(num-1))), square_mean_s.mutable_cpu_data()); caffe_scal(size_cov, Dtype(1./(num*(num-1))), square_mean_t.mutable_cpu_data()); //cov is (1/(num-1))*(D'*D) - (1/(num*(num-1)))*(mean)^T*(mean) caffe_sub(size_cov, cov_s.cpu_data(), square_mean_s.cpu_data(), cov_s.mutable_cpu_data()); caffe_sub(size_cov, cov_t.cpu_data(), square_mean_t.cpu_data(), cov_t.mutable_cpu_data()); //cov_s - cov_t caffe_sub(size_cov, cov_s.cpu_data(), cov_t.cpu_data(), diff_.mutable_cpu_data()); Dtype dot = caffe_cpu_dot(size_cov, diff_.cpu_data(), diff_.cpu_data()); //loss = (1/4)*(1/(dim*dim))*dot Dtype loss = dot / Dtype(4. * dim * dim); top[0]->mutable_cpu_data()[0] = loss; } template <typename Dtype> void CORALLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { int count = bottom[0]->count(); int num = bottom[0]->num(); int dim = count / num; // using chain rule to calculate gradients caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, num, dim, 1, (1./num), identity.cpu_data(), mean_s.cpu_data(), 0., bp_mean_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, num, dim, 1, (1./num), identity.cpu_data(), mean_t.cpu_data(), 0., bp_mean_t.mutable_cpu_data()); // calculate bp_der_s and bp_der_t caffe_sub(count, bottom[0]->cpu_data(), bp_mean_s.cpu_data(), bp_der_s.mutable_cpu_data()); caffe_sub(count, bottom[1]->cpu_data(), bp_mean_t.cpu_data(), bp_der_t.mutable_cpu_data()); //Calculate diff_data caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, num, dim, dim, (1./(dim*dim*(num-1))), bp_der_s.cpu_data(), diff_.cpu_data(), 0., diff_data_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, num, dim, dim, (1./(dim*dim*(num-1))), bp_der_t.cpu_data(), diff_.cpu_data(), 0., diff_data_t.mutable_cpu_data()); for (int i = 0; i < 2; ++i) { if (propagate_down[i]) { const Dtype sign = (i == 0) ? 1 : -1; const Dtype alpha = sign * top[0]->cpu_diff()[0]; if(i==0){ caffe_cpu_axpby( bottom[i]->count(), // count alpha, // alpha diff_data_s.cpu_data(), // a Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } else{ caffe_cpu_axpby( bottom[i]->count(), // count alpha, // alpha diff_data_t.cpu_data(), // a Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } } } } #ifdef CPU_ONLY STUB_GPU(CORALLossLayer); #endif INSTANTIATE_CLASS(CORALLossLayer); REGISTER_LAYER_CLASS(CORALLoss); } // namespace caffe
[ "baochens@gmail.com" ]
baochens@gmail.com
c582935ddb500b1c672fe3d0ad22dd3b33fac7c9
208650de138a6b05b8b8e7e4ca6df9dc72290402
/Contests/LT/2.cpp
420328deba7462ff448ab5cfa78a75c8458fe0c1
[]
no_license
cs15b047/CF
9fcf83c5fd09124b6eaebbd4ecd67d19a1302582
d220d73a2d8739bbb10f4ed71437c06625870490
refs/heads/master
2021-08-20T06:21:24.577260
2021-06-09T04:56:47
2021-06-09T04:57:29
177,541,957
0
0
null
null
null
null
UTF-8
C++
false
false
768
cpp
#include<bits/stdc++.h> using namespace std; typedef long long int ll; int main(int argc, char const *argv[]) { ll t;scanf("%lld",&t); for(int i=0;i<t;i++){ ll n,m;scanf("%lld%lld",&n,&m); vector<string>grid;grid.clear();grid.resize(n); for(int j=0;j<n;j++)cin >> grid[j]; bool flag = true; if((n<=1) || (m<=1))flag=0; for(int j=0;j<n;j++){ for(int k=0;k<m;k++){ if(grid[j][k] == '.'){ if(j==0){ bool c1=0; if(k!=m-1)c1 = c1 || (grid[j+1][k] != "#") && (grid[j+1][k+1] != "#") && (grid[j][k+1] != "#") ; if(k!=0)c1 = c1 || (grid[j+1][k] != "#") && (grid[j+1][k-1] != "#") && (grid[j][k-1]!="#") ; } } if(!flag)break; } if(!flag)break; } if(!flag)cout << "NO"<< endl; else cout << "YES" << endl; } }
[ "cs15b047@smail.iitm.ac.in" ]
cs15b047@smail.iitm.ac.in
14af0182179b5958c7a3eac6f57110e0b10d1896
598e1b350648db9fc0b3ce8a5a75b4a7d2382b65
/JsonApp_Andrusenko_2020/JsonLibrary/KeyValuePair.cpp
b0196441f34882ec50241cb9067b2e0b8b699346
[]
no_license
Maureus/CPP_Andrusenko
d629e39d192434c3fd465a417e1c7fbb3ef56395
ad69042e8f0d21868344d8f046efbd12d9c8f2a4
refs/heads/main
2023-02-11T06:25:59.207782
2021-01-05T17:28:35
2021-01-05T17:28:35
300,827,284
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
#include "pch.h" #include "api.h" KeyValuePair::KeyValuePair() = default; KeyValuePair::KeyValuePair(std::string key, Value * value) { if (key.empty() || value == nullptr) { throw invalid_argument("String is empry or value is nullptr"); } this->key = key; this->value = value; } KeyValuePair::~KeyValuePair() { } std::string KeyValuePair::getKey() const { return key; } Value* KeyValuePair::getValue() const { return value; }
[ "andriiandrusenko@gmail.com" ]
andriiandrusenko@gmail.com