blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
f4217edde04929fc036d6c6d8e3e6ccb86e33cb1
a07e60ba45f5ef3e19a4c0510d5beae70747cb0b
/Solver/Solver.cpp
3cec8ffbedd36c7921084617dc86b1e600c1991c
[]
no_license
hnefatl/Sudoku
c6cdfd9bb66681ce3c65c62b14d303633e365de8
3ed97ee1702058dad039559a117c94427f559b85
refs/heads/master
2020-07-23T19:29:46.769451
2016-08-30T18:19:44
2016-08-30T18:19:44
66,859,654
0
0
null
null
null
null
UTF-8
C++
false
false
4,537
cpp
Solver.cpp
#include "Solver.h" #include <queue> #include <iostream> #include <iomanip> double DefaultEvaluator(const std::vector<Variable> &Variables, const std::vector<Constraint *> &Constraints) { unsigned int HaveValue = 0; for (unsigned int x = 0; x < Variables.size(); x++) { if (Variables[x].HasValue) HaveValue++; } return (double)HaveValue / (double)Variables.size(); } bool SolverVerbose = false; Solution Solve(const std::vector<Variable> &Variables, const std::vector<Constraint *> &Constraints) { return Solve(Variables, Constraints, 1.0); } Solution Solve(const std::vector<Variable> &Variables, const std::vector<Constraint *> &Constraints, const double OptimalThreshold) { return Solve(Variables, Constraints, DefaultEvaluator, OptimalThreshold); } Solution Solve(const std::vector<Variable> &Variables, const std::vector<Constraint *> &Constraints, const std::function<double(const std::vector<Variable> &, const std::vector<Constraint *> &)> &Evaluator) { return Solve(Variables, Constraints, Evaluator, 1.0); } Solution Solve(const std::vector<Variable> &Variables, const std::vector<Constraint *> &Constraints, const std::function<double(const std::vector<Variable> &, const std::vector<Constraint *> &)> &Evaluator, const double OptimalThreshold) { clock_t StartClock = clock(); // Generate relationship from Variable->Constraint for efficiency std::vector<std::vector<Constraint *>> LinkedConstraints; LinkedConstraints.resize(Variables.size()); for (unsigned int x = 0; x < Constraints.size(); x++) { for (unsigned int y = 0; y < Constraints[x]->Variables.size(); y++) LinkedConstraints[Constraints[x]->Variables[y]].push_back(Constraints[x]); } std::set<State *, PointerComparator> Visited; std::priority_queue<State *, std::vector<State *>, PointerComparator> Pending; State *Start = new State(); Start->Variables = Variables; for (unsigned int x = 0; x < Variables.size(); x++) { if (!UpdateConstraints(Start->Variables, x, Constraints, LinkedConstraints)) return Solution(); } Start->Fitness = Evaluator(Start->Variables, Constraints); Visited.emplace(Start); Pending.push(Start); unsigned int Generated = 0; while (!Pending.empty() && Pending.top()->Fitness < OptimalThreshold) { const State Seed = *Pending.top(); if (SolverVerbose) std::cout << "Pending: " << Pending.size() << " Visited: " << Visited.size() << " Generated: " << Generated << " Greatest Fitness: " << std::setprecision(20) << Seed.Fitness << std::endl; Pending.pop(); for (unsigned int x = 0; x < Seed.Variables.size(); x++) { if (!Seed.Variables[x].HasValue) { for (std::set<unsigned int>::iterator DomainVal = Seed.Variables[x].Domain.begin(); DomainVal != Seed.Variables[x].Domain.end(); DomainVal++) { State *New = new State(); New->Variables = Seed.Variables; New->Variables[x].Value = *DomainVal; New->Variables[x].HasValue = true; New->Variables[x].Domain.clear(); New->Variables[x].Domain.emplace(*DomainVal); Generated++; if (!UpdateConstraints(New->Variables, x, Constraints, LinkedConstraints)) { delete New; continue; } New->Fitness = Evaluator(New->Variables, Constraints); if (Visited.emplace(New).second) // Store in pending if not already visited Pending.push(New); } } } } clock_t EndClock = clock(); Solution s; if (Pending.empty()) s = Solution(); else s = Solution(Pending.top()->Variables, Pending.top()->Fitness, EndClock - StartClock); for (std::set<State *>::iterator i = Visited.begin(); i != Visited.end(); i++) delete *i; return s; } bool UpdateConstraints(std::vector<Variable> &Variables, const unsigned int Index, const std::vector<Constraint *> &Constraints, const std::vector<std::vector<Constraint *>> &LinkedConstraints) { std::set<unsigned int> Pending; Pending.emplace(Index); while (!Pending.empty()) { unsigned int VariableIndex = *Pending.begin(); for (std::vector<Constraint *>::const_iterator Constraint = LinkedConstraints[VariableIndex].begin(); Constraint != LinkedConstraints[VariableIndex].end(); Constraint++) { if (!(*Constraint)->Enforce(Variables, Pending)) return false; } Pending.erase(Pending.begin()); } return true; } Solution::Solution() { Successful = false; Fitness = 0; Time = 0; } Solution::Solution(const std::vector<Variable> &State, const double Fitness, const clock_t Time) { Successful = true; this->State = State; this->Fitness = Fitness; this->Time = Time; }
1525a6702c889c5f2936f484b6e5b31a78e62585
6de7f1f0d9be7d0659902dc60c77dcaf332e927e
/src/libtsduck/base/types/tsBufferTemplate.h
c26ca1a7f4f7d9f73478ef40670ed9132007881d
[ "BSD-2-Clause" ]
permissive
ConnectionMaster/tsduck
ed41cd625c894dca96f9b64f7e18cc265ef7f394
32732db5fed5f663dfe68ffb6213a469addc9342
refs/heads/master
2023-08-31T20:01:00.538543
2022-09-30T05:25:02
2022-09-30T08:14:43
183,097,216
1
0
BSD-2-Clause
2023-04-03T23:24:45
2019-04-23T21:15:45
C++
UTF-8
C++
false
false
9,438
h
tsBufferTemplate.h
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2022, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // //---------------------------------------------------------------------------- #pragma once #include "tsIntegerUtils.h" //---------------------------------------------------------------------------- // Read the next n bits as an integer value and advance the read pointer. //---------------------------------------------------------------------------- template <typename INT, typename std::enable_if<std::is_integral<INT>::value && std::is_signed<INT>::value>::type*> INT ts::Buffer::getBits(size_t bits) { typedef typename std::make_unsigned<INT>::type UNSINT; const INT value = static_cast<INT>(getBits<UNSINT>(bits)); return SignExtend(value, bits); } template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type*> void ts::Buffer::getBits(Variable<INT>& value, size_t bits) { if (_read_error || currentReadBitOffset() + bits > currentWriteBitOffset()) { _read_error = true; value.clear(); } else { value = getBits<INT>(bits); } } template <typename INT, typename std::enable_if<std::is_integral<INT>::value && std::is_unsigned<INT>::value>::type*> INT ts::Buffer::getBits(size_t bits) { // No read if read error is already set or not enough bits to read. if (_read_error || currentReadBitOffset() + bits > currentWriteBitOffset()) { _read_error = true; return 0; } INT val = 0; if (_big_endian) { // Read leading bits up to byte boundary while (bits > 0 && _state.rbit != 0) { val = INT(val << 1) | INT(getBit()); --bits; } // Read complete bytes while (bits > 7) { val = INT(val << 8) | INT(_buffer[_state.rbyte++]); bits -= 8; } // Read trailing bits while (bits > 0) { val = INT(val << 1) | INT(getBit()); --bits; } } else { // Little endian decoding int shift = 0; // Read leading bits up to byte boundary while (bits > 0 && _state.rbit != 0) { val |= INT(getBit()) << shift; --bits; shift++; } // Read complete bytes while (bits > 7) { val |= INT(_buffer[_state.rbyte++]) << shift; bits -= 8; shift += 8; } // Read trailing bits while (bits > 0) { val |= INT(getBit()) << shift; --bits; shift++; } } return val; } //---------------------------------------------------------------------------- // Put the next n bits from an integer value and advance the write pointer. //---------------------------------------------------------------------------- template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type*> bool ts::Buffer::putBits(INT value, size_t bits) { // No write if write error is already set or read-only or not enough bits to write. if (_write_error || _state.read_only || remainingWriteBits() < bits) { _write_error = true; return false; } if (_big_endian) { // Write leading bits up to byte boundary while (bits > 0 && _state.wbit != 0) { putBit(uint8_t((value >> --bits) & 1)); } // Write complete bytes. while (bits > 7) { bits -= 8; _buffer[_state.wbyte++] = uint8_t(value >> bits); } // Write trailing bits while (bits > 0) { putBit(uint8_t((value >> --bits) & 1)); } } else { // Little endian encoding. Write leading bits up to byte boundary. while (bits > 0 && _state.wbit != 0) { putBit(uint8_t(value & 1)); value >>= 1; --bits; } // Write complete bytes. while (bits > 7) { _buffer[_state.wbyte++] = uint8_t(value); TS_PUSH_WARNING() TS_LLVM_NOWARNING(shift-count-overflow) // "shift count >= width of type" for 8-bit ints value >>= 8; TS_POP_WARNING() bits -= 8; } // Write trailing bits while (bits > 0) { putBit(uint8_t(value & 1)); value >>= 1; --bits; } } return true; } //---------------------------------------------------------------------------- // Internal put integer method. //---------------------------------------------------------------------------- template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type*> bool ts::Buffer::putint(INT value, size_t bytes, void (*putBE)(void*,INT), void (*putLE)(void*,INT)) { // Internally used to write up to 8 bytes (64-bit integers). assert(bytes <= 8); // No write if write error is already set or read-only. if (_write_error || _state.read_only) { _write_error = true; return false; } // Hypothetical new write pointer (bit pointer won't change). const size_t new_wbyte = _state.wbyte + bytes; if (new_wbyte > _state.end || (new_wbyte == _state.end && _state.wbit > 0)) { // Not enough bytes to write. _write_error = true; return false; } else if (_state.wbit == 0) { // Write pointer is byte aligned. Most common case. if (_big_endian) { putBE(_buffer + _state.wbyte, value); } else { putLE(_buffer + _state.wbyte, value); } _state.wbyte = new_wbyte; return true; } else { // Write pointer is not byte aligned. Use an intermediate buffer. uint8_t buf[8]; if (_big_endian) { putBE(buf, value); } else { putLE(buf, value); } putBytes(buf, bytes); assert(_state.wbyte == new_wbyte); return true; } } //---------------------------------------------------------------------------- // Read the next 4*n bits as a BCD value. //---------------------------------------------------------------------------- template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type*> INT ts::Buffer::getBCD(size_t bcd_count) { INT value = 0; getBCD(value, bcd_count); return value; } template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type*> bool ts::Buffer::getBCD(INT& value, size_t bcd_count) { typedef typename std::make_unsigned<INT>::type UNSINT; UNSINT uvalue = 0; if (_read_error || currentReadBitOffset() + 4 * bcd_count > currentWriteBitOffset()) { _read_error = true; value = 0; return false; } else { while (bcd_count-- > 0) { UNSINT nibble = getBits<UNSINT>(4); if (nibble > 9) { _read_error = true; nibble = 0; } uvalue = 10 * uvalue + nibble; } value = static_cast<INT>(uvalue); return true; } } //---------------------------------------------------------------------------- // Put the next 4*n bits as a BCD value. //---------------------------------------------------------------------------- template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type*> bool ts::Buffer::putBCD(INT value, size_t bcd_count) { // No write if write error is already set or read-only or not enough bits to write. if (_write_error || _state.read_only || remainingWriteBits() < 4 * bcd_count) { _write_error = true; return false; } if (bcd_count > 0) { typedef typename std::make_unsigned<INT>::type UNSINT; UNSINT uvalue = static_cast<UNSINT>(value); UNSINT factor = Power10<UNSINT>(bcd_count); while (bcd_count-- > 0) { uvalue %= factor; factor /= 10; putBits(uvalue / factor, 4); } } return true; }
8e7f5cd1a69fef4249060ef58e75a3b6fd27031f
facd97329e40f72587386ed3148cd519ad366a80
/StorageManagerPlugin/include/CatalogModel.h
2817ca2e56fd82ca5675c51c555983004864181f
[]
no_license
KernelMD/Catalog
51218be507b64f5e2b30117615d7242192e668a2
7742fdfefd6b099628050002d72422bf0df6fe90
refs/heads/master
2016-08-04T06:18:26.356487
2015-04-27T13:05:31
2015-04-27T13:05:31
34,670,364
0
0
null
null
null
null
UTF-8
C++
false
false
836
h
CatalogModel.h
#ifndef CATALOGMODEL_H #define CATALOGMODEL_H #include <QAbstractListModel> #include <QByteArray> #include <QHash> #include <QList> #include "../include/AbstractCatalogEntry.h" class CatalogModel : public QAbstractListModel { Q_OBJECT public: enum Roles { typeRole = Qt::UserRole + 1, identRole, parentIdentRole, nameRole, iconNameRole, // This is only for ItemCatalogEntry'es. costRole }; CatalogModel(QObject* parent = 0); ~CatalogModel(); int rowCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role) const; /// Appends copy of entry to the model. Q_INVOKABLE void Append(const AbstractCatalogEntry* entry); Q_INVOKABLE void Clear(); QHash<int, QByteArray> roleNames() const; private: QList<AbstractCatalogEntry*> m_data; }; #endif // CATALOGMODEL_H
ae7816e7c70c816a6e0f7c1f4367244e9a15c9d2
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_6559.cpp
d7d50b6b9eefe8db8644d5d2973ecb37e6c5cd7f
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
24
cpp
old_hunk_6559.cpp
} return buf; }
70437b946f612afb26b539ddef9adea466df01e7
ef7d308ff157eb43d9056dae91ea24effd2f32b2
/MissingParentheses.cpp
a11a651db54a5441a443fcc63f00f8f82c636125
[]
no_license
abhiranjankumar00/TopCoder-SRM-submissions
cd37f2f2638c2e40daa571d08e2b068382921f23
d0d3ee3bde2be630f6126d53f4bb0ea008a03150
refs/heads/master
2021-01-18T01:42:20.313261
2018-04-09T19:04:42
2018-04-09T19:04:42
5,789,738
2
4
null
null
null
null
UTF-8
C++
false
false
5,279
cpp
MissingParentheses.cpp
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cassert> #include <climits> #include <cstring> using namespace std; typedef long long int64; typedef vector<int> vi; typedef string ST; typedef stringstream SS; typedef vector< vector <int> > vvi; typedef pair<int,int> ii; typedef vector <string> vs; #define Pf printf #define Sf scanf #define ep 1e-9 #define PI M_PI #define E M_E #define CL(a, b) memset(a, b, sizeof(a)) #define mp make_pair #define pb push_back #define all(c) (c).begin(), (c).end() #define tr(i, c) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define present(x, c) ((c).find(x) != (c).end()) //map & set// #define cpresent(x, c) (find(all(c),x) != (c).end()) //vector & list// #define forn(i, n) for(int i = 0, loop_ends_here = (int)n; i < loop_ends_here; i++) #define forab(i, a, b) for(int i = a, loop_ends_here = (int) b; i <= loop_ends_here; i++) #define rep(i, a, b) for(int i = a, loop_ends_here = (int)b; i>=loop_ends_here; i--) class MissingParentheses { public: int countCorrections(string par) { int ret = 0; stack <char> st; forn(i, par.length()) { if(par[i] == '(') st.push('('); else { if(st.empty()) ++ret; else st.pop(); } } return ret + st.size(); } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.8 (beta) modified by pivanof #include <iostream> #include <string> #include <vector> using namespace std; bool KawigiEdit_RunTest(int testNum, string p0, bool hasAnswer, int p1) { cout << "Test " << testNum << ": [" << "\"" << p0 << "\""; cout << "]" << endl; MissingParentheses *obj; int answer; obj = new MissingParentheses(); clock_t startTime = clock(); answer = obj->countCorrections(p0); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << p1 << endl; } cout << "Your answer:" << endl; cout << "\t" << answer << endl; if (hasAnswer) { res = answer == p1; } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; string p0; int p1; { // ----- test 0 ----- p0 = "(()(()"; p1 = 2; all_right = KawigiEdit_RunTest(0, p0, true, p1) && all_right; // ------------------ } { // ----- test 1 ----- p0 = "()()(()"; p1 = 1; all_right = KawigiEdit_RunTest(1, p0, true, p1) && all_right; // ------------------ } { // ----- test 2 ----- p0 = "(())(()())"; p1 = 0; all_right = KawigiEdit_RunTest(2, p0, true, p1) && all_right; // ------------------ } { // ----- test 3 ----- p0 = "())(())((()))))()((())))()())())())()()()"; p1 = 7; all_right = KawigiEdit_RunTest(3, p0, true, p1) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // PROBLEM STATEMENT // // Given a string of parentheses, you must turn it into a well formed string by inserting as few parentheses as possible, at any position (you cannot delete or change any of the existing parentheses). // // A well formed string of parentheses is defined by the following rules: // // The empty string is well formed. // If s is a well formed string, (s) is a well formed string. // If s and t are well formed strings, their concatenation st is a well formed string. // // As examples, "(()())", "" and "(())()" are well formed strings and "())(", "()(" and ")" are malformed strings. // // Given a string par of parentheses, return the minimum number of parentheses that need to be inserted to make it into a well formed string. // // // DEFINITION // Class:MissingParentheses // Method:countCorrections // Parameters:string // Returns:int // Method signature:int countCorrections(string par) // // // CONSTRAINTS // -par will contain between 1 and 50 characters, inclusive. // -Each character of par will be an opening or closing parenthesis, i.e., '(' or ')'. // // // EXAMPLES // // 0) // "(()(()" // // Returns: 2 // // The string below is a possible well formed string you can get to by inserting the two closing parentheses marked. // // (())(()) // ^ ^ // // // 1) // "()()(()" // // Returns: 1 // // You can fix the string by inserting a single closing parenthesis at the end. // // 2) // "(())(()())" // // Returns: 0 // // The input string is well formed, so no insertion is needed. // // 3) // "())(())((()))))()((())))()())())())()()()" // // Returns: 7 // // // // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
9519ef5b1e945b32e422fedfc8bb382d9258e0eb
0454fb2210c70c0b48bfabe484c7efee7120eb8d
/gbjson.cpp
e98f0957dd4747b5eb290544b903a23ff95e61e9
[ "MIT" ]
permissive
fbuermann/gbjson
e1d4c05c71294ef85fa3aa80b619c286c0615180
a1e840f998a36c7a10041e4fc073fa7aba36f13f
refs/heads/master
2020-05-09T15:46:44.603377
2019-04-30T19:32:04
2019-04-30T19:52:13
181,245,260
0
1
null
null
null
null
UTF-8
C++
false
false
27,584
cpp
gbjson.cpp
/* * gbjson.cpp: GenBank<->JSON conversion library * * Copyright (c) 2019 Frank Buermann <fburmann@mrc-lmb.cam.ac.uk> * * gbjson is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ /** * @mainpage gbjson - A GenBank to JSON converter * * @section Introduction * * This program interconverts GenBank and JSON formats. The program contains * two executables. <b>gb2json</b> converts GenBank to JSON, * and <b>json2gb</b> does the reverse. * * @section Usage Example usage * @subsection File2File File conversion * $ gb2json <i>in.gb</i> <i>out.json</i> * * $ json2gb <i>in.json</i> <i>out.gb</i> * * @subsection File2Stdout Write to stdout * $ gb2json <i>in.gb</i> * * $ json2gb <i>in.json</i> * * @section Building Building from source * Use <a href="https://cmake.org/">CMake</a> to build from source. * * @subsection UNIX UNIX-like operating systems * $ cd gbjson\n * $ mkdir build\n * $ cd build\n * $ cmake -G "Unix Makefiles" ..\n * $ make * * @subsection WIN32 Windows * Building from source has been tested with <a href="https://visualstudio.microsoft.com/">Visual Studio/MSVC 2019</a> * using <a href="https://cmake.org/">CMake</a>. * * @subsection Library Use as a library * Using <b>gbjson</b> as a C++ library is straight forward. * Include gbjson.h in your source code. The functions <i>gb2json</i> and <i>json2gb</i> are the API. */ #include <iostream> #include <stdio.h> // fopen, fread #include <string> #include <sstream> // stringstream #include <algorithm> // find_if, remove #include <cctype> // isspace #include <cmath> // ceil #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" #include "rapidjson/reader.h" #include "gbjson.h" #define _CRT_SECURE_NO_WARNINGS // Bypass I/O *_s functions in MSVC gberror::gberror() : flag(false) {} /*************************************************************** * File handling ***************************************************************/ static inline void fileSize(FILE *fp, size_t *len) { size_t pos = ftell(fp); fseek(fp, 0, SEEK_END); *len = ftell(fp); fseek(fp, pos, SEEK_SET); } void fileToString(const std::string *filename, std::string *output, gberror *err) { FILE *input = fopen(filename->c_str(), "r"); if (!input) { err->flag = true; err->msg = "Failed to open "; err->msg.append(filename->c_str()); err->source = "fileToString"; return; } size_t len; // File size fileSize(input, &len); output->resize(len); len = fread(&(*output)[0], 1, len, input); output->resize(len); // Actual number of chars read fclose(input); } /*************************************************************** * String handling ***************************************************************/ static std::string makeSpaces(int n) { std::string spaces(n, ' '); return spaces; } static inline void stringTrimLeft(std::string *str) { str->erase(str->begin(), std::find_if(str->begin(), str->end(), [](int c) { return !std::isspace(c); })); } static inline void stringTrimRight(std::string *str) { str->erase(std::find_if(str->rbegin(), str->rend(), [](int c) { return !std::isspace(c); }).base(), str->end()); } static inline void stringTrim(std::string *str) { stringTrimLeft(str); stringTrimRight(str); } static inline void removeSpaces(std::string *str) { str->erase(std::remove(str->begin(), str->end(), ' '), str->end()); } /* * getline that handles \r, \r\n, and \n line endings for files moved * between platforms. * @param[in] is Input stream. * @param[out] line The line. */ static std::istream &safeGetline(std::istream &is, std::string &line) { // This was snatched from // https://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf // The characters in the stream are read one-by-one using a std::streambuf. // That is faster than reading them one-by-one using the std::istream. // Code that uses streambuf this way must be guarded by a sentry object. // The sentry object performs various tasks, // such as thread synchronization and updating the stream state. line.clear(); std::istream::sentry se(is, true); std::streambuf *sb = is.rdbuf(); for (;;) { int c = sb->sbumpc(); switch (c) { case '\n': return is; case '\r': if (sb->sgetc() == '\n') sb->sbumpc(); return is; case std::streambuf::traits_type::eof(): // Also handle the case when the last line has no line ending if (line.empty()) is.setstate(std::ios::eofbit); return is; default: line += (char)c; } } } /** * Split a string into lines and left pad with whitespace * @param[in] input The string. * @param[out] block The padded block. * @param[in] leader Number of leading whitespaces. * @param[in] len Line length. * @param[in] offset Offset for the first line. */ static void blockPad( const std::string *input, std::string *block, int leader, int len, int offset) { // Sanity check if (len < leader || len <= 0 || offset >= len - leader) { *block = ""; return; } // Make the streams std::stringstream in(*input); std::stringstream out; std::string line; // Consume first input line. This does not get leading whitespace. safeGetline(in, line); int writeLen = len - leader; // Length that contains parts of the string int nfrag = std::ceil(((double)line.length() + offset) / writeLen); // Number of fragments // First part that does not have leading whitespace. out << line.substr(0, writeLen - offset); out << "\n"; // Remaining parts for (int i = 0; i < nfrag - 1; i++) { out << makeSpaces(leader); out << line.substr(writeLen - offset + i * writeLen, writeLen) << "\n"; } // Consume remaining input lines while (!in.eof()) { safeGetline(in, line); nfrag = std::ceil(((double)line.length()) / writeLen); for (int i = 0; i < nfrag; i++) { out << makeSpaces(leader); out << line.substr(i * writeLen, writeLen) << "\n"; } } // Write result *block = out.str(); } /*************************************************************** * GenBank line processing ***************************************************************/ static void splitLine(const std::string *line, std::string *front, std::string *back) { *front = line->substr(0, 10); *back = line->substr(12, line->size()); } static void splitFeatureLine(const std::string *line, std::string *front, std::string *back) { *front = line->substr(0, 21); *back = line->substr(21, line->size()); } static void splitSequenceLine(const std::string *line, std::string *front, std::string *back) { *front = line->substr(0, 10); *back = line->substr(10, line->size()); removeSpaces(back); } static inline bool isInteger(const std::string *n) { return !n->empty() && n->end() == std::find_if(n->begin(), n->end(), [](char c) { return !std::isdigit(c); }); } static inline bool isLocus(const std::string *line) { return line->length() >= 13 && line->substr(0, 5) == "LOCUS" && !isspace((*line)[12]); } static inline bool isKeyword(const std::string *line) { return line->length() >= 13 && !isspace((*line)[0]) && isalpha((*line)[0]); } static inline bool isSubkeyword(const std::string *line) { return line->length() >= 3 && (line->substr(0, 2) == " ") && !isspace((*line)[2]); } static inline bool isSubsubkeyword(const std::string *line) { return line->length() >= 4 && (line->substr(0, 3) == " ") && !isspace((*line)[3]); } static inline bool isContinuation(const std::string *line) { return line->length() >= 11 && line->substr(0, 11) == " "; } static inline bool isFeatureHeader(const std::string *line) { return line->length() >= 8 && line->substr(0, 8) == "FEATURES"; } static inline bool isFeature(const std::string *line) { return line->length() >= 6 && (line->substr(0, 5) == " ") && !isspace((*line)[5]); } static inline bool isQualifier(const std::string *back) { return (*back)[0] == '/'; } static inline bool isOrigin(const std::string *line) { return line->length() >= 6 && line->substr(0, 6) == "ORIGIN"; } static inline bool isContig(const std::string *line) { return line->length() >= 6 && line->substr(0, 6) == "CONTIG"; } static bool isSequence(const std::string *line) { if (line->length() < 11) { return false; } std::string n(line->substr(3, 6)); stringTrimLeft(&n); return isInteger(&n) && std::isspace((*line)[9]) && !std::isspace((*line)[10]); } static inline bool isEnd(const std::string *line) { return line->length() >= 2 && line->substr(0, 2) == "//"; } // Function table for testing keyword level bool (*isItemLevel[3])(const std::string *line) = {&isKeyword, &isSubkeyword, &isSubsubkeyword}; /*************************************************************** * GenBank parsing ****************** * All values are parsed into JSON strings since GenBank * is lacking a type system. ***************************************************************/ /** * Parse a GenBank LOCUS entry. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseLocus( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer) { std::string back(line->substr(12, line->length() - 12)); writer->Key("LOCUS"); writer->StartArray(); writer->String(back.c_str(), back.length(), true); writer->StartArray(); // Dummy array for sub keywords writer->EndArray(); // Dummy array for sub keywords writer->EndArray(); safeGetline(*gbstream, *line); } /** * Parse a GenBank KEYWORD entry. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseKeyword( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer, int level // 0 for Keywords, 1 for Subkeywords, 2 for Subsubkeywords ) { std::string front, back; splitLine(line, &front, &back); // Copy content into buffer and trim whitespace std::string buffer(back); bool whitespace = isspace(back.back()); stringTrimRight(&buffer); if (whitespace) { buffer.append(" "); } stringTrim(&front); writer->Key(front.c_str(), front.length(), true); writer->StartArray(); // Top level array // Read the next line safeGetline(*gbstream, *line); // Push continuation lines into buffer while (isContinuation(line)) { splitLine(line, &front, &back); whitespace = isspace(back.back()); stringTrimRight(&back); if (whitespace) { back.append(" "); } buffer.append("\n"); buffer.append(back); safeGetline(*gbstream, *line); } // Write buffer to JSON writer->String(buffer.c_str(), buffer.length(), true); // Parse Sub keywords writer->StartArray(); if (level < 2) { // Genbank allows 3 levels for keywords while (isItemLevel[level + 1](line)) { writer->StartObject(); parseKeyword(gbstream, line, writer, level + 1); writer->EndObject(); } } writer->EndArray(); // Sub keywords writer->EndArray(); // Top level array } /** * Parse a GenBank qualifier entry. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseQualifier( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer) { // Push content into a buffer and trim whitespace std::string front, back; splitFeatureLine(line, &front, &back); std::string buffer(back); bool whitespace = isspace(back.back()); stringTrimRight(&buffer); if (whitespace) { buffer.append(" "); } buffer.append("\n"); // Read the next line safeGetline(*gbstream, *line); // Push continuation lines into the buffer if (isContinuation(line)) { splitFeatureLine(line, &front, &back); while (!isQualifier(&back) && isContinuation(line)) { whitespace = isspace(back.back()); stringTrimRight(&back); if (whitespace) { buffer.append(" "); } buffer.append(back); buffer.append("\n"); safeGetline(*gbstream, *line); if (isContinuation(line)) { splitFeatureLine(line, &front, &back); } else { break; } } } // Drop last newline if (!buffer.empty()) { buffer.pop_back(); } // Find the qualifier delimiter if it exists size_t equalSignPos = buffer.find('='); // Write out the buffer writer->StartObject(); // Qualifier start if (equalSignPos == -1 || equalSignPos == buffer.length() - 1) { // No qualifier value writer->Key(buffer.substr(1, buffer.length()).c_str(), buffer.length() - 1, true); writer->Null(); } else { // Key value pair std::string key(buffer.substr(1, equalSignPos - 1)); std::string value(buffer.substr(equalSignPos + 1, buffer.length() - equalSignPos)); writer->Key(key.c_str(), key.length(), true); writer->String(value.c_str(), value.length(), true); } writer->EndObject(); // Qualifier end } /** * Parse a GenBank feature entry. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseFeature( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer) { // Push content into a buffer std::string front, back; splitFeatureLine(line, &front, &back); std::string buffer(back); stringTrimRight(&buffer); stringTrim(&front); writer->StartObject(); // Feature start writer->Key(front.c_str(), front.length(), true); writer->StartArray(); // Qualifier array writer->StartObject(); // Location start writer->Key("Location"); // Consume location continuation lines safeGetline(*gbstream, *line); while (isContinuation(line)) { splitFeatureLine(line, &front, &back); if (isQualifier(&back)) { break; // Exit loop if this is not a continuation line } else { bool whitespace = isspace(back.back()); stringTrimRight(&back); if (whitespace) { back.append(" "); } buffer.append(back); safeGetline(*gbstream, *line); } } // Write location writer->String(buffer.c_str(), buffer.length(), true); writer->EndObject(); // Location end // Parse qualifiers while (isQualifier(&back) && isContinuation(line)) { parseQualifier(gbstream, line, writer); if (isContinuation(line)) { splitFeatureLine(line, &front, &back); } } writer->EndArray(); // Qualifier array writer->EndObject(); // Feature end } /** * Parse a GenBank feature table. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseFeatures( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer) { writer->Key("FEATURES"); safeGetline(*gbstream, *line); writer->StartArray(); // Features array if (!isFeature(line)) { // No features present goto cleanup; } while (isFeature(line)) { parseFeature(gbstream, line, writer); } cleanup: writer->EndArray(); // Features array } /** * Parse a GenBank origin entry. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseOrigin( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer) { std::string back(line->substr(6, 79 - 6)); stringTrimRight(&back); writer->Key("ORIGIN"); writer->StartArray(); if (back.empty()) { // No value writer->Null(); } else { // Entry writer->String(back.c_str(), back.length(), true); } writer->StartArray(); // Dummy array for sub keywords writer->EndArray(); // Dummy array for sub keywords writer->EndArray(); } /** * Parse a GenBank sequence entry. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseSequence( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer) { std::string front, back, buffer; safeGetline(*gbstream, *line); if (isContig(line)) { // Copy content into buffer and trim whitespace splitLine(line, &front, &back); buffer.append(back); stringTrimRight(&buffer); bool whitespace = isspace(back.back()); if (whitespace) { buffer.append(" "); } // Consume contig lines safeGetline(*gbstream, *line); while (isContinuation(line)) { splitLine(line, &front, &back); whitespace = isspace(back.back()); stringTrimRight(&back); if (whitespace) { back.append(" "); } buffer.append("\n"); buffer.append(back); safeGetline(*gbstream, *line); } // Write the data writer->Key("CONTIG"); writer->StartArray(); if (buffer.empty()) { writer->Null(); } else { writer->String(buffer.c_str(), buffer.length(), true); } writer->StartArray(); // Dummy array for sub keywords writer->EndArray(); // Dummy array for sub keywords writer->EndArray(); } else if (isSequence(line)) { // Consume the sequence lines while (isSequence(line)) { splitSequenceLine(line, &front, &back); buffer.append(back); safeGetline(*gbstream, *line); } // Write the data writer->Key("SEQUENCE"); writer->StartArray(); if (buffer.empty()) { writer->Null(); } else { writer->String(buffer.c_str(), buffer.length(), true); } writer->StartArray(); // Dummy array for sub keywords writer->EndArray(); // Dummy array for sub keywords writer->EndArray(); } } /** * Delegator function for parsing GenBank items. * @param[in] gbstream The input string stream. * @param[out] line The line buffer. * @param[in] writer The JSON writer object. */ static void parseItem( std::stringstream *gbstream, std::string *line, rapidjson::PrettyWriter<rapidjson::StringBuffer> *writer) { if (isLocus(line)) { writer->StartArray(); // Start the GenBank array writer->StartObject(); parseLocus(gbstream, line, writer); writer->EndObject(); } else if (isEnd(line)) { writer->EndArray(); // Start the GenBank array safeGetline(*gbstream, *line); } else if (isOrigin(line)) { writer->StartObject(); parseOrigin(gbstream, line, writer); writer->EndObject(); writer->StartObject(); parseSequence(gbstream, line, writer); writer->EndObject(); } else if (isKeyword(line) && !isFeatureHeader(line)) { writer->StartObject(); parseKeyword(gbstream, line, writer, 0); writer->EndObject(); } else if (isFeatureHeader(line)) { writer->StartObject(); parseFeatures(gbstream, line, writer); writer->EndObject(); } else { safeGetline(*gbstream, *line); } } /*************************************************************** * GenBank to JSON converter ***************************************************************/ /** * GenBank to JSON converter. * @param[in] gb The GenBank string. * @param[out] json The JSON string. * @param[out] err Error object. */ void gb2json(const std::string *gb, std::string *json, gberror *err) { // Initialize stream object std::stringstream gbstream(*gb); std::string line; // Initialize the writer rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); // Start the parsing safeGetline(gbstream, line); writer.StartArray(); while (!gbstream.eof()) { parseItem(&gbstream, &line, &writer); } // Close the JSON array and write to string writer.EndArray(); if (!writer.IsComplete()) { err->flag = true; err->msg = "Incomplete GenBank"; err->source = "gb2json"; } else { *json = buffer.GetString(); } } /*************************************************************** * JSON to GenBank converter * This feeds a events from a JSON stream into a rapidjson handler * object. The handler builds the GenBank string. ***************************************************************/ /** * Handler constructor. */ JSONHandler::JSONHandler() : state(START), nwritten(0), skipStateUpdate(false) {} // Unused handler functions bool JSONHandler::Bool(bool b) { return true; } bool JSONHandler::Int(int i) { return true; } bool JSONHandler::Uint(unsigned i) { return true; } bool JSONHandler::Int64(int64_t i) { return true; } bool JSONHandler::Uint64(uint64_t i) { return true; } bool JSONHandler::Double(double d) { return true; } bool JSONHandler::RawNumber(const char *str, rapidjson::SizeType length, bool copy) { return true; } /** * Update handler state based on a JSON key. * @param[in] key The key. */ void JSONHandler::updateState(const std::string key) { if (state == QUALIFIER && key == "Location") { state = QUALIFIER_LOCATION; } else if (state == QUALIFIER_LOCATION) { state = QUALIFIER; } else if (key == "LOCUS") { state = LOCUS; skipStateUpdate = true; } else if (key == "ORIGIN") { state = ORIGIN; skipStateUpdate = true; } else if (key == "SEQUENCE") { state = SEQUENCE; skipStateUpdate = true; } else if (key == "CONTIG") { state = CONTIG; skipStateUpdate = true; } else if (key == "FEATURES") { state = FEATURE_HEADER; } else if (!skipStateUpdate && (state == KEYWORD || state == SUBKEYWORD || state == SUBSUBKEYWORD)) { skipStateUpdate = true; } return; } bool JSONHandler::StartArray() { switch (state) { case KEYWORD: { if (skipStateUpdate) { skipStateUpdate = false; } else { state = SUBKEYWORD; } break; } case SUBKEYWORD: { if (skipStateUpdate) { skipStateUpdate = false; } else { state = SUBSUBKEYWORD; } break; } case LOCUS: { if (skipStateUpdate) { skipStateUpdate = false; } else { state = LOCUSSUB; } break; } case ORIGIN: { if (skipStateUpdate) { skipStateUpdate = false; } else { state = ORIGINSUB; } break; } case SEQUENCE: { if (skipStateUpdate) { skipStateUpdate = false; } else { state = SEQUENCESUB; } break; } case CONTIG: { if (skipStateUpdate) { skipStateUpdate = false; } else { state = CONTIGSUB; } break; } case END: { state = START; break; } default: break; } return true; } bool JSONHandler::EndArray(rapidjson::SizeType elementCount) { if (state == QUALIFIER || state == QUALIFIER_LOCATION) { state = FEATURE; } else if (state == FEATURE) { state = FEATURE_HEADER; } else if (state == FEATURE_HEADER) { state = KEYWORD; } else if (state == SUBSUBKEYWORD) { state = SUBKEYWORD; } else if (state == SUBKEYWORD) { state = KEYWORD; } else if (state == LOCUSSUB) { state = LOCUS; } else if (state == LOCUS) { state = KEYWORD; } else if (state == ORIGINSUB) { state = ORIGIN; } else if (state == ORIGIN) { state = KEYWORD; } else if (state == SEQUENCESUB) { state = SEQUENCE; } else if (state == CONTIGSUB) { state = CONTIG; } else if (state == SEQUENCE || state == CONTIG) { gb << "//\n"; nwritten = 0; state = END; } return true; } bool JSONHandler::StartObject() { switch (state) { case FEATURE_HEADER: { state = FEATURE; break; } case FEATURE: { state = QUALIFIER; break; } default: break; } return true; } bool JSONHandler::EndObject(rapidjson::SizeType elementCount) { if (state == QUALIFIER || state == QUALIFIER_LOCATION) { state = FEATURE; } return true; } /** * Consume a string value. * @param[in] value The value string. */ void JSONHandler::handleStringValue(const std::string *value) { // Set value indentation int valueIndentation = 12; switch (state) { case QUALIFIER: { valueIndentation = 21; break; } case QUALIFIER_LOCATION: { valueIndentation = 21; break; } case FEATURE: { valueIndentation = 21; break; } case KEYWORD: { valueIndentation = 12; break; } case SUBKEYWORD: { valueIndentation = 12; break; } case SUBSUBKEYWORD: { valueIndentation = 12; break; } default: break; } // Write equal sign for qualifiers if (state == QUALIFIER) { gb << "="; nwritten += 1; } // Split the value into padded lines std::string block; blockPad(value, &block, valueIndentation, 79, nwritten - valueIndentation); // Write the value gb << block; // Reset the column counter nwritten = 0; } /** * Consume the nucleotide sequence. * @param[in] value The string value. */ void JSONHandler::handleSequence(const std::string *value) { std::string line; int nlines = std::ceil(((double)value->length()) / 60); // Number of lines int nsections; // Number of 10 b sections for a given line std::string pos; // Coordinate at start of line for (int i = 0; i < nlines; i++) { // Loop through lines // Place leading number pos = std::to_string(i * 60 + 1); gb << makeSpaces(9 - pos.length()) << pos << " "; line = value->substr(i * 60, 60); nsections = std::ceil(((double)line.length() / 10)); for (int j = 0; j < nsections; j++) { // Build 10 b sections gb << line.substr(j * 10, 10); if (j < nsections - 1) { gb << " "; } } gb << "\n"; } // Reset column counter nwritten = 0; } bool JSONHandler::String(const char *str, rapidjson::SizeType length, bool copy) { std::string value(str); switch (state) { case LOCUS: { gb << str << "\n"; break; } case ORIGIN: { gb << str << "\n"; break; } case SEQUENCE: { handleSequence(&value); break; } default: { handleStringValue(&value); break; } } return true; } bool JSONHandler::Key(const char *str, rapidjson::SizeType length, bool copy) { std::string key(str); updateState(key); int keyIndentation = 0; // Whitespace before key int valueIndentation = 12; // Number of chars before value if (state == SEQUENCE) { return true; // Don't print a key } else if (state == FEATURE_HEADER) { gb << "FEATURES" << makeSpaces(21 - 8) << "Location/Qualifiers\n"; nwritten = 0; return true; } else if (state == QUALIFIER) { // Special formatting for qualifier key gb << makeSpaces(21) << "/" << key; nwritten = 22 + key.length(); return true; } else if (state == QUALIFIER_LOCATION) { return true; // Don't print a key } else { // Set indentation switch (state) { case KEYWORD: { keyIndentation = 0; valueIndentation = 12; break; } case SUBKEYWORD: { keyIndentation = 2; valueIndentation = 12; break; } case SUBSUBKEYWORD: { keyIndentation = 3; valueIndentation = 12; break; } case FEATURE: { keyIndentation = 5; valueIndentation = 21; break; } default: { break; } } } // Print key plus left/right padding gb << makeSpaces(keyIndentation); gb << key; gb << makeSpaces(valueIndentation - keyIndentation - key.length()); // Set column counter nwritten = valueIndentation; return true; } bool JSONHandler::Null() { gb << "\n"; return true; } /** * JSON to GenBank converter. * @param[in] json The JSON string. * @param[out] gb The GenBank string. * @param[out] err Error object. */ void json2gb(const std::string *json, std::string *gb, gberror *err) { JSONHandler handler; rapidjson::Reader reader; rapidjson::StringStream sstream(json->c_str()); reader.Parse(sstream, handler); if (reader.HasParseError()) { err->flag = true; err->msg = "Unable to parse JSON"; err->source = "json2gb"; } else { *gb = handler.gb.str(); } }
f7c072affd56b85ce17f0fcbef7b877a1705e96e
d11e48aacb94fc85a40e967d53a8283a0be3f0ff
/Classes/HelloWorldScene.h
70b718c7909a2e9dee9f79fc87473855f070c451
[]
no_license
retrobrain/ParanoidArkanoid
1007262356189956d35faf9b17eb97c6a668fc2c
6a662022f498965fd2f55c3ba7659554f0252ce9
refs/heads/master
2021-01-22T04:56:59.683173
2015-06-22T07:12:22
2015-06-22T07:12:22
28,586,188
0
0
null
null
null
null
UTF-8
C++
false
false
1,354
h
HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "Brick.h" USING_NS_CC; const float SPEED = 240.0; const int BORDER_AMOUNT = 4; const int BRICKS_AMOUNT = 4; class HelloWorld : public cocos2d::LayerColor { public: // there's no 'id' in cpp, so we recommend returning the class instance pointer static cocos2d::Scene* createScene(); // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // a selector callback void menuCloseCallback(Ref* pSender); //used only for MotionStreak position update virtual void update(float delta); //calculates and moves to target point creating a callback to this func on complete void moveToIntersectPoint(); //sets briks labels, hides bricks void checkGameState(); // implement the "static create()" method manually CREATE_FUNC(HelloWorld); private: Vec2 m_vBallPosition; Vec2 m_vBallDirection; float m_fBallRadius; Sprite *m_sBallSprite; MotionStreak *m_motionEffect; int m_currentBrick; int m_iHitsToWin; DrawNode *m_lineTrack; std::vector<Vec2>m_vBorderLines; std::vector<Brick*>m_vBricks; }; #endif // __HELLOWORLD_SCENE_H__
e2bd2b5ce3066a4aa09041048e0ba41bc90d3f51
5e1f5f2090013041b13d1e280f747aa9f914caa4
/src/virtualization/bin/vmm/device/virtio_magma.cc
95a19642720e314cacbfae410384df0fc468b6fd
[ "BSD-2-Clause" ]
permissive
mvanotti/fuchsia-mirror
477b7d51ae6818e456d5803eea68df35d0d0af88
7fb60ae374573299dcb1cc73f950b4f5f981f95c
refs/heads/main
2022-11-29T08:52:01.817638
2021-10-06T05:37:42
2021-10-06T05:37:42
224,297,435
0
1
BSD-2-Clause
2022-11-21T01:19:37
2019-11-26T22:28:11
C++
UTF-8
C++
false
false
21,275
cc
virtio_magma.cc
// Copyright 2018 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. #include "src/virtualization/bin/vmm/device/virtio_magma.h" #include <dirent.h> #include <fcntl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fdio/directory.h> #include <lib/fit/defer.h> #include <lib/syslog/cpp/log_settings.h> #include <lib/syslog/cpp/macros.h> #include <lib/trace-provider/provider.h> #include <lib/trace/event.h> #include <lib/zx/channel.h> #include <lib/zx/vmar.h> #include <zircon/status.h> #include "src/virtualization/bin/vmm/device/magma_image.h" #include "src/virtualization/bin/vmm/device/virtio_queue.h" static constexpr const char* kDeviceDir = "/dev/class/gpu"; #if VIRTMAGMA_DEBUG #include <lib/syslog/global.h> #define LOG_VERBOSE(msg, ...) _FX_LOGF(FX_LOG_INFO, "virtio_magma", msg, ##__VA_ARGS__) #else #define LOG_VERBOSE(msg, ...) #endif static zx_status_t InitFromImageInfo(zx::vmo vmo, ImageInfoWithToken& info, fuchsia::virtualization::hardware::VirtioImage* image) { if (info.token) { zx_status_t status = info.token.duplicate(ZX_RIGHT_SAME_RIGHTS, &image->token); if (status != ZX_OK) return status; } image->vmo = std::move(vmo); image->info.resize(sizeof(magma_image_info_t)); memcpy(image->info.data(), &info.info, sizeof(magma_image_info_t)); return ZX_OK; } static void InitFromVirtioImage(fuchsia::virtualization::hardware::VirtioImage& image, zx::vmo* vmo, ImageInfoWithToken* info) { *vmo = std::move(image.vmo); info->token = std::move(image.token); assert(image.info.size() >= sizeof(magma_image_info_t)); memcpy(&info->info, image.info.data(), sizeof(magma_image_info_t)); } VirtioMagma::VirtioMagma(sys::ComponentContext* context) : DeviceBase(context) {} void VirtioMagma::Start( fuchsia::virtualization::hardware::StartInfo start_info, zx::vmar vmar, fidl::InterfaceHandle<fuchsia::virtualization::hardware::VirtioWaylandImporter> wayland_importer, StartCallback callback) { auto deferred = fit::defer([&callback]() { callback(ZX_ERR_INTERNAL); }); if (wayland_importer) { wayland_importer_ = wayland_importer.BindSync(); } PrepStart(std::move(start_info)); vmar_ = std::move(vmar); out_queue_.set_phys_mem(&phys_mem_); out_queue_.set_interrupt( fit::bind_member<zx_status_t, DeviceBase>(this, &VirtioMagma::Interrupt)); auto dir = opendir(kDeviceDir); if (!dir) { FX_LOGS(ERROR) << "Failed to open device directory at " << kDeviceDir << ": " << strerror(errno); deferred.cancel(); callback(ZX_ERR_NOT_FOUND); return; } for (auto entry = readdir(dir); entry != nullptr && !device_fd_.is_valid(); entry = readdir(dir)) { device_path_ = std::string(kDeviceDir) + "/" + entry->d_name; device_fd_ = fbl::unique_fd(open(device_path_.c_str(), O_RDONLY)); if (!device_fd_.is_valid()) { FX_LOGS(WARNING) << "Failed to open device at " << device_path_ << ": " << strerror(errno); } } closedir(dir); if (!device_fd_.is_valid()) { FX_LOGS(ERROR) << "Failed to open any devices in " << kDeviceDir << "."; deferred.cancel(); callback(ZX_ERR_NOT_FOUND); return; } deferred.cancel(); callback(ZX_OK); } void VirtioMagma::Ready(uint32_t negotiated_features, ReadyCallback callback) { auto deferred = fit::defer(std::move(callback)); } void VirtioMagma::ConfigureQueue(uint16_t queue, uint16_t size, zx_gpaddr_t desc, zx_gpaddr_t avail, zx_gpaddr_t used, ConfigureQueueCallback callback) { TRACE_DURATION("machina", "VirtioMagma::ConfigureQueue"); auto deferred = fit::defer(std::move(callback)); if (queue != 0) { FX_LOGS(ERROR) << "ConfigureQueue on non-existent queue " << queue; return; } out_queue_.Configure(size, desc, avail, used); } void VirtioMagma::NotifyQueue(uint16_t queue) { TRACE_DURATION("machina", "VirtioMagma::NotifyQueue"); if (queue != 0) { return; } VirtioChain out_chain; while (out_queue_.NextChain(&out_chain)) { VirtioMagmaGeneric::HandleCommand(std::move(out_chain)); } } // Handle special commands here - notably, those that send back bytes beyond // what is contained in the response struct. zx_status_t VirtioMagma::HandleCommandDescriptors(VirtioDescriptor* request_desc, VirtioDescriptor* response_desc, uint32_t* used_out) { auto header = reinterpret_cast<virtio_magma_ctrl_hdr*>(request_desc->addr); switch (header->type) { case VIRTIO_MAGMA_CMD_READ_NOTIFICATION_CHANNEL2: { auto request_copy = *reinterpret_cast<virtio_magma_read_notification_channel2_ctrl_t*>(request_desc->addr); virtio_magma_read_notification_channel2_resp_t response{}; // TODO(fxbug.dev/83668) - check for sizeof(response) + request_copy.buffer_size if (response_desc->len < sizeof(response)) { FX_LOGS(ERROR) << "VIRTIO_MAGMA_CMD_READ_NOTIFICATION_CHANNEL2: response descriptor too small"; return ZX_ERR_INVALID_ARGS; } // The notification data immediately follows the response struct. auto notification_buffer = reinterpret_cast<virtio_magma_read_notification_channel2_resp_t*>(response_desc->addr) + 1; request_copy.buffer = reinterpret_cast<uint64_t>(notification_buffer); zx_status_t status = VirtioMagmaGeneric::Handle_read_notification_channel2(&request_copy, &response); if (status != ZX_OK) return status; if (response.result_return == MAGMA_STATUS_OK) { // For testing constexpr uint32_t kMagicFlags = 0xabcd1234; if (header->flags == kMagicFlags && request_copy.buffer_size >= sizeof(kMagicFlags) && response.buffer_size_out == 0) { memcpy(notification_buffer, &kMagicFlags, sizeof(kMagicFlags)); response.buffer_size_out = sizeof(kMagicFlags); } } memcpy(response_desc->addr, &response, sizeof(response)); *used_out = static_cast<uint32_t>(sizeof(response) + response.buffer_size_out); return ZX_OK; } // Returns the buffer size after the response struct. case VIRTIO_MAGMA_CMD_GET_BUFFER_HANDLE2: { auto request = reinterpret_cast<virtio_magma_get_buffer_handle2_ctrl_t*>(request_desc->addr); virtio_magma_get_buffer_handle2_resp_t response = { .hdr = { .type = VIRTIO_MAGMA_RESP_GET_BUFFER_HANDLE2, }, }; zx::vmo vmo; response.result_return = magma_get_buffer_handle2(request->buffer, vmo.reset_and_get_address()); response.handle_out = vmo.get(); memcpy(response_desc->addr, &response, sizeof(response)); *used_out = sizeof(response); if (response.result_return == MAGMA_STATUS_OK) { uint64_t buffer_size; zx_status_t status = vmo.get_size(&buffer_size); if (status != ZX_OK) return status; void* buffer_size_ptr = reinterpret_cast<virtio_magma_get_buffer_handle2_resp_t*>(response_desc->addr) + 1; memcpy(buffer_size_ptr, &buffer_size, sizeof(buffer_size)); *used_out += sizeof(buffer_size); // Keep the handle alive while the guest is referencing it. stored_handles_.push_back(std::move(vmo)); } return ZX_OK; } // Returns the buffer size after the response struct. case VIRTIO_MAGMA_CMD_QUERY_RETURNS_BUFFER2: { auto request = reinterpret_cast<virtio_magma_query_returns_buffer2_ctrl_t*>(request_desc->addr); virtio_magma_get_buffer_handle2_resp_t response = { .hdr = { .type = VIRTIO_MAGMA_RESP_QUERY_RETURNS_BUFFER2, }, }; const auto device = request->device; const auto id = request->id; zx::vmo vmo; response.result_return = magma_query_returns_buffer2(device, id, vmo.reset_and_get_address()); response.handle_out = vmo.get(); memcpy(response_desc->addr, &response, sizeof(response)); *used_out = sizeof(response); if (response.result_return == MAGMA_STATUS_OK) { uint64_t buffer_size; zx_status_t status = vmo.get_size(&buffer_size); if (status != ZX_OK) return status; void* buffer_size_ptr = reinterpret_cast<virtio_magma_query_returns_buffer2_resp_t*>(response_desc->addr) + 1; memcpy(buffer_size_ptr, &buffer_size, sizeof(buffer_size)); *used_out += sizeof(buffer_size); // Keep the handle alive while the guest is referencing it. stored_handles_.push_back(std::move(vmo)); } return ZX_OK; } } return ZX_ERR_NOT_SUPPORTED; } zx_status_t VirtioMagma::Handle_device_import(const virtio_magma_device_import_ctrl_t* request, virtio_magma_device_import_resp_t* response) { zx::channel server_handle, client_handle; zx_status_t status = zx::channel::create(0u, &server_handle, &client_handle); if (status != ZX_OK) return status; status = fdio_service_connect(device_path_.c_str(), server_handle.release()); if (status != ZX_OK) { LOG_VERBOSE("fdio_service_connect failed %d", status); return status; } auto modified = *request; modified.device_channel = client_handle.release(); return VirtioMagmaGeneric::Handle_device_import(&modified, response); } zx_status_t VirtioMagma::Handle_release_connection( const virtio_magma_release_connection_ctrl_t* request, virtio_magma_release_connection_resp_t* response) { zx_status_t status = VirtioMagmaGeneric::Handle_release_connection(request, response); if (status != ZX_OK) return ZX_OK; auto connection = reinterpret_cast<magma_connection_t>(request->connection); connection_image_map_.erase(connection); return ZX_OK; } zx_status_t VirtioMagma::Handle_release_buffer(const virtio_magma_release_buffer_ctrl_t* request, virtio_magma_release_buffer_resp_t* response) { zx_status_t status = VirtioMagmaGeneric::Handle_release_buffer(request, response); if (status != ZX_OK) return ZX_OK; auto connection = reinterpret_cast<magma_connection_t>(request->connection); const uint64_t buffer = request->buffer; connection_image_map_[connection].erase(buffer); return ZX_OK; } zx_status_t VirtioMagma::Handle_internal_map2(const virtio_magma_internal_map2_ctrl_t* request, virtio_magma_internal_map2_resp_t* response) { FX_DCHECK(request->hdr.type == VIRTIO_MAGMA_CMD_INTERNAL_MAP2); response->address_out = 0; response->hdr.type = VIRTIO_MAGMA_RESP_INTERNAL_MAP2; // Buffer handle must have been stored. auto iter = std::find(stored_handles_.begin(), stored_handles_.end(), request->buffer); if (iter == stored_handles_.end()) { response->result_return = MAGMA_STATUS_INVALID_ARGS; return ZX_OK; } const uint64_t length = request->length; zx::unowned_vmo vmo(request->buffer); zx_vaddr_t zx_vaddr; zx_status_t zx_status = vmar_.map(ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0 /*vmar_offset*/, *vmo, 0 /* vmo_offset */, length, &zx_vaddr); if (zx_status != ZX_OK) { FX_LOGS(ERROR) << "vmar map (length " << length << ") failed: " << zx_status; response->result_return = MAGMA_STATUS_INVALID_ARGS; return zx_status; } buffer_maps2_.emplace(zx_vaddr, std::pair<zx_handle_t, size_t>(request->buffer, length)); response->address_out = zx_vaddr; return ZX_OK; } zx_status_t VirtioMagma::Handle_internal_unmap2(const virtio_magma_internal_unmap2_ctrl_t* request, virtio_magma_internal_unmap2_resp_t* response) { FX_DCHECK(request->hdr.type == VIRTIO_MAGMA_CMD_INTERNAL_UNMAP2); response->hdr.type = VIRTIO_MAGMA_RESP_INTERNAL_UNMAP2; const uintptr_t address = request->address; auto iter = buffer_maps2_.find(address); if (iter == buffer_maps2_.end()) { response->result_return = MAGMA_STATUS_INVALID_ARGS; return ZX_OK; } const auto& mapping = iter->second; const zx_handle_t buffer_handle = mapping.first; const size_t length = mapping.second; if (buffer_handle != request->buffer) { response->result_return = MAGMA_STATUS_INVALID_ARGS; return ZX_OK; } buffer_maps2_.erase(iter); zx_status_t zx_status = vmar_.unmap(address, length); if (zx_status != ZX_OK) return zx_status; response->result_return = MAGMA_STATUS_OK; return ZX_OK; } zx_status_t VirtioMagma::Handle_internal_release_handle( const virtio_magma_internal_release_handle_ctrl_t* request, virtio_magma_internal_release_handle_resp_t* response) { FX_DCHECK(request->hdr.type == VIRTIO_MAGMA_CMD_INTERNAL_RELEASE_HANDLE); response->hdr.type = VIRTIO_MAGMA_RESP_INTERNAL_RELEASE_HANDLE; auto iter = std::find(stored_handles_.begin(), stored_handles_.end(), request->handle); if (iter == stored_handles_.end()) { response->result_return = MAGMA_STATUS_INVALID_ARGS; } else { stored_handles_.erase(iter); response->result_return = MAGMA_STATUS_OK; } return ZX_OK; } zx_status_t VirtioMagma::Handle_poll(const virtio_magma_poll_ctrl_t* request, virtio_magma_poll_resp_t* response) { auto request_mod = *request; // The actual items immediately follow the request struct. request_mod.items = reinterpret_cast<uint64_t>(&request[1]); // Transform byte count back to item count request_mod.count /= sizeof(magma_poll_item_t); return VirtioMagmaGeneric::Handle_poll(&request_mod, response); } zx_status_t VirtioMagma::Handle_export(const virtio_magma_export_ctrl_t* request, virtio_magma_export_resp_t* response) { if (!wayland_importer_) { LOG_VERBOSE("driver attempted to export a buffer without wayland present"); response->hdr.type = VIRTIO_MAGMA_RESP_EXPORT; response->buffer_handle_out = 0; response->result_return = MAGMA_STATUS_UNIMPLEMENTED; return ZX_OK; } // We only export images fuchsia::virtualization::hardware::VirtioImage image; { auto& image_map = connection_image_map_[reinterpret_cast<magma_connection_t>(request->connection)]; const uint64_t buffer = request->buffer; auto iter = image_map.find(buffer); if (iter == image_map.end()) { response->hdr.type = VIRTIO_MAGMA_RESP_EXPORT; response->buffer_handle_out = 0; response->result_return = MAGMA_STATUS_INVALID_ARGS; return ZX_OK; } ImageInfoWithToken& info = iter->second; // Get the VMO handle for this buffer. zx_status_t status = VirtioMagmaGeneric::Handle_export(request, response); if (status != ZX_OK) { LOG_VERBOSE("VirtioMagmaGeneric::Handle_export failed: %d", status); return status; } // Take ownership of the VMO handle. zx::vmo vmo(static_cast<zx_handle_t>(response->buffer_handle_out)); response->buffer_handle_out = 0; status = InitFromImageInfo(std::move(vmo), info, &image); if (status != ZX_OK) { LOG_VERBOSE("InitFromImageInfo failed: %d", status); return status; } } // TODO(fxbug.dev/13261): improvement backlog // Perform a blocking import of the image, then return the VFD ID in the response. // Note that since the virtio-magma device is fully synchronous anyway, this does // not impact performance. Ideally, the device would stash the response chain and // return it only when the Import call returns, processing messages from other // instances, or even other connections, in the meantime. uint32_t vfd_id; zx_status_t status = wayland_importer_->ImportImage(std::move(image), &vfd_id); if (status != ZX_OK) { LOG_VERBOSE("ImportImage failed: %d", status); return status; } response->buffer_handle_out = vfd_id; return ZX_OK; } zx_status_t VirtioMagma::Handle_import(const virtio_magma_import_ctrl_t* request, virtio_magma_import_resp_t* response) { if (!wayland_importer_) { LOG_VERBOSE("driver attempted to import a buffer without wayland present"); response->hdr.type = VIRTIO_MAGMA_RESP_IMPORT; response->result_return = MAGMA_STATUS_UNIMPLEMENTED; return ZX_OK; } uint32_t vfd_id = request->buffer_handle; std::unique_ptr<fuchsia::virtualization::hardware::VirtioImage> image; zx_status_t result; zx_status_t status = wayland_importer_->ExportImage(vfd_id, &result, &image); if (status != ZX_OK) { LOG_VERBOSE("VirtioWl ExportImage failed: %d", status); return status; } assert(image); if (result != ZX_OK) { LOG_VERBOSE("VirtioWl ExportImage returned result: %d", status); return result; } ImageInfoWithToken info; zx::vmo vmo; InitFromVirtioImage(*image.get(), &vmo, &info); { virtio_magma_import_ctrl_t request_copy = *request; request_copy.buffer_handle = vmo.release(); status = VirtioMagmaGeneric::Handle_import(&request_copy, response); if (status != ZX_OK) return status; } { auto& image_map = connection_image_map_[reinterpret_cast<magma_connection_t>(request->connection)]; image_map[response->buffer_out] = std::move(info); } return ZX_OK; } zx_status_t VirtioMagma::Handle_execute_command_buffer_with_resources2( const virtio_magma_execute_command_buffer_with_resources2_ctrl_t* request, virtio_magma_execute_command_buffer_with_resources2_resp_t* response) { // Command buffer payload comes immediately after the request auto command_buffer = reinterpret_cast<magma_command_buffer*>( const_cast<virtio_magma_execute_command_buffer_with_resources2_ctrl_t*>(request) + 1); auto exec_resources = reinterpret_cast<magma_exec_resource*>(command_buffer + 1); auto semaphore_ids = reinterpret_cast<uint64_t*>(exec_resources + command_buffer->resource_count); virtio_magma_execute_command_buffer_with_resources2_ctrl_t request_dupe; memcpy(&request_dupe, request, sizeof(request_dupe)); request_dupe.command_buffer = reinterpret_cast<uintptr_t>(command_buffer); request_dupe.resources = reinterpret_cast<uintptr_t>(exec_resources); request_dupe.semaphore_ids = reinterpret_cast<uintptr_t>(semaphore_ids); return VirtioMagmaGeneric::Handle_execute_command_buffer_with_resources2(&request_dupe, response); } zx_status_t VirtioMagma::Handle_virt_create_image( const virtio_magma_virt_create_image_ctrl_t* request, virtio_magma_virt_create_image_resp_t* response) { // Copy create info to ensure proper alignment magma_image_create_info_t image_create_info; memcpy(&image_create_info, reinterpret_cast<const magma_image_create_info_t*>(request + 1), sizeof(image_create_info)); ImageInfoWithToken image_info; zx::vmo vmo; response->hdr.type = VIRTIO_MAGMA_RESP_VIRT_CREATE_IMAGE; // Assuming the current connection is on the one and only physical device. uint32_t physical_device_index = 0; response->result_return = magma_image::CreateDrmImage(physical_device_index, &image_create_info, &image_info.info, &vmo, &image_info.token); if (response->result_return != MAGMA_STATUS_OK) return ZX_OK; auto connection = reinterpret_cast<magma_connection_t>(request->connection); { magma_buffer_t image; response->result_return = magma_import(connection, vmo.release(), &image); if (response->result_return != MAGMA_STATUS_OK) { printf("Failed to import VMO\n"); return ZX_OK; } response->image_out = image; } auto& map = connection_image_map_[connection]; map[response->image_out] = std::move(image_info); return ZX_OK; } zx_status_t VirtioMagma::Handle_virt_get_image_info( const virtio_magma_virt_get_image_info_ctrl_t* request, virtio_magma_virt_get_image_info_resp_t* response) { response->hdr.type = VIRTIO_MAGMA_RESP_VIRT_GET_IMAGE_INFO; auto connection = reinterpret_cast<magma_connection_t>(request->connection); auto& map = connection_image_map_[connection]; const magma_buffer_t image = request->image; auto iter = map.find(image); if (iter == map.end()) { response->result_return = MAGMA_STATUS_INVALID_ARGS; return ZX_OK; } ImageInfoWithToken& image_info = iter->second; auto image_info_out = reinterpret_cast<magma_image_info_t*>( const_cast<virtio_magma_virt_get_image_info_ctrl_t*>(request) + 1); *image_info_out = image_info.info; response->result_return = MAGMA_STATUS_OK; return ZX_OK; } int main(int argc, char** argv) { syslog::SetTags({"virtio_magma"}); async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread); trace::TraceProviderWithFdio trace_provider(loop.dispatcher()); std::unique_ptr<sys::ComponentContext> context = sys::ComponentContext::CreateAndServeOutgoingDirectory(); VirtioMagma virtio_magma(context.get()); return loop.Run(); }
af7e75300517c63b155a1641256998f614ba1869
11f574b5ee844b34cd98fe1d06b6e7178281d6d4
/Assignment1/producer.cpp
931445e857e4dee2a7bf85a8f9fa4cbed87ad28c
[]
no_license
TaberIV/cs492
c4f17f38b39a9afa70c0c7d3057454b880b4ee26
3f93aad3d5153160c935dfae254469f068641150
refs/heads/master
2021-04-26T23:42:36.053811
2018-05-07T16:09:27
2018-05-07T16:09:27
123,841,753
0
0
null
null
null
null
UTF-8
C++
false
false
1,437
cpp
producer.cpp
/*********************************************** * CS492 - Operating Systems * Assignment 1 * * Authors: E. Taber McFarlin and Matt Swentzel * We pledge our honor that we have abided by * the Stevens Honor System ***********************************************/ #include "assign1.h" void *producer(void *id) { int idNum = *(int *) id; Product *p; // Create Product and add Product to queue pthread_mutex_lock(&product_count_mutex); if (product_count < num_products) { p = new Product(product_count++); pthread_mutex_unlock(&product_count_mutex); // Wait if queue is full pthread_mutex_lock(&queue_back_mutex); while (productQueue.size() == queue_size && queue_size != 0) { if (debug) { printf(" Producer %d\t| Wait | -\t| %d/%d\n", idNum, (int) productQueue.size(), queue_size); } pthread_cond_wait(&queue_not_full, &queue_back_mutex); } // Push to queue productQueue.push(p); printf(" Producer %d\t| Produces | %d\t| %d/%d\n", idNum, p->id, (int) productQueue.size(), queue_size); pthread_mutex_unlock(&queue_back_mutex); pthread_cond_signal(&queue_not_empty); // Re-run producer function usleep(100000); producer(id); } else { // Exits after all products are produced pthread_mutex_unlock(&product_count_mutex); if (debug) printf(" Producer %d\t| Exit | -\t| -/%d\n", idNum, queue_size); pthread_exit(NULL); } }
1c2504bb6813a50df84e15d39aa1d70014b4b2f6
5fcc718e15e951bb0ef3fae7816ee2f33cfced82
/travelapac.cpp
2934300586c1afa218552937fd38812cca84b13e
[]
no_license
Shubhamsingh147/Codechef-Hackerrank-Hackerearth-etc
27ec108b05350222829450d9da8f66bfe1ebd085
8974aa238d3609a61f0003bee5fb56c3e2b31b01
refs/heads/master
2021-01-19T04:24:32.494028
2016-06-01T09:21:58
2016-06-01T09:21:58
60,162,140
0
0
null
null
null
null
UTF-8
C++
false
false
1,726
cpp
travelapac.cpp
#include <iostream> #include <map> #include <vector> #include <limits.h> using namespace std; int n; int findMin(int dist[]){ int min = INT_MAX; int minIndex = 1; for (int i = 1; i <= n; ++i) { if ( dist[i] < min ) { min = dist[i]; minIndex = i; } } return minIndex; } int main(){ int t,cases; cin>>t; cases = t; while(t--){ int m,x,y,z,s,k,start,d; pair<int,int> pr,pr2; cin>>n>>m>>k; int a[n+1][n+1]; map<pair<int,int> , vector<vector<int> > > mp; int dist[n+1]; for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) a[i][j] = 0; for (int i = 0; i < m; ++i) { cin>>x>>y; a[x][y] = 1; a[y][x] = 1; pr = make_pair(x,y); pr2 = make_pair(y,x); int ghj; vector<int> times; for(int j = 0 ; j < 24; j++) { cin>>ghj; times.push_back(ghj); } mp[pr].push_back(times); mp[pr2].push_back(times); } cout<<"Case #"<<cases-t<<": "; for (int i = 0; i < k; ++i) { cin>>d>>start; s = 1; for (int i = 1; i <= n; ++i) { dist[i] = INT_MAX; } dist[s] = 0; int temp,i=0; while(dist[d]!=temp){ if(dist[d]!=INT_MAX) temp = dist[d]; int index = findMin(dist); int timeHere = (i++ + start)%24; for (int j = 1; j <= n; ++j) { if (a[index][j] && (dist[index] != INT_MAX)) { vector<vector<int> > vc = mp[make_pair(index,j)]; int mini = INT_MAX; for (int r = 0; r < vc.size() ; ++r) { if(mini > vc[r][timeHere]) mini = vc[r][timeHere]; } if (dist[j] > (dist[index] + mini)) dist[j] = dist[index] + mini; } } } if(dist[d]!=INT_MAX) cout<<dist[d]<<" "; else cout<<-1<<" "; } cout<<endl; } }
6c830a5f9392d0d7281cc38105ecc97c43bd2666
375fccaa7deeefaa392036e9c7e4c2be1b8cef44
/include/octoon/runtime/singleton.h
a09ef0c2ce184855debdfe048bfe091c73184837
[ "MIT" ]
permissive
naeioi/octoon
b98678df257e87da9fb27e56f0f209ff46cc126b
e32152fe4730fa609def41114613dbe067d31276
refs/heads/master
2020-07-09T05:33:15.019542
2019-08-22T11:34:54
2019-08-22T11:34:58
203,893,478
1
0
MIT
2019-08-23T00:22:11
2019-08-23T00:22:11
null
UTF-8
C++
false
false
860
h
singleton.h
#ifndef OCTOON_SINGLETON_H_ #define OCTOON_SINGLETON_H_ #include <octoon/runtime/platform.h> #include <type_traits> namespace octoon { namespace runtime { template<typename T, typename = std::enable_if_t<std::is_class<T>::value>> class Singleton { public: static T* instance() noexcept { return &instance_; } protected: Singleton(void) = default; virtual ~Singleton(void) = default; private: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; private: static T instance_; }; template<typename _Tx, typename _Ty> _Tx Singleton<_Tx, _Ty>::instance_; } } #define OctoonDeclareSingleton(type) \ public:\ static type* instance();\ private: #define OctoonImplementSingleton(type) \ type* type::instance() \ {\ return runtime::Singleton<type>::instance();\ } #endif
b573867791dc0d7ee34eae68be0b58ed6436354c
d08f72f9b0f6251edb91871c3e63df376957cde7
/include/parser.hpp
c9843391b5efd33388c0baebf043eeee9377a35a
[]
no_license
whitead/WordModel
5dfafd67c1c75c87b6859e4b29dd1275f4ca4c6b
0788d107e42234a83d294355f9d02d01df02ee93
refs/heads/master
2020-04-05T05:16:49.408898
2015-03-22T13:49:20
2015-03-22T13:49:20
21,846,028
0
0
null
null
null
null
UTF-8
C++
false
false
4,103
hpp
parser.hpp
#ifndef PARSER_H #define PARSER_H #include <iostream> #include <vector> #include <unordered_map> #include <string> #include <utility> namespace wordmodel { typedef std::pair<std::size_t, std::size_t> Pair_Key; struct Pair_Key_Hasher { std::size_t operator()(const Pair_Key& k) const { //The multiplication is necessary so that the // two pairs don't commute ( x,y != y,x) return (k.first * 0x1f1f1f1f) ^ k.second; } }; /** \brief A parser for converting a tokenizer into information about * words. */ class Parser { public: /** \brief Default constructor * * */ Parser(); /** \brief Add a word, using the stored last index * * Just calls add_pair and assumes the last add_word call was the * previous word. */ void add_word(const std::string& word); /** \brief Add a word, given the index of the last word * * Pass in a last_index of 0 for a starting word. */ size_t add_pair(const std::string& word, size_t last_index); /** \brief Get an index for a given word * * \param word The word * \param index The index will be returned through this pointer * \return Success or failure. It can fail if the word has not been encountered by the parser */ bool get_index(std::string const& word, size_t* index) const; /** \brief Get the word corresponding to the given index * * \param index The index * \param word The word will be returned through this pointer * \return Success or failure. It can fail if the index is invalid */ bool get_word(size_t index, std::string* word) const; /** \brief Access the counts for a given word * * \param word The word * * \return The number of times a word was observed */ unsigned int count(std::string const& word) const; /** \brief Access the counts for a given word * * \param index The index of the word * * \return The number of times a word was observed */ unsigned int count(size_t index) const; /** \brief Access counts that word_j followed word_i * * \param word_i The first word * \param word_j The second word * * \return The number of times a word was observed */ unsigned int count(std::string const& word_i, std::string const& word_j) const; /** \brief Access counts that a word corresponding to index_j * followed a word corresponding to index_i * * \param index_i The first word index * \param index_j The second word index * * \return The number of times a word was observed */ unsigned int count(size_t index_i, size_t index_j) const; /** \brief Returns an iterator that iterates words that followed the * given word * */ const std::vector<size_t>& iterate_pairs(size_t index) const; /** \brief Returns an iterator that iterates words that followed the * given word * */ const std::vector<size_t>& iterate_pairs(std::string word) const; /** \brief Output summary statistics from the parsing * * \param out The stream where to print the statistics * */ void print_summary(std::ostream& out) const; size_t get_word_number() const { return word_number; }; private: size_t word_number; //the last index of the last word added size_t last_index_; //goes from words to index std::unordered_map<std::string, size_t> word_map; //count of words std::vector<unsigned int> counts; //goes from index to words std::vector<std::string> words; //for speeding computations, all the nonzero-pairs for a given word std::vector<std::vector<size_t> > nonzero_pairs; //pair counts std::unordered_map<Pair_Key, unsigned int, Pair_Key_Hasher> pair_counts; //Note: to add tuples beyond pairs, use the boost hash_combine function //to map the size_t indices of the words. }; } #endif //PARSER_H
e1b32170ab898730bb3073dfdbe90ededdb90d01
39b7774fef218d9d7e32e0c6fbb7b2cad7b6f0a2
/SecRTC/inlcude/maintabwidget.h
bbe91b0ef56e2d955305aa86da98112fe3b8d696
[]
no_license
xudabeauty/SecRTC
97f1aa9badfff9258c13f573fdec90c1c44e1969
cad8752044d1b4c44a6067a2ba40491ff104d6de
refs/heads/master
2021-09-10T05:37:35.663971
2018-03-21T06:13:39
2018-03-21T06:13:39
105,609,805
0
0
null
null
null
null
UTF-8
C++
false
false
501
h
maintabwidget.h
#ifndef MAINTABWIDGET_H #define MAINTABWIDGET_H #include<QtWidgets/QTableWidget> #endif // MAINTABWIDGET_H class LinkCmdWidget; class LinkFileWidget; class LinkProcessWidget; class LinkServiceWidget; class MainTabWidget:public QTabWidget { Q_OBJECT public: MainTabWidget(); ~MainTabWidget(); void createMainWeiget(); private: LinkCmdWidget*linkCmdWidget; LinkFileWidget*linkFileWidget; LinkProcessWidget*linkProcessWidget; LinkServiceWidget*linkServiceWidget; };
68b6b965b67b072aae58dfb4f7c1483668ab8d95
aec445e5cf456bc5110d5b152dfe96565fbc0b50
/tools/feetech_servo_library/FD Software-Open Source Code VS2008(170307)/FD-OPEN/SCServo/SCServo.h
ff6feca87e60004ebce75302d0060a74639f2ef5
[]
no_license
kbunal/hecatonquiros
761e1e9d3ec09e8c047f06e4ad6d70ad7fe3bf31
da0163ad2732bcea3852daef96d0610b420f47c4
refs/heads/master
2020-09-17T23:49:47.861844
2019-11-19T20:29:13
2019-11-19T20:29:13
null
0
0
null
null
null
null
GB18030
C++
false
false
532
h
SCServo.h
/* * SCServo.h * 硬件通信接口 * 日期: 2016.8.25 * 作者: 谭雄乐 */ #ifndef _SCSERVO_H #define _SCSERVO_H #include "SCSProtocol.h" #include "SCComm.h" class SCServo : public SCSProtocol { public: SCServo(void); virtual int writeSCS(unsigned char *nDat, int nLen);//输出nLen字节 virtual int readSCS(unsigned char *nDat, int nLen);//输入nLen字节 virtual int writeSCS(unsigned char bDat);//输出1字节 virtual void flushSCS();//刷新接口缓冲区 public: CSCComm *pSerial;//串口指针 }; #endif
bd819ee83926a382cba024a87bfd90cbee85fd96
aa6563e95fa62ba082845eb2a3f3791eb9ca891f
/gui/threading/safequeue.tpp
2c1a9ca7e4d3d60bc1169b26479b42e52b8e5e46
[ "MIT" ]
permissive
RobotApocalypseCommittee/PhysicsEngineC4
3c3b52d412f20d1580386b93680cd29ae7e390cc
adf547c3e6ab557a70cf52d6d1bd1e3e95e4cb9b
refs/heads/master
2022-12-15T10:17:53.290532
2020-09-15T14:19:38
2020-09-15T14:19:38
273,688,369
1
0
null
null
null
null
UTF-8
C++
false
false
641
tpp
safequeue.tpp
// // Created by Attoa on 25/06/2020. // #ifndef PHYSICS_C4_SAFEQUEUE_TPP #define PHYSICS_C4_SAFEQUEUE_TPP namespace threading { template<class T> SafeQueue<T>::SafeQueue() : q(), m(), c() {} template<class T> void SafeQueue<T>::enqueue(T item) { std::lock_guard<std::mutex> lockGuard(m); q.push(item); c.notify_one(); } template<class T> T SafeQueue<T>::dequeue() { std::unique_lock<std::mutex> uniqueLock(m); c.wait(uniqueLock, [=] { return !q.empty(); }); T item = q.front(); q.pop(); return item; } } #endif //PHYSICS_C4_SAFEQUEUE_TPP
e10bad7ebd5c17066bfda3c0814f8cc033704d23
18e89ca8c0c19d1eec4583fd1d9eb81afd3fbf3a
/Feb 2nd HW/nccc2s5.cpp
8fb07288eaba614b46ae6328bff55bd31615f0ad
[]
no_license
kevinlu1248/ccc
11d6c7326e2977a4cf0cdeeb5d866cda2328b94e
187a519842eb9bdc11cedb25031c1eaef3033e74
refs/heads/master
2020-08-03T00:59:06.935626
2020-02-23T21:23:54
2020-02-23T21:23:54
211,573,846
1
0
null
null
null
null
UTF-8
C++
false
false
3,236
cpp
nccc2s5.cpp
// nccc2s5 // created on 2/5/2020 11:09 PM by Kevin Lu // A Link/Cut Tree Problem /* Sample Input Copy 3 4 1 2 3 2 3 3 2 1 1 1 2 1 6 2 1 2 4 2 2 3 2 1 1 4 2 1 2 4 1 2 1 2 2 3 2 Sample Output Copy 0 1 1 0 */ #include <cstdio> #include <algorithm> #include <vector> // <bits/stdc++.h> using namespace std; const int N = 1010; int weights[N], mst[N], nxt[N], n, m, q; typedef struct Edge { int s, t, w, id; // t > s for edges Edge (int s = 0, int t = 0, int w = 0, int id = 0): s(s), t(t), w(w), id(id){}; bool operator < (Edge const a) const { // highest weight to lowest return w > a.w; } }Edge; vector<Edge> graph[N]; vector<Edge> edges; // all edges s.t. t > s void printGraph() { printf("graph:"); for (int i = 1; i <= n; i++) { printf(" "); for (Edge edge: graph[i]) printf("%d", edge.t); printf("\n"); } } void printArrs() { printf("Now printing nxt\n"); for (int i = 1; i <= n; i++) printf("%d, ", nxt[i]); printf("\n"); printf("Now printing mst\n"); for (int i = 1; i <= n; i++) printf("%d, ", mst[i]); printf("\n"); printf("Now printing weights\n"); for (int i = 1; i <= n; i++) printf("%d, ", weights[i]); printf("\n"); } bool query() { int ai, bi, wi; scanf("%d%d%d", &ai, &bi, &wi); // printf("Query: ai: %d, bi: %d, wi: %d\n", ai, bi, wi); if (ai > bi) swap(ai, bi); while (ai != bi) { if (ai == 1) swap(ai, bi); if (weights[ai] < wi) return false; ai = mst[ai]; } return true; } int next(int i) { if (nxt[i] == i) return i; return (nxt[i] = next(nxt[i])); } void kruskal() { // minimum spanning tree using Kruskal // printf("Running kruskal\n"); // printGraph(); int cnt = 0; for (int i = 0; i <= n; i++) mst[i] = i; for (int i = 0; i <= n; i++) nxt[i] = i; for (Edge edge: edges) { // printf("Now checking Edge(%d, %d, %d, %d);\n", edge.s, edge.t, edge.w, edge.id); // printArrs(); if (next(edge.s) == next(edge.t)) continue; // printf("Now connecting %d and %d;\n", edge.s, edge.t); mst[edge.t] = edge.s; weights[edge.t] = edge.w; nxt[next(edge.t)] = next(edge.s); if (++cnt == n - 1) break; } // printArrs(); } void update() { int mi, wi, id; scanf("%d%d", &mi, &wi); for (int j = 0; j < m; j++) if (edges[j].id == mi) { edges[j].w = wi; id = j; break; } // printf("%d\n", id); // sorting again (O(n*log(n))) (could be O(n) sort(edges.begin(), edges.end()); kruskal(); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); graph[a].push_back(Edge(a, b, c, i)); graph[b].push_back(Edge(b, a, c, i)); edges.push_back(Edge(min(a, b), max(a, b), c, i)); } sort(edges.begin(), edges.end()); // for (Edge edge: edges) printf("Edge(%d, %d, %d, %d);\n", edge.s, edge.t, edge.w, edge.id); kruskal(); scanf("%d", &q); while (q--) { int a; scanf("%d", &a); if (a == 1) update(); else printf("%d\n", query()); } return 0; }
088e5fc91d849417b43e59d8a18632def985458e
182322f4f2800f851754bb1bcb85fd4f9fc324ea
/zj/a170.cpp
61ae9e350ce450b42bac45580edc577067a17b39
[]
no_license
Tocknicsu/oj
66100fe94d76b6fe8d1bd3019f5ada9d686c1753
e84d6c87f3e8c0443a27e8efc749ea4b569a6c91
refs/heads/master
2021-01-17T08:12:32.510731
2016-04-18T02:09:04
2016-04-18T02:09:16
32,704,322
2
1
null
null
null
null
UTF-8
C++
false
false
211
cpp
a170.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ int n; scanf("%d", &n); while(n--){ ll a, b; scanf("%o%o",&a,&b); printf("%X\n", a+b); } }
d8017e534974d1216c871e4b4cfba403d15ca035
4bf9c6d368a9111de4ba813e8dd8a5614ac77d41
/source/main/main.cpp
a3cb23a31e754f1766a95133e2dc12ae632c36c7
[ "MIT" ]
permissive
t4th/cortex-m3-rtos-blinky-example
68a7ae187ffab8eec2bfe495bd318717cb5da469
6f3f96bf6c0daf9b9266bce62c9a0cb1759b0fe8
refs/heads/main
2023-03-18T17:51:13.712634
2021-03-13T11:15:57
2021-03-13T11:15:57
322,021,127
0
0
null
null
null
null
UTF-8
C++
false
false
3,602
cpp
main.cpp
// On target RTOS example: classic blinky. // HW used: stm32f103ze with keil ulink2 (should work with st-link). // 4 LEDs are connected to GPIOF, pins 6,7,8,9. // One task is blinking 1 LED - 4 tasks for 4 LEDs. // From human perspective it should look like // all 4 leds are blinking at the same time. #include <kernel.hpp> #include <gpio.hpp> struct LedState { bool led0; bool led1; bool led2; bool led3; }; // Global variable used for software debug analysis // when using simulator mode. volatile LedState g_ledStates; enum class Led { Number0, Number1, Number2, Number3 }; void setLed( Led a_led) { gpio::Pin pin; switch ( a_led) { case Led::Number0: gpio::setOutputPin< gpio::Port::F, gpio::Pin::Number6>(); g_ledStates.led0 = true; break; case Led::Number1: gpio::setOutputPin< gpio::Port::F, gpio::Pin::Number7>(); g_ledStates.led1 = true; break; case Led::Number2: gpio::setOutputPin< gpio::Port::F, gpio::Pin::Number8>(); g_ledStates.led2 = true; break; case Led::Number3: gpio::setOutputPin< gpio::Port::F, gpio::Pin::Number9>(); g_ledStates.led3 = true; break; default: break; } } void clearLed( Led a_led) { gpio::Pin pin; switch ( a_led) { case Led::Number0: gpio::clearOutputPin< gpio::Port::F, gpio::Pin::Number6>(); g_ledStates.led0 = false; break; case Led::Number1: gpio::clearOutputPin< gpio::Port::F, gpio::Pin::Number7>(); g_ledStates.led1 = false; break; case Led::Number2: gpio::clearOutputPin< gpio::Port::F, gpio::Pin::Number8>(); g_ledStates.led2 = false; break; case Led::Number3: gpio::clearOutputPin< gpio::Port::F, gpio::Pin::Number9>(); g_ledStates.led3 = false; break; default: break; } } void blinkLed( Led a_led, kernel::Time_ms a_time) { setLed( a_led); kernel::task::sleep( a_time); clearLed( a_led); kernel::task::sleep( a_time); } void task_blink_led_0 ( void * a_parameter) { while( true) { blinkLed( Led::Number0, 1000U); } } void task_blink_led_1 ( void * a_parameter) { while( true) { blinkLed( Led::Number1, 1000U); } } void task_blink_led_2 ( void * a_parameter) { while( true) { blinkLed( Led::Number2, 1000U); } } void task_blink_led_3 ( void * a_parameter) { while( true) { blinkLed( Led::Number3, 1000U); } } int main() { RCC->APB2ENR |= RCC_APB2ENR_IOPFEN; // enable gpiof gpio::setPinAsOutput< gpio::Port::F, gpio::Pin::Number6, gpio::OutputSpeed::Max50MHZ, gpio::OutputMode::GeneralPurposePushPull>(); gpio::setPinAsOutput< gpio::Port::F, gpio::Pin::Number7, gpio::OutputSpeed::Max50MHZ, gpio::OutputMode::GeneralPurposePushPull>(); gpio::setPinAsOutput< gpio::Port::F, gpio::Pin::Number8, gpio::OutputSpeed::Max50MHZ, gpio::OutputMode::GeneralPurposePushPull>(); gpio::setPinAsOutput< gpio::Port::F, gpio::Pin::Number9, gpio::OutputSpeed::Max50MHZ, gpio::OutputMode::GeneralPurposePushPull>(); kernel::hardware::debug::print("test"); kernel::init(); kernel::task::create( task_blink_led_0, kernel::task::Priority::Low); kernel::task::create( task_blink_led_1, kernel::task::Priority::Low); kernel::task::create( task_blink_led_2, kernel::task::Priority::Low); kernel::task::create( task_blink_led_3, kernel::task::Priority::Low); kernel::start(); for(;;); }
ff1b9e015be359aa2d56750dd3196b7d499a62f6
653e629a7fe91d7451ff61b28d1bc91c7336cdd9
/kernel/src/glue/v4-x86/x64/space.cc
365303f7f17acbd74189feb5c830b0ec3d9063f0
[]
no_license
Insecurity-plan15/l4ka-pistachio
a65ca7affedd6ed93d20ad5bf1124bdca5d064f3
9424d8232887e4938032888acb310e5bf83e251f
refs/heads/master
2021-01-17T08:52:06.277070
2010-01-08T11:33:26
2010-01-08T11:33:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,213
cc
space.cc
/**************************************************************************** * * Copyright (C) 2002, 2006, Karlsruhe University * * File path: glue/v4-amd64/space.cc * Description: AMD64 space_t implementation. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $Id: space.cc,v 1.23 2006/11/18 10:15:54 stoess Exp $ * ***************************************************************************/ #include <debug.h> #include <kmemory.h> #include <generic/lib.h> #include <linear_ptab.h> #include INC_API(tcb.h) #include INC_API(smp.h) #include INC_API(kernelinterface.h) #include INC_ARCH(mmu.h) #include INC_ARCH(trapgate.h) #include INC_ARCH(pgent.h) #include INC_GLUE(cpu.h) #include INC_GLUE(memory.h) #include INC_GLUE(space.h) #if defined(CONFIG_X86_COMPATIBILITY_MODE) #include INC_GLUE_SA(x32comp/kernelinterface.h) #endif /* defined(CONFIG_X86_COMPATIBILITY_MODE) */ word_t space_t::readmem_phys(addr_t paddr) { ASSERT( (word_t) paddr < (1ULL << 32)); return * (word_t *) ( (word_t) paddr + REMAP_32BIT_START); } #if defined(CONFIG_SMP) void pgent_t::smp_sync(space_t * space, pgsize_e pgsize) { ASSERT(pgsize >= size_sync); switch (pgsize) { case size_512g: for (cpuid_t cpu = 0; cpu < cpu_t::count; cpu++) if (cpu != space->data.reference_ptab && space->get_top_pdir(cpu)) { //TRACEF("smp sync pml4 %d / %x -> %d / %x\n", // space->data.reference_ptab, space->pgent(idx()), // cpu, space->pgent(idx(), cpu)); *space->pgent(idx(), cpu) = *space->pgent(idx()); } break; case size_1g: ASSERT(space->get_top_pdir()->get_kernel_pdp()); if (!is_cpulocal(space, size_1g) && (this - idx() == space->get_top_pdir(space->data.reference_ptab)->get_kernel_pdp_pgent())) { ASSERT(space->get_top_pdir(space->data.reference_ptab)->get_kernel_pdp()); for (cpuid_t cpu = 0; cpu < cpu_t::count; cpu++) if (cpu != space->data.reference_ptab && space->get_top_pdir(cpu) && space->get_top_pdir(cpu)->get_kernel_pdp_pgent()) { //TRACEF("smp sync kernel pdp %x idx %d cpu %d cpulocal = %s\n", // this - idx(), idx(), cpu, (is_cpulocal(space, size_2m) ? "cpulocal" : "global")); *space->get_top_pdir(cpu)->get_kernel_pdp_pgent()->next(space, size_2m, idx()) = *space->get_top_pdir(space->data.reference_ptab)->get_kernel_pdp_pgent()->next(space, size_2m, idx()); } break; } default: break; } } word_t pgent_t::smp_reference_bits(space_t * space, pgsize_e pgsize, addr_t vaddr) { printf("L4 Kernel BUG: X64 shouldn't have non-global superpages"); UNIMPLEMENTED(); } #endif /** * ACPI memory handling */ addr_t acpi_remap(addr_t addr) { //TRACE_INIT("ACPI remap: %p -> %x\n", addr, (word_t) addr + REMAP_32BIT_START); ASSERT((word_t) addr < (1ULL << 32)); return (addr_t) ((word_t) addr + REMAP_32BIT_START); } void acpi_unmap(addr_t addr) { /* empty */ } #if defined(CONFIG_X86_COMPATIBILITY_MODE) extern addr_t utcb_page; word_t space_t::space_control(word_t ctrl) { // Ignore parameter if 'c' bit is not set. if ((ctrl & (((word_t) 1) << 63)) == 0) return 0; if (!data.compatibility_mode) { data.compatibility_mode = true; /* Add 32-bit UTCB mapping, since the gs segment descriptor is truncated in 32-bit mode. Copied from init_kernel_mappings. */ remap_area((addr_t) UTCB_MAPPING_32, virt_to_phys(utcb_page), pgent_t::size_4k, X86_PAGE_SIZE, true, false, false); /* Replace 64-bit KIP mapping with 32-bit KIP. Copied from init. */ if (is_initialized()) { add_mapping(get_kip_page_area().get_base(), virt_to_phys((addr_t) x32::get_kip()), pgent_t::size_4k, false, false, false); } } // Set 'e' bit. return (((word_t) 1) << 63); } #else /* !defined(CONFIG_X86_COMPATIBILITY_MODE) */ word_t space_t::space_control(word_t ctrl) { return 0; } #endif /* defined(CONFIG_X86_COMPATIBILITY_MODE) */
0c2786770fe019a7f6f601f16545500f181d1b8f
d39478288134a05f31204d9538cbfb9431069541
/lab2 dyn , triangle/Trinagle/Triangle.h
65b3a3a98cf85bd7e23780fa6db14356982a6043
[]
no_license
navidRashik/Data_Structure_cpp
3000f6ed6abab6212239d69f1591f4050411e2cd
5fac66cba191b7a611131a709793a8e92c6ebc8b
refs/heads/master
2021-06-30T20:05:53.999119
2017-09-18T20:45:50
2017-09-18T20:45:50
103,988,521
0
0
null
null
null
null
UTF-8
C++
false
false
333
h
Triangle.h
#ifndef TRIANGLE_H #define TRIANGLE_H template <typename t> class Triangle { private: t base; t height; public: Triangle(); Triangle(t , t); void SetBase(t); void SetHeight(t); t ComputeHypotenuse(); t ComputeArea(); }; #endif // TRIANGLE_H #include "Triangle.cpp"
efc52c05bae24bb4325d6901d0475758a7872694
1243ce6d5f164c6593f7d4b1717885ef76f44dd1
/Stage 1/BankAccount_Stage_1.cpp
126ae66046fde3cfa6dfe61db382dddce7d97a73
[]
no_license
kanee98/InterBanking-Pty
dca7f6883eae0ec4bb4635881fb3d436993ad888
c5267cbbe8bdd6d2b3b37dbcab3d55c18c582f6a
refs/heads/master
2020-03-30T07:13:28.928039
2018-10-01T04:28:32
2018-10-01T04:28:32
150,924,096
0
0
null
null
null
null
UTF-8
C++
false
false
1,672
cpp
BankAccount_Stage_1.cpp
/** * Created by KanishkaUdapitiya on 21/11/2017. */ #include "stdafx.h" #include <iostream> #include <string> using namespace std; struct BankAccount{ int accountNumber; double accountBalance; char customerName[100]; char password[25]; }; int main(){ BankAccount obj; cout<<"Welcome to InterBanking Pty"<<endl; cout<<"-------------------------------"<<endl; cout<<"Input Account Number : "; cin>>obj.accountNumber; cout<<"Input Account Balance : $"; cin>>obj.accountBalance; cout<<"Input Customer Name : "; cin>>obj.customerName; cout<<"Input Password : "; cin>>obj.password; cout<<""<<endl; cout<<"Display Details"<<endl; cout<<"--------------------------------"<<endl; cout<<"Account Number : "<<obj.accountNumber<<endl; cout<<"Account Balance : $"<<obj.accountBalance<<endl; cout<<"Customer Name : "<<obj.customerName<<endl; cout<<"Password : "<<obj.password<<endl; cout<<"--------------------------------"<<endl; cout<<""<<endl; int accountNumber; string customerName; cout<<"Input Account Number : "; cin>>accountNumber; cout<<"Input Customer Name : "; cin>>customerName; cout<<""<<endl; if((accountNumber == obj.accountNumber) && (customerName == obj.customerName)){ cout<<"View Account Details"<<endl; cout<<"--------------------------------"<<endl; cout<<"The Account Number is : "<<obj.accountNumber<<endl; cout<<"The Account Balance is : $"<<obj.accountBalance<<endl; cout<<"The Customer Name is : "<<obj.customerName<<endl; } else{ cout<<"Warning! Customer Records are not in the database"<<endl; } system("pause"); return 0; }
51d64b288db3323f9699ede706b6a3f6131c00b9
db0ee6a9dcd98287b5512324dc4bd3850e1c4aaf
/QUEST5_spoj.cpp
c1ac72c26787ab93a0ef72cb29104fddb84af695
[]
no_license
saurav52/spoj-solutions
d17bfa76adba9da609ba2f9dfaab8c07b6dfcb9d
efd2b08e26f3204793478d7bd99045c10800ba80
refs/heads/master
2021-01-21T17:23:45.149352
2017-12-19T08:34:35
2017-12-19T08:34:35
91,949,159
0
0
null
null
null
null
UTF-8
C++
false
false
616
cpp
QUEST5_spoj.cpp
#include<bits/stdc++.h> using namespace std; int main() { int t,a,b,n; cin>>t; for(int z=1;z<=t;z++) { vector <pair<int,int> > v; cin>>n; for(int i=0;i<n;i++) { cin>>a>>b; v.push_back(make_pair(b,a)); } sort(v.begin(),v.end()); int k=0,count=1; for(int i=1;i<n;i++) { if(v[i].second > v[k].first) { k=i; ++count; } } cout<<count<<endl; vector <pair<int,int> > ().swap(v); } }
f31ae6d11d4582381505843235b21dce784ad4f0
0bd63ea82005e5e1d4b1e015b164e6bfdc410a9d
/CDrawTool.cpp
57406be20dc8998d5db8739b06573b02b8b038d3
[]
no_license
tonymin/DrawTool
442ef62d74b43d8032a0911001ae27e5464fe44d
9c22caede19c22a519336e11eda36e9ad68bf03b
refs/heads/master
2022-11-08T23:27:30.854092
2020-05-22T21:58:04
2020-05-22T21:58:04
266,177,019
0
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
CDrawTool.cpp
#include "CDrawTool.h" #include "Graphics/CGraphicsView.h" #include <QToolBar> using namespace Core; using namespace Core::Graphics; CDrawTool::CDrawTool(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); m_view = new CGraphicsView(); this->setCentralWidget(m_view); createToolBar(); } void CDrawTool::createToolBar() { QToolBar* toolbar = this->addToolBar("ToolBar"); m_debugAct = new QAction("Debug", this); m_debugAct->setStatusTip("Degug"); toolbar->addAction(m_debugAct); connect(m_debugAct, &QAction::triggered, this, &CDrawTool::onDebug); auto* runAct = new QAction("Run Algorithm", this); runAct->setStatusTip("Run Algorithm"); toolbar->addAction(runAct); connect(runAct, &QAction::triggered, this, &CDrawTool::onRun); auto* generateAct = new QAction("Generate Graph", this); generateAct->setStatusTip("Generate Graph"); toolbar->addAction(generateAct); connect(generateAct, &QAction::triggered, this, &CDrawTool::onGenerate); } void CDrawTool::onGenerate() { m_view->generateVisual(); } void CDrawTool::onRun() { m_view->runAlgorithm(); } void CDrawTool::onDebug() { }
79e22ad5bfca9d6e7749ffba6d568a5fad88c5b4
244d099ed37a40e99650d63436864f39d9aacacd
/Igrica/MonsterManager.cpp
f8b4d9adccceb3a60c937287f631395f5dc8d6af
[]
no_license
luka93x/igricaNova
50ab1784bd21ac78573be77c60b2dd727a5b4953
60cface5bbc4c15648dc320fd9d0f4f060507b02
refs/heads/master
2020-08-26T19:38:49.446122
2019-11-15T13:11:16
2019-11-15T13:11:16
217,122,775
0
0
null
null
null
null
UTF-8
C++
false
false
2,312
cpp
MonsterManager.cpp
#include "MonsterManager.h" #include "AttackManager.h" #include "Stats.h" #include "Npc.h" #include "MovmentManager.h" MonsterManager* MonsterManager::instance = nullptr; MonsterManager * MonsterManager::getInstance() { if (!instance) { instance = new MonsterManager(); } return instance; } void MonsterManager::resolveAllMonsters(vector<Path*> filledSpots) { for (int x = 0; x < filledSpots.size(); x++) { Path* monster = filledSpots[x]; attackOrMove(monster); } } MonsterManager::MonsterManager() { } MonsterManager::~MonsterManager() { } void MonsterManager::attackOrMove(Path* monster) { Cordinate cor = Mapa::getInstance()->getCordinateOfPath(monster); vector<Path*>surroundingPaths = pathsAroundMonster(cor); auto karakterSlot = isKarakterNext(surroundingPaths); if (karakterSlot) { Npc* npc = monster->getObjetOnPath()->toNpc(); if (npc->getRace() == MERCHANT) { if (MovmentManager::getInstace()->getplayer()->getAttackedMerchant()) { Stats* karakter = karakterSlot->getObjetOnPath()->toStats(); Stats* attacker = monster->getObjetOnPath()->toStats(); AttackManager::getInstance()->attack(attacker, karakter); } } else { Stats* karakter = karakterSlot->getObjetOnPath()->toStats(); Stats* attacker = monster->getObjetOnPath()->toStats(); AttackManager::getInstance()->attack(attacker, karakter); } } else { int randomIndex = rand() % surroundingPaths.size(); Path* toMove = surroundingPaths[randomIndex]; Npc* n = monster->getObjetOnPath()->toNpc(); toMove->setObjectOnPath(n); monster->setObjectOnPath(nullptr); } } vector<Path*> MonsterManager::pathsAroundMonster(Cordinate cor) { vector<Path*> surroundingPaths; vector <Path*> pathsAroud = Mapa::getInstance()->getPathsAroundByCord(cor); for (int i = 0; i < pathsAroud.size(); i++) { Path* p = pathsAroud[i]; if (p->isOccupied()) { if (p->getObjetOnPath()->isKarakter()) { surroundingPaths.push_back(p); } } else if (!p->isOccupied()) { if (p->displayChar() == '.') { surroundingPaths.push_back(p); } } } return surroundingPaths; } Path* MonsterManager::isKarakterNext(vector<Path*> paths) { for (int x = 0; x < paths.size(); x++) { Path* p = paths[x]; if (p->getObjetOnPath()->isKarakter()) { return p; } } return nullptr; }
9f15c7d251baa3636e3b82f83779a0edd7a7bdd5
6b6908754b647d193a83ce96b6dce58a395ccbe3
/Lab 8/Box.cpp
797e0b2a099331cbe2f73e98f239e0b36970e12b
[]
no_license
AustinStephens/CPPSemester2
1879b38dab6267d2e77736665f2860ecc28ce3a2
dbb6b6e670b5830131dcf5634ab72afe4ea07070
refs/heads/master
2021-08-26T09:46:27.147541
2017-11-23T06:13:50
2017-11-23T06:13:50
111,770,416
0
0
null
null
null
null
UTF-8
C++
false
false
492
cpp
Box.cpp
#include "Shape3d.h" #include "Rectangle.h" #include "Box.h" Box::Box():Rectangle(),Shape3d() { setHeight(0); } Box::Box(float h, float l, float w):Rectangle(l,w),Shape3d(l*w*h) { setHeight(h); } //accessor float Box::getHeight() const { return height; } //mutator void Box::setHeight(float h) { if (h < 0) h = 0; height = h; setVolume(getArea() * h); } void Box::setArea(float a) { if (a < 0) a = 0; area = a; setVolume(a * getHeight()); }
a313bdd80dfe8427b3cc29497e0a29bc6c03c934
588f693a95216fd882918867f0a95b8ee6a608c5
/modules/ngx_pagespeed/src/ngx_fetch.h
b86ca29887eafa1b5e43b089b22358a118b834a6
[ "BSD-2-Clause", "Apache-2.0" ]
permissive
braniewski/nginx_rtmp
0b75ca88937ebda5b21727d3e39571ec28e5b6d1
57e0c32935dfb84ee8b1ab46993638400cc8e418
refs/heads/master
2021-01-10T20:09:53.967121
2015-01-20T18:30:02
2015-01-20T18:30:02
15,631,471
2
5
null
null
null
null
UTF-8
C++
false
false
4,561
h
ngx_fetch.h
/* * Copyright 2012 Google Inc. * * 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. */ // Author: x.dinic@gmail.com (Junmin Xiong) // // The fetch is started by the main thread. It will fetch the remote resource // from the specific url asynchronously. #ifndef NET_INSTAWEB_NGX_FETCH_H_ #define NET_INSTAWEB_NGX_FETCH_H_ extern "C" { #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> } #include "ngx_url_async_fetcher.h" #include <vector> #include "net/instaweb/util/public/basictypes.h" #include "net/instaweb/util/public/pool.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/http/public/url_async_fetcher.h" #include "net/instaweb/http/public/response_headers.h" #include "net/instaweb/http/public/response_headers_parser.h" namespace net_instaweb { typedef bool (*response_handler_pt)(ngx_connection_t* c); class NgxUrlAsyncFetcher; class NgxFetch : public PoolElement<NgxFetch> { public: NgxFetch(const GoogleString& url, AsyncFetch* async_fetch, MessageHandler* message_handler, ngx_msec_t timeout_ms, ngx_log_t* log); ~NgxFetch(); // Start the fetch. bool Start(NgxUrlAsyncFetcher* fetcher); // Show the completed url, for logging purposes. const char* str_url(); // This fetch task is done. Call Done() on the async_fetch. It will copy the // buffer to cache. void CallbackDone(bool success); // Show the bytes received. size_t bytes_received(); void bytes_received_add(int64 x); int64 fetch_start_ms(); void set_fetch_start_ms(int64 start_ms); int64 fetch_end_ms(); void set_fetch_end_ms(int64 end_ms); MessageHandler* message_handler(); int get_major_version() { return static_cast<int>(status_->http_version / 1000); } int get_minor_version() { return static_cast<int>(status_->http_version % 1000); } int get_status_code() { return static_cast<int>(status_->code); } ngx_event_t* timeout_event() { return timeout_event_; } void set_timeout_event(ngx_event_t* x) { timeout_event_ = x; } void release_resolver() { if (resolver_ctx_ != NULL && resolver_ctx_ != NGX_NO_RESOLVER) { ngx_resolve_name_done(resolver_ctx_); resolver_ctx_ = NULL; } } private: response_handler_pt response_handler; // Do the initialized work and start the resolver work. bool Init(); bool ParseUrl(); // Prepare the request and write it to remote server. int InitRequest(); // Create the connection with remote server. int Connect(); void set_response_handler(response_handler_pt handler) { response_handler = handler; } // Only the Static functions could be used in callbacks. static void NgxFetchResolveDone(ngx_resolver_ctx_t* ctx); // Write the request. static void NgxFetchWrite(ngx_event_t* wev); // Wait for the response. static void NgxFetchRead(ngx_event_t* rev); // Read and parse the first status line. static bool NgxFetchHandleStatusLine(ngx_connection_t* c); // Read and parse the HTTP headers. static bool NgxFetchHandleHeader(ngx_connection_t* c); // Read the response body. static bool NgxFetchHandleBody(ngx_connection_t* c); // Cancel the fetch when it's timeout. static void NgxFetchTimeout(ngx_event_t* tev); // Add the pagespeed User-Agent. void FixUserAgent(); void FixHost(); const GoogleString str_url_; ngx_url_t url_; NgxUrlAsyncFetcher* fetcher_; AsyncFetch* async_fetch_; ResponseHeadersParser parser_; MessageHandler* message_handler_; int64 bytes_received_; int64 fetch_start_ms_; int64 fetch_end_ms_; int64 timeout_ms_; bool done_; int64 content_length_; bool content_length_known_; struct sockaddr_in sin_; ngx_log_t* log_; ngx_buf_t* out_; ngx_buf_t* in_; ngx_pool_t* pool_; ngx_http_request_t* r_; ngx_http_status_t* status_; ngx_event_t* timeout_event_; ngx_connection_t* connection_; ngx_resolver_ctx_t* resolver_ctx_; DISALLOW_COPY_AND_ASSIGN(NgxFetch); }; } // namespace net_instaweb #endif // NET_INSTAWEB_NGX_FETCH_H_
5489716070c8404f1b3c5676ae8b9e1e1e470046
2555cbc320199097f339b1de7ffc3b1fe197bc4e
/Source/AgeOfSurvival/CPPCharacterAI.h
1d661226915d64c231e9c99a81dfe4971a285516
[ "BSD-2-Clause" ]
permissive
JensenJ/AgeOfSurvival
74c55c99ccd63905150848b5ed3ec861a9c98802
8329ad9f96e039818f0e731318435d06f56f3f2f
refs/heads/Distribution
2020-04-15T00:40:47.780523
2019-01-26T22:20:39
2019-01-26T22:20:39
164,248,766
0
0
BSD-2-Clause
2019-01-26T22:20:40
2019-01-05T20:29:14
C++
UTF-8
C++
false
false
301
h
CPPCharacterAI.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "CPPCharacterBase.h" #include "CPPCharacterAI.generated.h" /** * */ UCLASS() class AGEOFSURVIVAL_API ACPPCharacterAI : public ACPPCharacterBase { GENERATED_BODY() };
97515e29e2fb32cd8ed675e8edaf6373f1b98b87
678465f0ee681c0c3e4ce1050f6b539fa2fc17fc
/program/unused/image_camera.cc
da14b77d5898a6b1b9629cf5a849838fcbe306a3
[]
no_license
timlenertz/Thesis
528f15024bbfc92073fab303577236681ce2496f
78a7c1f12be5f945d43ffb27f9cf070fe0360a78
refs/heads/master
2021-01-25T19:23:36.239621
2015-08-15T19:01:39
2015-08-15T19:01:39
24,094,197
0
0
null
null
null
null
UTF-8
C++
false
false
638
cc
image_camera.cc
#include "projection_camera.h" namespace pcf { projection_camera(const pose& ps, const projection_frustum& fr, std::size_t imw) : camera(ps, fr), image_width(imw), image_height(imw / fr.aspect_ratio()) { } projection_camera(const camera& cam, std::size_t imw) : projection_camera(cam.pose_, cam.frustum_) { } float aspect_ratio() const { return float(image_width) / image_height; } image_coordinates to_image(const Eigen::Vector3f& p) const { } spherical_coordinates image_to_spherical(const image_coordinates& ic, float distance) const { } Eigen::Vector3f point(const image_coordinates& ic, float z) const { } }
9cdce35598d7ae42c163467e6ee3e572c25113e6
aa535962a74a348c9a5c489532dcf354eb7bf378
/CrazyFlieNavigator/Occupancy/inverse_sensor_model.h
fee756ef6c6d800984a1bd9c614fb60fa1604c33
[ "MIT" ]
permissive
mmaldacker/CrazyFlieNavigator
56ff4da9206d89f214d324e4ff5592f0b54042cd
82437f761b47783635d2b29795a49f663291667b
refs/heads/master
2020-12-02T13:17:45.742562
2016-08-31T08:45:18
2016-08-31T08:45:18
67,019,830
0
0
null
null
null
null
UTF-8
C++
false
false
254
h
inverse_sensor_model.h
#ifndef inverse_sensor_model_h #define inverse_sensor_model_h #include <vector> struct InverseSensorModel { struct Location { int x,y; double logOdd; }; virtual std::vector<Location> GetLogOdds() const = 0; }; #endif
bf2bda40ac28c2d36d467c53b041f70aaac62a12
af217731f0aa60e94b3713133239271c680f8806
/sources/Interpreter/est.hpp
c876675262d6aa7c98677c8328f392ca81ae79d6
[ "MIT" ]
permissive
dbanisimov/mipt-scheme-compiler
531a688fdc60980e12c705f00353c59aea80e29f
144062cdeff667bd950e12fa5c1c89e5947dc904
refs/heads/master
2021-01-19T21:40:10.802015
2014-05-28T01:08:24
2014-05-28T01:08:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,253
hpp
est.hpp
/** * @file:est.hpp * A declaration of a set of classes reprodusing Execution State Tree * of Scheme language, used by Interpreter as representation of * a program. */ /* * Copyright 2012 MIPT-COMPILER team */ #pragma once #include "interpreter_dep.hpp" #include "activation.hpp" #include <iostream> namespace interpreter { namespace est { using namespace parser::ast; typedef boost::shared_ptr<std::istream> Istreamp; typedef boost::shared_ptr<std::ostream> Ostreamp; class Visitor :public parser::ast::Visitor { public: virtual SExprp onFunId( SExprp subj) = 0; virtual SExprp onMacId( SExprp subj) = 0; virtual SExprp onSpecId( SExprp subj) = 0; virtual SExprp onPort( SExprp subj) = 0; virtual SExprp onDelayedCall( SExprp subj) = 0; virtual SExprp onEofVal( SExprp subj) = 0; virtual SExprp onSyntax( SExprp subj) = 0; }; #undef VISITING #define VISITING( funName) \ SExprp visit( Visitor* v, SExprp me) \ { return v->funName( me);} class SystemObj :public Atom { public: enum DynamicType { funid = SExpr::types_num, macid, specid, port, delayed_call, eof_val, syntax }; public: SystemObj( Type t) :Atom( t) {} SExprp visit( parser::ast::Visitor *v, SExprp me); virtual SExprp visit( Visitor *v, SExprp me) = 0; }; class Handle :public SystemObj { public: Handle( int val_, Type t) :val( val_), SystemObj( t){} int id() const { return val; } private: int val; }; class FunId :public Handle { public: FunId( int val_) :Handle( val_, funid) {} VISITING( onFunId); static SExprp make( int id); }; class MacId :public Handle { public: MacId( int val_) :Handle( val_, macid){} VISITING( onMacId); static SExprp make( int id); }; class SpecId :public Handle { public: SpecId( int val_) :Handle( val_, specid) {} VISITING( onSpecId); static SExprp make( int id); }; class Port :public SystemObj { public: Port( Istreamp in, Ostreamp out) :ost( out), ist( in), SystemObj( port) {} VISITING( onPort); Istreamp in() { return ist; } Ostreamp out() { return ost; } static SExprp make( Istreamp in, Ostreamp out); private: Istreamp ist; Ostreamp ost; }; class DelayedCall :public SystemObj { public: DelayedCall( int id, SExprp args, string name) :SystemObj( delayed_call), id_( id), args_( args), name_( name) {} VISITING( onDelayedCall); static SExprp make( int id, SExprp args, string name); int id() const { return id_; } SExprp args() const { return args_; } string name() const { return name_; } private: int id_; SExprp args_; string name_; }; class EofVal :public SystemObj { public: EofVal() :SystemObj( eof_val) {} VISITING( onEofVal); static SExprp make(); }; class Syntax :public SystemObj { public: Syntax( SExprp obj, Activationp ctx) :SystemObj( syntax), obj_(obj), ctx_(ctx) {} VISITING( onSyntax); static SExprp make( SExprp obj, Activationp ctx); const SExprp& obj() const { return obj_; } const Activationp& ctx() const { return ctx_; } private: SExprp obj_; Activationp ctx_; }; }//namespace est }//namespace interpreter
c21ec5382b71eb8de395b773757f811b7c3212d1
131416ed956c82f2d527f56f627f90c4555f3f5b
/test/1940-ddms-ext/ddm_ext.cc
452187bdcbea774d570f75ecf584eacd859cdbf6
[ "Apache-2.0" ]
permissive
LineageOS/android_art
5edf0db5fc8861deb699a3b9299172cfef00c58a
96ac90faab12beb9cf671ae73f85f02225c96039
refs/heads/lineage-18.0
2022-11-19T21:06:09.486629
2019-03-01T14:30:59
2020-09-15T14:01:35
75,633,906
21
205
NOASSERTION
2020-10-07T19:19:48
2016-12-05T14:45:12
C++
UTF-8
C++
false
false
8,455
cc
ddm_ext.cc
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jvmti.h" // Test infrastructure #include "jvmti_helper.h" #include "nativehelper/scoped_local_ref.h" #include "nativehelper/scoped_primitive_array.h" #include "test_env.h" namespace art { namespace Test1940DdmExt { using DdmHandleChunk = jvmtiError(*)(jvmtiEnv* env, jint type_in, jint len_in, const jbyte* data_in, jint* type_out, jint* len_data_out, jbyte** data_out); struct DdmsTrackingData { DdmHandleChunk send_ddm_chunk; jclass test_klass; jmethodID publish_method; }; template <typename T> static void Dealloc(T* t) { jvmti_env->Deallocate(reinterpret_cast<unsigned char*>(t)); } template <typename T, typename ...Rest> static void Dealloc(T* t, Rest... rs) { Dealloc(t); Dealloc(rs...); } extern "C" JNIEXPORT jobject JNICALL Java_art_Test1940_processChunk(JNIEnv* env, jclass, jobject chunk) { DdmsTrackingData* data = nullptr; if (JvmtiErrorToException( env, jvmti_env, jvmti_env->GetEnvironmentLocalStorage(reinterpret_cast<void**>(&data)))) { return nullptr; } CHECK(chunk != nullptr); CHECK(data != nullptr); CHECK(data->send_ddm_chunk != nullptr); ScopedLocalRef<jclass> chunk_class(env, env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk")); if (env->ExceptionCheck()) { return nullptr; } jfieldID type_field_id = env->GetFieldID(chunk_class.get(), "type", "I"); jfieldID offset_field_id = env->GetFieldID(chunk_class.get(), "offset", "I"); jfieldID length_field_id = env->GetFieldID(chunk_class.get(), "length", "I"); jfieldID data_field_id = env->GetFieldID(chunk_class.get(), "data", "[B"); jint type = env->GetIntField(chunk, type_field_id); jint off = env->GetIntField(chunk, offset_field_id); jint len = env->GetIntField(chunk, length_field_id); ScopedLocalRef<jbyteArray> chunk_buf( env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk, data_field_id))); if (env->ExceptionCheck()) { return nullptr; } ScopedByteArrayRO byte_data(env, chunk_buf.get()); jint out_type; jint out_size; jbyte* out_data; if (JvmtiErrorToException(env, jvmti_env, data->send_ddm_chunk(jvmti_env, type, len, &byte_data[off], /*out*/&out_type, /*out*/&out_size, /*out*/&out_data))) { return nullptr; } else { ScopedLocalRef<jbyteArray> chunk_data(env, env->NewByteArray(out_size)); env->SetByteArrayRegion(chunk_data.get(), 0, out_size, out_data); Dealloc(out_data); ScopedLocalRef<jobject> res(env, env->NewObject(chunk_class.get(), env->GetMethodID(chunk_class.get(), "<init>", "(I[BII)V"), out_type, chunk_data.get(), 0, out_size)); return res.release(); } } static void DeallocParams(jvmtiParamInfo* params, jint n_params) { for (jint i = 0; i < n_params; i++) { Dealloc(params[i].name); } } static void JNICALL PublishCB(jvmtiEnv* jvmti, JNIEnv* jnienv, jint type, jint size, jbyte* bytes) { DdmsTrackingData* data = nullptr; if (JvmtiErrorToException(jnienv, jvmti, jvmti->GetEnvironmentLocalStorage(reinterpret_cast<void**>(&data)))) { return; } ScopedLocalRef<jbyteArray> res(jnienv, jnienv->NewByteArray(size)); jnienv->SetByteArrayRegion(res.get(), 0, size, bytes); jnienv->CallStaticVoidMethod(data->test_klass, data->publish_method, type, res.get()); } extern "C" JNIEXPORT void JNICALL Java_art_Test1940_initializeTest(JNIEnv* env, jclass, jclass method_klass, jobject publish_method) { void* old_data = nullptr; if (JvmtiErrorToException(env, jvmti_env, jvmti_env->GetEnvironmentLocalStorage(&old_data))) { return; } else if (old_data != nullptr) { ScopedLocalRef<jclass> rt_exception(env, env->FindClass("java/lang/RuntimeException")); env->ThrowNew(rt_exception.get(), "Environment already has local storage set!"); return; } DdmsTrackingData* data = nullptr; if (JvmtiErrorToException(env, jvmti_env, jvmti_env->Allocate(sizeof(DdmsTrackingData), reinterpret_cast<unsigned char**>(&data)))) { return; } memset(data, 0, sizeof(DdmsTrackingData)); data->test_klass = reinterpret_cast<jclass>(env->NewGlobalRef(method_klass)); data->publish_method = env->FromReflectedMethod(publish_method); if (env->ExceptionCheck()) { return; } // Get the extensions. jint n_ext = 0; jvmtiExtensionFunctionInfo* infos = nullptr; if (JvmtiErrorToException(env, jvmti_env, jvmti_env->GetExtensionFunctions(&n_ext, &infos))) { return; } for (jint i = 0; i < n_ext; i++) { jvmtiExtensionFunctionInfo* cur_info = &infos[i]; if (strcmp("com.android.art.internal.ddm.process_chunk", cur_info->id) == 0) { data->send_ddm_chunk = reinterpret_cast<DdmHandleChunk>(cur_info->func); } // Cleanup the cur_info DeallocParams(cur_info->params, cur_info->param_count); Dealloc(cur_info->id, cur_info->short_description, cur_info->params, cur_info->errors); } // Cleanup the array. Dealloc(infos); if (data->send_ddm_chunk == nullptr) { ScopedLocalRef<jclass> rt_exception(env, env->FindClass("java/lang/RuntimeException")); env->ThrowNew(rt_exception.get(), "Unable to find memory tracking extensions."); return; } if (JvmtiErrorToException(env, jvmti_env, jvmti_env->SetEnvironmentLocalStorage(data))) { return; } jint event_index = -1; bool found_event = false; jvmtiExtensionEventInfo* events = nullptr; if (JvmtiErrorToException(env, jvmti_env, jvmti_env->GetExtensionEvents(&n_ext, &events))) { return; } for (jint i = 0; i < n_ext; i++) { jvmtiExtensionEventInfo* cur_info = &events[i]; if (strcmp("com.android.art.internal.ddm.publish_chunk", cur_info->id) == 0) { found_event = true; event_index = cur_info->extension_event_index; } // Cleanup the cur_info DeallocParams(cur_info->params, cur_info->param_count); Dealloc(cur_info->id, cur_info->short_description, cur_info->params); } // Cleanup the array. Dealloc(events); if (!found_event) { ScopedLocalRef<jclass> rt_exception(env, env->FindClass("java/lang/RuntimeException")); env->ThrowNew(rt_exception.get(), "Unable to find ddms extension event."); return; } JvmtiErrorToException(env, jvmti_env, jvmti_env->SetExtensionEventCallback( event_index, reinterpret_cast<jvmtiExtensionEvent>(PublishCB))); return; } } // namespace Test1940DdmExt } // namespace art
b4cf4bab4a940e0726be7e9802dcdd47630ac49d
42ab733e143d02091d13424fb4df16379d5bba0d
/third_party/draco/src/draco/compression/attributes/point_d_vector_test.cc
59f28f80b006fab1b0110ac6736744c485504e62
[ "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "MIT" ]
permissive
google/filament
11cd37ac68790fcf8b33416b7d8d8870e48181f0
0aa0efe1599798d887fa6e33c412c09e81bea1bf
refs/heads/main
2023-08-29T17:58:22.496956
2023-08-28T17:27:38
2023-08-28T17:27:38
143,455,116
16,631
1,961
Apache-2.0
2023-09-14T16:23:39
2018-08-03T17:26:00
C++
UTF-8
C++
false
false
13,159
cc
point_d_vector_test.cc
// Copyright 2018 The Draco Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "draco/compression/attributes/point_d_vector.h" #include "draco/compression/point_cloud/algorithms/point_cloud_types.h" #include "draco/core/draco_test_base.h" namespace draco { class PointDVectorTest : public ::testing::Test { protected: template <typename PT> void TestIntegrity() {} template <typename PT> void TestSize() { for (uint32_t n_items = 0; n_items <= 10; ++n_items) { for (uint32_t dimensionality = 1; dimensionality <= 10; ++dimensionality) { draco::PointDVector<PT> var(n_items, dimensionality); ASSERT_EQ(n_items, var.size()); ASSERT_EQ(n_items * dimensionality, var.GetBufferSize()); } } } template <typename PT> void TestContentsContiguous() { for (uint32_t n_items = 1; n_items <= 1000; n_items *= 10) { for (uint32_t dimensionality = 1; dimensionality < 10; dimensionality += 2) { for (uint32_t att_dimensionality = 1; att_dimensionality <= dimensionality; att_dimensionality += 2) { for (uint32_t offset_dimensionality = 0; offset_dimensionality < dimensionality - att_dimensionality; ++offset_dimensionality) { PointDVector<PT> var(n_items, dimensionality); std::vector<PT> att(n_items * att_dimensionality); for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { att[val * att_dimensionality + att_dim] = val; } } const PT *const attribute_data = att.data(); var.CopyAttribute(att_dimensionality, offset_dimensionality, attribute_data); for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { ASSERT_EQ(var[val][offset_dimensionality + att_dim], val); } } } } } } } template <typename PT> void TestContentsDiscrete() { for (uint32_t n_items = 1; n_items <= 1000; n_items *= 10) { for (uint32_t dimensionality = 1; dimensionality < 10; dimensionality += 2) { for (uint32_t att_dimensionality = 1; att_dimensionality <= dimensionality; att_dimensionality += 2) { for (uint32_t offset_dimensionality = 0; offset_dimensionality < dimensionality - att_dimensionality; ++offset_dimensionality) { PointDVector<PT> var(n_items, dimensionality); std::vector<PT> att(n_items * att_dimensionality); for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { att[val * att_dimensionality + att_dim] = val; } } const PT *const attribute_data = att.data(); for (PT item = 0; item < n_items; item += 1) { var.CopyAttribute(att_dimensionality, offset_dimensionality, item, attribute_data + item * att_dimensionality); } for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { ASSERT_EQ(var[val][offset_dimensionality + att_dim], val); } } } } } } } template <typename PT> void TestContentsCopy() { for (uint32_t n_items = 1; n_items <= 1000; n_items *= 10) { for (uint32_t dimensionality = 1; dimensionality < 10; dimensionality += 2) { for (uint32_t att_dimensionality = 1; att_dimensionality <= dimensionality; att_dimensionality += 2) { for (uint32_t offset_dimensionality = 0; offset_dimensionality < dimensionality - att_dimensionality; ++offset_dimensionality) { PointDVector<PT> var(n_items, dimensionality); PointDVector<PT> dest(n_items, dimensionality); std::vector<PT> att(n_items * att_dimensionality); for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { att[val * att_dimensionality + att_dim] = val; } } const PT *const attribute_data = att.data(); var.CopyAttribute(att_dimensionality, offset_dimensionality, attribute_data); for (PT item = 0; item < n_items; item += 1) { dest.CopyItem(var, item, item); } for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { ASSERT_EQ(var[val][offset_dimensionality + att_dim], val); ASSERT_EQ(dest[val][offset_dimensionality + att_dim], val); } } } } } } } template <typename PT> void TestIterator() { for (uint32_t n_items = 1; n_items <= 1000; n_items *= 10) { for (uint32_t dimensionality = 1; dimensionality < 10; dimensionality += 2) { for (uint32_t att_dimensionality = 1; att_dimensionality <= dimensionality; att_dimensionality += 2) { for (uint32_t offset_dimensionality = 0; offset_dimensionality < dimensionality - att_dimensionality; ++offset_dimensionality) { PointDVector<PT> var(n_items, dimensionality); PointDVector<PT> dest(n_items, dimensionality); std::vector<PT> att(n_items * att_dimensionality); for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { att[val * att_dimensionality + att_dim] = val; } } const PT *const attribute_data = att.data(); var.CopyAttribute(att_dimensionality, offset_dimensionality, attribute_data); for (PT item = 0; item < n_items; item += 1) { dest.CopyItem(var, item, item); } auto V0 = var.begin(); auto VE = var.end(); auto D0 = dest.begin(); auto DE = dest.end(); while (V0 != VE && D0 != DE) { ASSERT_EQ(*D0, *V0); // compare PseudoPointD // verify elemental values for (auto index = 0; index < dimensionality; index += 1) { ASSERT_EQ((*D0)[index], (*V0)[index]); } ++V0; ++D0; } for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { ASSERT_EQ(var[val][offset_dimensionality + att_dim], val); ASSERT_EQ(dest[val][offset_dimensionality + att_dim], val); } } } } } } } template <typename PT> void TestPoint3Iterator() { for (uint32_t n_items = 1; n_items <= 1000; n_items *= 10) { const uint32_t dimensionality = 3; // for (uint32_t dimensionality = 1; dimensionality < 10; // dimensionality += 2) { const uint32_t att_dimensionality = 3; // for (uint32_t att_dimensionality = 1; // att_dimensionality <= dimensionality; att_dimensionality += 2) { for (uint32_t offset_dimensionality = 0; offset_dimensionality < dimensionality - att_dimensionality; ++offset_dimensionality) { PointDVector<PT> var(n_items, dimensionality); PointDVector<PT> dest(n_items, dimensionality); std::vector<PT> att(n_items * att_dimensionality); std::vector<draco::Point3ui> att3(n_items); for (PT val = 0; val < n_items; val += 1) { att3[val][0] = val; att3[val][1] = val; att3[val][2] = val; for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { att[val * att_dimensionality + att_dim] = val; } } const PT *const attribute_data = att.data(); var.CopyAttribute(att_dimensionality, offset_dimensionality, attribute_data); for (PT item = 0; item < n_items; item += 1) { dest.CopyItem(var, item, item); } auto aV0 = att3.begin(); auto aVE = att3.end(); auto V0 = var.begin(); auto VE = var.end(); auto D0 = dest.begin(); auto DE = dest.end(); while (aV0 != aVE && V0 != VE && D0 != DE) { ASSERT_EQ(*D0, *V0); // compare PseudoPointD // verify elemental values for (auto index = 0; index < dimensionality; index += 1) { ASSERT_EQ((*D0)[index], (*V0)[index]); ASSERT_EQ((*D0)[index], (*aV0)[index]); ASSERT_EQ((*aV0)[index], (*V0)[index]); } ++aV0; ++V0; ++D0; } for (PT val = 0; val < n_items; val += 1) { for (PT att_dim = 0; att_dim < att_dimensionality; att_dim += 1) { ASSERT_EQ(var[val][offset_dimensionality + att_dim], val); ASSERT_EQ(dest[val][offset_dimensionality + att_dim], val); } } } } } void TestPseudoPointDSwap() { draco::Point3ui val = {0, 1, 2}; draco::Point3ui dest = {10, 11, 12}; draco::PseudoPointD<uint32_t> val_src1(&val[0], 3); draco::PseudoPointD<uint32_t> dest_src1(&dest[0], 3); ASSERT_EQ(val_src1[0], 0); ASSERT_EQ(val_src1[1], 1); ASSERT_EQ(val_src1[2], 2); ASSERT_EQ(dest_src1[0], 10); ASSERT_EQ(dest_src1[1], 11); ASSERT_EQ(dest_src1[2], 12); ASSERT_NE(val_src1, dest_src1); swap(val_src1, dest_src1); ASSERT_EQ(dest_src1[0], 0); ASSERT_EQ(dest_src1[1], 1); ASSERT_EQ(dest_src1[2], 2); ASSERT_EQ(val_src1[0], 10); ASSERT_EQ(val_src1[1], 11); ASSERT_EQ(val_src1[2], 12); ASSERT_NE(val_src1, dest_src1); } void TestPseudoPointDEquality() { draco::Point3ui val = {0, 1, 2}; draco::Point3ui dest = {0, 1, 2}; draco::PseudoPointD<uint32_t> val_src1(&val[0], 3); draco::PseudoPointD<uint32_t> val_src2(&val[0], 3); draco::PseudoPointD<uint32_t> dest_src1(&dest[0], 3); draco::PseudoPointD<uint32_t> dest_src2(&dest[0], 3); ASSERT_EQ(val_src1, val_src1); ASSERT_EQ(val_src1, val_src2); ASSERT_EQ(dest_src1, val_src1); ASSERT_EQ(dest_src1, val_src2); ASSERT_EQ(val_src2, val_src1); ASSERT_EQ(val_src2, val_src2); ASSERT_EQ(dest_src2, val_src1); ASSERT_EQ(dest_src2, val_src2); for (auto i = 0; i < 3; i++) { ASSERT_EQ(val_src1[i], val_src1[i]); ASSERT_EQ(val_src1[i], val_src2[i]); ASSERT_EQ(dest_src1[i], val_src1[i]); ASSERT_EQ(dest_src1[i], val_src2[i]); ASSERT_EQ(val_src2[i], val_src1[i]); ASSERT_EQ(val_src2[i], val_src2[i]); ASSERT_EQ(dest_src2[i], val_src1[i]); ASSERT_EQ(dest_src2[i], val_src2[i]); } } void TestPseudoPointDInequality() { draco::Point3ui val = {0, 1, 2}; draco::Point3ui dest = {1, 2, 3}; draco::PseudoPointD<uint32_t> val_src1(&val[0], 3); draco::PseudoPointD<uint32_t> val_src2(&val[0], 3); draco::PseudoPointD<uint32_t> dest_src1(&dest[0], 3); draco::PseudoPointD<uint32_t> dest_src2(&dest[0], 3); ASSERT_EQ(val_src1, val_src1); ASSERT_EQ(val_src1, val_src2); ASSERT_NE(dest_src1, val_src1); ASSERT_NE(dest_src1, val_src2); ASSERT_EQ(val_src2, val_src1); ASSERT_EQ(val_src2, val_src2); ASSERT_NE(dest_src2, val_src1); ASSERT_NE(dest_src2, val_src2); for (auto i = 0; i < 3; i++) { ASSERT_EQ(val_src1[i], val_src1[i]); ASSERT_EQ(val_src1[i], val_src2[i]); ASSERT_NE(dest_src1[i], val_src1[i]); ASSERT_NE(dest_src1[i], val_src2[i]); ASSERT_EQ(val_src2[i], val_src1[i]); ASSERT_EQ(val_src2[i], val_src2[i]); ASSERT_NE(dest_src2[i], val_src1[i]); ASSERT_NE(dest_src2[i], val_src2[i]); } } }; TEST_F(PointDVectorTest, VectorTest) { TestSize<uint32_t>(); TestContentsDiscrete<uint32_t>(); TestContentsContiguous<uint32_t>(); TestContentsCopy<uint32_t>(); TestIterator<uint32_t>(); TestPoint3Iterator<uint32_t>(); } TEST_F(PointDVectorTest, PseudoPointDTest) { TestPseudoPointDSwap(); TestPseudoPointDEquality(); TestPseudoPointDInequality(); } } // namespace draco
4b8bb5b9e683c0401affd4c12c381de5b287ecf1
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
/Engine/Code/Network/Interface/Detail/ClientImpl.h
afb24a51655aeccdfeb403176f495f0f9cdf084b
[ "BSD-3-Clause" ]
permissive
WuyangPeng/Engine
d5d81fd4ec18795679ce99552ab9809f3b205409
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
refs/heads/master
2023-08-17T17:01:41.765963
2023-08-16T07:27:05
2023-08-16T07:27:05
246,266,843
10
0
null
null
null
null
GB18030
C++
false
false
2,494
h
ClientImpl.h
/// Copyright (c) 2010-2023 /// Threading Core Render Engine /// /// 作者:彭武阳,彭晔恩,彭晔泽 /// 联系作者:94458936@qq.com /// /// 标准:std:c++20 /// 引擎版本:0.9.0.8 (2023/05/09 10:49) #ifndef NETWORK_NETWORK_INTERFACE_CLIENT_IMPL_H #define NETWORK_NETWORK_INTERFACE_CLIENT_IMPL_H #include "Network/NetworkDll.h" #include "CoreTools/MessageEvent/EventInterface.h" #include "Network/Configuration/ConfigurationStrategy.h" #include "Network/Interface/NetworkInternalFwd.h" #include "Network/NetworkMessage/MessageEventManager.h" #include "Network/NetworkMessage/MessageInterface.h" namespace Network { class NETWORK_HIDDEN_DECLARE ClientImpl : public CoreTools::EventInterface { public: using ClassType = ClientImpl; using ParentType = EventInterface; using FactoryType = ClientFactory; using CallbackParameters = CoreTools::CallbackParameters; using EventInterfaceSharedPtr = CoreTools::EventInterfaceSharedPtr; public: ClientImpl(ConfigurationStrategy configurationStrategy, const MessageEventManagerSharedPtr& messageEventManager) noexcept; ~ClientImpl() noexcept = default; ClientImpl(const ClientImpl& rhs) noexcept = delete; ClientImpl& operator=(const ClientImpl& rhs) noexcept = delete; ClientImpl(ClientImpl&& rhs) noexcept = delete; ClientImpl& operator=(ClientImpl&& rhs) noexcept = delete; CLASS_INVARIANT_OVERRIDE_DECLARE; NODISCARD virtual int64_t Connect() = 0; virtual void AsyncConnect() = 0; virtual void Send(int64_t socketId, const MessageInterfaceSharedPtr& message) = 0; virtual void AsyncSend(int64_t socketId, const MessageInterfaceSharedPtr& message) = 0; virtual void Receive() = 0; virtual void AsyncReceive() = 0; virtual void ImmediatelySend(int64_t socketId) = 0; virtual void ImmediatelyAsyncSend(int64_t socketID) = 0; NODISCARD ConfigurationStrategy GetConfigurationStrategy() const noexcept; NODISCARD virtual int64_t GetSocketId() const noexcept; protected: NODISCARD MessageEventManagerSharedPtr GetMessageEventManagerSharedPtr(); private: using MessageEventManagerWeakPtr = std::weak_ptr<MessageEventManager>; private: ConfigurationStrategy configurationStrategy; MessageEventManagerWeakPtr messageEventManager; }; } #endif // NETWORK_NETWORK_INTERFACE_CLIENT_IMPL_H
a0593d46875cb4ae3be60045369660a73574fa02
a7068c5ee1ced08580388377a6fdee37f1e49431
/cpp/cpp2/headers/triangle.hpp
319c465ce3e6c6383ce707e01c49bd7889cebf75
[ "Apache-2.0" ]
permissive
j-dwo/codeexamples
ddf3cee6176328ef74686e7e33fa097a0c1bd5c4
bcb3398385b69a0a05f6088189b0460f35d550a4
refs/heads/master
2023-08-02T09:52:25.466882
2021-09-29T05:52:50
2021-09-29T05:52:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
415
hpp
triangle.hpp
#ifndef TRIANGLE_HPP #define TRIANGLE_HPP #include<iostream> #include"shape.hpp" class Triangle : public Shape { private: float base; float height; public: Triangle(float b, float h, const std::string &t="Triangle") : Shape(t), base(b), height(h) {} float area() const override; float perimeter() const override; void print() const; }; #endif
ac2896c539418efaef55b49db2c6eab9fec77885
0cbc4cd60bad6222892763964374c2500144729b
/Project Twitter/Classes/Tweet/Tweet.h
bc84852ca1d4dbc5305f3fe44ddfac94f02c5367
[]
no_license
WangWillis/CIS_22C
a7351a1c6df0db03ded68e903641a72a67a73a6c
924d4cc278e3b9c2f79b1c8ba8d2075003be44f9
refs/heads/master
2016-08-12T09:56:52.968807
2016-03-03T02:46:24
2016-03-03T02:46:24
43,714,493
3
0
null
null
null
null
UTF-8
C++
false
false
1,307
h
Tweet.h
#ifndef TWEET_H #define TWEET_H #define _CRT_SECURE_NO_WARNINGS_ #define _CRT_SECURE_NO_DEPRECATE_ #include <iostream> #include <string> #include <time.h> using namespace std; class Tweet; class Tweet{ private: //holds the body of the tweet and the user id string text, userId; //holds the post time time_t postTime; public: Tweet(){}; //sets the username and the body Tweet(const string, const string); Tweet(const string, const string, const time_t); //sets the username void setUser(string); //sets the body void setTweets(string); //sets the post time void setpostim(time_t); //gets the post time time_t getTime() const; //gets the body string getText() const; //gets the username string getUserId() const; //so tweets can be compaired friend bool operator<(const Tweet& lhs, const Tweet& rhs){ //compaired by time if time is before return true if(difftime(lhs.getTime(), rhs.getTime()) < 0){ return true; } return false; } //for printing the tweets friend ostream &operator << (ostream& strm, const Tweet& obj){ time_t temp = obj.getTime(); strm << "User: " << obj.getUserId() << endl; strm << "Time Posted: " << ctime(&temp); strm << "Tweet: " << endl << obj.getText() << endl << endl; return strm; } }; #endif
058aabb6cf82db3a5852e3053a048494773afde1
16d5cd8328ff8b31334afac4030754e59151c376
/source/bayeux/configuration.h
8f600bff46dd9e63ffbe9178581d4f208d1cfc6e
[ "MIT" ]
permissive
TorstenRobitzki/Sioux
c443083677b10a8796dedc3adc3f950e273758e5
709eef5ebab5fed896b0b36f0c89f0499954657d
refs/heads/master
2023-03-31T18:44:55.391134
2023-03-16T06:51:56
2023-03-16T06:51:56
5,154,565
19
9
MIT
2023-03-16T06:51:57
2012-07-23T16:51:12
C++
UTF-8
C++
false
false
3,031
h
configuration.h
// Copyright (c) Torrox GmbH & Co KG. All rights reserved. // Please note that the content of this file is confidential or protected by law. // Any unauthorised copying or unauthorised distribution of the information contained herein is prohibited. #ifndef CONFIGURATION_H_ #define CONFIGURATION_H_ #include <boost/date_time/posix_time/posix_time_types.hpp> #include <iosfwd> namespace bayeux { /** * @brief configuration data for a bayeux server * * It's not save to use one instance from multiple threads. */ class configuration { public: /** * @brief a configuration object with all values set to defaults */ configuration(); /** * @brief maximum time, a client can be disconnected until the client will be unsubscribed and freed */ boost::posix_time::time_duration session_timeout() const; /** * @brief changes the maximum time, a client can be disconnected until the client be unsubscribed and freed */ configuration& session_timeout( const boost::posix_time::time_duration& time_out ); /** * @brief default value for long-polling timeout */ boost::posix_time::time_duration long_polling_timeout() const; /** * @brief set the default value for long-polling timeout */ configuration& long_polling_timeout( const boost::posix_time::time_duration& time_out ); /** * @brief maximum number of messages, that will be buffered for a client before messages will be discard. * * If messages have to be discard, older messages get discarded first. */ unsigned max_messages_per_client() const; /** * @brief sets a new value for the maximum messages count per client limit * @post max_messages_per_client() == new_limit * @post &o.max_messages_per_client( X ) == &o */ configuration& max_messages_per_client( unsigned new_limit ); /** * @brief maximum size of messages, that will be buffered for a client before messages will be discard. * * If the size of all stored messages exceeds this limit, messages will be dropped until the size is back to * or under the limit. Earlier messages are droped first. */ std::size_t max_messages_size_per_client() const; /** * @brief sets a new value for the maximum messages size per client limit * @post max_messages_size_per_client() == new_limit * @post &o.max_messages_size_per_client( X ) == &o */ configuration& max_messages_size_per_client( std::size_t new_limit ); /** * @brief prints the configuration in a human readable manner */ void print( std::ostream& ) const; private: boost::posix_time::time_duration max_disconnected_time_; boost::posix_time::time_duration long_polling_timeout_; unsigned max_messages_per_client_; std::size_t max_messages_size_per_client_; }; /** * @brief prints the configuration in a human readable manner * @relates configuration */ std::ostream& operator<<( std::ostream& out, const configuration& config ); } #endif /* CONFIGURATION_H_ */
21c40e3dea6baf227751ca79ef2f20d1c78a89ec
a3ec7ce8ea7d973645a514b1b61870ae8fc20d81
/Codeforces/B/514.cc
a81bcf4e4b19fd3d9891a87e57fda897a8f83a7c
[]
no_license
userr2232/PC
226ab07e3f2c341cbb087eecc2c8373fff1b340f
528314b608f67ff8d321ef90437b366f031e5445
refs/heads/master
2022-05-29T09:13:54.188308
2022-05-25T23:24:48
2022-05-25T23:24:48
130,185,439
1
0
null
null
null
null
UTF-8
C++
false
false
352
cc
514.cc
#include <iostream> #include <set> #include <utility> using namespace std; int main() { int n, x0, y0, x, y; cin >> n >> x0 >> y0; set<double> s; for(int i = 0; i < n; ++i) { cin >> x >> y; if(x == x0) s.insert(1e6); else s.insert((y - y0) * 1.0 / (x - x0)); } cout << s.size() << endl; return 0; }
fe2f561b5cdbb5f0a66c2cbdbeb420af8db1b3ba
9b4eb13e5e65a1b2743c1681acc085f354cdcadf
/src/PowerUpper.hpp
9d71358285b862e15984c36c54fe8957cbb75ce4
[]
no_license
DqmSIer/DQMSL-MaxStatusSearcher
b0e38f7a558a598ed0d96387b6aa3388a916284a
59e38e6b339589861d6f8a55723e4967ce777dc2
refs/heads/master
2020-03-17T23:11:12.145232
2018-05-19T06:42:16
2018-05-19T06:42:16
134,034,850
0
0
null
null
null
null
UTF-8
C++
false
false
984
hpp
PowerUpper.hpp
#ifndef POWERUPPER_CLASS #define POWERUPPER_CLASS #include "Status.hpp" class PowerUpper { public: /* define */ static const int PU_RATE = 2; public: /* function */ static inline int calcPowerUp(const int value) { return (value * PU_RATE + 100 - 1) / 100; } static inline Status getPowerUpValue(const Status &main) { Status result; for (int i = 0; i < Status::STAT_NUM; i++) result[i] = PowerUpper::calcPowerUp(main[i]); return result; } static inline Status getPowerUpValue(const Status &main, const Status &sub) { Status result; for (int i = 0; i < Status::STAT_NUM; i++) result[i] = PowerUpper::calcPowerUp(main[i]) + PowerUpper::calcPowerUp(sub[i]); return result; } static inline Status powerUp(const Status &main, const Status &sub) { Status result; for (int i = 0; i < Status::STAT_NUM; i++) result[i] = main[i] + PowerUpper::calcPowerUp(main[i]) + PowerUpper::calcPowerUp(sub[i]); return result; } }; #endif //POWERUPPER_CLASS
714746246315ae3737b95102b911783d0baf3d1b
b7d4fc29e02e1379b0d44a756b4697dc19f8a792
/deps/boost/boost/beast/core/detail/clamp.hpp
95a8fab4256526407f7572750d5d9094d8d5f27b
[ "GPL-1.0-or-later", "MIT", "BSL-1.0" ]
permissive
vslavik/poedit
45140ca86a853db58ddcbe65ab588da3873c4431
1b0940b026b429a10f310d98eeeaadfab271d556
refs/heads/master
2023-08-29T06:24:16.088676
2023-08-14T15:48:18
2023-08-14T15:48:18
477,156
1,424
275
MIT
2023-09-01T16:57:47
2010-01-18T08:23:13
C++
UTF-8
C++
false
false
1,229
hpp
clamp.hpp
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_CORE_DETAIL_CLAMP_HPP #define BOOST_BEAST_CORE_DETAIL_CLAMP_HPP #include <cstdlib> #include <limits> #include <type_traits> namespace boost { namespace beast { namespace detail { template<class UInt> static std::size_t clamp(UInt x) { if(x >= (std::numeric_limits<std::size_t>::max)()) return (std::numeric_limits<std::size_t>::max)(); return static_cast<std::size_t>(x); } template<class UInt> static std::size_t clamp(UInt x, std::size_t limit) { if(x >= limit) return limit; return static_cast<std::size_t>(x); } // return `true` if x + y > z, which are unsigned template< class U1, class U2, class U3> constexpr bool sum_exceeds(U1 x, U2 y, U3 z) { static_assert( std::is_unsigned<U1>::value && std::is_unsigned<U2>::value && std::is_unsigned<U3>::value, ""); return y > z || x > z - y; } } // detail } // beast } // boost #endif
b77550433e6675841f22280f6d88e6c817e93161
324e08b88134a8e8924bc61edcfd8601d8f568fe
/syzygy/assm/buffer_serializer_unittest.cc
95416543b406018b835f79641929a59be9cc4daa
[ "Apache-2.0" ]
permissive
supriyantomaftuh/syzygy
fc5f560c187471f3f3502eacf5f8fbae0baeb308
84acba74e8483b6430a8dd316f03d0f730ca92ca
refs/heads/master
2018-01-14T06:37:37.856415
2015-09-30T16:48:00
2015-09-30T16:48:00
43,473,795
0
1
null
null
null
null
UTF-8
C++
false
false
1,857
cc
buffer_serializer_unittest.cc
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/assm/buffer_serializer.h" #include "gtest/gtest.h" #include "syzygy/assm/unittest_util.h" namespace assm { class BufferSerializerTest : public testing::Test { public: BufferSerializerTest() { } void NopTest(size_t nop_size) { const size_t kOffset = 5U; const size_t kBufferSize = 1024U; // Initialize buffer. uint8 buffer[kBufferSize]; ::memset(buffer, 0, kBufferSize); // Assemble a NOP into the buffer. BufferSerializer bs(buffer, kBufferSize); AssemblerImpl asm_(reinterpret_cast<uint32>(&buffer[kOffset]), &bs); asm_.nop(nop_size); // Should not touch any bytes before offset. for (size_t i = 0; i < kOffset; ++i) { EXPECT_EQ(0U, buffer[i]); } // Should write the proper NOP. for (size_t i = 0; i < nop_size; ++i) { EXPECT_EQ(testing::kNops[nop_size][i], buffer[kOffset + i]); } // Should not touch any bytes after the NOP. for (size_t i = kOffset + nop_size; i < kBufferSize; ++i) { EXPECT_EQ(0U, buffer[i]); } } }; TEST_F(BufferSerializerTest, Nop) { const size_t kMaxNopSizeToTest = 10; for (size_t nop_size = 0; nop_size <= kMaxNopSizeToTest; ++nop_size) { NopTest(nop_size); } } } // namespace assm
e7c4e4b98e9b3db08d4670d207d1ebfdff925b0f
bf05f93afa28e02a03fad194a392e3b422745761
/src/timer.cpp
6ad60ea3c7d5981017bc9700db75229c3364735e
[]
no_license
JoanEspasa/rantanplan-public
8a5ea964a64ed107bc12fe0e64e168bc642c0334
e2e920e20c73e3561e5b6e16046ef90ec9b4640b
refs/heads/master
2020-03-31T20:38:18.142346
2018-11-03T10:41:21
2018-11-03T10:41:21
152,548,596
2
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
timer.cpp
#include "timer.h" Timer::Timer() { } high_resolution_clock::duration Timer::elapsed() const { return high_resolution_clock::now() - epoch; } void Timer::start() { epoch = high_resolution_clock::now(); }
a3476e6aec9b3d7884039c74134bbc980d84144e
33482b83f975a1b90becd375b9959f96cab330e8
/include/pcl_utility.h
c9ae12621391d25c453be38cd5497801dde8dbb6
[]
no_license
MartianInStardust/carton_expansion_detection
6723c09bf9bde02bee5daa726d1c671c139a2b7a
d64befcc7011a288098f841375706f8a715fb36a
refs/heads/master
2023-07-17T10:53:11.810140
2021-09-03T07:40:56
2021-09-03T07:40:56
386,276,591
0
0
null
null
null
null
UTF-8
C++
false
false
4,830
h
pcl_utility.h
/* * @Author: Aiden * @Date: 2021-07-05 14:25:38 * @LastEditTime: 2021-07-14 15:15:29 */ #ifndef PCL_UTILITY_H #define PCL_UTILITY_H #include <pcl/ModelCoefficients.h> #include <pcl/io/pcd_io.h> #include <pcl/io/ply_io.h> #include <pcl/point_types.h> #include <pcl/common/centroid.h> #include <pcl/features/normal_3d.h> #include <pcl/filters/extract_indices.h> #include <pcl/visualization/pcl_visualizer.h> #include <vtkPlaneSource.h> // graph plane #include <thread> #include <chrono> #include <string> #include <cmath> #include <numeric> #include <algorithm> #include <boost/format.hpp> // for formating strings #include "yaml-cpp/yaml.h" using namespace std::chrono_literals; // #define USED_DISTANCE #define USED_GROUND_PLANE template <typename T> using eigen_alloc_vector = std::vector<T, Eigen::aligned_allocator<T>>; typedef enum DOWNSAMPLE_EMTHOD_LIST { VOXELGRID = 0, APPROXIMATE_VOXELGRID = 1 } DOWNSAMPLE_EMTHOD_LIST; typedef int32_t DOWNSAMPLE_EMTHOD; typedef enum FILTER_METHOD_LIST { NONE_PROCESS = 0, STATISICAL_OUTLIER_REMOVAL = 1, CONDITIONAL_REMOVAL = 2, USED_ALL_METHOD = 3 } FILTER_METHOD_LIST; typedef int32_t FILTER_METHOD; typedef enum ESTIMATE_NORMAL_METHOD_LIST { KDTREE_MEAN = 0, KDTREE_RADIUS = 1 } ESTIMATE_NORMAL_METHOD_LIST; typedef int32_t ESTIMATE_NORMAL_METHOD; typedef enum CHECK_DIRECTION_LIST { NO_CHECK = 0, CHECK_POSITIVE = 1 } CHECK_DIRECTION_LIST; typedef int32_t CHECK_DIRECTION; // Sort in ascending order, return the serial number of the original array // reference: https://www.itranslater.com/qa/details/2120991385611404288 template <typename T> std::vector<size_t> sort_indexes(const std::vector<T> &v) { // initialize original index locations std::vector<size_t> idx(v.size()); std::iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in v std::sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) { return v[i1] < v[i2]; }); return idx; } class Pcl_utility { public: Pcl_utility(); ~Pcl_utility(); bool loadCloudFile(const std::string filename, pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud); bool loadCloudRGB(const std::string filename, pcl::PointCloud<pcl::PointXYZRGB>::Ptr &point_cloud_ptr); static bool loadConfigFile(const std::string filename); void simpleVis(pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud); void rgbVis(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, std::vector<pcl::PointIndices> clusters); void visualization(const pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, const pcl::PointCloud<pcl::Normal>::Ptr &normals, const pcl::ModelCoefficients::Ptr coefficients, const pcl::PointIndices::Ptr inliers); void visualization(const pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, const Eigen::VectorXf &coeff, const std::vector<int> inliers); //x, y, z indicate where to draw the plane, scale (x, y) is a targeted scaling factor for x, y of the plane vtkSmartPointer<vtkPolyData> createPlane(const pcl::ModelCoefficients &coefficients, double x, double y, double z, float scale[2] = nullptr); double findMaxDistanceToPlane(Eigen::VectorXf &coeff, pcl::PointCloud<pcl::PointXYZRGB>::Ptr &select_cloud_ptr, std::vector<uint32_t> searchCloudIndex); //#######################Load Config Params##########################// static std::string sensor_name; static DOWNSAMPLE_EMTHOD downsample_method; static float leaf_size; static FILTER_METHOD filter_method; static int filter_meanK; static std::string field_name; static float min_limit; static float max_limit; static std::vector<float> standard_box_front_normal; static std::vector<float> standard_ground_plane_normal; static std::vector<float> standard_ground_plane_coeff; static int clusters_maxsize_segements; static int clusters_min_points_size; static int clusters_max_points_size; static int clusters_num_neighbours; static float clusters_normal_error_threshold; static float clusters_curvature_threshold; static int bottom_expect_points; static float bottom_fitting_angle_error; static float bottom_fitting_dist_error; static float ground_fitting_dist_error; static int standard_point_cloud_size; ////// static int32_t depth_w; static int32_t depth_h; static std::vector<float> depth_intrinsic; static std::vector<float> depth_extrinsic; static std::vector<float> depth_distortion; static int32_t color_w; static int32_t color_h; static std::vector<float> color_intrinsic; static std::vector<float> color_extrinsic; static std::vector<float> color_distortion; static double max_contou_area; static bool debug_show; }; #endif //PCL_UTILITY_H
593569b5dbf76e36814661c5e8d2ed9ba22ee3e0
af76b549c097c27bbcab55d7ea1e9fc514dd900d
/include/Transforms/Loops/ExtractInvariant/ExtractInvariant.h
700fb389f1829eb3f540ebcdf0cba4c098945512
[ "BSD-3-Clause" ]
permissive
OpsGroup/open-ops
6d88b2da7cb0a65967c87a26c8a439306b304b8c
b1ab8da354c4aecc0fe76a562395f5861bffc207
refs/heads/master
2023-06-22T06:23:51.731609
2017-10-25T14:43:28
2017-10-25T14:43:28
98,927,791
25
3
BSD-3-Clause
2023-06-09T11:44:43
2017-07-31T20:39:14
C++
UTF-8
C++
false
false
262
h
ExtractInvariant.h
#ifndef EXTRACTINVARIANT_H #define EXTRACTINVARIANT_H #include <Reprise/Reprise.h> namespace OPS { namespace Analysis { void extractInvariant(Reprise::BasicCallExpression* expressionForReplace, Reprise::ForStatement* target); } } #endif // EXTRACTINVARIANT_H
e50370a64d99a3d0ba028f379dee1c357c53210a
5f9459edf94e2bb124dbea8fa75ec729448c3a02
/golf.h
ef092f466971924ea09e9e6b8a0c49d4bcb13e6a
[]
no_license
AlN7Ex/cpp.prata.act9.homework
f6c5ffe846844c3acb726fd618e9b6c64b19d3c5
1f815dc2189bc6dc8b926237a6fa9a9bae4ab6fb
refs/heads/master
2023-03-10T09:54:27.282062
2021-02-15T16:27:56
2021-02-15T16:27:56
339,136,086
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
golf.h
//golf.h - for 9.1.cpp constexpr size_t Len = 40; struct golf { char fullname[Len]; int handicap; size_t flag; }; void setgolf(golf & g, const char * name, int hc); int setgolf(golf & g); void handicap(golf & g, int hc); void showgolf(const golf & g);
fda338e0dc3210abc8387f3d7f4d4289bfac962a
4237db22a38293042adcbdaa0161fd3bf323443b
/exercises/Assignment.2.1.cpp
9d6ed7466922567601c22bf3d67a671b6e2433ae
[]
no_license
kakukogou/cs106b
d074695fac3887d5db756bef8dca92ff260a9b64
f7bc455c9ee37ba39920c5ff64435585283b52aa
refs/heads/master
2021-05-08T14:59:44.029998
2012-08-08T03:19:45
2012-08-08T03:19:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,548
cpp
Assignment.2.1.cpp
/* * File: BlankProject.cpp * -------------------------- * You can use this file as a starter for * testing things out that aren't assignments. */ #include <iostream> #include <iomanip> #include <string> #include "console.h" #include "simpio.h" #include "vector.h" #include "queue.h" #include "lexicon.h" using namespace std; string letters = "abcdefghijklmnopqrstuvwxyz"; bool contains(Vector<string> & ladder, string str) { int i = ladder.size(); while (i--) { if (ladder[i] == str) { return true; } } return false; } Vector<string> clone(Vector<string> ladder) { Vector<string> newLadder; for (int i = 0; i < ladder.size(); i++) { newLadder += ladder[i]; } return newLadder; } Vector<string> wordsByOneLetter (Lexicon & lex, string word) { Vector<string> words; string original = word; for (int i = 0; i < word.length(); i++) { char originalCh = word[i]; for (int j = 0; j < letters.length(); j++) { word[i] = letters[j]; if (word == original) continue; if (contains(words, word)) continue; if (!lex.contains(word)) continue; words += word; } word[i] = originalCh; } return words; } Vector<string> wordLadder(Lexicon & lex, string start, string target) { Vector<string> startingLadder; startingLadder += start; Queue<Vector <string> > queue; queue.enqueue(startingLadder); Vector<string> seen; while(!queue.isEmpty()) { Vector<string> lastLadder = queue.dequeue(); string lastWord = lastLadder.get(lastLadder.size() - 1); if (lastWord == target) return lastLadder; foreach (string word in wordsByOneLetter(lex, lastWord)) { if (contains(lastLadder, word)) continue; if (contains(seen, word)) continue; Vector<string> ladder = clone(lastLadder); seen += word; ladder += word; queue.enqueue(ladder); } } Vector <string> emptyLadder; return emptyLadder; } int main() { Lexicon lex("in/dictionary.txt"); while (true) { string start = getLine("Enter a starting word [or blank to end]: "); if (start == "") break; string end = getLine("Enter a starting word [or blank to quit]: "); if (end == "") break; cout << "Please wait while I connect '" << start << "' with '" << end << "'" << endl; Vector<string> ladder = wordLadder(lex, start, end); if (ladder.size() == 0) { cout << "No ladder found!" << endl; continue; } foreach (string word in ladder) { cout << word << " "; } cout << endl; } return 0; }
e704c587063e78802010e91aab832b8f278c2de7
46d877808efec0032d96db1542873be270edd57d
/test/Library/Mathematics/Objects/Vector.test.cpp
85a9e798030c5e386e8b2bd69573563f862857a2
[ "MPL-2.0", "BSL-1.0", "Apache-2.0" ]
permissive
cowlicks/library-mathematics
44c9fa365595173127807155de5e53d22543e804
f1ff3257bb2da5371a9eacfcec538b2c00871696
refs/heads/master
2020-07-29T03:56:53.933981
2019-07-18T19:36:42
2019-07-18T19:36:42
209,660,751
0
0
Apache-2.0
2019-09-19T22:44:04
2019-09-19T22:44:04
null
UTF-8
C++
false
false
14,324
cpp
Vector.test.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Library/Mathematics /// @file Library/Mathematics/Objects/Vector.test.cpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <Library/Mathematics/Objects/Vector.hpp> #include <Global.test.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (Library_Mathematics_Objects_Vector2i, Constructor) { using library::math::obj::Vector2i ; { const Vector2i vector(1, 2) ; EXPECT_EQ(1, vector(0)) ; EXPECT_EQ(2, vector(1)) ; } } TEST (Library_Mathematics_Objects_Vector2i, ToString) { using library::math::obj::Vector2i ; { const Vector2i vector(1, 2) ; EXPECT_EQ("[1, 2]", vector.toString()) ; EXPECT_EQ("[1, 2]", vector.toString(0)) ; EXPECT_EQ("[1, 2]", vector.toString(1)) ; EXPECT_EQ("[1, 2]", vector.toString(2)) ; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (Library_Mathematics_Objects_Vector3i, Constructor) { using library::math::obj::Vector3i ; { const Vector3i vector(1, 2, 3) ; EXPECT_EQ(1, vector(0)) ; EXPECT_EQ(2, vector(1)) ; EXPECT_EQ(3, vector(2)) ; } { const Vector3i vector = Vector3i::X() ; EXPECT_EQ(1, vector(0)) ; EXPECT_EQ(0, vector(1)) ; EXPECT_EQ(0, vector(2)) ; } { const Vector3i vector = Vector3i::Y() ; EXPECT_EQ(0, vector(0)) ; EXPECT_EQ(1, vector(1)) ; EXPECT_EQ(0, vector(2)) ; } { const Vector3i vector = Vector3i::Z() ; EXPECT_EQ(0, vector(0)) ; EXPECT_EQ(0, vector(1)) ; EXPECT_EQ(1, vector(2)) ; } } TEST (Library_Mathematics_Objects_Vector3i, ToString) { using library::math::obj::Vector3i ; { const Vector3i vector(1, 2, 3) ; EXPECT_EQ("[1, 2, 3]", vector.toString()) ; EXPECT_EQ("[1, 2, 3]", vector.toString(0)) ; EXPECT_EQ("[1, 2, 3]", vector.toString(1)) ; EXPECT_EQ("[1, 2, 3]", vector.toString(2)) ; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (Library_Mathematics_Objects_Vector2d, Constructor) { using library::math::obj::Vector2d ; { const Vector2d vector(1.0, 2.0) ; EXPECT_EQ(1.0, vector(0)) ; EXPECT_EQ(2.0, vector(1)) ; } { const Vector2d vector = Vector2d::Undefined() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const Vector2d vector = Vector2d::NaN() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const Vector2d vector = Vector2d::Inf() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_FALSE(vector.isNaN()) ; EXPECT_TRUE(vector.isInf()) ; } } TEST (Library_Mathematics_Objects_Vector2d, ToString) { using library::math::obj::Vector2d ; { const Vector2d vector(1.0, 2.0) ; EXPECT_EQ("[1.0, 2.0]", vector.toString()) ; EXPECT_EQ("[1, 2]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.00]", vector.toString(2)) ; } { const Vector2d vector(1.0, 2.01) ; EXPECT_EQ("[1.0, 2.01]", vector.toString()) ; EXPECT_EQ("[1, 2]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.01]", vector.toString(2)) ; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (Library_Mathematics_Objects_Vector3d, Constructor) { using library::math::obj::Vector3d ; { const Vector3d vector(1.0, 2.0, 3.0) ; EXPECT_EQ(1.0, vector(0)) ; EXPECT_EQ(2.0, vector(1)) ; EXPECT_EQ(3.0, vector(2)) ; } { const Vector3d vector = Vector3d::X() ; EXPECT_EQ(1.0, vector(0)) ; EXPECT_EQ(0.0, vector(1)) ; EXPECT_EQ(0.0, vector(2)) ; } { const Vector3d vector = Vector3d::Y() ; EXPECT_EQ(0.0, vector(0)) ; EXPECT_EQ(1.0, vector(1)) ; EXPECT_EQ(0.0, vector(2)) ; } { const Vector3d vector = Vector3d::Z() ; EXPECT_EQ(0.0, vector(0)) ; EXPECT_EQ(0.0, vector(1)) ; EXPECT_EQ(1.0, vector(2)) ; } { const Vector3d vector = Vector3d::Undefined() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const Vector3d vector = Vector3d::NaN() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const Vector3d vector = Vector3d::Inf() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_FALSE(vector.isNaN()) ; EXPECT_TRUE(vector.isInf()) ; } } TEST (Library_Mathematics_Objects_Vector3d, ToString) { using library::math::obj::Vector3d ; { const Vector3d vector(1.0, 2.0, 3.0) ; EXPECT_EQ("[1, 2, 3]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0, 3.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.00, 3.00]", vector.toString(2)) ; EXPECT_EQ("[1.0, 2.0, 3.0]", vector.toString()) ; } { const Vector3d vector(1.0, 2.01, 3.001) ; EXPECT_EQ("[1.0, 2.01, 3.001]", vector.toString()) ; EXPECT_EQ("[1, 2, 3]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0, 3.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.01, 3.00]", vector.toString(2)) ; EXPECT_EQ("[1.000, 2.010, 3.001]", vector.toString(3)) ; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (Library_Mathematics_Objects_Vector4d, Constructor) { using library::math::obj::Vector4d ; { const Vector4d vector(1.0, 2.0, 3.0, 4.0) ; EXPECT_EQ(1.0, vector(0)) ; EXPECT_EQ(2.0, vector(1)) ; EXPECT_EQ(3.0, vector(2)) ; EXPECT_EQ(4.0, vector(3)) ; } { const Vector4d vector = Vector4d::Undefined() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const Vector4d vector = Vector4d::NaN() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const Vector4d vector = Vector4d::Inf() ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_FALSE(vector.isNaN()) ; EXPECT_TRUE(vector.isInf()) ; } } TEST (Library_Mathematics_Objects_Vector4d, IsNear) { using library::math::obj::Vector4d ; { const Vector4d vector(1.0, 2.0, 3.0, 4.0) ; EXPECT_TRUE(vector.isNear(vector, 0.0)) ; } { const Vector4d firstVector(1.0, 2.0, 3.0, 4.0) ; const Vector4d secondVector(2.0, 2.0, 3.0, 4.0) ; EXPECT_TRUE(firstVector.isNear(secondVector, 1.0)) ; EXPECT_FALSE(firstVector.isNear(secondVector, 0.0)) ; } { EXPECT_ANY_THROW(Vector4d::NaN().isNear(Vector4d::NaN(), 0.0)) ; } } TEST (Library_Mathematics_Objects_Vector4d, ToString) { using library::math::obj::Vector4d ; { const Vector4d vector(1.0, 2.0, 3.0, 4.0) ; EXPECT_EQ("[1, 2, 3, 4]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0, 3.0, 4.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.00, 3.00, 4.00]", vector.toString(2)) ; EXPECT_EQ("[1.0, 2.0, 3.0, 4.0]", vector.toString()) ; } { const Vector4d vector(1.0, 2.01, 3.001, 4.0001) ; EXPECT_EQ("[1.0, 2.01, 3.001, 4.0001]", vector.toString()) ; EXPECT_EQ("[1, 2, 3, 4]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0, 3.0, 4.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.01, 3.00, 4.00]", vector.toString(2)) ; EXPECT_EQ("[1.000, 2.010, 3.001, 4.000]", vector.toString(3)) ; EXPECT_EQ("[1.0000, 2.0100, 3.0010, 4.0001]", vector.toString(4)) ; } } TEST (Library_Mathematics_Objects_Vector4d, Parse) { using library::math::obj::Vector4d ; { const Vector4d vector = Vector4d::Parse("[1.000000, 2.000000, 3.000000, 4.000000]") ; EXPECT_EQ(4, vector.size()) ; EXPECT_EQ(1.0, vector(0)) ; EXPECT_EQ(2.0, vector(1)) ; EXPECT_EQ(3.0, vector(2)) ; EXPECT_EQ(4.0, vector(3)) ; } { EXPECT_ANY_THROW(Vector4d::Parse("")) ; EXPECT_ANY_THROW(Vector4d::Parse("[]")) ; EXPECT_ANY_THROW(Vector4d::Parse("1.000000, 2.000000, 3.000000, 4.000000, 5.000000")) ; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (Library_Mathematics_Objects_VectorXd, Constructor) { using library::math::obj::VectorXd ; { VectorXd vector(5) ; vector(0) = 1.0 ; vector(1) = 2.0 ; vector(2) = 3.0 ; vector(3) = 4.0 ; vector(4) = 5.0 ; EXPECT_EQ(1.0, vector(0)) ; EXPECT_EQ(2.0, vector(1)) ; EXPECT_EQ(3.0, vector(2)) ; EXPECT_EQ(4.0, vector(3)) ; EXPECT_EQ(5.0, vector(4)) ; } { const VectorXd vector = VectorXd::Undefined(5) ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const VectorXd vector = VectorXd::NaN(5) ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_TRUE(vector.isNaN()) ; EXPECT_FALSE(vector.isInf()) ; } { const VectorXd vector = VectorXd::Inf(5) ; EXPECT_FALSE(vector.isDefined()) ; EXPECT_FALSE(vector.isNaN()) ; EXPECT_TRUE(vector.isInf()) ; } } TEST (Library_Mathematics_Objects_VectorXd, IsNear) { using library::math::obj::VectorXd ; { VectorXd vector(5) ; vector(0) = 1.0 ; vector(1) = 2.0 ; vector(2) = 3.0 ; vector(3) = 4.0 ; vector(4) = 5.0 ; EXPECT_TRUE(vector.isNear(vector, 0.0)) ; } { VectorXd firstVector(2) ; firstVector(0) = 1.0 ; firstVector(1) = 2.0 ; VectorXd secondVector(2) ; secondVector(0) = 1.1 ; secondVector(1) = 2.0 ; EXPECT_TRUE(firstVector.isNear(secondVector, 1.0)) ; EXPECT_FALSE(firstVector.isNear(secondVector, 0.0)) ; } { EXPECT_ANY_THROW(VectorXd::NaN(3).isNear(VectorXd::NaN(3), 0.0)) ; } { VectorXd firstVector(2) ; firstVector(0) = 1.0 ; firstVector(1) = 2.0 ; VectorXd secondVector(3) ; secondVector(0) = 1.1 ; secondVector(1) = 2.0 ; secondVector(2) = 3.0 ; EXPECT_ANY_THROW(firstVector.isNear(secondVector, 1.0)) ; } } TEST (Library_Mathematics_Objects_VectorXd, ToString) { using library::math::obj::VectorXd ; { VectorXd vector(5) ; vector(0) = 1.0 ; vector(1) = 2.0 ; vector(2) = 3.0 ; vector(3) = 4.0 ; vector(4) = 5.0 ; EXPECT_EQ("[1, 2, 3, 4, 5]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0, 3.0, 4.0, 5.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.00, 3.00, 4.00, 5.00]", vector.toString(2)) ; EXPECT_EQ("[1.0, 2.0, 3.0, 4.0, 5.0]", vector.toString()) ; } { VectorXd vector(7) ; vector(0) = 1.0 ; vector(1) = 2.01 ; vector(2) = 3.001 ; vector(3) = 4.0001 ; vector(4) = 5.00001 ; vector(5) = -6.000001 ; vector(6) = -2.6988e-10 ; EXPECT_EQ("[1.0, 2.01, 3.001, 4.0001, 5.00001, -6.000001, -2.6988e-10]", vector.toString()) ; EXPECT_EQ("[1, 2, 3, 4, 5, -6, -0]", vector.toString(0)) ; EXPECT_EQ("[1.0, 2.0, 3.0, 4.0, 5.0, -6.0, -0.0]", vector.toString(1)) ; EXPECT_EQ("[1.00, 2.01, 3.00, 4.00, 5.00, -6.00, -0.00]", vector.toString(2)) ; EXPECT_EQ("[1.000, 2.010, 3.001, 4.000, 5.000, -6.000, -0.000]", vector.toString(3)) ; EXPECT_EQ("[1.0000, 2.0100, 3.0010, 4.0001, 5.0000, -6.0000, -0.0000]", vector.toString(4)) ; EXPECT_EQ("[1.00000, 2.01000, 3.00100, 4.00010, 5.00001, -6.00000, -0.00000]", vector.toString(5)) ; EXPECT_EQ("[1.000000, 2.010000, 3.001000, 4.000100, 5.000010, -6.000001, -0.000000]", vector.toString(6)) ; } } TEST (Library_Mathematics_Objects_VectorXd, Parse) { using library::math::obj::VectorXd ; { const VectorXd vector = VectorXd::Parse("[1.000000, 2.000000, 3.000000, 4.000000, 5.000000]") ; EXPECT_EQ(5, vector.size()) ; EXPECT_EQ(1.0, vector(0)) ; EXPECT_EQ(2.0, vector(1)) ; EXPECT_EQ(3.0, vector(2)) ; EXPECT_EQ(4.0, vector(3)) ; EXPECT_EQ(5.0, vector(4)) ; } { EXPECT_ANY_THROW(VectorXd::Parse("")) ; EXPECT_ANY_THROW(VectorXd::Parse("[]")) ; EXPECT_ANY_THROW(VectorXd::Parse("1.000000, 2.000000, 3.000000, 4.000000, 5.000000")) ; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
8e6d7a4156c93320ddf1e4a23f96b234120e7b2a
7e7a3cd90fdeb556dd3459eb5e6a8f68a0718d1d
/GBemu/gb/debug/gbDis.h
888440d046509c335418c2fb9391e77f20807984
[ "Apache-2.0" ]
permissive
robojan/EmuAll
7d3c792fce79db4b10613b93f0a0a7c23f42a530
0a589136df9fefbfa142e605e1d3a0c94f726bad
refs/heads/master
2021-01-21T04:50:46.603365
2016-07-22T10:44:18
2016-07-22T10:44:18
44,864,341
1
0
null
null
null
null
UTF-8
C++
false
false
460
h
gbDis.h
#ifndef _GBDIS_H_ #define _GBDIS_H_ #include "../Gameboy.h" #include <map> typedef struct { unsigned int location; char size; std::string raw; std::string instr; } DisassembleLine_t; class GbDis { public: GbDis(Gameboy *master); ~GbDis(); char Disassemble(const char **rawStr, const char **instrStr, address_t address); char Disassemble(const char **rawStr, const char **instrStr, const unsigned char *data); private: Gameboy *_master; }; #endif
5422626cc832f5921c0b7ab4b6b1f9abb9c64fc8
caff3a997ffc93fbe3500a9e43d608bdff48ba1f
/src/utilities/testutils.cpp
74a049a6fa05e15f1c12248b10efa464dba47d20
[]
no_license
nithinjs88/cpp_basics
f24cb7a13f24a6ba21aeef7f4219fcb9e458b6a7
79fdd5f1d3929bd7eeea91d0cab2840da2d7b83f
refs/heads/master
2021-01-13T02:22:48.916989
2015-08-07T06:33:21
2015-08-07T06:33:21
40,344,883
0
0
null
null
null
null
UTF-8
C++
false
false
207
cpp
testutils.cpp
/* * testutils.cpp * * Created on: 24-Jun-2015 * Author: nithin */ #include <iostream> #include "utilities.h" using namespace std; /* int main(int argc, char **argv) { cout<<getMax(1,2); } */
4ff08f2dcd9c0c7f0427717084c33e0e7349bfb2
60512deec8d46a06e4b3db4b07620c623090fc2f
/TP_5/Worm.cpp
e232abf1756cd6c45e592bc652339ce2038050f2
[]
no_license
ffarall/EDA_TP_5
5ef7a4154b3c0dbf6b0be8aab4e698e571a231ec
6b13b9de7c4d48d7203a8b96950f1c5225e7cef5
refs/heads/master
2020-03-27T11:57:46.152055
2018-09-04T20:13:50
2018-09-04T20:13:50
146,517,289
0
0
null
null
null
null
UTF-8
C++
false
false
9,365
cpp
Worm.cpp
#include "Worm.h" #include <cmath> using namespace std; #define WORM_FSM_STATES 7 #define WORM_FSM_EVENTS 6 #define NO_MOTION_FRAME_COUNT 8 #define JUMPING_WORM_UP_FRAMES 6 #define FRAMES_PER_DX 14 #define SCENARIO_LEFT_EDGE 685 #define SCENARIO_RIGHT_EDGE 1170 #define SCENARIO_FLOOR 616 #define WORM_MOVE_DIF 9.0 Worm::Worm(): pos() { currentState = IDLE; lookingRight = true; // If more worms were to be added to the game, initializing with rand() would be advisable. frameCounter = 0; } Worm::Worm(Vector pos_): pos(pos_) { currentState = IDLE; lookingRight = true; // If more worms were to be added to the game, initializing with rand() would be advisable. frameCounter = 0; } Worm::Worm(Vector pos_, char ku, char kl, char kr): pos(pos_) { currentState = IDLE; lookingRight = true; // If more worms were to be added to the game, initializing with rand() would be advisable. frameCounter = 0; keyUp = ku; keyRight = kr; keyLeft = kl; } Worm::Worm(int x_, int y_, char ku, char kl, char kr): pos(x_, y_) { currentState = IDLE; lookingRight = true; // If more worms were to be added to the game, initializing with rand() would be advisable. frameCounter = 0; keyUp = ku; keyRight = kr; keyLeft = kl; } Worm::Worm(int x_, int y_): pos(x_, y_) { currentState = IDLE; lookingRight = true; // If more worms were to be added to the game, initializing with rand() would be advisable. frameCounter = 0; } Worm::~Worm() { } /* GETTERS */ Vector Worm::get_pos() { return pos; } bool Worm::get_orientation() { return lookingRight; } uint Worm::get_frameCounter() { return frameCounter; } char Worm::get_event() { return ev; } wormState_n Worm::get_currentState() { return currentState; } double Worm::get_jumpSpeed() { return jumpSpeed; } double Worm::get_gravity() { return g; } double Worm::get_angle() { return angle; } char Worm::get_keyUp() { return keyUp; } char Worm::get_keyLeft() { return keyLeft; } char Worm::get_keyRight() { return keyRight; } /* SETTERS */ void Worm::set_pos(Vector pos_) { pos.set_x(pos_.get_x()); pos.set_y(pos_.get_y()); } void Worm::set_pos(int x_, int y_) { pos.set_x(x_); pos.set_y(y_); } void Worm::set_x(int x_) { pos.set_x(x_); } void Worm::set_y(int y_) { pos.set_y(y_); } void Worm::inc_x(int x_) { pos.inc_x(x_); } void Worm::inc_y(int y_) { pos.inc_y(y_); } void Worm::set_keys(char ku, char kl, char kr) { keyUp = ku; keyRight = kr; keyLeft = kl; } void Worm::set_orientation(bool orient) { lookingRight = orient; } void Worm::inc_frameCounter() { frameCounter++; } void Worm::set_frameCounter(uint fc) { frameCounter = fc; } void Worm::set_currentState(wormState_n st) { currentState = st; } /* Internal function to interprete the event and turn it into a Worm event, easier to handle by the fsm */ wormEvent_n Worm::event_decoder(Event& ev_) { ev = ev_.get_key_event_keycode(); switch (ev_.get_event_type()) { case POSSIBLE_WORM_MOVE: { if (ev == keyLeft) { return KEY_MOVE_LEFT_DOWN; } else if (ev == keyRight) { return KEY_MOVE_RIGHT_DOWN; } else if (ev == keyUp) { return KEY_JUMP_DOWN; } else { return NOT_VALID; } } break; case POSSIBLE_WORM_STOP: { if (ev == keyLeft || ev == keyRight) { return KEY_MOVE_UP; } else { return NOT_VALID; } } break; case REFRESH: { return NEW_FRAME; } break; default: break; } } void Worm::update(Event& ev) { /* Fsm table */ const wormFsmCell_n wormFsm[WORM_FSM_EVENTS][WORM_FSM_STATES] = { // START_MOVING, MOVING, STOP_MOVING, IDLE, START_JUMPING JUMPING LANDING {{START_MOVING, no_act_routine}, {MOVING, no_act_routine}, {STOP_MOVING, no_act_routine}, {START_MOVING, turn_worm}, {START_JUMPING, no_act_routine}, {JUMPING, no_act_routine}, {LANDING, no_act_routine}}, // KEY_MOVE_RIGHT_DOWN {{START_MOVING, no_act_routine}, {MOVING, no_act_routine}, {STOP_MOVING, no_act_routine}, {START_MOVING, turn_worm}, {START_JUMPING, no_act_routine}, {JUMPING, no_act_routine}, {LANDING, no_act_routine}}, // KEY_MOVE_LEFT_DOWN {{IDLE, no_act_routine}, {STOP_MOVING, no_act_routine}, {STOP_MOVING, no_act_routine}, {IDLE, no_act_routine}, {START_JUMPING, no_act_routine}, {JUMPING, no_act_routine}, {LANDING, no_act_routine}}, // KEY_MOVE_UP {{START_MOVING, refresh_start_moving}, {MOVING, refresh_moving}, {STOP_MOVING, refresh_stop_moving}, {IDLE, no_act_routine}, {START_JUMPING, refresh_start_jumping}, {JUMPING, refresh_jumping}, {LANDING, refresh_landing}}, // NEW_FRAME {{START_JUMPING, start_jumping}, {START_JUMPING, start_jumping}, {START_JUMPING, start_jumping}, {START_JUMPING, start_jumping}, {START_JUMPING, no_act_routine}, {JUMPING, no_act_routine}, {LANDING, no_act_routine}}, // KEY_JUMP_DOWN {{START_MOVING, no_act_routine}, {MOVING, no_act_routine}, {STOP_MOVING, no_act_routine}, {IDLE, no_act_routine}, {START_JUMPING, no_act_routine}, {JUMPING, no_act_routine}, {LANDING, no_act_routine}} // NOT_VALID }; wormEvent_n wormEv = event_decoder(ev); wormState_n wormSt = currentState; currentState = wormFsm[wormEv][wormSt].nextState; (wormFsm[wormEv][wormSt]).action_routine(this); } void Worm::move() { if (lookingRight) { pos.inc_x(WORM_MOVE_DIF); } else { pos.inc_x(-WORM_MOVE_DIF); } } void no_act_routine(void * worm_) { } void turn_worm(void * worm_) { Worm * worm = (Worm *) worm_; worm->set_frameCounter(0); // Initializing frameCounter for movement. if (worm->get_event() == worm->get_keyRight() && !(worm->get_orientation())) // If moving right but looking left, turn. { worm->set_orientation(true); } else if (worm->get_event() == worm->get_keyLeft() && worm->get_orientation()) // If moving left but looking right, turn. { worm->set_orientation(false); } } void refresh_start_moving(void * worm_) { Worm * worm = (Worm *)worm_; worm->inc_frameCounter(); if (worm->get_frameCounter() == NO_MOTION_FRAME_COUNT) // After the moving warm-up, state changes to moving. { worm->set_currentState(MOVING); } } void refresh_moving(void * worm_) { Worm * worm = (Worm *)worm_; worm->inc_frameCounter(); switch (worm->get_frameCounter()) // Every 14 frames after the warm up, the worm moves 9 pixels in the corresponding way. { case (NO_MOTION_FRAME_COUNT + FRAMES_PER_DX): worm->move(); break; case (NO_MOTION_FRAME_COUNT + 2 * FRAMES_PER_DX): worm->move(); break; case (NO_MOTION_FRAME_COUNT + 3 * FRAMES_PER_DX): { worm->move(); worm->set_frameCounter(NO_MOTION_FRAME_COUNT); // After last movement, since key is still down, the movement is restarted AFTER the warm-up. } break; } if (worm->get_pos().get_x() < SCENARIO_LEFT_EDGE) // If worm crosses the left edge, it gets pulled back into the allowed area. { worm->set_x(SCENARIO_LEFT_EDGE); } else if (worm->get_pos().get_x() > SCENARIO_RIGHT_EDGE) // If worm crosses the right edge, it gets pulled back into the allowed area. { worm->set_x(SCENARIO_RIGHT_EDGE); } } void refresh_stop_moving(void * worm_) { Worm * worm = (Worm *)worm_; worm->inc_frameCounter(); switch (worm->get_frameCounter()) // After a key up event, worm stops moving ONLY after any movement cycle's been completed. { case (NO_MOTION_FRAME_COUNT + FRAMES_PER_DX): case (NO_MOTION_FRAME_COUNT + 2 * FRAMES_PER_DX): case (NO_MOTION_FRAME_COUNT + 3 * FRAMES_PER_DX): { worm->move(); worm->set_currentState(IDLE); worm->set_frameCounter(NO_MOTION_FRAME_COUNT); } break; default: break; } } void start_jumping(void * worm_) { Worm * worm = (Worm *)worm_; worm->set_frameCounter(0); // Initializing frameCounter for jump. } void refresh_start_jumping(void * worm_) { Worm * worm = (Worm *)worm_; worm->inc_frameCounter(); if (worm->get_frameCounter() == NO_MOTION_FRAME_COUNT) // After the moving warm-up, state changes to jumping. { worm->set_currentState(JUMPING); } } void refresh_landing(void * worm_) { Worm * worm = (Worm *)worm_; worm->inc_frameCounter(); if (worm->get_frameCounter() == JUMPING_WORM_UP_FRAMES) { worm->set_currentState(IDLE); // If the worm finishes landing, goes back to resting. worm->set_frameCounter(0); } } void refresh_jumping(void * worm_) { Worm * worm = (Worm *)worm_; worm->inc_frameCounter(); double angle = worm->get_angle(); double jumpSpeed = worm->get_jumpSpeed(); double gravity = worm->get_gravity(); if (worm->get_orientation()) { worm->inc_x(jumpSpeed * cos(angle)); } else { worm->inc_x(-jumpSpeed * cos(angle)); } if (worm->get_pos().get_x() < SCENARIO_LEFT_EDGE) // If worm crosses the left edge, it gets pulled back into the allowed area. { worm->set_x(SCENARIO_LEFT_EDGE); } else if (worm->get_pos().get_x() > SCENARIO_RIGHT_EDGE) // If worm crosses the right edge, it gets pulled back into the allowed area. { worm->set_x(SCENARIO_RIGHT_EDGE); } worm->set_y(SCENARIO_FLOOR - jumpSpeed * sin(angle) * worm->get_frameCounter() + (gravity / 2) * pow(worm->get_frameCounter(), 2)); if (worm->get_pos().get_y() > SCENARIO_FLOOR) // If worm crosses the floor, it gets pulled back to the right position. { worm->set_y(SCENARIO_FLOOR); worm->set_currentState(LANDING); // If the worm got back to the floor, goes to LANDING state. worm->set_frameCounter(0); } }
92905722ec5a7b33175246d8cc99bad72d352ad6
3a8440b26e67b9ee9f3e27a7d47e28cf3cc72d7d
/include/peripheral/ComTransmit.h
0cc9facb72a0b66550096cdf50ee036da65474b9
[]
no_license
tdautc19841202/v200
7e48e852250c331db2c33735e84f829e5aecc69e
3c9dc92e4c58389acb4f3f6b93e04f0aad520e72
refs/heads/master
2020-03-25T06:57:11.095875
2017-05-08T06:07:55
2017-05-08T06:07:55
null
0
0
null
null
null
null
GB18030
C++
false
false
1,479
h
ComTransmit.h
#ifndef _COM_TRANSMIT_H_ #define _COM_TRANSMIT_H_ #include <string.h> #include <pthread.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> typedef struct { unsigned long baudrate; /*波特率*/ unsigned char databit; /*数据位,取值5、6、7、8*/ unsigned char parity; /*奇偶校验位,取值'n':无校验'o':奇校验'e'偶校验*/ unsigned char stopbit; /*停止位,取值1,2*/ unsigned char reserve; /*保留字节*/ }Terminal; typedef struct { int sysSpeed; unsigned long userSpeed; }speedPara; typedef enum { READ_TIMEOUT_F = 0, WRITE_TIMEOUT_F }SELECT_TIMEOUT_F; typedef enum { BAUTRATE_1200 = 0, BAUTRATE_2400, BAUTRATE_4800, BAUTRATE_9600, BAUTRATE_19200, BAUTRATE_38400, BAUTRATE_57600, BAUTRATE_115200, }SERIALBAUTRATE_E; class CComTransmit { private: // FILE *m_fp; int m_fd; struct timeval Rtimeout; struct timeval Wtimeout; public: // CComTransmit(); ~CComTransmit(); int OpenCom(const char *deviceName); void CloseCom(); int SetComSpeed(unsigned int speed); int SetComParity(int databits,int stopbits,int parity,int flowctrl); int SetComRawMode(); int SetComSelectTimeOut(int sec,int usec,SELECT_TIMEOUT_F RWflag);//0--read,1--wirte int IOFlush(); int ReadCom(char *ReadBuffer,int size,int *retSize); int WriteCom(char *WriteBuffer,int size); void ConvertCR2LF(int Switch); int GetPortFD(); FILE* GetPortFP(); protected: // }; #endif//_COM_TRANSMIT_H_
999f681278e56e1f9a4b889b9965b2f1b4d793ca
4a75f1b4c906b02c1b27beb5120d2fcfcc5442ac
/prog2.hpp
780ee92f31ab4ae9138f3ac16dc995e4bad209ba
[]
no_license
Chineme1/ALLmyFiles
8e7342d9ab6378568b149e0542be6320d64dbcb0
3c5cb5bd7462052cfa3b1bc83c715a7e067f9cf1
refs/heads/main
2023-06-29T01:06:23.315569
2021-07-29T16:51:44
2021-07-29T16:51:44
390,439,307
0
0
null
null
null
null
UTF-8
C++
false
false
336
hpp
prog2.hpp
#ifndef PROG2_HPP #define PROG2_HPP #include <tuple> #include <vector> std::tuple<bool, std::vector<unsigned>> isSubsetSum( const std::vector<int>& itemVals, int target); std::tuple<bool, std::vector<unsigned>, std::vector<unsigned>> isSetPartionable(const std::vector<int>& vals); #endif // PROG2_HPP
02586862f92bc6064b48926b6fbee5be588e833d
58958463ae51c6af762ade55e53154cdd57e9b71
/OpenSauce/shared/Include/blamlib/Halo1/input/input_windows.hpp
b8ca25f0b2cbf4e982a50db11ad5f37b5b405266
[]
no_license
yumiris/OpenSauce
af270d723d15bffdfb38f44dbebd90969c432c2b
d200c970c918921d40e9fb376ec685c77797c8b7
refs/heads/master
2022-10-10T17:18:20.363252
2022-08-11T20:31:30
2022-08-11T20:31:30
188,238,131
14
3
null
2020-07-14T08:48:26
2019-05-23T13:19:31
C++
UTF-8
C++
false
false
5,152
hpp
input_windows.hpp
/* Yelo: Open Sauce SDK Halo 1 (CE) Edition See license\OpenSauce\Halo1_CE for specific license information */ #pragma once namespace Yelo { namespace Enums { enum { k_maximum_buffered_keystrokes = 64, // MAXIMUM_BUFFERED_KEYSTROKES k_maximum_gamepads = 4, k_maximum_gamepad_axes = 32, k_maximum_gamepad_buttons = 32, k_maximum_gamepad_povs = 16, k_maximum_enumerated_joysticks = 8, k_number_of_virtual_codes = 256, }; enum { _axis_direction_positive, _axis_direction_negative, k_number_of_axis_directions, // NUMBER_OF_AXIS_DIRECTIONS }; enum { _pov_direction_none = NONE, _pov_direction_north, _pov_direction_north_east, _pov_direction_east, _pov_direction_south_east, _pov_direction_south, _pov_direction_south_west, _pov_direction_west, _pov_direction_north_west, k_number_of_pov_directions = 8, // NUMBER_OF_POV_DIRECTIONS }; enum { _mouse_button_left, _mouse_button_middle, _mouse_button_right, _mouse_button4, _mouse_button5, _mouse_button6, _mouse_button7, _mouse_button8, k_number_of_mouse_buttons, // NUMBER_OF_MOUSE_BUTTONS }; enum { _mouse_axes_horiz, _mouse_axes_vert, _mouse_axes_wheel, k_number_of_mouse_axes, // NUMBER_OF_MOUSE_AXES }; enum key_code : _enum { _key_code_invalid = NONE, _key_code_escape = 0x0, _key_code_f1 = 0x1, _key_code_f2 = 0x2, _key_code_f3 = 0x3, _key_code_f4 = 0x4, _key_code_f5 = 0x5, _key_code_f6 = 0x6, _key_code_f7 = 0x7, _key_code_f8 = 0x8, _key_code_f9 = 0x9, _key_code_f10 = 0xA, _key_code_f11 = 0xB, _key_code_f12 = 0xC, _key_code_print_screen = 0xD, _key_code_scroll_lock = 0xE, _key_code_pause = 0xF, _key_code_tilde = 0x10, _key_code_1 = 0x11, _key_code_2 = 0x12, _key_code_3 = 0x13, _key_code_4 = 0x14, _key_code_5 = 0x15, _key_code_6 = 0x16, _key_code_7 = 0x17, _key_code_8 = 0x18, _key_code_9 = 0x19, _key_code_0 = 0x1A, _key_code_minus = 0x1B, _key_code_plus = 0x1C, _key_code_backspace = 0x1D, _key_code_tab = 0x1E, _key_code_Q = 0x1F, _key_code_W = 0x20, _key_code_E = 0x21, _key_code_R = 0x22, _key_code_T = 0x23, _key_code_Y = 0x24, _key_code_U = 0x25, _key_code_I = 0x26, _key_code_O = 0x27, _key_code_P = 0x28, _key_code_left_bracket = 0x29, _key_code_right_bracket = 0x2A, _key_code_pipe = 0x2B, _key_code_caps = 0x2C, _key_code_A = 0x2D, _key_code_S = 0x2E, _key_code_D = 0x2F, _key_code_F = 0x30, _key_code_G = 0x31, _key_code_H = 0x32, _key_code_J = 0x33, _key_code_K = 0x34, _key_code_L = 0x35, _key_code_colon = 0x36, _key_code_quote = 0x37, _key_code_enter = 0x38, _key_code_left_shift = 0x39, _key_code_Z = 0x3A, _key_code_X = 0x3B, _key_code_C = 0x3C, _key_code_V = 0x3D, _key_code_B = 0x3E, _key_code_N = 0x3F, _key_code_M = 0x40, _key_code_comma = 0x41, _key_code_period = 0x42, _key_code_slash = 0x43, _key_code_right_shift = 0x44, _key_code_left_ctrl = 0x45, _key_code_left_windows = 0x46, _key_code_left_alt = 0x47, _key_code_space = 0x48, _key_code_right_alt = 0x49, _key_code_right_windows = 0x4A, _key_code_apps_menu = 0x4B, _key_code_right_ctrl = 0x4C, _key_code_up = 0x4D, _key_code_down = 0x4E, _key_code_left = 0x4F, _key_code_right = 0x50, _key_code_insert = 0x51, _key_code_home = 0x52, _key_code_page_up = 0x53, _key_code_delete = 0x54, _key_code_end = 0x55, _key_code_page_down = 0x56, _key_code_nums_lock = 0x57, _key_code_num_divide = 0x58, _key_code_num_multiply = 0x59, _key_code_Num0 = 0x5A, _key_code_Num1 = 0x5B, _key_code_Num2 = 0x5C, _key_code_Num3 = 0x5D, _key_code_Num4 = 0x5E, _key_code_Num5 = 0x5F, _key_code_Num6 = 0x60, _key_code_Num7 = 0x61, _key_code_Num8 = 0x62, _key_code_Num9 = 0x63, _key_code_num_minus = 0x64, _key_code_num_add = 0x65, _key_code_num_enter = 0x66, _key_code_num_dot = 0x67, _key_code_68 = 0x68, // DIK_ABNT_C2 _key_code_69 = 0x69, // DIK_AT _key_code_6A = 0x6A, // DIK_COLON _key_code_6B = 0x6B, // DIK_PREVTRACK _key_code_6C = 0x6C, // OEM_102 k_number_of_keys = 0x6D, _key_code_shift = 0x6E, _key_code_ctrl = 0x6F, _key_code_windows = 0x70, _key_code_alt = 0x71, }; }; namespace Flags { enum buffered_key_flags : byte_flags { _buffered_key_shift_bit, // SHIFT key pressed _buffered_key_control_bit, // CTRL key pressed _buffered_key_alt_bit, // ALT key pressed }; }; namespace Input { struct s_buffered_key { Flags::buffered_key_flags flags; byte state; // how long its been pressed until 0xFF, 0 if not pressed Enums::key_code key_code; }; BOOST_STATIC_ASSERT( sizeof(s_buffered_key) == 0x4 ); }; namespace blam { bool PLATFORM_API input_key_is_down(_enum key_code); }; };
b676570d49ca5653f7cfa25b355662a93c47397a
5a63bd6870346aa6593233b990303e743cdb8861
/SDK/UI_Container_parameters.h
e3ab4c3d4fbc4402a9985175b94849293530ff9f
[]
no_license
zH4x-SDK/zBlazingSails-SDK
dc486c4893a8aa14f760bdeff51cea11ff1838b5
5e6d42df14ac57fb934ec0dabbca88d495db46dd
refs/heads/main
2023-07-10T12:34:06.824910
2021-08-27T13:42:23
2021-08-27T13:42:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,768
h
UI_Container_parameters.h
#pragma once #include "../SDK.h" // Name: BS, Version: 1.536.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function UI_Container.UI_Container_C.SetTakeAllButtonVisiblity struct UUI_Container_C_SetTakeAllButtonVisiblity_Params { ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function UI_Container.UI_Container_C.ShowDepositAll struct UUI_Container_C_ShowDepositAll_Params { ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function UI_Container.UI_Container_C.ShowEmptyInventory struct UUI_Container_C_ShowEmptyInventory_Params { ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function UI_Container.UI_Container_C.ShowEmptyContainer struct UUI_Container_C_ShowEmptyContainer_Params { ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function UI_Container.UI_Container_C.SetContainerWeight struct UUI_Container_C_SetContainerWeight_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function UI_Container.UI_Container_C.SetCharacterWeight struct UUI_Container_C_SetCharacterWeight_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function UI_Container.UI_Container_C.BndEvt__Btn_Join_K2Node_ComponentBoundEvent_51_OnButtonClickedEvent__DelegateSignature struct UUI_Container_C_BndEvt__Btn_Join_K2Node_ComponentBoundEvent_51_OnButtonClickedEvent__DelegateSignature_Params { }; // Function UI_Container.UI_Container_C.Destruct struct UUI_Container_C_Destruct_Params { }; // Function UI_Container.UI_Container_C.CloseThisContainer struct UUI_Container_C_CloseThisContainer_Params { }; // Function UI_Container.UI_Container_C.RefreshContainer struct UUI_Container_C_RefreshContainer_Params { }; // Function UI_Container.UI_Container_C.Tick struct UUI_Container_C_Tick_Params { struct FGeometry MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) float InDeltaTime; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function UI_Container.UI_Container_C.Construct struct UUI_Container_C_Construct_Params { }; // Function UI_Container.UI_Container_C.BndEvt__Button_0_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature struct UUI_Container_C_BndEvt__Button_0_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature_Params { }; // Function UI_Container.UI_Container_C.ExecuteUbergraph_UI_Container struct UUI_Container_C_ExecuteUbergraph_UI_Container_Params { int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
26d5136986951ee11a04ccc91d218b80115ff8e3
51375a1366c06d78f9a2b7f99a5397fedd96f2a5
/Source/contour_extractor.h
451c547b4577eaeddea9e792dd86cd79c2faa77b
[ "MIT" ]
permissive
Ungetym/Drosophila_Tracker
f0a4fe1fb35014a0c0f16564441953cc5022fb56
0753741ea72cd0fb67e0690f6de3e98aba17753e
refs/heads/master
2021-09-14T13:21:41.520185
2018-05-14T08:56:03
2018-05-14T08:56:03
103,679,171
0
0
null
null
null
null
UTF-8
C++
false
false
1,429
h
contour_extractor.h
#ifndef CONTOUR_EXTRACTOR_H #define CONTOUR_EXTRACTOR_H #include "opencv2/opencv.hpp" #include "basic_calc.h" class contour_extractor { public: contour_extractor(); // initializes background image for background subtraction void initBackground(cv::Mat *image, float* threshold=NULL); /// /// \brief extractContours calculates the binary image from the input image and extracts as well as filters the contours /// \param image input gray value image /// \param binary_image result binary image /// \param min_area minimum area enclosed by a contour to be considered a larva contour /// \param max_area pendant to min_area /// \return contours extracted from the binary image /// std::vector<std::vector<cv::Point>> extractContours(cv::Mat *image, cv::Mat *binary_image, int min_area, int max_area, float threshold=20.0); private: cv::Mat current_background; //adds image region to the background image void addBackgroundObject(cv::Mat* bounding_rectangle, std::vector<cv::Point> contour, int x_pos, int y_pos); //background subtraction cv::Mat subtract(cv::Mat* source); //calculates histogramm std::vector<float> calcHist(cv::Mat* image, float size); //iterative flood fill algorithm void revFloodFill(cv::Mat* image, int a, int b); }; #endif // CONTOUR_EXTRACTOR_H
bced492b9949e348fc303b33f12830402b29cadb
1b93fbe260ab74894454a869d7258de0fb7ecb33
/GPUHelpers.h
36a9bed9548637b39e42ea0155b4a9ef3699731a
[]
no_license
JackLeEmmerdeur/knfancurve
bc342b23774218456194f345ef06791a4cecc705
721f0e659ca86ee36a75dfd3a3a41f2091e2fbd7
refs/heads/master
2022-12-21T05:26:16.385024
2020-09-23T00:38:30
2020-09-23T00:38:30
290,026,450
0
0
null
null
null
null
UTF-8
C++
false
false
536
h
GPUHelpers.h
#ifndef GPUHELPERS_H #define GPUHELPERS_H #include <QLayout> #include <QMessageBox> #include <QProcess> #include <QStringList> #include <QVariant> #include <QString> #include <QDebug> #include <QTextCodec> class GPUHelpers { public: GPUHelpers(); static QProcess *createProcess(QStringList args); // static QProcess *runProcess(const QString &procpath, QStringList args); static QVariant *getProcRes(QStringList args, bool getLines); static QString readGPUValue(int index, QString gpuvalue); }; #endif // GPUHELPERS_H
9a22081f114255d5fbfa4afe48a7dca23241c30d
3d7bf36e9327904b4d87e479bf268f507d192155
/Triangle.cpp
9ae597738441d8ece620b9e8bde7aba832cf1a16
[]
no_license
Nishi-666/Noriuturi
4e18d5995390af81e2e7410ab11c9eaf645e0e6b
044479bc53f73420aaa71f695df37b3637fa423b
refs/heads/master
2023-02-01T10:01:06.580437
2020-12-20T05:13:56
2020-12-20T05:13:56
309,291,533
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,996
cpp
Triangle.cpp
#include "Triangle.h" //#include "Config.h" #include "Sprite.h" #include"MyDirect3D.h" #include <d3d9.h> #include <d3d9.h> #include "TexMan.h" #include <memory.h> typedef struct Vertex3D_tag { D3DXVECTOR3 Position; D3DCOLOR Collar; D3DXVECTOR2 TexCoord; }Vertex3D; #define FVF_VERTEX3D (D3DFVF_XYZ| D3DFVF_DIFFUSE|D3DFVF_TEX1)//|D3DFVF_TEX1)//game.hにcofig.hあるから除かす ////グローバル変数宣言//// //頂点データ配列(3DTriangle) static Vertex3D g_TriangleVerttex[] = { //手前 {D3DXVECTOR3(0.0f , 0.5f ,-0.0f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0)},//赤 {D3DXVECTOR3(0.5f , -0.5f ,-0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0.25f,0)}, {D3DXVECTOR3(-0.5f , -0.5f ,-0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0.25f)}, //右 {D3DXVECTOR3(0.0f , 0.5f ,-0.0f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0)},//青 {D3DXVECTOR3(0.5f , -0.5f ,0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0.25f,0)} , {D3DXVECTOR3(0.5f , -0.5f ,-0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0.25f)}, //後方 {D3DXVECTOR3(0.0f , 0.5f ,0.0f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0)},//赤 {D3DXVECTOR3(-0.5f , -0.5f ,0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0.25f,0)}, {D3DXVECTOR3(0.5f , -0.5f ,0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0.25f)}, //左 {D3DXVECTOR3(-0.0f , 0.5f ,0.0f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0)},//白 {D3DXVECTOR3(-0.5f , -0.5f ,-0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0.25f)}, {D3DXVECTOR3(-0.5f , 0-.5f ,0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0.25f,0)} , //下 {D3DXVECTOR3(-0.5f , -0.5f ,-0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0)}, {D3DXVECTOR3(0.5f , -0.5f ,-0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0.25f,0)} , {D3DXVECTOR3(-0.5f ,-0.5f ,0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0.25f)}, {D3DXVECTOR3(0.5f , -0.5f ,-0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0.25f,0)}, {D3DXVECTOR3(0.5f , -0.5f ,0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0.25f,0.25f)}, {D3DXVECTOR3(-0.5f , -0.5f ,0.5f),D3DCOLOR_RGBA(255,255,255,225),D3DXVECTOR2(0,0.25f)}, }; static LPDIRECT3DVERTEXBUFFER9 g_pVertexBuffer = NULL;//頂点バッファインタフェース static LPDIRECT3DINDEXBUFFER9 g_pIndexBuffer = NULL; //インデックスバッファインタフェース static D3DCOLOR g_Collar = D3DCOLOR_RGBA(255, 255, 255, 255);//ポリゴンカラー//驚きの白さ //テクスチャの管理番号 static int g_BoxTextureId = TEXTURE_INVALID_ID; ///////////////////////// void Triangle_initialize(void) { return; LPDIRECT3DDEVICE9 pDevice = MyDirect3D_GetDevice(); g_BoxTextureId = Texture_SetTextureLoadFile("Asset\\spice_and_wolf.png"); if (Texture_Load() > 0) { MessageBox(NULL, "アプリケーション終了します", "Aテクスチャの読み込みが失敗しましたのでDA", MB_OK);//OKを押されるまでプログラムがとまる return; } static const D3DXVECTOR2 uv_offsets[] = { D3DXVECTOR2(0,0),D3DXVECTOR2(0.25f,0),D3DXVECTOR2(0.5f,0),D3DXVECTOR2(0.75f,0), D3DXVECTOR2(0,0.25f),D3DXVECTOR2(0.25f,0.25f) }; for (int i = 0; i < 6; i++) { for (int s = 0; s < 6; s++) { g_TriangleVerttex[i * 6 + s].TexCoord += uv_offsets[i]; } } Texture_Load(); } void Triangle_Update(void) { } void Triangle_Draw(D3DXMATRIX* pMtxWorld) { return; LPDIRECT3DDEVICE9 pDevice = MyDirect3D_GetDevice(); pDevice->SetTransform(D3DTS_WORLD, pMtxWorld); //ビュー変換行列の作成 pDevice->SetFVF(FVF_VERTEX3D); pDevice->SetTexture(0, texture_GetTexture(g_BoxTextureId)); //ライトを無効にする pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); //ポリゴンを描画!! pDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 9, &g_TriangleVerttex, sizeof(Vertex3D)); } void Triangle_Finalize(void) { return; Texture_Release(&g_BoxTextureId, 1); }
76ba777a96a26fe2d75608790dbb979d34a104a4
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/noesy_assign/Resonance.hh
314a9aff3b50b2460668f2d601d538cb406b7199
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
4,778
hh
Resonance.hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file CrossPeakList.hh /// @author Oliver Lange #ifndef INCLUDED_protocols_noesy_assign_Resonance_hh #define INCLUDED_protocols_noesy_assign_Resonance_hh // Unit Headers #include <protocols/noesy_assign/Resonance.fwd.hh> // Package Headers #include <protocols/noesy_assign/FoldResonance.fwd.hh> #include <protocols/noesy_assign/PeakCalibrator.fwd.hh> // Project Headers #include <utility/pointer/ReferenceCount.hh> #include <core/chemical/AA.hh> #include <core/types.hh> #include <core/id/NamedAtomID.hh> // Utility headers #include <utility/vector1.hh> #include <utility/pointer/access_ptr.hh> //// C++ headers #include <deque> namespace protocols { namespace noesy_assign { /*! @detail Resonance combines resonanceID (label), chemical shift (freq), tolerance (error), and the assigned atom (atom, name, resid) (provided accessor methods of "Resonance": label, atom, resid, name, freq, error, tolerance, calibration_atom_type ) */ class Resonance : public utility::pointer::ReferenceCount { public: typedef utility::vector1< core::Size > ResonanceIDs; typedef std::pair< core::Size, core::Size > ResonancePair; typedef utility::vector1< ResonancePair > ResonancePairs; typedef utility::vector1< ResonanceAP > ResonanceAPs; Resonance(); Resonance( core::Size label, core::Real freq, core::Real error, core::id::NamedAtomID const& id, core::chemical::AA, core::Real intensity = 1.0 ); ~Resonance() override; virtual ResonanceOP clone() = 0; /// @brief output virtual void write_to_stream( std::ostream& ) const; virtual void write_to_stream( std::ostream&, core::chemical::AA aa ) const; virtual core::Size ambiguity() const { return 1; } /// @brief ResonanceID core::Size label() const { return label_; } virtual core::Size float_label( core::Size /*ifloat*/ ) const { return label_; } /// @brief Atom core::id::NamedAtomID const& atom() const { return atom_; } core::Size resid() const { return atom_.rsd(); } std::string const& name() const { return atom_.atom(); } bool is_proton() const { return is_proton_; } /// @brief resonance frequency (chemical shift) core::Real freq() const { return freq_; } core::Real error() const { return error_; } core::Real tolerance() const { return error_; } /// @brief Resonance matches the given cross-peaks frequency bool match( core::Real freq, core::Real error, FoldResonance const& folder ) const { return pmatch( freq, error, folder ) <= 1.0; } /// @brief match the proton and corresponding label atom at same time virtual bool match2D( core::Real proton_freq, core::Real proton_error, FoldResonance const& proton_folder, core::Real label_freq, core::Real label_error, FoldResonance const& label_folder, ResonancePairs& matches ) const = 0; void add_connected_resonance( ResonanceAP ptr ); void clear_connected_resonances(); bool has_connected_resonances() const { return connected_resonance_ids_.size() > 0; } Resonance const& first_connected_resonance() const; ResonanceIDs const& connected_resonance_ids() const { return connected_resonance_ids_; } ResonanceAPs const& connected_resonances() const; virtual core::Real pmatch( core::Real freq, core::Real error, FoldResonance const& folder ) const; void combine( std::deque< ResonanceOP >& last_resonances, bool drain ); core::chemical::AA aa() const { return aa_; } /// @brief in ILV-labelled proteins, the both LV methyls are labelled randomly with 50% probability, /// whereas I delta methyls are labelled 100% core::Real intensity() const { return intensity_; } void set_intensity( core::Real setting ) { intensity_ = setting; } /// @brief classification for calibration... e.g., Backbone, sidechain, etc.. CALIBRATION_ATOM_TYPE calibration_atom_type() const { return calibration_atom_type_; } core::Real _pmatch( core::Real freq, core::Real error, FoldResonance const& folder ) const; private: void _write_to_stream( std::ostream& ) const; core::Size label_; core::Real freq_; core::Real error_; bool is_proton_; core::id::NamedAtomID atom_; core::chemical::AA aa_; core::Real intensity_; CALIBRATION_ATOM_TYPE calibration_atom_type_; ResonanceIDs connected_resonance_ids_; ResonanceAPs connected_resonance_ptrs_; }; } } #endif
6c449d25c4835a4e180ddf9ac4deba04fea0df23
0d8ec12cb25a22ea65e25a95d2cc20ad86fc5e63
/src/creditsReader.h
0ce07ff435660fabd81a0b5cffdc9ff4f2151ae6
[]
no_license
BlinksTale/cubior
7bd903a23bd5f44ef37ffc35e526e756c37d2931
b025d71df1e5118f5cb2a10647fdd8b76256d9ca
refs/heads/master
2020-04-02T01:01:19.131964
2013-08-27T07:05:03
2013-08-27T07:05:03
3,175,518
2
0
null
null
null
null
UTF-8
C++
false
false
282
h
creditsReader.h
/* * creditsReader.h * by Brian Handy * 12/5/12 * Header for the .txt to credits converter */ #ifndef CREDITSREADER #define CREDITSREADER #include <string> using namespace std; class CreditsReader { public: static string* readCredits(const std::string&); }; #endif
a0ed4e12ba0728fdf685e107188b350e71d1931f
55996d3071249043b509b1a9eed46036e98afa68
/rc.cpp
631e1592ae0fc8e947eb629b0151154230112589
[]
no_license
Gyorathel/IC
594d12b740b7584c624b21bfc1e26bb8defa3f18
17a9658f86ee64ddf771c6618bb94d2e98c907c3
refs/heads/master
2021-01-01T05:23:24.418050
2016-05-18T16:39:24
2016-05-18T16:39:24
59,133,471
0
0
null
null
null
null
UTF-8
C++
false
false
13,688
cpp
rc.cpp
#include <iostream> #include <vector> #include <cstdio> #include <cstdlib> #include <ctime> #include <fstream> #include <string> #include <sstream> using namespace std; #define stepMax 1000 #define graphSize 200 // mudar para o arquivo de config int mi; int gama; int alfa; int corr; int lambda; class Node { private: int status; // -1 = S, 0 = R, 1 = I int pos; // posição, auxiliar public: vector<int> neighbors; Node(int status) { pos=-999; this->status=status; } int getStatus() { return status; } int getSize() { return neighbors.size(); } int setStatus(int status) { this->status=status; } void setPos(int pos) { this->pos=pos; } int getPos() { return pos; } void addNeighbor(int a) { neighbors.push_back(a); } void printNeighbors() { for(int i = 0 ; i < neighbors.size() ; i++) cout << " " << neighbors[i]; } }; class Graph { private: int counter; int infected; int ignorant; int stifler; int spreader; vector<Node*> epidemicLayer; vector<Node*> informationLayer; bool sir; bool cor; public: Graph(bool sir, bool cor, int nNodes) { counter=0; infected=0; stifler=0; spreader=0; for(int i = 0 ; i < nNodes ; i++) // ajustar { addNode(new Node(-1),new Node(-1)); } this->sir=sir; this->cor=cor; ignorant=informationLayer.size(); } /** Função addNode Adiciona os nós aos grafos das redes */ void addNode(Node* A,Node* B) { A->setPos(counter); B->setPos(counter); epidemicLayer.push_back(A); informationLayer.push_back(B); counter++; } void addNeighbor(int src, int des, string layer, bool directed) { if(layer.compare("information")==0) { informationLayer[src]->addNeighbor(des); if(!directed) informationLayer[des]->addNeighbor(src); } else { epidemicLayer[src]->addNeighbor(des); if(!directed) epidemicLayer[des]->addNeighbor(src); } } int getCounter() // Não utilizado - Para Debug { return counter; } void infectInit(double i) { if(epidemicLayer.size()>0) { do { int chosen = rand()%epidemicLayer.size(); if(epidemicLayer[chosen]->getStatus()==-1) { epidemicLayer[chosen]->setStatus(1); infected++; } }while(i>infectedTotalPercent()); } else { cerr << "Grafo Vazio!" << endl; } } void spreadInit(double i) { if(informationLayer.size()>0) { do { int chosen = rand()%informationLayer.size(); if(informationLayer[chosen]->getStatus()==-1) { informationLayer[chosen]->setStatus(0); spreader++; ignorant--; } }while(i>getSpreaderPercent()); } else { cerr << "Grafo Vazio!" << endl; } } vector<Node*> getEpidemicLayer() // Não utilizado - Para Debug { return epidemicLayer; } vector<Node*> getInformationLayer() // Não utilizado - Para Debug { return informationLayer; } int getInfected() { return infected; } int getSpreader() { return spreader; } int getIgnorant() { return ignorant; } int getStifler() { return stifler; } double getSpreaderPercent() { double spreaderPercent = (double) (spreader); spreaderPercent = spreaderPercent/informationLayer.size(); return spreaderPercent; } double getIgnorantPercent() { double ignorantPercent = (double) (ignorant); ignorantPercent = ignorantPercent/informationLayer.size(); return ignorantPercent; } double getStiflerPercent() { double stiflerPercent = (double) (stifler); stiflerPercent = stiflerPercent/informationLayer.size(); return stiflerPercent; } void printList() // Não utilizado - Para Debug { for(int i = 0 ; i < epidemicLayer.size() ; i++) { cout << "\nNode " << i << "\nstatus: " << epidemicLayer[i]->getStatus() << "\nVizinhos: "; epidemicLayer[i]->printNeighbors(); } } void printState() // Não utilizado - Para Debug { for(int i = 0 ; i < epidemicLayer.size() ; i++) { cout << "\nNode " << i << " esta: "; if(epidemicLayer[i]->getStatus()==-1) cout << "suscetível"; if(epidemicLayer[i]->getStatus()==0) cout << "recuperado"; if(epidemicLayer[i]->getStatus()==1) cout << "infectado"; } } int getInfectedDebug() // Não utilizado - Para Debug { int aux = 0; for(int i = 0 ; i < epidemicLayer.size() ; i++) { if(epidemicLayer[i]->getStatus()==1) aux += 1; } return aux; } float infectedTotalPercent() { float aux = (float)infected; return aux/epidemicLayer.size(); } void healAll() { for(int i = 0 ; i < epidemicLayer.size() ; i++) { epidemicLayer[i]->setStatus(-1); } infected=0; } vector<Node*> getInfectedList() { vector<Node*> infList; for(int i =0 ; i < epidemicLayer.size() ; i++) { if(epidemicLayer[i]->getStatus()==1) { infList.push_back(epidemicLayer[i]); } } return infList; } vector<Node*> getSpreadingList() { vector<Node*> awareList; for(int i =0 ; i < informationLayer.size() ; i++) { if(informationLayer[i]->getStatus()==0) { awareList.push_back(informationLayer[i]); } } return awareList; } void infectContact(int escolhido, vector<Node*> infectedList, float beta) { int tam = infectedList[escolhido]->neighbors.size(); if(tam>0) { int chosenOne = rand()%tam; int tryToInfect = rand()%100 + 1; if(epidemicLayer[infectedList[escolhido]->neighbors[chosenOne]]->getStatus()==-1 && ( tryToInfect <= beta)) { epidemicLayer[infectedList[escolhido]->neighbors[chosenOne]]->setStatus(1); // infecta infected++; } } } void infectReactive(int escolhido, vector<Node*> infectedList, float beta) { for(int j = 0 ; j < infectedList[escolhido]->neighbors.size() ; j++) { int tryToInfect = rand()%100 + 1; if((epidemicLayer[infectedList[escolhido]->neighbors[j]])->getStatus()==-1 && ( tryToInfect <= (beta))) { (epidemicLayer[infectedList[escolhido]->neighbors[j]])->setStatus(1); // infecta infected++; } } } void heal(int escolhido, vector<Node*> infectedList) { int chosen = escolhido; int tryToHeal = rand()%100 + 1; if(tryToHeal <= mi) { if(sir) { infectedList[chosen]->setStatus(0); //sir } else { infectedList[chosen]->setStatus(-1); //sis } //cout << "\nO node " << infectedList[chosen]->getPos() << " se recuperou."; infected--; } } int infectRun(float beta) { vector<Node*> infectedList = getInfectedList(); if(infectedList.size()!=0) { for(int i = 0; i < infectedList.size(); i++) { heal(i,infectedList); // permite reinfecção } for(int i = 0; i < infectedList.size(); i++) { if(cor) { infectContact(i,infectedList,beta); } else { infectReactive(i,infectedList,beta); } } } return getInfected(); } }; void loadConfig() { ifstream config("config.txt"); string line, dummy; int nLine=1; if (config.is_open()) { while ( getline (config,line) ) { if(nLine>3&&nLine<10) { istringstream iss(line); iss >> dummy; if(nLine==4) iss >> mi; else if(nLine==5) iss >> gama; else if(nLine==6) iss >> alfa; else if(nLine==7) iss >> corr; else if(nLine==8) iss >> lambda; else if(nLine==9) iss >> graphSize; } nLine++; } config.close(); } else { cout << "O arquivo config.txt nao foi encontrado ou esta corrupto" << endl; } } /** Main - */ int main() { /* Atribuição de Variáveis Globais */ mi = 0; gama = 0; alfa = 0; corr = 1; lambda = 0; graphSize = 0; loadConfig(); /* Início do Main, Declaração de Variáveis */ int veof; // Auxiliar para o descritor de arquivos double initialSeed = 0.05; // Semente Inicial para Início da Epidemia char* saidaTxt; FILE* pFileInEpidemic; // Descritor de arquivos de entrada FILE* pFileInInformation; // Descritor de arquivos de entrada Graph* G; // Grafo base srand(time(NULL)); // Semente do Random Number //############################################################################# /* Arquivo de entrada Formato utilizado: X Y Z X Y Z X Y Z X = nó origem possui aresta com Y = nó destino, Z é utilizado para finalizar a leitura do arquivo, 1 = continua, 0 = pare */ pFileInEpidemic=fopen("netf.txt","r"); if(pFileInEpidemic==NULL) { printf("\033c"); cerr << "Falha ao abrir arquivo." << endl; exit(EXIT_FAILURE); } pFileInInformation=fopen("netf.txt","r"); if(pFileInInformation==NULL) { printf("\033c"); cerr << "Falha ao abrir arquivo." << endl; exit(EXIT_FAILURE); } //############################################################################# /* Inicialização do Grafo */ if(!mi) { if(corr) { G = new Graph(true,true,graphSize); } else { G = new Graph(true,false,graphSize); } } else { if(corr) { G = new Graph(false,true,graphSize); } else { G = new Graph(false,false,graphSize); } } /* Leitura do arquivo e criação dos nós */ do { int a, b; fscanf(pFileInEpidemic,"%d",&a); fscanf(pFileInEpidemic,"%d",&b); fscanf(pFileInEpidemic,"%d",&veof); G->addNeighbor(a,b,"epidemic",0); }while(veof==0); do { int a, b; fscanf(pFileInInformation,"%d",&a); fscanf(pFileInInformation,"%d",&b); fscanf(pFileInInformation,"%d",&veof); G->addNeighbor(a,b,"information",0); }while(veof==0); int aux = 0; vector<float> vpersistence; vector<float> vbeta; for(int i = 0 ; i < 95 ; i+=5 ) { G->healAll(); vector<float> n_Infected; // Vector para Amostra de Nro Infectados int step = 1; // Contador de passos G->infectInit(initialSeed); // Primeiros infectados //cout << G->getInfected() << endl << endl; // debug func n_Infected.push_back(G->getInfected()); do { if(step!=1) { if(G->getInfected()>0) { n_Infected.push_back(G->infectRun(i)); //G->printState(); DEBUG FUNC } else { break; } } step++; }while(step<stepMax); int tam = n_Infected.size(); int au = (int)tam*0.05; float mean = 0; for(int j = tam-au ; j < tam ; j++) { mean = mean + n_Infected[j]; } float v = (float)mean; if(mean==0) { mean=0; } else { mean/=au; mean/=200; } vpersistence.push_back(mean); float b = (float)i; b/=100; vbeta.push_back(b); cout << "beta: " << vbeta[aux] << " persitence: " << vpersistence[aux] << endl; aux++; } /** Modelo de saída para Windows */ if(!mi) { if(corr) { saidaTxt="SIRC.txt"; } else { saidaTxt="SIRR.txt"; } } else { if(corr) { saidaTxt="SISC.txt"; } else { saidaTxt="SISR.txt"; } } FILE* pFileOut; char* end = (char*)saidaTxt; pFileOut=fopen(saidaTxt,"w"); if(pFileOut==NULL) { cerr << "Falha ao abrir arquivo." << endl; exit(EXIT_FAILURE); } //for(int i = 0 ; i < n_Infected.size() ; i++) //{ // fprintf(pFileOut,"%d %d\n", i, n_Infected[i]); //} cout << "\n\nPrograma finalizado com sucesso"; //############################################################################# exit(EXIT_SUCCESS); return 0; }
db4b8c4579b30a19d7da6d4ab5bbf3ed51add820
5211c66c05586032c171003cbd02d0241f896144
/src/e_copia.h
4506c4cbd46f0540d5a64da68413768ffd4587ab
[ "MIT" ]
permissive
D33pBlue/AnimalGame-lite-
d2133224f395a09d3421b6b380f28e07eb1c4ad2
9fb7ce6fa1ab4736abcb38a539db6c1e690b3201
refs/heads/master
2021-09-09T16:04:25.182814
2018-03-17T16:52:53
2018-03-17T16:52:53
125,650,035
0
0
null
null
null
null
UTF-8
C++
false
false
234
h
e_copia.h
#ifndef E_COPIA_H #define E_COPIA_H #include "effetto.h" class E_copia : public Effetto { public: E_copia(const QString&); virtual E_copia* clona()const; virtual void onTira(Partita*,Giocatore*); }; #endif // E_COPIA_H
38a3626331eefe2985be883d36b305dc7e0749fd
ec219e3a747108e3ea7d6dad73ab6d3bedbe7e75
/DataStructures/Stacks/3.EqualStacks.cpp
0d2f96f6f214d6d11e8377d5d21a60ecda0d820a
[]
no_license
johnty05/Hackerrank
b687672dfe2abf6214dc7a7918a73f6f77f43965
dfa75f67235161cbc25550650d7fd3ad36856e9c
refs/heads/master
2022-11-14T15:17:01.672337
2022-11-11T19:46:17
2022-11-11T19:46:17
134,028,613
2
0
null
null
null
null
UTF-8
C++
false
false
1,333
cpp
3.EqualStacks.cpp
#include <map> #include <set> #include <list> #include <cmath> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include<iostream> using namespace std; int main(){ int n1; int n2; int n3; cin >> n1 >> n2 >> n3; int h1 = 0, h2 = 0, h3 = 0; // heights of the 3 stacks vector<int> T1(n1); for(int i = 0; i < n1; i++){ cin>>T1[i]; h1 += T1[i]; } vector<int> T2(n2); for(int i = 0; i < n2; i++){ cin>>T2[i]; h2 += T2[i]; } vector<int> T3(n3); for(int i = 0; i < n3; i++){ cin>>T3[i]; h3 += T3[i]; } //Remove the blocks from the tallest first bool eqHt = false; if(h1 == h2 && h2 == h3) { eqHt = true; } int r1 = 0, r2 = 0, r3 = 0; // index of which cylinder to remove while(!eqHt) { if(h1 >= h2 && h1 >= h3) { h1 -= T1[r1]; r1++; } else if(h2 >= h1 && h2 >= h3) { h2 -= T2[r2]; r2++; } else if(h3 >= h1 && h3 >= h2) { h3 -= T3[r3]; r3++; } if((h1 == h2 && h2 == h3) || (h1 == 0 && h2 == 0 && h3 == 0)) { eqHt = true; } } cout<<h1; return 0; }
a349701093ea296e1963960a89a450e11d49cd26
771e582527e78f7650e937bcd00513b3c9e30e0f
/src/GLShader.cpp
1ddb1d43cc1a7d3ac349ffe66048dc06f5fea029
[]
no_license
ElFeesho/GlTest
6cf5a9bc8a5f46cab964df5893d3d538b1a951b1
001b257d8684a744be3388a01e78e02e1bd7f6ef
refs/heads/master
2021-01-11T20:12:04.214120
2017-01-22T18:29:04
2017-01-22T18:29:04
79,064,921
0
0
null
null
null
null
UTF-8
C++
false
false
1,315
cpp
GLShader.cpp
#include "GLShader.h" #include <algorithm> GLShader::GLShader(GLuint shaderId) : _shaderId{shaderId} { } void GLShader::use(std::function<void()> bindingContext) { glUseProgram(_shaderId); bindingContext(); glUseProgram(0); } void GLShader::locateUniforms(std::vector<std::string> uniformNames) { std::for_each(uniformNames.begin(), uniformNames.end(), [&](std::string &uniform) { locateUniform(uniform); }); } void GLShader::locateUniform(std::string &uniformName) { _uniformLocations[uniformName] = glGetUniformLocation(_shaderId, uniformName.c_str()); } void GLShader::setUniform(const std::string &uniformName, glm::vec3 value){ glUniform3fv(_uniformLocations[uniformName], 1, glm::value_ptr(value)); } void GLShader::setUniform(const std::string &uniformName, glm::vec4 value){ glUniform4fv(_uniformLocations[uniformName], 1, glm::value_ptr(value)); } void GLShader::setUniform(const std::string &uniformName, glm::mat4 value){ glUniformMatrix4fv(_uniformLocations[uniformName], 1, GL_FALSE, glm::value_ptr(value)); } void GLShader::setUniform(const std::string &uniformName, float x, float y, float z){ glUniform3f(_uniformLocations[uniformName], x, y, z); } void GLShader::setUniform(const std::string &uniformName, GLuint value){ glUniform1i(_uniformLocations[uniformName], value); }
70a733ded6cada327618e61581414f9b4189a399
b69a21b62bcdab75ab24264b3354a1947acf5e6f
/client/ModelGenerated/getuserinfobyloginresult.h
881fcdb70f318f644383453db70d3ffa9678e2c0
[ "CC-BY-4.0", "MIT" ]
permissive
aernesto/moodbox_aka_risovaska
97ee1127e1ed7a2ddcc85079cab15c70b575d05f
5943452e4c7fc9e3c828f62f565cd2da9a040e92
refs/heads/master
2021-01-01T17:17:39.638815
2012-02-28T15:31:55
2012-02-28T15:31:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,728
h
getuserinfobyloginresult.h
#ifndef GETUSERINFOBYLOGINRESULT_H #define GETUSERINFOBYLOGINRESULT_H #include <QObject> #include <QSharedData> #include "transportableobject.h" #include "fault.h" #include "userinfo.h" #include "callbackcallertools.h" namespace MoodBox { class GetUserInfoByLoginResultData : public QSharedData { public: GetUserInfoByLoginResultData(); GetUserInfoByLoginResultData(UserInfo result); virtual ~GetUserInfoByLoginResultData(); UserInfo result; }; class GetUserInfoByLoginResult : public TransportableObject { public: GetUserInfoByLoginResult(); GetUserInfoByLoginResult(UserInfo result); virtual ~GetUserInfoByLoginResult(); protected: GetUserInfoByLoginResult(GetUserInfoByLoginResultData* dataRef) { this->d = dataRef; } public: // never use ___new_ in your code!!! static GetUserInfoByLoginResult* ___new_() { return new GetUserInfoByLoginResult(new GetUserInfoByLoginResultData()); } static GetUserInfoByLoginResult empty() { return GetUserInfoByLoginResult(new GetUserInfoByLoginResultData()); } virtual bool isNull() const { return !d; } virtual void resultCall(Callback callback, QVariant state); UserInfo getResult() const; void setResult(UserInfo value); static qint32 getRepresentedTypeId(); virtual qint32 getTypeId() const; virtual void writeProperties(PropertyWriter *writer); virtual PropertyReadResult readProperty(qint32 propertyId, qint32 typeId, PropertyReader *reader); private: QExplicitlySharedDataPointer<GetUserInfoByLoginResultData> d; }; class GetUserInfoByLoginResultCallbackCaller : public QObject { Q_OBJECT public: static void call(Callback &callback, QVariant state, UserInfo result) { GetUserInfoByLoginResultCallbackCaller caller; caller.callInternal(callback, state, Fault(), result); } static void call(Callback &callback, QVariant state, Fault fault) { GetUserInfoByLoginResultCallbackCaller caller; caller.callInternal(callback, state, fault, UserInfo()); } signals: void callbackSignal(QVariant state, Fault fault, UserInfo result); private: void callInternal(Callback &callback, QVariant state, Fault fault, UserInfo result) { if(connect(this, SIGNAL(callbackSignal(QVariant, Fault, UserInfo)), callback.target, callback.method)) { emit callbackSignal(state, fault, result); disconnect(); } else { CallbackCallerTools::onConnectFail("GetUserInfoByLoginResult", SIGNAL(callbackSignal(QVariant, Fault, UserInfo)), callback.method); } } }; } #endif // GETUSERINFOBYLOGINRESULT_H
fafae66fdecdff28b61e2e22c1fa243e8fd1d983
444a2443868fe7a72483b1a090c1312397a4c8de
/RateSource/PathGenerators/SingleFactorGMB.cpp
6716c91359cb5a947277b7508918f1a34f34f19c
[]
no_license
daveysj/sjd
e2dd2aeef3422ef54309dd3d67c7537ceea913c8
f48abae6f2e8fc91d27961b8567be3d8f0eb62d9
refs/heads/master
2021-01-10T12:51:33.786317
2018-06-25T14:54:50
2018-06-25T14:55:28
51,246,593
0
0
null
null
null
null
UTF-8
C++
false
false
11,544
cpp
SingleFactorGMB.cpp
#include "SingleFactorGMB.h" namespace sjd { /*====================================================================================== EconomicScenarioGenerator =======================================================================================*/ void EconomicScenarioGenerator::resetErrorMessages() { errorTracking->clearErrorMessages(); } vector<string> EconomicScenarioGenerator::getErrorMessages() { return errorTracking->getErrorMessages(); } string EconomicScenarioGenerator::getErrorMessageAsString() { return errorTracking->getErrorMessagesAsString(); } bool EconomicScenarioGenerator::isOK() { resetErrorMessages(); if (re == 0) { errorTracking->populateErrorMessage("Rates environment not set"); return false; } if (!re->isOK()) { errorTracking->populateErrorMessage(re->getErrorMessages()); } if ((simulationDates.size() > 0) && (simulationDates.front() < anchorDate)) { errorTracking->populateErrorMessage("Simulation dates before anchor date"); return false; } if ((simulationDates.size() > 0) && (!re->isInRange(simulationDates.back()))) { errorTracking->populateErrorMessage("Simulation dates after rate source end"); return false; } return !errorTracking->getHasErrors(); } Date EconomicScenarioGenerator::getAnchorDate() { return anchorDate; } void EconomicScenarioGenerator::setBaseRates(const boost::shared_ptr<RatesEnvironment> reInput) { re = reInput; anchorDate = re->getAnchorDate(); } boost::shared_ptr<RatesEnvironment> EconomicScenarioGenerator::getBaseRates() { return re; } bool EconomicScenarioGenerator::setSimulationDates(set<Date> simulationDatesSet) { simulationDates = vector<Date>(simulationDatesSet.begin(), simulationDatesSet.end()); numDates = simulationDates.size(); return true; } /*====================================================================================== SingleFactorEconomicScenarioGenerator =======================================================================================*/ SingleFactorEconomicScenarioGenerator::SingleFactorEconomicScenarioGenerator(const boost::shared_ptr<RatesEnvironment> re) : nd(0,1), rng((boost::uint32_t) time(0)), normalVariable(rng, nd) { errorTracking = boost::shared_ptr<sjdTools::ErrorTracking>(new sjdTools::ErrorTracking("SingleFactorEconomicScenarioGenerator")); setBaseRates(re); } void SingleFactorEconomicScenarioGenerator::setBaseRates(const boost::shared_ptr<RatesEnvironment> re) { EconomicScenarioGenerator::setBaseRates(re); frsDependsOnInterestRateDifferential = false; if (re->hasDRS()) { drs = boost::dynamic_pointer_cast<sjd::DeterministicDiscountRateSource>(re->getDRS()); } if (re->hasForeignDRS()) { foreigndrs = boost::dynamic_pointer_cast<sjd::DeterministicDiscountRateSource>(re->getForeignDRS()); } if (re->hasVRS()) { vrs = boost::dynamic_pointer_cast<sjd::DeterministicVolatilityRateSource>(re->getVRS()); } if (re->hasFRS()) { frs = boost::dynamic_pointer_cast<sjd::ForwardRateSourceStochastic>(re->getFRS()); boost::shared_ptr<sjd::UsesInterestRateDifferential> tmpFRS = boost::dynamic_pointer_cast<sjd::UsesInterestRateDifferential>(frs); if (tmpFRS != 0) { frsDependsOnInterestRateDifferential = true; } } if (re->hasFixingRS()) { fixingrs = boost::dynamic_pointer_cast<sjd::RollingFixingRateSource>(re->getFixingRS()); } } bool SingleFactorEconomicScenarioGenerator::isOK() { if (!EconomicScenarioGenerator::isOK()) { return false; } if (drs == 0) { errorTracking->populateErrorMessage( "Rates environment does not contain a discounting rate source that rolls deterministically"); } if (foreigndrs == 0 && (re->hasForeignDRS())) // foreign DRS may not be required { errorTracking->populateErrorMessage( "Rates environment does not contain a foreign discounting rate source that rolls deterministically"); } if (vrs == 0) { errorTracking->populateErrorMessage( "Rates environment does not contain a volatility rate source that rolls deterministically"); } if (frs == 0) { errorTracking->populateErrorMessage( "Rates environment does not contain a forward rate source that rolls stochastically"); } if (frsDependsOnInterestRateDifferential && foreigndrs == 0) { errorTracking->populateErrorMessage( "FRS requires a foreign interest rate source but rates environment does not contain one that rolls deterministically"); } if (re->hasFixingRS() && (fixingrs == 0)) { errorTracking->populateErrorMessage( "Rates environment does not contain a fixing rate source that rolls"); } return !errorTracking->getHasErrors(); } bool SingleFactorEconomicScenarioGenerator::setSimulationDates(set<Date> simulationDatesSet) { EconomicScenarioGenerator::setSimulationDates(simulationDatesSet); if (isOK()) { drs->setForwardValuationDates(simulationDatesSet); drss = drs->rollForward(); if (foreigndrs != 0) { foreigndrs->setForwardValuationDates(simulationDatesSet); foreigndrss = foreigndrs->rollForward(); } vrs->setForwardValuationDates(simulationDatesSet); vrss = vrs->rollForward(); frs->setForwardValuationDates(simulationDatesSet); // fill it with something randomNumbers = vector<double>(numDates, 0); frs->setRandomVariables(randomNumbers); frss = frs->rollForward(); fixingrss.clear(); vector<boost::shared_ptr<RatesEnvironment>> ratesPath; for (size_t i = 0; i < numDates; ++i) { boost::shared_ptr<RatesEnvironment> tmpRE = boost::shared_ptr<RatesEnvironment>( new RatesEnvironment(simulationDates[i])); tmpRE->setDRS(drss[i]); if (foreigndrs != 0) { tmpRE->setForeignDRS(foreigndrss[i]); if (frsDependsOnInterestRateDifferential) { updateFXForwardWithRolledDiscountRateSources(i); } } tmpRE->setFRS(frss[i]); tmpRE->setVRS(vrss[i]); if (re->hasFixingRS()) { allFixingDates = fixingrs->getFixingDatesFor(simulationDates); allFixingRates = vector<double>(allFixingDates.size(), 0); boost::shared_ptr<RollingFixingRateSource> rolledfixingrs = fixingrs->rollForward(simulationDates[i], allFixingDates, allFixingRates); fixingrss.push_back(rolledfixingrs); tmpRE->setFixingRS(rolledfixingrs); } ratesPath.push_back(tmpRE); } path = boost::shared_ptr<Path>(new Path(ratesPath)); return true; } return false; } void SingleFactorEconomicScenarioGenerator::setRandomSeed(long seedInput) { seed = seedInput; } boost::shared_ptr<Path> SingleFactorEconomicScenarioGenerator::getConfidenceInterval(double confidenceInterval) { boost::math::normal dist(0.0, 1.0); double epsi = quantile(dist, confidenceInterval); frs->setRandomVariables(vector<double>(numDates, epsi)); if (fixingrs == 0) { for (size_t i = 0; i < numDates; ++i) { frss[i] = frs->rollForward(simulationDates[i], epsi); if (frsDependsOnInterestRateDifferential) { updateFXForwardWithRolledDiscountRateSources(i); } path->getRatesEnvironment(i)->setFRS(frss[i]); } } else { vector<Date>::iterator endIt; for (size_t i = 0; i < numDates; ++i) { endIt = upper_bound(allFixingDates.begin(), allFixingDates.end(), simulationDates[i]); vector<Date> datesSubset = vector<Date>(allFixingDates.begin(), endIt); vector<double> rateSets = vector<double>(datesSubset.size()); frss[i] = frs->rollForward(simulationDates[i], epsi, datesSubset, rateSets); if (frsDependsOnInterestRateDifferential) { updateFXForwardWithRolledDiscountRateSources(i); } fixingrss[i]->updateAppedededRates(rateSets); path->getRatesEnvironment(i)->setFRS(frss[i]); path->getRatesEnvironment(i)->setFixingRS(fixingrss[i]); } } return path; } boost::shared_ptr<Path> SingleFactorEconomicScenarioGenerator::getRandomPath() { for (size_t i = 0; i < numDates; ++i) { randomNumbers[i] = normalVariable(); } return getPathForRandomNumber(randomNumbers); } boost::shared_ptr<Path> SingleFactorEconomicScenarioGenerator::getAntitheticPath() { for (size_t i = 0; i < numDates; ++i) { randomNumbers[i] = -randomNumbers[i]; } return getPathForRandomNumber(randomNumbers); } boost::shared_ptr<Path> SingleFactorEconomicScenarioGenerator::getPathForRandomNumber(vector<double> randomNumbers) { frs->setRandomVariables(randomNumbers); if (fixingrs == 0) { frss = frs->rollForward(); } else { frss = frs->rollForward(allFixingDates, allFixingRates); for (size_t i = 0; i < fixingrss.size(); ++i) { fixingrss[i]->updateAppedededRates(allFixingRates); } } for (size_t i = 0; i < numDates; ++i) { path->getRatesEnvironment(i)->setFRS(frss[i]); } return path; } boost::shared_ptr<Path> SingleFactorEconomicScenarioGenerator::getPathForSpot(vector<double> spot) { vector<double> impliedRV = frs->getImpliedRandomNumbers(spot); return getPathForRandomNumber(impliedRV); } void SingleFactorEconomicScenarioGenerator::updateFXForwardWithRolledDiscountRateSources(size_t stepNumber) { boost::shared_ptr<sjd::UsesInterestRateDifferential> tmpFRS = boost::dynamic_pointer_cast<sjd::UsesInterestRateDifferential>(frss[stepNumber]); if (tmpFRS != 0) { tmpFRS->setRateSources(drss[stepNumber], foreigndrss[stepNumber]); } } }
e469b0bdefef71de11cb609582762f144011f835
d17a2f15fe3a7697a794cf9dc0d5e291f8cb0022
/main.cpp
2f1804125194d9ef04484467acc149e4d71fca59
[]
no_license
sidpendyala/DesignUnit12021
682e0415c9214a1aaa89c538985e89b9aa704e42
37c7750c986db5de89519754b9c10448b75efb09
refs/heads/main
2023-09-02T00:53:08.142165
2021-11-08T08:54:56
2021-11-08T08:54:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
923
cpp
main.cpp
#include <Arduino.h> //Ultrasound sensor pins const int trigPin = 9; const int echoPin = 10; //These are required to measure distance long duration; int distanceInch; //This happens in the beginning of the power it has, it defines the pins and the power given. void setup() { Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(11,OUTPUT); pinMode(12,OUTPUT); } //This part of the code happens again and again in a loop. It defines the function void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distanceInch = duration*0.0133/2; Serial.println("Distance: "); Serial.println(distanceInch); if(distanceInch < 72) { digitalWrite(11,HIGH); digitalWrite(12,HIGH); } else { digitalWrite(11,LOW); digitalWrite(12,LOW); } }
a28f1f6013ff0b971739e46133eb99ca52faf3d1
95036e503519f476e653b51209669f156ae6a331
/longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters2.cpp
7a73e0de40bbdef4b8ad8100bd3d038175c8c6ed
[]
no_license
jingminglake/Leetcode
c414ff3385c1c6e0ccf17fb51d89bca3e0648afe
0aa509d74e20bc73a015ebfd966fd3b44aac1f66
refs/heads/master
2023-02-19T15:42:28.880314
2023-02-14T07:47:52
2023-02-14T07:47:52
83,025,474
18
4
null
null
null
null
UTF-8
C++
false
false
926
cpp
longestSubstringWithoutRepeatingCharacters2.cpp
#include <iostream> #include <unordered_map> #include <algorithm> using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map<char, int> hm; int maxLength = 0; int n = s.length(); int i = 0, j = 0; while (j < n) { unordered_map<char, int>::iterator it = hm.find(s[j]); if ( it != hm.end() ) { //find! if (i <= it->second) { //cout << "-----1-1----" << endl; i = it->second + 1; } it->second = j; }else { //cout << s[j] << "---1---" << endl; hm.insert(make_pair<char, int>((char)s[j], (int)j)); } //if (j - i + 1 > maxLength) // maxLength = j - i + 1; maxLength = max(maxLength, j - i + 1); j++; } // cout << (int)hm.size() << "---"<< endl; return maxLength; } }; int main() { string s; cin >> s; Solution sl; cout << sl.lengthOfLongestSubstring(s) << endl; }
f4628be12e3ab51dedc77dfd1d3f8b4275555906
f459a74af9a4b6fe37815987e3a007ba243e9ebc
/Tfp.cpp
76795d06eb60b48584890f4c118e96a5cfe30522
[]
no_license
stiltskincode/lemur-game
6c80856c9a7a2a852ec4973d7a1b78b127e51216
348cb0d3f99576c61ed7d63aa8f00e62688fb70e
refs/heads/master
2021-01-10T03:05:03.312223
2016-02-04T15:29:58
2016-02-04T15:29:58
51,084,796
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
5,433
cpp
Tfp.cpp
#include "Tfp.h" using namespace std; Tfp::Tfp() { path = ""; } Tfp::Tfp(std::string archFileName) { open(archFileName); } Tfp::Tfp(string archFileName, string path) { open(archFileName); this->path = path; } Tfp::~Tfp() { } bool Tfp::compress(string archFileName, string *fileNamesToCompress, unsigned int num) { fstream f; int *length = new int [num]; file.open(archFileName.c_str(),ios_base::out|ios_base::binary); file.write("TFP! ",5); file.write((char*)&num,sizeof(int)); file.write(" ", sizeof(char)); if(!file) { writeErr("Nie mona utworyżyć pliku archiwum."); file.close(); return false; } for(unsigned int i=0;i<num;i++) { f.open(fileNamesToCompress[i].c_str(),ios_base::in|ios_base::binary); if(!f) { writeErr("Nie można odnaleść pliku do dodania lub plik jest aktualnie używany."); f.close(); return false; } f.seekg( 0, ios::end ); file.write(fileNamesToCompress[i].c_str(), fileNamesToCompress[i].length()); file.write(" ", sizeof(char)); int tellg = f.tellg(); file.write((char*)&tellg, sizeof(int)); length[i] = tellg; f.seekg( 0, ios::beg ); f.clear(); f.close(); } for(unsigned int i=0;i<num;i++) { char *buffer=NULL; buffer = new char[length[i]]; ifstream in(fileNamesToCompress[i].c_str(),ios::binary); in.read(buffer,length[i]); file.write(buffer,length[i]); in.close(); delete buffer; buffer=NULL; } file.close(); return true; } bool Tfp::open(string archFileName) { string header; header = ""; file.open(archFileName.c_str(),ios_base::in|ios_base::binary); if(!file) { writeErr("Nie można odnaleść pliku lub plik jest aktualnie używany."); file.close(); return false; } file>>header; file.get(); if(header.compare("TFP!") < 0) { writeErr("Plik nie jest poprawnym archiwum TFP!"); file.close(); return false; } headerSize=0; file.read((char*)&numFiles,sizeof(int)); for(unsigned int i=0;i<numFiles;i++) { file>>names[i]; file.get(); file.read((char*)&fileSizes[i],sizeof(int)); headerSize+=names[i].length()+5; } return true; } bool Tfp::close() { file.close(); return true; } bool Tfp::decompress(unsigned int id) { ofstream out; char *outBuffer=NULL; outBuffer = new char[getFileSize(id)]; string extractPath; if((path.substr(path.length()-1,1) == "/")) { extractPath=path+names[id]; out.open(extractPath.c_str(),ios_base::binary); } else { extractPath=path+"/"+names[id]; out.open(extractPath.c_str(),ios_base::binary); } getFile(id).read(outBuffer,getFileSize(id)); tempNames[id] = names[id]; out.write(outBuffer,getFileSize(id)); out.close(); delete outBuffer; outBuffer = NULL; return true; } void Tfp::setExtractPath(string path) { this->path=path; } string Tfp::getExtractPath() { return path; } bool Tfp::decompress(string fileName) { ofstream out; char *outBuffer=NULL; outBuffer = new char[getFileSize(fileName)]; string extractPath; if((path.substr(path.length()-1,1) == "/")) { extractPath=path+fileName; out.open(extractPath.c_str(),ios_base::binary); } else { extractPath=path+"/"+fileName; out.open(extractPath.c_str(),ios_base::binary); } getFile(fileName).read(outBuffer,getFileSize(fileName)); tempNames[getFileId(fileName)] = fileName; out.write(outBuffer,getFileSize(fileName)); out.close(); delete outBuffer; outBuffer = NULL; return true; } fstream &Tfp::getFile(string fileName) { for(unsigned int id=0;id<numFiles;id++) { if(names[id].compare(fileName.c_str()) == 0) { unsigned int size=0; for(unsigned int i=0;i<id;i++) size+=fileSizes[i]; file.seekg(10+headerSize+size); break; } } return file; } fstream &Tfp::getFile(unsigned int id) { unsigned int size=0; for(unsigned int i=0;i<id;i++) size+=fileSizes[i]; file.seekg(10+headerSize+size); return file; } unsigned int Tfp::getFileSize(string fileName) { for(unsigned int id=0;id<numFiles;id++) { if(names[id].compare(fileName.c_str()) == 0) { return fileSizes[id]; break; } } return 0; } unsigned int Tfp::getFileSize(unsigned int id) { return fileSizes[id]; } unsigned int Tfp::getFileId(string fileName) { for(unsigned int id=0;id<numFiles;id++) { if(names[id].compare(fileName.c_str()) == 0) { return id; break; } } return 0; } string* Tfp::getFileNamesFromTfp(string fileName) { string header; header = ""; ifstream f; f.open(fileName.c_str(),ios_base::in|ios_base::binary); if(!f) { writeErr("Nie można odnaleść pliku lub plik jest aktualnie używany."); f.close(); return false; } f>>header; f.get(); if(header.compare("TFP!") < 0) { writeErr("Plik nie jest poprawnym archiwum TFP!"); f.close(); return false; } headerSize=0; f.read((char*)&numFiles,sizeof(int)); for(unsigned int i=0;i<numFiles;i++) f>>names[i]; f.get(); f.close(); return names; } void Tfp::deteleDecompressedFiles() { string delPath; for(unsigned int i=0;i<numFiles;i++) { if(tempNames[i].compare("") != 0) { if((path.substr(path.length()-1,1) == "/")) delPath = path+tempNames[i]; else delPath = path+"/"+tempNames[i]; if(remove(delPath.c_str()) != 0) { string err = "Nie można usunąć pliku "+delPath; writeErr(err); } } } }
338fe9d7659cdde511c3dbdd2bae2ba96bb80186
5baf53d52f1acab7d177489473d2a3ec78fe8744
/ESP8266Demo/ArduinoSlave20.2_LCD_Servo/ArduinoSlave20.2_LCD_Servo.ino
fd1cb6dff78e0db66601e1ff6e811b7143c83e1e
[]
no_license
fukuda-ryoya/3DPrinterSTLFiles
3bc533e43d9e52331f1fa411f570d484e1807ef2
ee4d8c30b15ad710205c4ee732356abcfdfb7858
refs/heads/master
2022-03-20T22:30:47.189476
2017-02-01T20:46:53
2017-02-01T20:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,508
ino
ArduinoSlave20.2_LCD_Servo.ino
#include <Servo.h> #include <Wire.h> #include "U8glib.h" #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif #define backlight_pin 9 U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6); // CLK=8, DIN=4, CE=7, DC=5, RST=6 #define I2CAddressESPWifi 6 #define ledPin 13 #define numberOfBytes 15 // number of bytes expected by ESP8266 // Which pin on the Arduino is connected to the NeoPixels? // On a Trinket or Gemma we suggest changing this to 1 #define PIN 2 // How many NeoPixels are attached to the Arduino? #define NUMPIXELS 1 byte r = 0; byte g = 0; byte b = 0; byte angle = 0; // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals. // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest // example for more information on possible values. Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); // buffer for return-message: char charBuffer[] = "012345678901234"; // initilize buffer with 15 bytes! char currentText[] = ""; // text to display on LCD // counter to have something going and see changing values.. for testing purpose unsigned long counter = 0; Servo myservo; // create servo object to control a servo void setup() { Wire.begin(I2CAddressESPWifi); // join I2Cbus as slave with identified address Wire.onReceive(receiveEvent); // register a function to be called when slave receive a transmission from master// Wire.onRequest(requestEvent); // register a function when master request data from this slave device// Serial.begin(9600); //set serial baud rate // say hello to internal LED pinMode(ledPin, OUTPUT); flashLEDMany(); pixels.begin(); // This initializes the NeoPixel library. r = 10; g = 0; b = 0; updateNeoPixel(); // Nokia-LCD 5110 analogWrite(backlight_pin, 50); /* Set the Backlight intensity */ displayText("ready!"); myservo.attach(11); // attaches the servo on pin 11 to the servo object angle = 100; myservo.write(angle); Serial.println("Hello, ArduinoSlave Version 11.9 with RGB-LED here!"); } void loop() { // nothing really happens in main-loop: // just increment the couter delay(250); counter++; if (counter > 4294967294) { counter = 0; } updateNeoPixel(); updateServo(); } // when slave receives string from master, trigger this event. void receiveEvent(int howMany) { String message = ""; while ( Wire.available() ) // execute repeatedly and read all bytes in the data packet from master// { char c = Wire.read(); // receive data from master and assign it to char c message += c; } displayText(message); updatePixelValues(message); updateServoValues(message); if (isGetServo(message)) { pushMessageToCharBuffer("Servo-angle:" + getStringFixLengthFromUnsignedLong(numberOfBytes - 12, angle), charBuffer); } else { // preparing the messageBuffer for the answer to ESP8266 when requested by requestEvent() pushMessageToCharBuffer("OK" + getStringFixLengthFromUnsignedLong(numberOfBytes - 2, counter), charBuffer); } } // trigger this event when master requests data from slave, void requestEvent() { // IMPORTANT! this code needs to be executed quickly, so do not write any other code in here! // buffer containing message (answer) must have a fixed length of 15 because ESP expects so... Wire.write(charBuffer); } // flash the Onboard-LED to show a message is received void flashLEDOnce() { digitalWrite(ledPin, HIGH); delay(25); digitalWrite(ledPin, LOW); } // flash the Onboard-LED to show Arduino is ready! void flashLEDMany() { for (int i = 0; i < 15; i++) { digitalWrite(ledPin, HIGH); delay(10); digitalWrite(ledPin, LOW); delay(20); } } void updateServo() { myservo.write(angle); } void updateNeoPixel() { pixels.setPixelColor(0, pixels.Color(r, g, b)); pixels.show(); // This sends the updated pixel color to the hardware. } void updatePixelValues(String s) { if (s.startsWith("/pixel", 0)) { int indexStart = s.indexOf("r<"); if (indexStart > 0) { r = s.substring(indexStart + 2 , indexStart + 5).toInt(); } indexStart = s.indexOf("g<"); if (indexStart > 0) { g = s.substring(indexStart + 2 , indexStart + 5).toInt(); } indexStart = s.indexOf("b<"); if (indexStart > 0) { b = s.substring(indexStart + 2 , indexStart + 5).toInt(); } } } bool isGetServo(String s) { if (s.startsWith("/getServo", 0)) { return 1; } return 0; } void updateServoValues(String s) { if (s.startsWith("/servo", 0)) { int indexStart = s.indexOf("v<"); if (indexStart > 0) { angle = s.substring(indexStart + 2 , indexStart + 5).toInt(); Serial.println("new angle: " + String(angle)); } } } // convert message to char-buffer void pushMessageToCharBuffer(String s, char *charArray) { unsigned int len = s.length() + 1; // one extra for null-terminator s.toCharArray(charArray, len); } // fill up string with hashes in front of value String getStringFixLengthFromUnsignedLong(int stringSize, unsigned long value) { String s = String(value); String f = ""; int spacers = stringSize - s.length(); for (int i = 0; i < spacers; i++) { f += "#"; } return (f + s).substring(0, stringSize); } void draw(String s) { const int charactersPerLine = 14; const int maxLines = 5; // initalize with 14 spaces char line[maxLines][charactersPerLine + 1] = {" ", " ", " ", " ", " "}; int i = 0; while (s.length() > charactersPerLine && i < (maxLines - 1)) { if (s.length() >= charactersPerLine) { pushMessageToCharBuffer(s.substring(0, charactersPerLine), line[i]); // cut off 14 characters s = s.substring(charactersPerLine, s.length()); } i++; } if (s.length() >= charactersPerLine) { pushMessageToCharBuffer(s.substring(0, charactersPerLine), line[i]); } else if (s.length() > 0) { pushMessageToCharBuffer(s, line[i]); } u8g.setFont(u8g_font_profont11); // select font const int offset = 8; for (int i = 0; i < (maxLines); i++) { u8g.drawStr(0, offset + i * 10, line[i]); // text-line n } } void displayText(String text) { // Nokia-LCD 5110 show on display u8g.firstPage(); do { draw(text); } while ( u8g.nextPage() ); }
77f92c5e3fb493a5e4a5cc87a32827d6d3e0cb26
34c3b4449c61862a71ac8967cd271670762cf863
/include/vectors.hpp
89ffdeea3fc1f00d121e08739fdb0ef27c030ce9
[]
no_license
alu0101102726/DAA_P9
1151cd5ec8106ba1c9e54499fb6061207b42d13c
b7b10f31606ccc897356d339b4f191c9190b56bd
refs/heads/master
2022-08-29T16:56:49.960232
2020-05-18T21:23:27
2020-05-18T21:23:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
773
hpp
vectors.hpp
#pragma once #include <vector> #include <string> #include <cmath> #include "file.hpp" /** * @brief Esta clase representa la información que se ha obtenido * del fichero */ class Vectors { private: std::vector < std::vector < float > > data; int dimension; public: Vectors() {} Vectors(std::string fileName); Vectors(std::vector < std::vector < float > > otherVect); ~Vectors() {}; int getDimension(); float getDataValue(int currentElement, int K); std::vector < std::vector < float > > getData(); friend std::ostream& operator <<(std::ostream& os, Vectors currentData); int getSize(); int getElementSize(int position); float getEuclideanDistance(int firstVect, int secondVect); };
b98fc98c6e66ef755ac5d30022bad21b9884855f
7915e215d09d0d792093b2deff2433be802990df
/vicky_counter/vicky_counter.ino
26300c1c66668dfd5256ec581c869bb8cfc39b6e
[]
no_license
parthishere/My-Arduino-Projects
1ea33d3967b40dd617f264638614c3fa658886f3
7f4dfc376ef25d63452c51abb8fe5b93c600e588
refs/heads/master
2023-05-24T06:28:35.023127
2021-06-18T17:03:19
2021-06-18T17:03:19
378,215,886
0
0
null
null
null
null
UTF-8
C++
false
false
438
ino
vicky_counter.ino
int l1=13, l2=12, l3=11, l4=10, l5=9, sw=8, count=0; void setup() { // put your setup code here, to run once: pinMode(l1, OUTPUT); pinMode(l2, OUTPUT); pinMode(l3, OUTPUT); pinMode(l4, OUTPUT); pinMode(l5, OUTPUT); pinMode(sw, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int i = digitalRead(sw); if(i == 1){ delay(250); count++; } Serial.println(count); }
610f2e328b7fbc427cdf009f7658d848d7c5d624
993eb877c2a72e7d5090d8e61a9fc7f9eb9c6f0d
/DeadReckonging/spline_temp/.ipynb_checkpoints/main-checkpoint.cpp
6a0bf396776f16afe26d2bad0ba0f30dd5ffcc9b
[]
no_license
sjlee1218/CBNU_SCRC_2018_winter
e0d185f710c9db280759d04ecfbd694ee17f6457
024f16e137971ccb946663984c8beb7da11acc37
refs/heads/master
2020-04-15T08:54:08.621097
2019-03-10T12:21:31
2019-03-10T12:21:31
164,531,368
1
0
null
null
null
null
UTF-8
C++
false
false
2,792
cpp
main-checkpoint.cpp
#include <iostream> #include "CatmullRom.h" #include <fstream> #include <string.h> //void demo_bezier(); //void demo_bspline(); void demo_catmullrom(); using namespace std; int main(int argc,char** argv) { //demo_bezier(); //demo_bspline(); demo_catmullrom(); } /* void demo_bezier() { Curve* curve = new Bezier(); curve->set_steps(100); // generate 100 interpolate points between the last 4 way points curve->add_way_point(Vector(1, 1, 0)); curve->add_way_point(Vector(2, 3, 0)); curve->add_way_point(Vector(3, 2, 0)); curve->add_way_point(Vector(4, 6, 0)); std::cout << "nodes: " << curve->node_count() << std::endl; std::cout << "total length: " << curve->total_length() << std::endl; for (int i = 0; i < curve->node_count(); ++i) { std::cout << "node #" << i << ": " << curve->node(i).toString() << " (length so far: " << curve->length_from_starting_point(i) << ")" << std::endl; } delete curve; } void demo_bspline() { Curve* curve = new BSpline(); curve->set_steps(100); // generate 100 interpolate points between the last 4 way points curve->add_way_point(Vector(1, 1, 0)); curve->add_way_point(Vector(2, 3, 0)); curve->add_way_point(Vector(3, 2, 0)); curve->add_way_point(Vector(4, 6, 0)); std::cout << "nodes: " << curve->node_count() << std::endl; std::cout << "total length: " << curve->total_length() << std::endl; for (int i = 0; i < curve->node_count(); ++i) { std::cout << "node #" << i << ": " << curve->node(i).toString() << " (length so far: " << curve->length_from_starting_point(i) << ")" << std::endl; } delete curve; } */ void demo_catmullrom() { Curve* curve = new CatmullRom(); curve->set_steps(1); // generate 100 interpolate points between the last 4 way points /* curve->add_way_point(Vector(1, 1, 0)); curve->add_way_point(Vector(2, 3, 0)); curve->add_way_point(Vector(3, 2, 0)); curve->add_way_point(Vector(4, 6, 0)); */ ifstream in("/Users/leeseungjoon/Desktop/GitHub_SJLEE/CBNU_SCRC_2018_winter/DeadReckonging/spline_temp/temp_only_lat_lon.txt"); if (!in.is_open()){ cout<<"input error!"<<endl; return; } char inputString[30]; while(!in.eof()){ in.getline(inputString, 30); char *ptr = strtok(inputString, "\t"); float lon=(float)atoi(ptr)/1000; ptr = strtok(NULL, "\t"); float lat=(float)atoi(ptr)/1000; curve->add_way_point(Vector(lon, lat, 0)); cout<< "original node: "<<lon<<'\t'<<lat<<endl; } std::cout << "nodes: " << curve->node_count() << std::endl; std::cout << "total length: " << curve->total_length() << std::endl; for (int i = 0; i < curve->node_count(); ++i) { std::cout << "node #" << i << ": " << curve->node(i).toString() << " (length so far: " << curve->length_from_starting_point(i) << ")" << std::endl; } delete curve; }
d9bd5681e78a83d2cef2695c31f743443d945eb3
8776e5e32be27c16c7f8cd2a9a4259b6fb7a012b
/im_client/Mini_Client/MINI139_SRC/Im/FloorPageRecent.h
cdcddd3f1ba4bd2057af94bfe2f4980934d3ff9f
[]
no_license
736229999/im
970b9754da2e15fd5cdaaed6ba189e7c497e15e3
dc00c52e77a99fae28df9dba8366e31b578a7831
refs/heads/master
2021-01-15T11:11:56.737294
2017-06-14T07:56:44
2017-06-14T07:56:44
null
0
0
null
null
null
null
GB18030
C++
false
false
762
h
FloorPageRecent.h
#pragma once #include "customlistctrl.h" // CFloorPageRecent 对话框 class CFloorPageRecent : public CDialog { DECLARE_DYNAMIC(CFloorPageRecent) public: CFloorPageRecent(CWnd* pParent = NULL); // 标准构造函数 virtual ~CFloorPageRecent(); // 对话框数据 enum { IDD = IDD_FLOOR_RECENT }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 virtual void OnOK() {} virtual void OnCancel() {} virtual BOOL OnInitDialog(); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnPaint(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnBnClickedButtonClear(); DECLARE_MESSAGE_MAP() protected: // CFlatButton m_btnClear; CRecentListCtrl m_wndRecentList; };
b9197edf18024c342a41399475985cd82eceedc0
f7efc7e844b064ed5887e945b32629538c8b4baf
/assignment3-DiceRollGame.cpp
a43cbe5c328d8a0469062ba395270afbe4804939
[]
no_license
tayrembos/CPP
51d1b17c6be2876fbadc5558cabc3d8807bd0354
bac2075dbdfb0994d287f3cf3e0a025ac2bf7cad
refs/heads/master
2022-08-04T06:53:57.104012
2020-05-29T01:07:27
2020-05-29T01:07:27
267,678,963
1
0
null
null
null
null
UTF-8
C++
false
false
2,857
cpp
assignment3-DiceRollGame.cpp
#include <iostream> #include <cstdlib> using std::cout; using std::cin; using std::endl; int dieRoll(); int humanTurn(int); int computerTurn(int); int main() { int humanTotalScore = 0; int computerTotalScore = 0; // loop until someone scores at least 100 do { humanTotalScore = humanTotalScore + humanTurn(humanTotalScore); // add the score from a new turn to the running total cout << "Your total score so far is " << humanTotalScore << "." << endl; if(humanTotalScore >= 100) { cout << "You win!"; break; } computerTotalScore = computerTotalScore + computerTurn(computerTotalScore); // add the score from current turn to total cout << "The computer's total score so far is " << computerTotalScore << "." << endl; if(computerTotalScore >= 100) { cout << "Computer wins!"; break; } } // keeps running while both players have a total score under 100 while(humanTotalScore < 100 && computerTotalScore < 100); return 0; } // simulate rolling of die int dieRoll() { return(rand() % 6) + 1; // gives range of 0-5 with plus 1 to avoid 0 returns 1-6 } int humanTurn(int humanTotalScore) { int thisTurnScore = 0; int score = 0; char rollOrHold; char rollDice; cout << "It's your turn!" << endl; // loop as long as user chooses Roll Again or a 1 ends the turn do { score = dieRoll(); //roll the die if(score == 1) { cout << "You rolled a 1. End of turn." << endl; // rolling 1 ends the user's turn break; } thisTurnScore = thisTurnScore + score; // total current score for user cout << "You rolled a " << score << "." << endl; cout << "Your score this round is: " << thisTurnScore << "." << endl; cout << "Press 'h' to hold or 'r' to roll again. " << endl; cin >> rollOrHold; } while(rollOrHold == 'r' || rollOrHold == 'R'); if(rollOrHold == 'h' || rollOrHold == 'H') return thisTurnScore; // finish turn and return total current user score if hold is selected return 0; } int computerTurn(int computerTotalScore) { int thisTurnScore = 0; int score = 0; // loop to keep going as long as the CPU score for this turn is less than 20 cout << "It's the computer's turn!" << endl; do { score = dieRoll(); // roll the die if(score == 1) // roll of 1 ends turn { cout << "The computer rolled a 1. End of turn." << endl; break; } thisTurnScore = thisTurnScore + score; // total current score for this turn for the computer cout << "The computer rolled a " << score << ". Score so far this turn is " << thisTurnScore << "." << endl; } while(thisTurnScore < 20); // finish turn and return total current score if the computer scored >= 20 if(thisTurnScore >= 20) // The computer holds if score is >=20 { cout << "CPU holds." << endl; return thisTurnScore; } return 0; }
cf81af98a000757979581448bff95c79b4144230
63b780d4f90e6c7c051d516bf380f596809161a1
/FreeViewer/src/mark/ModelStyleWidget.h
7147fd50789b8f6eb4b49aebd285f8eeb3378652
[]
no_license
hewuhun/OSG
44f4a0665b4a20756303be21e71f0e026e384486
cfea9a84711ed29c0ca0d0bfec633ec41d8b8cec
refs/heads/master
2022-09-05T00:44:54.244525
2020-05-26T14:44:03
2020-05-26T14:44:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,256
h
ModelStyleWidget.h
/************************************************************************************************** * @file ModelStyleWidget.h * @note 模型属性窗口 * @author g00034 * @date 2017.02.20 **************************************************************************************************/ #ifndef MODEL_TAB_WIDGET_H_12 #define MODEL_TAB_WIDGET_H_12 #include <mark/BaseStyleWidget.h> #include <mark/Common.h> #include <FeExtNode/ExLodModelNode.h> #include <FeShell/SystemService.h> #include "ui_ModelStyleWidget.h" namespace FreeViewer { /** * @class CModelStyleWidget * @brief 模型属性窗口类 * @author g00034 */ class CModelStyleWidget : public CBaseStyleWidget { Q_OBJECT public: /** * @note 构造和析构函数 */ CModelStyleWidget(FeShell::CSystemService* pSystemService, FeExtNode::CExLodModelNode *pModelNode, bool bCreate, QWidget *parent = 0); ~CModelStyleWidget(); /** * @brief 拒绝修改属性信息 * @return bool */ virtual bool Reject(); private: /** * @note 角度设置 */ void SetAngle(double dAngle); double GetAngle()const; bool GetAngle(double& dAngle)const; /** * @note 大小设置 */ void SetScale(double dScale); double GetScale()const; bool GetScale(double& dScale)const; /** * @note 位置设置 */ void SetCenture(const osg::Vec3& centure); osg::Vec3 GetCenture()const; bool GetCenture(osg::Vec3& vec)const; protected: void InitTab(); //初始化服务界面 void InitService(); protected slots: /** * @note 模型选择槽函数 */ void SlotSimplePath(bool); void SlotServicePath(int); /** * @note 模型可视范围槽函数 */ void SlotSimpleLow(double); void SlotSimpleHigh(double); void SlotServiceLow(double); void SlotServiceHigh(double); /** * @note 模型位置槽函数 */ void SlotLongChanged(double); void SlotHeightChanged( double dLong); void SlotLatChanged( double dLong); /** * @note 模型缩放槽函数 */ void SlotScaleChanged( double dLong); /** * @note 模型旋转槽函数 */ void SlotZAngleChanged( double dLong); void SlotYAngleChanged( double dLong); void SlotXAngleChanged( double dLong); /** * @note 模型路径槽函数 */ void SlotSimplePathChanged(const QString&); void SlotServicePathChanged(const QString&); /** * @note 服务模型链接槽函数 */ void SlotServicePathLinked(); /** * @note SDK 事件处理槽函数 */ virtual void SlotSDKEventHappend(unsigned int); /** * @note radio切换槽函数 */ void SLotLocalRadioClicked(); void SLotServiceRadioClicked(); /** * @note 服务地址栏被点击 */ void SlotUrlClicked(); /** * @note 服务地址栏丢失焦点 */ void SlotUrlEditFinished(); private: Ui::model_style_widget ui; bool m_bCreate; bool m_bServicePathChanged; /// 显示范围 double dSimpleLow; double dSimpleHigh; double dNormalLow; double dNormalHigh; double dBestLow; double dBestHigh; double dServiceLow; double dServiceHigh; /// 模型节点 FeExtNode::CExLodModelNode * m_pModelNode; /// 系统服务对象 osg::observer_ptr<FeShell::CSystemService> m_opSystemService; ///初始值 private: /// 整个节点的属性 FeExtNode::CExLodModelNodeOption m_markOpt; /// 各个分级模型的属性 typedef struct ModelInfo { FeExtNode::CExLodModelGroup::LodNodeInfo lodNodeInfo; FeExtNode::CExLodNodeOption lodNodeOpt; ModelInfo(){} ModelInfo(const FeExtNode::CExLodModelGroup::LodNodeInfo& info) { lodNodeInfo = info; if(lodNodeInfo.node.valid()) { lodNodeOpt = *(lodNodeInfo.node->GetOption()); } } }ModelInfo; std::map<int, ModelInfo> m_mapModelInfo; }; } #endif // MODEL_TAB_WIDGET_H_12
4dc118ae6d87d43746b6405c0d347db8703c5582
6a2f5f466d8d9f445599c706166ce91dd6aa86a4
/(7 kyu) Mumbling/(7 kyu) Mumbling.cpp
c7df030879c56882948c6078e0a47d86a8b867da
[ "MIT" ]
permissive
novsunheng/codewars
04fe3390df340d82155805fc94cc35cef2e178ed
c54b1d822356889b91587b088d02ca0bd3d8dc9e
refs/heads/master
2020-05-29T15:30:34.152366
2019-05-20T09:23:36
2019-05-20T09:23:36
189,223,993
1
0
MIT
2019-05-29T12:46:46
2019-05-29T12:46:46
null
UTF-8
C++
false
false
1,002
cpp
(7 kyu) Mumbling.cpp
#include <string> #include <cctype> // #1 // class Accumul // { // public: // static std::string accum(const std::string &s) // { // std::string res; // for (int i = 0; i < s.length(); i++) // { // std::string word; // for (int j = 0; j <= i; j++) // if (j == 0) // word += std::toupper(s[i]); // else // word += std::tolower(s[i]); // res += word; // if (i < s.length() - 1) // res += "-"; // } // return res; // } // }; // #2 class Accumul { public: static std::string accum(const std::string &s) { std::string result; for (int i = 0; i < s.length(); i++) { result.append("-"); result.append(std::string(1, toupper(s[i]))); result.append(std::string(i, tolower(s[i]))); } return result.substr(1, result.length()); } };
4468f184d8e48538891bdf88bbb8d105dd5c8316
952a0362fbb572133f60da919526f73519e3b339
/problem-7/problem-7.cpp
ab3d84e6a2b02bfdadf8769a299ee45b008d75da
[ "MIT" ]
permissive
Tariod/DS-problems
40d8b50be23e772486b01e14933b6c46256fc881
0b43f80de9e2f1955adf7227b639df0b927ae949
refs/heads/master
2020-03-13T04:12:27.479377
2018-05-16T16:17:45
2018-05-16T16:17:45
130,958,791
0
0
null
null
null
null
UTF-8
C++
false
false
1,195
cpp
problem-7.cpp
#include <iostream> #include <string> #include <ctime> #include "../binary-tree/BinaryTree.h" using namespace std; int randNumber(); int main() { srand(time(NULL)); BinaryTree *tree; int counter = 0; string value; cout << "Enter the value of the root:" << endl; getline(cin, value); if(!value.empty()) tree = new BinaryTree(stoi(value)); else tree = new BinaryTree(randNumber()); counter++; while (true) { cout << "Q to stop" << endl; getline(cin, value); if("Q" == value || value.empty()) break; counter++; tree->insert(stoi(value)); } for(;counter < 14; counter++) tree->insert(randNumber()); cout << "tree" << endl; tree->printTree(); cout << "Remove composite numbers:" << endl; int compositeNumbers[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; for(int i = 0; i < 25; i++) tree->findAddRemove(compositeNumbers[i]); cout << "tree" << endl; tree->printTree(); delete tree; return 0; } int randNumber() { return -99 + rand() % 199; };
59602e6957a6069807236357bebecfc2806d1b79
a95d5b833646071be2ae864067e7e797dcaeba1b
/compulsory/Reception.cpp
e2d3628419b8345b87df1393d4ebd967969a37f8
[]
no_license
mihanloko/patterns
ff1350353ec0b6f400de77e11e6da6da2e0be8af
ca48546c863c1497228b66fda14c2309eaad7a41
refs/heads/master
2020-07-30T05:15:13.680704
2020-01-07T15:31:09
2020-01-07T15:31:09
210,099,062
1
0
null
2020-01-07T15:31:11
2019-09-22T06:06:35
C++
UTF-8
C++
false
false
299
cpp
Reception.cpp
// // Created by mikhail on 12.11.2019. // #include "Reception.h" Reception::Reception(int priority) : CompulsoryService(priority) { expert = InformationExpert::getInstance(); } bool Reception::serve(Passenger *passenger) { Logger l("Reception"); l.info("Served"); return true; }
36949fa0040d8c0dee3cbeb0595638cf3859ae12
8812cddcaa19671817e2b9cc179d3f41f6c620b2
/Trunk/Client/src/Engine/Include/Engine/AIRSubMesh.h
0c5247694a2d884a01b34ef811c5fd180d79ea13
[]
no_license
Hengle/airengine
7e6956a8a649ef0ca07fcf892c55ae2451ce993c
2f5fbfbfe83eb3f2d1d44af4401b3a48ae75cb24
refs/heads/master
2023-03-17T00:17:33.284538
2020-02-04T03:25:48
2020-02-04T03:25:48
null
0
0
null
null
null
null
GB18030
C++
false
false
11,226
h
AIRSubMesh.h
// *************************************************************** // AIRSubMesh version: 1.0 · date: 01/01/2010 // ------------------------------------------------------------- // Author liangairan // ------------------------------------------------------------- // Copyright (C) 2010 - All Rights Reserved // *************************************************************** // // *************************************************************** #pragma once //#include "IReference.h" #include "AIRStaticMesh.h" #include "Camera.h" #include "IVertexBuffer.h" #include "IIndexBuffer.h" //#include "Renderable.h" #include "ITexture.h" #include "VertexDef.h" //#include "AIRSkeletonRes.h" #include "DataStream.h" #include "VertexAnimation.h" #include "OBB.h" //权值数据 typedef struct tagWeight { int nBoneID; //骨头索引 float fWeight; //权值 }MESHWEIGHT, *LPMESHWEIGHT; //非硬件加速的网格顶点数据 typedef struct tagMeshVertNormal { VERTEX_NORMAL vertex; //顶点数据 u8 boneID[4]; float fWeights[4]; //int nWeightIndex; //权值索引号 //int nWeightCount; //从索引号开始的权重个数 }MESHVERTNORMAL, *LPMESHVERTNORMAL; //用于硬件加速的网格顶点数据 typedef struct tagHardwareMeshVertex { VERTEXNORMALBONEWEIGHTS vertex; //带权重的顶点格式 //int nWeightIndex; //权值索引号 //int nWeightCount; //从索引号开始的权重个数 }HARDWAREMESHVERTEX, *LPHARDWAREMESHVERTEX; class CModelInstance; class AIRModel; class AIRKeyframeAnimationRes; //动画类型 enum MeshAnimationType { eMAT_NoAnimation = 0, //静态网格 eMAT_SkeletionAnimation = 1, //骨骼动画 eMAT_VertexAnimation = 2, //顶点动画 }; typedef AIRVector<MESHWEIGHT> SOFTWARE_BLEND_WEIGHT_LIST; typedef AIRVector<LPMESHVERTNORMAL> SOFTWARE_BLEND_VERTEX_LIST; typedef AIRVector<LPHARDWAREMESHVERTEX> HARDWARE_BLEND_VERTEX_LIST; typedef AIRVector<AIRMESHTRI> FACE_LIST; struct VertexData { VertexData():m_pMeshVB(NULL), m_pMeshIB(NULL) {} IVertexBuffer* m_pMeshVB; // 当前lod下的顶点缓冲 IIndexBuffer* m_pMeshIB; // 当前lod下的索引缓冲 }; // 网格的lod数据信息 // 说明: 第0层保存的是原始网格数据; // 从第1层起,每层的m_pvtHardwareBlendVertex, m_pvtSoftwareBlendVertex, m_pvtFaces, m_pMeshVB, m_pMeshIB是独立创建的数据; // 而非0层的 m_pvtSoftwareBlendWeight 引用的是第0层的 m_pvtSoftwareBlendWeight; class LodData// : public EngineAllocator(LodData) { EngineAllocator(LodData) public: //LodData( void ) : //m_pvtSoftwareBlendWeight(NULL), //m_pvtSoftwareBlendVertex(NULL), //m_pvtHardwareBlendVertex(NULL), //m_pvtFaces(NULL), //m_pMeshVB(NULL), //m_pMeshIB(NULL) //{} LodData( void ) { } ~LodData( void ) { } public: //SOFTWARE_BLEND_WEIGHT_LIST* m_pvtSoftwareBlendWeight; // 当前lod下的顶点权重列表 //SOFTWARE_BLEND_VERTEX_LIST* m_pvtSoftwareBlendVertex; // 当前lod下的软件蒙皮顶点列表 //HARDWARE_BLEND_VERTEX_LIST* m_pvtHardwareBlendVertex; // 当前lod下的硬件蒙皮顶点列表 //FACE_LIST* m_pvtFaces; // 当前lod下的三角面列表 //IVertexBuffer* m_pMeshVB; // 当前lod下的顶点缓冲 //IIndexBuffer* m_pMeshIB; // 当前lod下的索引缓冲 //SOFTWARE_BLEND_WEIGHT_LIST m_pvtSoftwareBlendWeight; // 当前lod下的顶点权重列表 SOFTWARE_BLEND_VERTEX_LIST m_pvtSoftwareBlendVertex; // 当前lod下的软件蒙皮顶点列表 HARDWARE_BLEND_VERTEX_LIST m_pvtHardwareBlendVertex; // 当前lod下的硬件蒙皮顶点列表 FACE_LIST m_pvtFaces; // 当前lod下的三角面列表 VertexData m_VertexData; // 当前lod下的顶点渲染数据 }; typedef AIRVector< LodData* > MESH_LOD_LIST; class EngineExport CAIRSubMesh// : public EngineAllocator(CAIRSubMesh) { EngineAllocator(CAIRSubMesh) public: CAIRSubMesh(); ~CAIRSubMesh(); //virtual void Render(CCamera* pCamera); // 创建顶点缓冲 //@nVertexCount 顶点数量 void CreateVertices(int nVertexCount); // 创建索引数据 //@nFacesCount 面数 void CreateIndices(int nFacesCount); // 从文本文件加载 bool LoadFromFileData(CDataStream* pFileStream, const char* szFilename); // 从二进制文件读入 bool LoadFromFileDataBinary(CDataStream* pFileStream, AIRModel* pModel); //直接创建静态模型 bool Create(LPVERTEX_NORMAL pVertices, u32 nVerticesNum, u16* pIndices, u32 nIndicesNum); //带骨骼动画 bool Create(LPMESHVERTNORMAL pVertices, u32 nVerticesNum, u16* pIndices, u32 nIndicesNum); // 设置骨骼 //void SetSkeletonRes(CAIRSkeletonRes* pSkeleton) //{ // m_pSkeleton = pSkeleton; //} // 是否静态网格 bool IsStaticMesh() const { return m_animationType == eMAT_NoAnimation; } // 设置动画类型 void SetAnimationType(u8 type) { m_animationType = type; } // 获得子网格的动画类型 u8 GetAnimationType( void ) const { return m_animationType; } // 计算顶点数据 void CaculateVertices(const SColor& colorDiffuse, Matrix4f* pBoneMatrix, f32 fTimePos); // 设置网格的透明度 void SetTransparent(bool bAlpha = true, u8 nAlpha = 128); // 获得网格的材质名称 const AIRString& GetMaterialName() const { return m_strMaterialName; } // 设置当前是否渲染网格的法线 void SetDrawMeshNormal( bool b ); // 是否点中网格 bool IsPick(const Vector3Df& vOrg, const Vector3Df& vPickDir, const Matrix4f& matTransform); bool IsPick(const Vector3Df& vOrg, const Vector3Df& vPickDir, const Matrix4f& matTransform, float& distFromEyeToObject); // 计算顶点动画 void CaculateVerticesByVertexAnimation( float fInterpolate, VertexAnimationKeyframe* pKeyframe1, VertexAnimationKeyframe* pKeyframe2, s32 nAnimationMask); // 清空lod数据列表 void ClearLodList( void ); // 设置当前的lod级别 void SetCurLodLevel( u16 nCurLodLevel ); // 获得网格当前的lod级别 u16 GetCurLodLevel( void ) { return m_nCurLodLevel; } // 创建模型的lod数据列表 void CreateLodDataList( void ); // 获得初始网格的面数 u32 GetFacesNum() const { return m_nFacesCount; } // 获得初始网格的顶点数 u32 GetVerticesNum() const { return m_nVerticesCount; } // 获得当前的lod级别的数据 LodData* GetCurLodData( void ) { return m_pCurLodData; } // 获得网格的lod列表 MESH_LOD_LIST& GetLodList( void ) { return m_LodList; } // 获得第nLod层的lod数据 LodData* GetLodData(size_t nLod); // 添加第nLod层的lod数据 void AddLodData(size_t nLod, LodData* pLodData); void Clear(); ////获得网格的顶点缓冲 IVertexBuffer* GetVertexBuffer(); //获得网格的索引缓冲 IIndexBuffer* GetIndexBuffer(); //// 获得软件蒙皮的权重列表 //SOFTWARE_BLEND_WEIGHT_LIST& GetSoftwareBlendWeightList( void ) //{ // return m_vtWeights; //} //// 获得软件蒙皮的顶点列表 //SOFTWARE_BLEND_VERTEX_LIST& GetSoftwareBlendVertexList( void ) //{ // return m_vtVertices; //} //// 获得硬件蒙皮的顶点列表 //HARDWARE_BLEND_VERTEX_LIST& GetHardwareBlendVertexList( void ) //{ // return m_vtHardwareVertices; //} //// 获得网格面列表信息 //FACE_LIST& GetFaceList( void ) //{ // return m_vtFaces; //} //// 获得初始网格的三角面列表 //const FACE_LIST& GetMeshFaces() const //{ // return m_vtFaces; //} //// 获得初始网格的软件蒙皮/静态网格/顶点动画的顶点列表 //SOFTWARE_BLEND_VERTEX_LIST& GetVerticesData() //{ // return m_vtVertices; //} void SetName(const char* szName) { m_strName = szName; } const AIRString& GetName() const { return m_strName; } const AABBBox3Df& GetBoundingBox() const { return m_boundingBox; } IMaterial* GetMaterial() { return m_pMaterial; } void CaculateKeyframeVertices(f32 fTimePos); void SetKeyframeAnimationRes(AIRKeyframeAnimationRes* pAnimationRes) { m_pVertexAnimationRes = pAnimationRes; } inline const OBBoxf& GetObb() { return m_obb; } void CacheVertexBuffer(); void SetMaterial(IMaterial* pMaterial) { m_pMaterial = pMaterial; } protected: //virtual void PreRender(CCamera* pCamera); //计算顶点位置,这里是处理静态模型 void ComputeVertexBuffer(AIRVector<VERTEX_NORMAL>* vertices); //处理的是带骨骼数据的模型 void ComputeVertexBuffer(AIRVector<LPMESHVERTNORMAL>* vertices); //处理基于vs的顶点数据 void ComputeVertexBuffer(AIRVector<LPHARDWAREMESHVERTEX>* vertices); //计算索引缓冲 void ComputeIndexBuffer(AIRVector<AIRMESHTRI>* vtFaces); //计算法线 void ComputeVertexNormal(AIRVector<VERTEX_NORMAL>* vertices, AIRVector<AIRMESHTRI>* vtFaces); //计算法线 void ComputeVertexNormal(AIRVector<LPMESHVERTNORMAL>* vertices, AIRVector<AIRMESHTRI>* vtFaces); //计算基于vertexshader的法线 void ComputeVertexNormal(AIRVector<LPHARDWAREMESHVERTEX>* vertices, AIRVector<AIRMESHTRI>* vtFaces); //清空渲染物信息 void ClearRenderableImp( void ); //计算三角面法线 void ComputeFaceNormal( const Vector3Df& v1, const Vector3Df& v2, const Vector3Df& v3, Vector3Df& vNormal ); //用帧数据计算顶点位置 void CaculateVertices( const SColor& colorDiffuse, Matrix4f* pBoneMatrix, LPVERTEX_NORMAL* pVertex, f32 fTimePos); //创建法线顶点缓冲 void GenNormalVB( void ); //清空第nLod层的lod数据 void ClearLodData( size_t nLod ); private: //IVertexBuffer* m_pVertexBuffer; //顶点缓冲 //IIndexBuffer* m_pIndexBuffer; //索引缓冲 //SOFTWARE_BLEND_WEIGHT_LIST m_vtWeights; //影响该模型的权重 //SOFTWARE_BLEND_VERTEX_LIST m_vtVertices; //初始顶点数据 //HARDWARE_BLEND_VERTEX_LIST m_vtHardwareVertices; //基于vs的顶点数据 //FACE_LIST m_vtFaces; //面信息 //AIRVector<VERTEX_NORMAL> m_vtNoSkelVertices; //没有骨骼数据的骨骼动画 s32 m_nVerticesCount; //顶点数 s32 m_nFacesCount; //面数 AIRString m_strMaterialName; //材质名称 //CAIRSkeletonRes* m_pSkeleton; //影响该mesh的骨骼资源,如果指针为空,则为静态模型 AIRKeyframeAnimationRes* m_pVertexAnimationRes; // 顶点动画 IVertexBuffer* m_pNormalVB; //保存网格法线数据的顶点缓冲 bool m_bGenNormalVB; //是否已经生成法线 u8 m_animationType; //动画类型 MESH_LOD_LIST m_LodList; //lod数据容器 u16 m_nCurLodLevel; //当前lod级别 LodData* m_pCurLodData; //当前lod级别的数据 IMaterial* m_pMaterial; //对应的material AABBBox3Df m_boundingBox; OBBoxf m_obb; AIRString m_strName; };
d71266c307a0484fd0e0a275bd0c4c5bb747c9bc
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/inetsrv/query/h/noise.hxx
b47901036e2b7c53a82807081aafffe89bec9d07
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
9,020
hxx
noise.hxx
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1991 - 1992. // // File: NOISE.HXX // // Contents: Noise word list // // Classes: CNoiseList, NoiseListInit, NoiseListEmpty // CLString, CStringList, CStringTable // // History: 11-Jul-91 BartoszM Created // //---------------------------------------------------------------------------- #pragma once #include <plang.hxx> const NOISE_WORD_LENGTH = cbKeyPrefix + sizeof( WCHAR ); // word length for detecting // and filtering noise words //+--------------------------------------------------------------------------- // // Class: CLString // // Purpose: Linkable String // // History: 16-Jul-91 BartoszM Created // //---------------------------------------------------------------------------- class CLString { public: CLString ( UINT cb, const BYTE* buf, CLString* next ); void* operator new ( size_t n, UINT cb ); #if _MSC_VER >= 1200 void operator delete( void * p, UINT cb ) { ::delete(p); } void operator delete( void * p ) { ::delete(p); } #endif inline BOOL Equal ( UINT cb, const BYTE* str ) const; CLString * Next() { return _next; } #if CIDBG == 1 void Dump() const { ciDebugOut (( DEB_ITRACE, "%s ", _buf )); } #endif private: CLString * _next; UINT _cb; #pragma warning(disable : 4200) // 0 sized array in struct is non-ansi BYTE _buf[]; #pragma warning(default : 4200) }; //+--------------------------------------------------------------------------- // // Member: CLString::Equal, public // // Synopsis: String comparison // // Arguments: [cb] -- length // [str] -- string // // History: 16-Jul-91 BartoszM Created. // //---------------------------------------------------------------------------- inline BOOL CLString::Equal ( UINT cb, const BYTE* str ) const { return ( (cb == _cb) && (memcmp ( str, _buf, _cb ) == 0) ); } //+--------------------------------------------------------------------------- // // Class: CStringList // // Purpose: List of Linkable Strings // // History: 16-Jul-91 BartoszM Created // //---------------------------------------------------------------------------- class CStringList { public: CStringList(): _head(0) {} ~CStringList(); void Add ( UINT cb, const BYTE * str ); BOOL Find ( UINT cb, const BYTE* str ) const; BOOL IsEmpty () const { return _head == 0; } #if CIDBG == 1 void Dump() const; #endif private: CLString * _head; }; //+--------------------------------------------------------------------------- // // Class: CStringTable // // Purpose: Hash Table of strings // // History: 16-Jul-91 BartoszM Created // //---------------------------------------------------------------------------- class CStringTable { public: CStringTable( UINT size ); ~CStringTable(); void Add ( UINT cb, const BYTE* str, UINT hash ); inline BOOL Find ( UINT cb, const BYTE* str, UINT hash ) const; #if CIDBG == 1 void Dump() const; #endif private: UINT _index ( UINT hash ) const { return hash % _size; } UINT _size; CStringList* _bucket; }; //+--------------------------------------------------------------------------- // // Member: CStringTable::Find, public // // Synopsis: String comparison // // Arguments: [cb] -- length // [str] -- string // // History: 16-Jul-91 BartoszM Created. // //---------------------------------------------------------------------------- inline BOOL CStringTable::Find ( UINT cb, const BYTE* str, UINT hash ) const { return _bucket [ _index(hash) ].Find ( cb, str ); } class PKeyRepository; //+--------------------------------------------------------------------------- // // Class: CNoiseList // // Purpose: Discard meaningless words from the input stream // // History: 02-May-91 BartoszM Created stub. // 30-May-91 t-WadeR Created first draft. // //---------------------------------------------------------------------------- class CNoiseList: public PNoiseList { public: CNoiseList( const CStringTable& table, PKeyRepository& krep ); ~CNoiseList() {}; void GetBuffers( UINT** ppcbInBuf, BYTE** ppbInBuf ); void GetFlags ( BOOL** ppRange, CI_RANK** ppRank ); void PutAltWord( UINT hash ); void PutWord( UINT hash ); void StartAltPhrase(); void EndAltPhrase(); void SkipNoiseWords( ULONG cWords ) { _cNoiseWordsSkipped += cWords; *_pocc += cWords; } void SetOccurrence( OCCURRENCE occ ) { *_pocc = occ; } BOOL FoundNoise() { return _fFoundNoise; } OCCURRENCE GetOccurrence() { return *_pocc; } private: const CStringTable& _table; UINT _cbMaxOutBuf; UINT* _pcbOutBuf; BYTE* _pbOutBuf; PKeyRepository& _krep; OCCURRENCE* _pocc; BOOL _fFoundNoise; // One way trigger to TRUE when noise word found. ULONG _cNoiseWordsSkipped; // count of noise words that haven't // been passed onto the key repository. // Care must be taken to ensure that // noise words at the same occurrence // (ie alternate words) are not counted // multiple times. ULONG _cNonNoiseAltWords; // count of non-noise words at current // occurrence }; //+--------------------------------------------------------------------------- // // Class: CNoiseListInit // // Purpose: Initializer for the noise list // // History: 16-Jul-91 BartoszM Created // //---------------------------------------------------------------------------- class CNoiseListInit: INHERIT_VIRTUAL_UNWIND, public PNoiseList { INLINE_UNWIND( CNoiseListInit ) public: CNoiseListInit( UINT size ); ~CNoiseListInit() { delete _table; }; void GetBuffers( UINT** ppcbInBuf, BYTE** ppbInBuf ); void PutAltWord( UINT hash ); void PutWord( UINT hash ); CStringTable * AcqStringTable() { CStringTable* tmp = _table; _table = 0; return tmp; } private: CKeyBuf _key; CStringTable * _table; }; //+--------------------------------------------------------------------------- // // Class: CNoiseListEmpty // // Purpose: Empty Noise List (used as default) // // History: 16-Jul-91 BartoszM Created // //---------------------------------------------------------------------------- class CNoiseListEmpty: public PNoiseList { public: CNoiseListEmpty( PKeyRepository& krep, ULONG ulFuzzy ); void GetBuffers( UINT** ppcbInBuf, BYTE** ppbInBuf ); void GetFlags ( BOOL** ppRange, CI_RANK** ppRank ); void PutAltWord( UINT hash ); void PutWord( UINT hash ); void StartAltPhrase(); void EndAltPhrase(); void SkipNoiseWords( ULONG cWords ) { _cNoiseWordsSkipped += cWords; *_pocc += cWords; } void SetOccurrence( OCCURRENCE occ ) { *_pocc = occ; } BOOL FoundNoise() { return _fFoundNoise; } OCCURRENCE GetOccurrence() { return *_pocc; } private: UINT _cbMaxOutBuf; UINT* _pcbOutBuf; BYTE* _pbOutBuf; PKeyRepository& _krep; OCCURRENCE* _pocc; ULONG _ulGenerateMethod; // Fuzzines of query BOOL _fFoundNoise; // One way trigger to TRUE when noise word found. ULONG _cNoiseWordsSkipped; // count of noise words that haven't // been passed onto the key repository. // Care must be taken to ensure that // noise words at the same occurrence // (ie alternate words) are not counted // multiple times. ULONG _cNonNoiseAltWords; // count of non-noise words at current // occurrence };
929d1fc6b042760c83b202873f2619d2848d3495
1e8465fe181fdc1cc3d3c275b0826f2e22b0ed2b
/11_C_serial.cpp
d8fac58b66662b700b5a0748b44bed49537e64d9
[]
no_license
xmikiesx/Capitulo3
41a58f27e8f72f0b42fedd2520380afffbf871d6
80dab2fdf6f47d2e6bb576d641c1666d8b498992
refs/heads/master
2020-07-27T20:41:49.124393
2019-09-18T20:42:39
2019-09-18T20:42:39
209,210,480
0
1
null
null
null
null
UTF-8
C++
false
false
407
cpp
11_C_serial.cpp
#include <stdio.h> #include <stdlib.h> #define SIZE 16 int main(void) { int a[SIZE]; int sum[SIZE]; int i; for (i=0; i<SIZE; i++){ a[i]=rand()%50; } sum[0]=a[0]; for (i=1; i<SIZE; i++) { sum[i]=sum[i-1]+a[i]; } for (i=0;i<SIZE;i++){ printf("A[%2d]=%9d SUM[%2d]=%9d\n", i, a[i], i, sum[i]); } return 0; }
a69dbfb4b50de6358dd5a2500c8899afa30175ad
3b2814bfc52ce874442251f258245541ee513932
/R3/CDlgListBase.cpp
a9d581cff7b7eecc9285a30f64d89d82099f1acd
[]
no_license
bb33bb/MyLittleARK
3e589636ce7a5a3e6ab5a43b9860f00674a13c7f
73ad0d59fe51bc876d69acbd66525c2bda9eedca
refs/heads/master
2023-06-11T06:45:31.127999
2020-01-01T11:42:45
2020-01-01T11:42:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
646
cpp
CDlgListBase.cpp
// CDlgListBase.cpp: 实现文件 // #include "pch.h" #include "R3.h" #include "CDlgListBase.h" #include "afxdialogex.h" // CDlgListBase 对话框 IMPLEMENT_DYNAMIC(CDlgListBase, CDialogEx) CDlgListBase::CDlgListBase(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_CDlgListBase, pParent) , m_hDev(NULL) { } CDlgListBase::~CDlgListBase() { } void CDlgListBase::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LISTBASE, m_listCtrl); } void CDlgListBase::SetDev(HANDLE hDev) { m_hDev = hDev; } BEGIN_MESSAGE_MAP(CDlgListBase, CDialogEx) END_MESSAGE_MAP() // CDlgListBase 消息处理程序
6196434283d4e3bb08efeea0bba88c768da3e6ca
8c6ac005f8efd3dd9af76c4516b2a25b15834b52
/MFCTool/UiTool.h
7b9ea0931f94068e18c5fc59c24600dccbf6c6b9
[]
no_license
qaws1134/MFCTool_Team
1b5cf873a1feb359456230ec8b8649181f86f3eb
2494a84a7e96f0b03ad71a333c3c8ada699057d0
refs/heads/main
2023-06-04T04:47:24.990456
2021-06-26T08:44:57
2021-06-26T08:44:57
378,180,776
0
0
null
null
null
null
UHC
C++
false
false
2,206
h
UiTool.h
#pragma once #include "afxwin.h" // CUiTool 대화 상자입니다. class CMFCToolView; class CUiTool : public CDialog { DECLARE_DYNAMIC(CUiTool) public: CUiTool(CWnd* pParent = NULL); // 표준 생성자입니다. virtual ~CUiTool(); // 대화 상자 데이터입니다. #ifdef AFX_DESIGN_TIME enum { IDD = IDD_UITOOL }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. DECLARE_MESSAGE_MAP() public: void SetImageView(CString Objectkey, const CStatic& PictureBox); void PickingPos(D3DXVECTOR3 vMouse); void Render_UI(); void SetView(CMFCToolView* pView) { m_pView = pView; } bool ColArrow(D3DXVECTOR3 vMouse,RECT rc); bool ColCircle(D3DXVECTOR3 vMouse); void Collision_Move(D3DXVECTOR3 vMouse); void Collision_Down(D3DXVECTOR3 vMouse); void Collision_Up(); public : afx_msg void OnBnClickedTranslation(); afx_msg void OnBnClickedRotation(); afx_msg void OnBnClickedScale(); afx_msg void OnBnClickedAdd(); afx_msg void OnBnClickedClear(); afx_msg void OnBnClickedResultSave(); afx_msg void OnBnClickedResultLoad(); afx_msg void OnBnClickedApply(); afx_msg void OnBnClickedPrefabLoad(); afx_msg void OnLbnSelchangeImageListBox(); afx_msg void OnDropFiles(HDROP hDropInfo); afx_msg void OnLbnSelchangeResultList(); CString m_wstrObjID; CStatic m_Picture; CStatic m_Picture_Prefab; CComboBox m_ComboID; CListBox m_Image_ListBox; CListBox m_Prefab_ListBox; CListBox m_Result_ListBox; afx_msg void OnBnClickedMouseTrans(); CString m_wstrMatMod; float m_fPosX; float m_fPosY; float m_fRotZ; float m_fScaleX; float m_fScaleY; OBJECTINFO m_tPrefabInfo; private : map<CString, PLACEMENT*> m_mapPlacementInfo; map<CString, CString> m_mapFileInfo; list<int>m_listResult; CString m_wstrID; //텍스트박스 아이디를 저장할 변수 CMFCToolView* m_pView; bool m_bMatTrans; bool m_bMatRot; bool m_bMatScale; bool m_bPicking; bool m_bPicKingStart; bool m_bArrowX; bool m_bArrowY; bool m_bCircle; bool m_bMouseDown; D3DXVECTOR3 m_vStartMouse; D3DXVECTOR3 m_vStartPos; int m_iNowResultIdx; int m_KeyIndex; bool m_beIDObject; public: afx_msg void OnLbnSelchangePrefabList(); };
30aa7fbb01bf239f93caf85d650ab074e5c6c051
9d32d6f7112d292a9b2b11d8e2796743cfbe8761
/Image.cpp
5faf7e81c6c36f31a48726c81938930cbf204375
[]
no_license
iskay/Wavelet
1c7f0457e5f4429877b3329d4b9588315165e81b
7a3ffda05b0fa93ee6e42d6e0ea8b3383f317abd
refs/heads/master
2021-01-19T14:33:43.831526
2010-12-16T01:38:54
2010-12-16T01:38:54
1,172,874
14
4
null
null
null
null
UTF-8
C++
false
false
7,012
cpp
Image.cpp
#include <fstream> #include <string.h> #include "Image.h" #include "Structs.h" using namespace std; //Loads a BMP for compression. //fname = the name of the bmp to open //header_addr and img_addr are used to store the address of the header and image //arrays in memory after the file has been loaded. //header_size and img_size are used to store the size in bytes of the header //and image arrays. //Currently, the input BMP must be a square with sides = 2^n, (n>1), otherwise //the wavelet transform algorithms won't work. int LoadBMP(char *fname, int &header_addr, int &header_size, int &img_addr, int &img_size) { fstream file; //open with position pointer at end of file file.open(fname, ios::in | ios::binary); if(!file.is_open()) return 0; //get the filesize file.seekg(0, ios::end); long size = file.tellg(); file.seekg(ios::beg); //back to beginning of file unsigned char *mem = new unsigned char[size]; file.read((char *)mem, size); file.close(); //check first two bytes -- should always be "BM" //if this is a valid bmp if(mem[0] != 'B' || mem[1] != 'M') return 0; //bytes 11-14 contain the offset to the actual image data int offset; offset = mem[10]; offset += 256 * mem[11]; offset += 256 * 256 * mem[12]; offset += 256 * 256 * 256 * mem[13]; //now split the bmp into header and image data //they will be compressed seperately header_size = offset; img_size = size-offset; unsigned char *header_buf = new unsigned char[header_size]; double *img_buf = new double[img_size]; memcpy(header_buf, mem, header_size); for(int i=0; i<(img_size); i++) img_buf[i] = mem[offset + i]; header_addr = (int)header_buf; img_addr = (int)img_buf; delete[] mem; return 1; } //Saves a bmp //fname = the file name to save as //header_data is a pointer to the bmp header data, and header_size is its size in bytes //img_data is a pointer to the image data, and img_size is its size in bytes int SaveBMP(char *fname, unsigned char *header_data, int header_size, double *img_data, int img_size) { //recombine the bmp file int file_size = header_size + img_size; unsigned char *mem = new unsigned char[file_size]; unsigned char *img_buf = new unsigned char[img_size]; for(int i=0; i<img_size; i++) { img_data[i] = (int)(img_data[i]+0.5); //round up or down if(img_data[i] < 0) img_data[i] = 0; //one last check for valid values if(img_data[i] > 255) img_data[i] = 255; img_buf[i] = (unsigned char)img_data[i]; } memcpy(mem, header_data, header_size); memcpy(mem+header_size, img_buf, img_size); //write to disk fstream file; file.open(fname, ios::out | ios::binary); if(!file.is_open()) return 0; file.write((char *)mem, file_size); file.close(); delete[] mem; delete[] img_buf; return 1; } //Saves a compressed file //fname = the file name to save as //wlt is a struct that holds the data that will be written into the file's header //(it should already be filled out before calling this function) //the other parameters are pointers to the bmp header and (Huffman encoded) image data //and their sizes in bytes int SaveWLT(char *fname, wlt_header_info wlt, unsigned char *bmp_header_data, int bmp_header_size, unsigned char *img_data, int img_size) { //combine file data int file_size = wlt.hsize + bmp_header_size + img_size; unsigned char *mem = new unsigned char[file_size]; //write the wlt header //bytes 0 - 1, wlt header size mem[0] = (wlt.hsize & 255); mem[1] = (wlt.hsize & (256*256-1)) >> 8; //bytes 2 - 5, number of uncompressed image bytes mem[2] = (wlt.img_size & 0x000000FF); mem[3] = (wlt.img_size & 0x0000FF00) >> 8; mem[4] = (wlt.img_size & 0x00FF0000) >> 16; mem[5] = (wlt.img_size & 0xFF000000) >> 24; //byte 6, # of downsample steps (1 or 0); mem[6] = wlt.steps; //bytes 7 - 10, # of encoded image bytes mem[7] = (wlt.input_bytes & 0x000000FF); mem[8] = (wlt.input_bytes & 0x0000FF00) >> 8; mem[9] = (wlt.input_bytes & 0x00FF0000) >> 16; mem[10] = (wlt.input_bytes & 0xFF000000) >> 24; //byte 11, # of encoding padding bits mem[11] = wlt.h_padding; //bytes 12 - 19, scaling factor for transformed coefficients memcpy(mem + 12, &wlt.scale, sizeof(double)); //remaining header bytes, huffman freq table int f_length = wlt.hsize - HEADER_SIZE; for(int i=0; i<f_length; i++) mem[HEADER_SIZE+i] = wlt.frequency[i]; //copy bmp and image data memcpy(mem+wlt.hsize, bmp_header_data, bmp_header_size); memcpy(mem+wlt.hsize+bmp_header_size, img_data, img_size); //write to disk fstream file; file.open(fname, ios::out | ios::binary); if(!file.is_open()) return 0; file.write((char *)mem, file_size); file.close(); delete[] mem; return 1; } //Loads a compressed file //fname = the file name //wlt should be an empty header struct where info from the file header will be stored for later use //bmp_header_addr is used to store the address of the bmp header after it is loaded //img_addr is used to store the address of the (Huffman encoded) image data after it is loaded //bmp_header_size and img_size are used to store their sizes in bytes int LoadWLT(char *fname, wlt_header_info &wlt, int &bmp_header_addr, int &bmp_header_size, int &img_addr, int &img_size) { fstream file; //open with position pointer at end of file file.open(fname, ios::in | ios::binary); if(!file.is_open()) return 0; //get the filesize file.seekg(0, ios::end); long size = file.tellg(); file.seekg(ios::beg); //back to beginning of file unsigned char *mem = new unsigned char[size]; file.read((char *)mem, size); file.close(); //read bytes 0 - 1 to get wlt header size wlt.hsize = mem[0]; wlt.hsize += 256 * mem[1]; //read bytes 2 - 5 to get number of uncompressed image bytes wlt.img_size = mem[2]; wlt.img_size += 256 * mem[3]; wlt.img_size += 256 * 256 * mem[4]; wlt.img_size += 256 * 256 * 256 * mem[5]; //read byte 6 to get # of downsample steps; wlt.steps = mem[6]; //read bytes 7 - 10 to get # of encoded image bytes wlt.input_bytes = mem[7]; wlt.input_bytes += 256 * mem[8]; wlt.input_bytes += 256 * 256 * mem[9]; wlt.input_bytes += 256 * 256 * 256 * mem[10]; //read byte 11 to get # of encoding padding bits wlt.h_padding = mem[11]; //read bytes 12 - 19 to get scaling factor memcpy(&wlt.scale, mem+12, sizeof(double)); //read remaining header bytes to get huffman freq table int f_length = wlt.hsize - HEADER_SIZE; wlt.frequency = ""; for(int i=0; i<f_length; i++) wlt.frequency += mem[HEADER_SIZE+i]; bmp_header_size = 54; //constant for bitmaps img_size = wlt.img_size; //split file into parts unsigned char *bmp_hbuf = new unsigned char[bmp_header_size]; unsigned char *img_buf; if(wlt.steps != 0) { img_buf = new unsigned char[img_size*4*wlt.steps]; } else { img_buf = new unsigned char[img_size]; } memcpy(bmp_hbuf, mem + wlt.hsize, bmp_header_size); memcpy(img_buf, mem+ wlt.hsize + bmp_header_size, wlt.input_bytes); bmp_header_addr = (int)bmp_hbuf; img_addr = (int)img_buf; delete[] mem; return 1; }
1f0efc18a240d465f2fb30939d65e7202f04ebc7
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_mpl_map_aux__has_key_impl.hpp
65f05295615ba36fba90fd6f29ce00abb3bbf65b
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
47
hpp
boost_mpl_map_aux__has_key_impl.hpp
#include <boost/mpl/map/aux_/has_key_impl.hpp>
e5b26efddbca501670ac56be8190a3ac6351c4a4
f4818ed7e80487d399bc642aa36eb74b26d89ce1
/c_cpp/tutorials/simple/containers/multi/array/at_example/amalgamation/array_at_cplusplus.cc
31a5ec63f2f625657089aea2e98d02086a5b5ca6
[]
no_license
AlitalipSever/gtu-mat-214
496b7a278e4239dc1222fe8d0b35f33908a6b263
8846dd00096541ed5e8fe70ab18c84a3e0dab0e5
refs/heads/master
2020-04-05T19:11:23.622756
2017-10-11T10:53:12
2017-10-11T10:53:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,309
cc
array_at_cplusplus.cc
/* * Adapted from: * http://www.cplusplus.com/reference/array/array/at/ * * */ // array::at #include <iostream> #include <array> class MyClass { private: int num_; private: static bool flag_talks_; public: // MyClass(int num = 0) : num_(num) {} MyClass(int num) : num_(num) { if ( flag_talks_ ) std::cout << "Constructor with int arg called." << std::endl; } MyClass() : num_(0) { if ( flag_talks_ ) std::cout << "Constructor with no arg called." << std::endl; } ~MyClass() { if ( flag_talks_ ) std::cout << "Destructor called." << std::endl; } int get_number (void) const { return num_; } void set_number (int number) { this->num_ = number; } public: static void set_flag_talks(bool lval) { flag_talks_ = lval; } }; bool MyClass::flag_talks_ = true; int main () { // MyClass::flag_talks = false; // MyClass::set_flag_talks(false); std::array<MyClass,10> myarray; // assign some values: for (int i=0; i<10; i++) myarray.at(i).set_number( i+1 ); // print content: std::cout << "myarray contains:"; for (int i=0; i<10; i++) std::cout << ' ' << myarray.at(i).get_number(); std::cout << '\n'; // MyClass::flag_talks = false; MyClass::set_flag_talks(false); return 0; }
0060314e185a974f7765840313b098af0470058c
d3f6ef48b20c58fc2d98e6a4fc65f90772cbee96
/src/Sorting_Algorithms/Sorting_shellSort.h
5575b719f55bab4816babb3a144a371b728278a3
[]
no_license
PequalsNPaspirant/MM_SortingAlgorithms
d43bc7fd37fa9b3799e8e9ef33eb3a9b125d3af5
b0a923f821e44157e29964bf074724e964164457
refs/heads/master
2022-11-05T21:31:06.140290
2022-10-31T15:30:13
2022-10-31T15:30:13
158,047,453
0
0
null
null
null
null
UTF-8
C++
false
false
1,594
h
Sorting_shellSort.h
#pragma once #include <iostream> #include "Sorting_dataStructure/Sorting_dataStructure.h" namespace mm { //=======================+============+ // | Shell Sort | //=======================+============+ // Shell Sort - common functions //======================================================================================= void InsertionSort_t1_modifiedToResuseForShellSort(DataSet& obj, const vector<int>& gapSequence); //This algo is more efficient than above binary search in case of shell sort, since in shell sort //the original array is subdivided and the insertion sort is performed over a shorter length array (at indices 0, 0 + gap, 0 + 2*gap, ...etc) //So binary search over previous array is not required. Binary search is useful when the element is to be inserted in the large sorted array void InsertionSort_t2_modifiedToResuseForShellSort(DataSet& obj, const vector<int>& gapSequence); // Shell Sort 1 - fibonacci series as gap sequence //======================================================================================= void ShellSort_t1(DataSet& obj); void ShellSort_t2(DataSet& obj); // Shell Sort 1 - gap sequence - 1, 2, 4, 8, ..., 2^n //======================================================================================= void ShellSort_t3(DataSet& obj); void ShellSort_t4(DataSet& obj); // Shell Sort 1 - gap sequence - n/2, n/4, n/8, ..., 1 //======================================================================================= void ShellSort_t5(DataSet& obj); void ShellSort_t6(DataSet& obj); }
d65c2c47c9ea5f66c8e8f3fdd656366d7e2c4405
f28c54ed419b90ea9d8786318e021c05e26c1fd5
/archivos/objetoOpenGL.h
427a22a38f8b9cdd27366a4994a110db3609913e
[]
no_license
hushP31/voleybol-tracking
acaafde7cc3a8f4c32a71d20ee7e07528d910b45
cb7e30370f59bf087cf6db5ad733e16a508453cd
refs/heads/master
2021-07-08T02:20:25.826998
2018-05-24T08:25:26
2018-05-24T08:25:26
95,792,601
0
0
null
null
null
null
UTF-8
C++
false
false
2,837
h
objetoOpenGL.h
#include <vector> #include <GL/gl.h> #include "vertex.h" #include <stdlib.h> #include "file_ply_stl.h" #include "misObjetos.h" #include "stdlib.h" using namespace std; // variables que definen la posicion de la camara en coordenadas polares GLfloat Observer_distance; GLfloat Observer_angle_x; GLfloat Observer_angle_y; // variables que controlan la ventana y la transformacion de perspectiva GLfloat Window_width,Window_height,Front_plane,Back_plane; // variables que determninan la posicion y tamaño de la ventana X int UI_window_pos_x=50,UI_window_pos_y=50,UI_window_width=1080,UI_window_height=720; float altura = 1.0; void clear_window(); void change_projection(); void change_observer(); void draw_axis(); char seleccion = 1; // selector de las teclas que usamos para cambiar el modelo a pintar. char antseleccion = 1; char mode = 1; //Objeto vector<int> caras; vector<int> aristas; vector<float> vertices; /* // Tetraedro vector<float> v_piramide; vector<int> c_piramide; //Cubo vector<float> v_cubo; vector<int> c_cubo; */ bool limite = true; vector<float> v_basico1; vector<int> c_basico1; vector<float> v_basico2; vector<int> c_basico2; //************************************************************************* //Lector de .PLY //************************************************************************* void leeply(char* nombreFichero, vector<float> &vertices, vector<int> &caras); void terreno_juego(vector<float> &vertices, vector<int> &caras); void red_juego(vector<float> &vertices, vector<int> &caras); void campo_voleibol(vector<float> &tvertices, vector<int> &tcaras, vector<float> &rvertices, vector<int> &rcaras); void nuevo_tetraedro(vector<float> &pvertices, vector<int> &pcaras, float altura); void draw_points(vector<float> vertices); void draw_aristas(vector<float> vertices, vector<int> aristas); void draw_caras(vector<float> vertices, vector<int> caras); void draw_solido(vector<float> vertices, vector<int> caras); void draw_ajedrez(vector<float> vertices, vector<int> caras); void draw_all(vector<float> vertices, vector<int> caras); void draw_campo_juego_lines(vector<float> tvertices, vector<float> rvertices); void draw_campo_juego_solid(vector<float> tvertices, vector<float> rvertices); int modo=1; int pinta=0; //0=puntos, 1=aristas, 2=solido, 3=ajedrez bool actualiza = true; int perfiles = 10; int inicio_giro = 0; int final_giro = 360; bool cargado1 = false; int inicio = 0; int fin = 10; void puntos_tracking_ball(vector <MiPunto4D> coordenadas, int inicio, int fin); void draw_objects(); void draw_scene(void); void change_window_size(int Ancho1,int Alto1); void normal_keys(unsigned char Tecla1,int x,int y); void special_keys(int Tecla1,int x,int y); void initialize(void);
75adc5d3634a0f4522089568e8ba8dcf9ad66f10
da972bd5de3c23046509cb1673f2d2e75d67da7f
/mbition/main.cpp
ded91d35a2e1a3553eb1bc4d7a37e057b23afbb7
[]
no_license
zaidyes/mbition
6c8acff4ce22468f261540bd415b8c90b765e9d9
1ca261fae9dde12b762fc9415101f0ab1870e126
refs/heads/master
2021-07-18T19:51:15.661719
2017-10-26T13:51:27
2017-10-26T13:51:27
107,904,721
0
0
null
null
null
null
UTF-8
C++
false
false
1,510
cpp
main.cpp
#include <QDebug> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickWindow> #include <QQmlContext> #include <parser/CPUInfoParser.h> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext *ctxt = engine.rootContext(); CPUInfoParser cpuInfoParser; /// set empty models until the file is parsed ctxt->setContextProperty("summary", QVariant::fromValue(cpuInfoParser.getCpuSummary())); ctxt->setContextProperty("procInfoModel", QVariant::fromValue(cpuInfoParser.getProcObjects())); /// connect relevant signal to set model once the information changes QObject::connect(&cpuInfoParser, &CPUInfoParser::finished, [&]() { ctxt->setContextProperty("summary", QVariant::fromValue(cpuInfoParser.getCpuSummary())); ctxt->setContextProperty("procInfoModel", QVariant::fromValue(cpuInfoParser.getProcObjects())); }); /// connect our error signal. If there is any will be showed on the ui QObject::connect(&cpuInfoParser, &CPUInfoParser::error, [&ctxt](const QString &error) { ctxt->setContextProperty("summary", QVariant::fromValue(QStringList() << "Error getting information: " + error)); }); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); /// start parsing if (cpuInfoParser.isValid()) { cpuInfoParser.startParsing(); } else { qDebug() << cpuInfoParser.getFileName() << "cannot be read"; } return app.exec(); }
77a20913c6825e3437706146439d2948bcdf0b29
b5caebe7597445ff927cc7b02cf75d7065ad30e1
/Libraries/pump/pump.cpp
b8c5e87a1bc1637efe5d456cfcd43fa21f07632a
[]
no_license
scrottty/BASICWATERPUMP
9324efe9b2a95e9e53d0e02f28759296498449af
43e6fc4f2cc336218e6aa604b59f89f7bd2bb8eb
refs/heads/master
2020-03-28T08:49:01.589422
2018-09-09T09:36:45
2018-09-09T09:36:45
147,991,387
0
0
null
null
null
null
UTF-8
C++
false
false
212
cpp
pump.cpp
#include <Arduino.h> #include "pump.h" pump::pump(int pinNumber) { pinMode(pinNumber,OUTPUT); } void pump::run() { digitalWrite(pinNumber,HIGH); } void pump::stop() { digitalWrite(pinNumber,LOW); }
0e19f7416b3d3f31d2f233cd2a45369f52cf4270
310786d31c228271d3c4c965ee5b2eada9816b67
/ECS/ECS/Component.h
2df261afc91658d4da3e8dc57573b4c9d320d05f
[]
no_license
JamieJ619/GamesEngineering-ECS
bf6c86965055b5c9030a8b925c8f1841f7abc5cd
760b5fd549e9b41cff9fe60c804fa7906bbcad84
refs/heads/master
2021-01-25T07:07:25.307627
2017-02-05T16:01:21
2017-02-05T16:01:21
80,714,893
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
h
Component.h
#pragma once #include <vector> #include "Vector2.h" class Component { public: Component(int id) : m_id(id) { }; ~Component() {}; int getId() { return m_id; } private: int m_id; }; class HealthComponent : public Component { public: HealthComponent(int id) : Component(id) , m_health(10) {} ~HealthComponent() {}; int getHealth() { return m_health; } void setHealth(int health) { m_health = health; } private: int m_health; }; class PositionComponent : public Component { public: PositionComponent(int id) : Component(id) , m_position({ 0, 0 }) {} ~PositionComponent() {}; Vector2 getPosition() { return m_position; } void setPosition(Vector2 position) { m_position = position; } private: Vector2 m_position; }; class ControlComponent : public Component { public: ControlComponent(int id) : Component(id) , m_direction(0) {} ~ControlComponent() {}; int getPosition() { return m_direction; } void setPosition(int dir) { m_direction = dir; } private: int m_direction; };
50c35e602dccf56380d52ee4b2aa05194c7feb72
c6d187832a65b964e7c184e6db14d5208fadbda8
/week 2/tempConvert.cpp
86729f9f15a3fadef8533dc931d29283cded50f6
[]
no_license
mccabmic/CS-161
9729a40b5e658a99e1f9ca227a42a4c4cd71f327
811997c2e87cef6756d5ddd7297ea8e58752e225
refs/heads/master
2021-05-07T14:45:23.449466
2017-12-01T05:05:41
2017-12-01T05:05:41
109,871,830
0
0
null
null
null
null
UTF-8
C++
false
false
532
cpp
tempConvert.cpp
/************************************ ** Author: Michael McCabe ** Date: October 3, 2017 ** Description: This program takes the temperature in C and converts it into F ** ************************************/ #include <iostream> using namespace std; int main() { double tempInC, tempInF; cout << "Please enter a Celsius temperature." << endl; cin >> tempInC; tempInF = (9.0 /5.0) * tempInC + 32; cout << "The equivalent Fahrenheit temperature is:" << endl; cout << tempInF; return 0; }
7cc21b07711a2d26f72d911b68c9fa51ef5bde11
d27127cd29a451a1d14ac9ab58db3b1f7cc6bad7
/Training/Training/MoveSemantic.h
4bd9cbc3fb247c1afe1f22d035036427bb870078
[]
no_license
anitamiring/C-training
31fabb9d73f18875b9446a7431d10b8f6bc00e0c
995654d2537725a922f9c1036fa372a7de7e5355
refs/heads/master
2020-06-03T22:17:33.710904
2019-06-14T08:29:32
2019-06-14T08:29:32
191,753,783
0
0
null
null
null
null
UTF-8
C++
false
false
369
h
MoveSemantic.h
#pragma once #include <iostream> class MoveSemantic { int* ptr; unsigned int size; public: MoveSemantic(unsigned int size); MoveSemantic(MoveSemantic& other); MoveSemantic& operator=(const MoveSemantic& other); MoveSemantic(MoveSemantic&& other) noexcept; MoveSemantic& operator=(MoveSemantic&& other) noexcept; ~MoveSemantic(); };
908915a399b2b25a34fdb77848fb69572d2e546b
c8e1a00ac0649ecc043b8eb17367ff1e33065279
/Numerical Methods/main.cpp
97f0e143d84fdc9b32db63c8919739fa01250a74
[]
no_license
PWilkosz99/NumericalMethodsPW
2d9122e552b1055719e8fc09e2a4726f72ddb111
6d7ac7dcb031b968f30c47fcce368eff604ffcc6
refs/heads/main
2023-06-01T13:07:53.716029
2021-06-21T10:24:46
2021-06-21T10:24:46
345,970,864
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
main.cpp
#include <iostream> #include <locale.h> #include <fstream> #include "headers.h" using namespace std; //Definicje funkcji znajdują się w pliku differentialeq.cpp int main() { cout << EulerMethod(1000, 0, 300, 1200, ThermalConductivityEQ, -1E-12, 0) << endl; cout << HeunMethod(1000, 0, 300, 1200, ThermalConductivityEQ, -1E-12, 0) << endl; cout << ModifiedEulerMethod(1000, 0, 300, 1200, ThermalConductivityEQ, -1E-12, 0) << endl; cout << RungeKutta4(1000, 0, 300, 1200, ThermalConductivityEQ, -1E-12, 0) << endl; }
6daa9aab6dedd99b334f1e2be99e20116e11e6c4
e320d5a7f0d8c5abc276b58e6ed2f9433d8d4d95
/src/ui/Image.cpp
c432f80e14fe1a74ef00c655d09cbdbe94e753bf
[]
no_license
HansLehnert/frontend
09b281f2f1db76e752f6743a4d55fe9578c38aa7
3b14af7242c8e4dcf6f48c20b2a3431d2df02f4b
refs/heads/master
2021-01-13T03:05:00.837957
2020-09-06T23:21:03
2020-09-06T23:21:03
76,988,914
0
0
null
null
null
null
UTF-8
C++
false
false
1,127
cpp
Image.cpp
#include "ui/Image.hpp" #include <string> #include "glm/glm.hpp" #include "core/Texture.hpp" #include "core/Program.hpp" Image::Image(std::shared_ptr<Texture> texture, std::string name) : Plane(name), fill_mode_(Image::FillMode::Fit), tint_color_(0), opacity_(1), texture_(texture) { program_ = Program::getProgram("image"); }; void Image::render() const { glUniform4fv(program().uniformLocation("tint"), 1, (float*)&tint_color_); glUniform1f(program().uniformLocation("opacity"), opacity_); glUniform1i(program().uniformLocation("image"), 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_->getId()); Plane::draw(true); } /* void Image::fitBounds(float max_width, float max_height) { float bounds_ratio = max_width / max_height; float texture_ratio = (float)texture->getWidth() / texture->getHeight(); if (bounds_ratio < texture_ratio) { scale.x = max_width; scale.y = max_width / texture_ratio; } else { scale.x = max_height * texture_ratio; scale.y = max_height; } }*/
d3d6194915919374c6abf2bd86f3d7824b5a7ec7
96dbd470db1da75cfbe0f6971a44e0e3611cb0f1
/LeetCode_572/main.cpp
b3442b9aa710c261b745ca031074ceb0c1fad99a
[]
no_license
MatrixDeity/Problems
1d3c0ce1075f425f8ac4d39c32a0c87d94fc4061
f7899cebbb8c09b1cd526dfe6ee9d649e0071327
refs/heads/master
2023-07-09T08:01:05.575383
2023-06-24T21:32:07
2023-06-24T21:32:07
102,288,478
0
0
null
null
null
null
UTF-8
C++
false
false
907
cpp
main.cpp
/** LeetCode_572 https://leetcode.com/problems/subtree-of-another-tree/description/ MatrixDeity, 2018. */ #include <iostream> #include <functional> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSubtree(TreeNode* s, TreeNode* t) { if (s == nullptr || t == nullptr) return s == t; function<bool(TreeNode*, TreeNode*)> impl = [&impl] (TreeNode* s, TreeNode* t) { if (s == nullptr || t == nullptr) return s == t; return s->val == t->val && impl(s->left, t->left) && impl(s->right, t->right); }; return impl(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t); } }; int main() { return 0; }
8062818a1e9d1188db304a893b7df4c749fec19f
3d839b8c98a08640e1c19006ebfadb246e00fdaf
/Lista4_1/Lista4_1.ino
b4f7d3064558a659a7ff8348a74a722f622d688e
[]
no_license
mnahajowski/Arduino
448b466a803ea8ff709db9b05fb8a5364438339d
8938c4d57a18cca66d205c561c0f56443a89da72
refs/heads/master
2021-02-16T07:04:10.637466
2020-06-01T17:27:41
2020-06-01T17:27:41
244,978,444
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
ino
Lista4_1.ino
#define BUTTON_PIN_RED 2 #define BUTTON_PIN_GREEN 4 #define RED 6 #define GREEN 5 #define BLUE 3 #define DEFAULT_DELAY 200 #define STANDARD_DELAY 20 #define ADC_PIN A3 int analogValue = 0; bool lastBtnState_red = HIGH; bool lastBtnState_green = HIGH; bool led_state = LOW; int my_delay = 0; long time_start = 0; long time_end = 0; int last = BLUE; void setup() { // put your setup code here, to run once: pinMode(BUTTON_PIN_RED, INPUT_PULLUP); pinMode(BUTTON_PIN_GREEN, INPUT_PULLUP); pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); my_delay = DEFAULT_DELAY; } void loop() { time_end = millis(); if(time_end - time_start > my_delay) { time_start = time_end; if(last == BLUE) { digitalWrite(BLUE, LOW); digitalWrite(RED, HIGH); last = RED; } else if(last == RED) { digitalWrite(RED, LOW); digitalWrite(GREEN, HIGH); last = GREEN; } else if(last == GREEN) { digitalWrite(GREEN, LOW); digitalWrite(BLUE, HIGH); last = BLUE; } } analogs(); bool currentBtnState_red = digitalRead(BUTTON_PIN_RED); // obecny stan pierwszego buttona bool currentBtnState_green = digitalRead(BUTTON_PIN_GREEN); // obecny stan drugiego buttona if(currentBtnState_red != lastBtnState_red) { delay(STANDARD_DELAY); currentBtnState_red = digitalRead(BUTTON_PIN_RED); if(currentBtnState_red != lastBtnState_red) { my_delay += 50; } } if(currentBtnState_green != lastBtnState_green) { delay(STANDARD_DELAY); currentBtnState_green = digitalRead(BUTTON_PIN_GREEN); if(currentBtnState_green != lastBtnState_green) { my_delay -= 50; if(my_delay <= 0) { my_delay = 0; digitalWrite(RED, HIGH); // miganie ustaje, stale swiatlo } } } } void analogs() { analogValue = analogRead(ADC_PIN); int power = map(analogValue, 0, 1023, 0, 255); analogWrite(last, power); }
addc26dd7bafc9d906e0777ffdb5adcb911356b7
6d94c3d0c9037ecd54859a76703bfd18394f2c76
/Io_16P_16C_default/MyBlueGoldHandler.cpp
6b8b1ce57036db4278426e75c275b2db9a79abe9
[]
no_license
openlcb/Arduino
765ba833b399028107badafa48bbe2e622e5cf38
ae38096e25d920afb70f325d4e77776e371658f9
refs/heads/master
2020-05-23T08:13:05.457363
2017-03-30T19:24:39
2017-03-30T19:24:38
70,288,310
1
4
null
2017-03-30T19:24:39
2016-10-07T22:50:02
C++
UTF-8
C++
false
false
11,055
cpp
MyBlueGoldHandler.cpp
#include "MyBlueGoldHandler.h" #define ShortBlinkOn 0x00010001L #define ShortBlinkOff 0xFFFEFFFEL #define PRESS_DELAY 75 #define LONG_DOUBLE 3000 #define VERY_LONG_DOUBLE 8000 void MyBlueGoldHandler::create(OLCB_Link *link, OLCB_NodeID *nid, MyEventHandler *eventHandler) { OLCB_Virtual_Node::create(link,nid); _index = -1; _input_index = -1; _input_count = 0; _started = false; _event_handler = eventHandler; // initial blue/gold setting blue.on(0); // turn off blue.process(); _last_blue = blue.state; gold.on(UNREADY_BLINK); // unready blink until intialized gold.process(); _last_gold = gold.state; //get the inputs to monitor _input_buttons = _event_handler->getInputs(); _double_press = _last_double = 0; } void MyBlueGoldHandler::moveToIdle(bool reset) { blue.on(0x00000000); gold.on(READY_BLINK); if(reset) { for (uint8_t i = 0; i < 32; i++) { _event_handler->markToTeach(i, false); _event_handler->markToLearn(i, false); } } for(uint8_t i = 0; i < 8; ++i) { digitalWrite(i, LOW); } _index = -1; _input_index = -1; _event_handler->disInhibit(); _state = BG_IDLE; } void MyBlueGoldHandler::update(void) { if(!isPermitted()) { return; } if (!_started) { _started = true; gold.on(READY_BLINK); // turn off waiting to init flash, start heartbeat ready blink } //determine which buttons have been pressed since last time. blue.process(); gold.process(); for(uint8_t i = 0; i < 8; ++i) // first, check and see if we've got a double-press _double_state = (blue.state && gold.state); if(_double_state) { _last_blue = blue.state; _last_gold = gold.state; if(blue.duration > VERY_LONG_DOUBLE) { _double_state = 3; } else if(blue.duration > LONG_DOUBLE) { _double_state = 2; } } if(_last_double != _double_state) //check if state has changed, { _last_double = _double_state; _double_press = _double_state; if(_double_state == 0); //reset the LEDs in case we are backing down from a flash reset { blue.on(0x00); gold.on(READY_BLINK); } } else { _double_press = 0; } // check if blue button pressed if (_last_blue != blue.state) //see if change { if(blue.duration > PRESS_DELAY) //give it 75 ms before we count it { _last_blue = blue.state; if(blue.state) { _blue_pressed = true; } } } else //if no change in input, ignore it { _blue_pressed = false; } // check if gold button pressed if (_last_gold != gold.state) //see if change { if(gold.duration > PRESS_DELAY) //give it 75 ms before we count it { _last_gold = gold.state; if(gold.state) { _gold_pressed = true; } } } else //if no change in input, ignore it { _gold_pressed = false; } //check if input buttons were pressed for(uint8_t i = 0; i < 8; ++i) //check each button! { uint8_t ibstate = digitalRead(_input_buttons[i]); if( ((_last_input & (1<<i))>>i) != ibstate) //see if change { if(ibstate == HIGH) { _last_input |= (1<<i); _input_pressed |= (1<<i); } else { _last_input &= ~(1<<i); } } else //no change in input, ignore it { _input_pressed &= ~(1<<i); } } //possibilities: Blue and Gold was pressed, only Blue was pressed or only Gold was pressed, and/or an input button was pressed. uint8_t channel, prev_channel; //blue has been pressed. switch(_state) { case BG_IDLE: if(_double_press == 3) //8 seconds each { factoryReset(); } else if(_double_press == 2) //3 seconds, begin factory reset warning { gold.on(0xAAAAAAAA); blue.on(0x55555555); } else if(_double_press == 1) { sendIdent(); } else if(_blue_pressed) { //we were doing nothing before; a press of blue puts us in LEARN mode _state = BG_LEARN; //inhibit the EventHandler to avoid confusions _event_handler->inhibit(); blue.on(0xF0F0F0F0); //light the BLUE lamp solid for learning for(uint8_t i = 0; i < 8; ++i) { digitalWrite(i, LOW); } } else if(_gold_pressed) { //we were doing nothing before; a press of gold puts us in TEACH mode _state = BG_TEACH; //inhibit the EventHandler to avoid confusions _event_handler->inhibit(); //TODO is this right? gold.on(0xF0F0F0F0); //light the GOLD lamp solid for learning for(uint8_t i = 0; i < 8; ++i) { digitalWrite(i, LOW); } } break; case BG_LEARN: if(_double_press) { moveToIdle(true); } else if(_blue_pressed) { gold.on(0); //we've entered learn state, now we're indexing over the outputs _index = ((_index+2)%33)-1; if(_index == -1) //cycled through, return to beginning. { digitalWrite(7, LOW); //turn off last channel. moveToIdle(true); } else if(_index > 15) { gold.on(0x0AAA000A); channel = (_index-16) >> 1; // if _index is even, we are handling the consumer for the output being off; blink the blue LED to indicate if(_index & 0x01) { blue.on(0xA000A000); } else { blue.on(0xFFFFFFFF); } digitalWrite(channel, HIGH); if(_index == 16) { digitalWrite(7, LOW); } else if(_index>1) { digitalWrite(channel-1, LOW); //turn off previous channel } } else { channel = _index >> 1; // if _index is even, we are handling the producer for the output being off; blink the blue LED to indicate if(_index & 0x01) { blue.on(0x000A000A); } else { blue.on(0xFFFFFFFF); } digitalWrite(channel, HIGH); if(_index>1) { digitalWrite(channel-1, LOW); //turn off previous channel } } } else if(_gold_pressed) { //send off the LEARN messages! //producers first if(_input_index > -1) _event_handler->markToLearn(_input_index, true); //consumers second if(_index > 15) _event_handler->markToLearn(_index-16, true); else if(_index > -1) _event_handler->markToLearn(_index+16, true); moveToIdle(false); } else if(_input_pressed) { //figure out which input was pressed uint8_t in; for(in = 0; in < 8; ++in) { if((_input_pressed) & (1<<in)) break; } //check to see if this is first, second, or third time. //First time, we flag "on" producer for that channel //Second time, we unflag "on", flag "off" //Third time, we unflag "off" //check "on" //first, check to see if user has moved to a different input, changing their mind. if((_input_index == -1) || (in != (_input_index>>1))) { gold.on(0x000A000A); _input_index = (in << 1); blue.on(0xFFFFFFFF); _input_count = 1; } else if(_input_count == 1) { _input_index = (in << 1) + 1; blue.on(0x000A000A); //indicate that "off" is selected _input_count = 2; } else if(_input_count == 2) { gold.on(0); _input_index = -1; _input_count = 0; blue.on(0xF0F0F0F0); //indicate that nothing is selected for learning } } break; case BG_TEACH: //we've entered teach state, now we're indexing over the outputs if(_double_press) { moveToIdle(true); } else if(_blue_pressed) { gold.on(0xF0F0F0F0); _index = ((_index+2)%33)-1; if(_index == -1) //cycled through, return to beginning. { digitalWrite(7, LOW); //turn off last channel. blue.on(0xF0F0F0F0); //the difference is that we don't leave BG_TEACH state when we've wrapped around the outputs } else if(_index > 15) { gold.on(0x0AAA000A); channel = (_index-16) >> 1; // if _index is even, we are handling the consumer for the output being off; blink the blue LED to indicate if(_index & 0x01) { blue.on(0xA000A000); } else { blue.on(0xFFFFFFFF); } digitalWrite(channel, HIGH); if(_index == 16) { digitalWrite(7, LOW); } else if(_index>1) { digitalWrite(channel-1, LOW); //turn off previous channel } } else { channel = _index >> 1; // if _index is even, we are handling the producer for the output being off; blink the blue LED to indicate if(_index & 0x01) { blue.on(0xA000A000); } else { blue.on(0xFFFFFFFF); } digitalWrite(channel, HIGH); if(_index>1) { digitalWrite(channel-1, LOW); //turn off previous channel } } } else if(_gold_pressed) { //send off the TEACH messages! //producers first if(_input_index > -1) _event_handler->markToTeach(_input_index, true); //consumers second if(_index > 15) _event_handler->markToTeach(_index-16, true); else if(_index > -1) _event_handler->markToTeach(_index+16, true); moveToIdle(false); } else if(_input_pressed) { //figure out which input was pressed uint8_t in; for(in = 0; in < 8; ++in) { if((_input_pressed) & (1<<in)) break; } //check to see if this is first, second, or third time. //First time, we flag "on" producer for that channel //Second time, we unflag "on", flag "off" //Third time, we unflag "off" //check "on" //first, check to see if user has moved to a different input, changing their mind. if((_input_index == -1) || (in != (_input_index>>1))) { _input_index = (in << 1); blue.on(0xFFFFFFFF); _input_count = 1; } else if(_input_count == 1) { _input_index = (in << 1) + 1; blue.on(0x000A000A); //indicate that "off" is selected _input_count = 2; } else if(_input_count == 2) { _input_index = -1; _input_count = 0; blue.on(0x00); //indicate that nothing is selected for learning } } break; } } /** * Send an event in response to the "ident" button pushes */ void MyBlueGoldHandler::sendIdent() { _link->sendIdent(NID); } /** * Fire factory reset * ToDo: better name! Not really a true "factory reset" */ void MyBlueGoldHandler::factoryReset() { _event_handler->factoryReset(); delay(100); //just because. Don't know if we need it // reboot // cast a 0 to a function pointer, then dereference it. Ugly! (* ((void (*)())0) )(); }
1e8998364599158aa632377e1e53336e47c90ec3
2c786297aec94de1b73ef353ff8083ebe49afd90
/src/test.cpp
7582df26baec913419e77d4598c82ca2fb4534af
[ "MIT" ]
permissive
MegrezZhu/Database-BallTree
341e2f47f1ea70fd718a2cccf3d73cee31cfb8ad
8c5ef50c8196aa12b7fe5e8d236b9068ce056a91
refs/heads/master
2021-01-23T00:29:01.273133
2017-06-06T15:50:01
2017-06-06T15:50:01
92,814,181
2
6
null
null
null
null
UTF-8
C++
false
false
5,018
cpp
test.cpp
#include <iostream> #include <ctime> #include "BallTree.h" #include "Utility.h" #include "Page.h" #define MNIST #ifdef MNIST char dataset[L] = "Mnist"; int n = 60000, d = 50; int qn = 1000; #endif #ifdef YAHOO char dataset[L] = "Yahoo"; int n = 624, d = 300; int qn = 1000; #endif #ifdef MINIMAL char dataset[L] = "Minimal"; int n = 25, d = 2; int qn = 1; #endif #ifdef NETFLIX char dataset[L] = "Netflix"; int n = 17770, d = 50; int qn = 1000; #endif #ifdef RANDOM char dataset[L] = "Random"; int n = 1000, d = 10; int qn = 10; #endif int mainTest(); void pageTest(); void readTest(); int simpleTest(); int naive(); int main() { srand(2333); mainTest(); //simpleTest(); //pageTest(); //readTest(); //naive(); system("pause"); } void pageTest() { cout << sizeof(int); auto page = Page::create(2, 5); page->setBySlot(0, "1234"); page->setBySlot(1, "4567"); page->writeBack("tmp/1.page"); } int simpleTest() { char data_path[L], query_path[L]; char index_path[L], output_path[L]; float** data = nullptr; float** query = nullptr; sprintf(data_path, "%s/src/dataset.txt", dataset); sprintf(query_path, "%s/src/query.txt", dataset); sprintf(index_path, "%s/index", dataset); sprintf(output_path, "%s/dst/answer.txt", dataset); if (!read_data(n, d, data, data_path)) { system("pause"); return 1; } BallTree ball_tree1; ball_tree1.buildTree(n, d, data); if (!read_data(qn, d, query, query_path)); FILE* fout = fopen(output_path, "w"); if (!fout) { printf("can't open %s!\n", output_path); system("pause"); return 1; } for (int i = 0; i < qn; i++) { cout << i << ": "; int index = ball_tree1.mipSearch(d, query[i]); fprintf(fout, "%d\n", index); } fclose(fout); for (int i = 0; i < n; i++) { delete[] data[i]; } for (int i = 0; i < qn; i++) { delete[] query[i]; } system("pause"); return 0; } int naive() { char data_path[L], query_path[L]; char index_path[L], output_path[L]; float** data = nullptr; float** query = nullptr; sprintf(data_path, "%s/src/dataset.txt", dataset); sprintf(query_path, "%s/src/query.txt", dataset); sprintf(index_path, "%s/index", dataset); sprintf(output_path, "%s/dst/answer_naive.txt", dataset); if (!read_data(n, d, data, data_path)) { system("pause"); return 1; } if (!read_data(qn, d, query, query_path)); FILE* fout = fopen(output_path, "w"); if (!fout) { printf("can't open %s!\n", output_path); system("pause"); return 1; } for (int i = 0; i < qn; i++) { auto startTime = clock(); auto res = naiveSolve(query[i], n, d, data); fprintf(fout, "%d\n", res.first); printf("done in %d ms.\n", (clock() - startTime) * 1000 / CLOCKS_PER_SEC); } fclose(fout); /* for (int i = 0; i < qn; i++) { cout << i << ": "; int index = ball_tree1.mipSearch(d, query[i]); fprintf(fout, "%d\n", index); } fclose(fout); */ for (int i = 0; i < n; i++) { delete[] data[i]; } for (int i = 0; i < qn; i++) { delete[] query[i]; } return 0; } int mainTest() { char data_path[L], query_path[L]; char index_path[L], output_path[L]; float** data = nullptr; float** query = nullptr; sprintf(data_path, "%s/src/dataset.txt", dataset); sprintf(query_path, "%s/src/query.txt", dataset); sprintf(index_path, "%s/index", dataset); sprintf(output_path, "%s/dst/answer.txt", dataset); if (!read_data(n, d, data, data_path)) { system("pause"); return 1; } BallTree ball_tree1; ball_tree1.buildTree(n, d, data); ball_tree1.storeTree(index_path); if (!read_data(qn, d, query, query_path)); FILE* fout = fopen(output_path, "w"); if (!fout) { printf("can't open %s!\n", output_path); system("pause"); return 1; } BallTree ball_tree2; ball_tree2.restoreTree(index_path); for (int i = 0; i < qn; i++) { int index = ball_tree2.mipSearch(d, query[i]); fprintf(fout, "%d\n", index); } fclose(fout); for (int i = 0; i < n; i++) { delete[] data[i]; } for (int i = 0; i < qn; i++) { delete[] query[i]; } return 0; } void readTest() { char data_path[L], query_path[L]; char index_path[L], output_path[L]; float** data = nullptr; float** query = nullptr; sprintf(data_path, "%s/src/dataset.txt", dataset); sprintf(query_path, "%s/src/query.txt", dataset); sprintf(index_path, "%s/index", dataset); sprintf(output_path, "%s/dst/answer.txt", dataset); if (!read_data(n, d, data, data_path)) { system("pause"); } if (!read_data(qn, d, query, query_path)); FILE* fout = fopen(output_path, "w"); if (!fout) { printf("can't open %s!\n", output_path); system("pause"); } BallTree ball_tree2; ball_tree2.restoreTree(index_path); for (int i = 0; i < qn; i++) { int index = ball_tree2.mipSearch(d, query[i]); fprintf(fout, "%d\n", index); } fclose(fout); /* for (int i = 0; i < qn; i++) { cout << i << ": "; int index = ball_tree1.mipSearch(d, query[i]); fprintf(fout, "%d\n", index); } fclose(fout); */ for (int i = 0; i < n; i++) { delete[] data[i]; } for (int i = 0; i < qn; i++) { delete[] query[i]; } }
3f155e802af76216a925dcc7dcf62239ae8dc58f
2a99407309904cd05fea8befaafb14b332c816dd
/d02/ex01/Fixed.cpp
1847cd8b34f0971a62490f84cb0690c6027defc9
[]
no_license
maxencealluin/cpp
ea33396c5f7aafcfa0bcb25356f1fa62a34da8db
b3442e4815a4b3f3b4b42907b8541f7ecc95f189
refs/heads/master
2020-07-05T05:52:46.926089
2020-01-28T12:55:59
2020-01-28T12:55:59
202,544,521
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
cpp
Fixed.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: malluin <malluin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/10 11:21:52 by malluin #+# #+# */ /* Updated: 2020/01/10 15:05:26 by malluin ### ########.fr */ /* */ /* ************************************************************************** */ #include "Fixed.hpp" #include <cmath> const int Fixed::_nb_fractionals = 8; Fixed::Fixed(void) { std::cout << "Default constructor called" << std::endl; this->_fpvalue = 0; } Fixed::Fixed(Fixed const & instance) { std::cout << "Copy constructor called" << std::endl; *this = instance; } Fixed::Fixed(int const val) { std::cout << "Int constructor called" << std::endl; this->_fpvalue = val << Fixed::_nb_fractionals; } Fixed::Fixed(float const val) { std::cout << "Float constructor called" << std::endl; this->_fpvalue = roundf(val * (1 << Fixed::_nb_fractionals)); } float Fixed::toFloat( void ) const { return (float)(this->_fpvalue) / (1 << Fixed::_nb_fractionals); } int Fixed::toInt( void ) const { return this->_fpvalue >> Fixed::_nb_fractionals; } Fixed::~Fixed(void) { std::cout << "Destructor called" << std::endl; } int Fixed::getRawBits( void ) const { return this->_fpvalue; } void Fixed::setRawBits( int const raw ) { std::cout << "setRawBits member function called" << std::endl; this->_fpvalue = raw; } Fixed & Fixed::operator=(Fixed const & rhs) { std::cout << "Assignation operator called" << std::endl; this->_fpvalue = rhs.getRawBits(); return *this; } std::ostream& operator<<(std::ostream & stream, Fixed const & rhs) { stream << rhs.toFloat(); return stream; }
bb0f3f8bda221c100310550fa99e7503f1ee05d5
37b30edf9f643225fdf697b11fd70f3531842d5f
/chrome/browser/ash/dbus/ash_dbus_helper.cc
f235df93848c5bca736714ab52f577d8920c1563
[ "BSD-3-Clause" ]
permissive
pauladams8/chromium
448a531f6db6015cd1f48e7d8bfcc4ec5243b775
bc6d983842a7798f4508ae5fb17627d1ecd5f684
refs/heads/main
2023-08-05T11:01:20.812453
2021-09-17T16:13:54
2021-09-17T16:13:54
407,628,666
1
0
BSD-3-Clause
2021-09-17T17:35:31
2021-09-17T17:35:30
null
UTF-8
C++
false
false
10,089
cc
ash_dbus_helper.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 "chrome/browser/ash/dbus/ash_dbus_helper.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_paths.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/system/sys_info.h" #include "chrome/browser/ash/settings/device_settings_service.h" #include "chrome/browser/ash/wilco_dtc_supportd/wilco_dtc_supportd_client.h" #include "chrome/common/chrome_paths.h" #include "chromeos/components/chromebox_for_meetings/buildflags/buildflags.h" // PLATFORM_CFM #include "chromeos/cryptohome/system_salt_getter.h" #include "chromeos/dbus/arc/arc_camera_client.h" #include "chromeos/dbus/arc/arc_sensor_service_client.h" #include "chromeos/dbus/attestation/attestation_client.h" #include "chromeos/dbus/audio/cras_audio_client.h" #include "chromeos/dbus/authpolicy/authpolicy_client.h" #include "chromeos/dbus/biod/biod_client.h" #include "chromeos/dbus/cdm_factory_daemon/cdm_factory_daemon_client.h" #include "chromeos/dbus/cicerone/cicerone_client.h" #include "chromeos/dbus/concierge/concierge_client.h" #include "chromeos/dbus/constants/dbus_paths.h" #include "chromeos/dbus/cros_healthd/cros_healthd_client.h" #include "chromeos/dbus/cups_proxy/cups_proxy_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/dlcservice/dlcservice_client.h" #include "chromeos/dbus/dlp/dlp_client.h" #include "chromeos/dbus/federated/federated_client.h" #include "chromeos/dbus/hermes/hermes_clients.h" #include "chromeos/dbus/init/initialize_dbus_client.h" #include "chromeos/dbus/ip_peripheral/ip_peripheral_service_client.h" #include "chromeos/dbus/kerberos/kerberos_client.h" #include "chromeos/dbus/machine_learning/machine_learning_client.h" #include "chromeos/dbus/media_analytics/media_analytics_client.h" #include "chromeos/dbus/missive/missive_client.h" #include "chromeos/dbus/os_install/os_install_client.h" #include "chromeos/dbus/pciguard/pciguard_client.h" #include "chromeos/dbus/permission_broker/permission_broker_client.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/resourced/resourced_client.h" #include "chromeos/dbus/rmad/rmad_client.h" #include "chromeos/dbus/seneschal/seneschal_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/dbus/system_clock/system_clock_client.h" #include "chromeos/dbus/system_proxy/system_proxy_client.h" #include "chromeos/dbus/tpm_manager/tpm_manager_client.h" #include "chromeos/dbus/typecd/typecd_client.h" #include "chromeos/dbus/u2f/u2f_client.h" #include "chromeos/dbus/upstart/upstart_client.h" #include "chromeos/dbus/userdataauth/arc_quota_client.h" #include "chromeos/dbus/userdataauth/cryptohome_misc_client.h" #include "chromeos/dbus/userdataauth/cryptohome_pkcs11_client.h" #include "chromeos/dbus/userdataauth/install_attributes_client.h" #include "chromeos/dbus/userdataauth/userdataauth_client.h" #include "chromeos/tpm/install_attributes.h" #include "device/bluetooth/dbus/bluez_dbus_manager.h" #include "device/bluetooth/floss/floss_dbus_manager.h" #include "device/bluetooth/floss/floss_features.h" #if BUILDFLAG(PLATFORM_CFM) #include "chromeos/components/chromebox_for_meetings/features/features.h" #include "chromeos/dbus/chromebox_for_meetings/cfm_hotline_client.h" #endif namespace { // If running on desktop, override paths so that enrollment and cloud policy // work correctly, and can be tested. void OverrideStubPathsIfNeeded() { base::FilePath user_data_dir; if (!base::SysInfo::IsRunningOnChromeOS() && base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) { chromeos::RegisterStubPathOverrides(user_data_dir); chromeos::dbus_paths::RegisterStubPathOverrides(user_data_dir); } } } // namespace namespace ash { void InitializeDBus() { using chromeos::InitializeDBusClient; OverrideStubPathsIfNeeded(); chromeos::SystemSaltGetter::Initialize(); // Initialize DBusThreadManager for the browser. chromeos::DBusThreadManager::Initialize(); // Initialize Chrome dbus clients. dbus::Bus* bus = chromeos::DBusThreadManager::Get()->GetSystemBus(); // NOTE: base::Feature is not initialized yet, so any non MultiProcessMash // dbus client initialization for Ash should be done in Shell::Init. InitializeDBusClient<chromeos::ArcCameraClient>(bus); InitializeDBusClient<chromeos::ArcQuotaClient>(bus); InitializeDBusClient<chromeos::ArcSensorServiceClient>(bus); InitializeDBusClient<chromeos::AttestationClient>(bus); InitializeDBusClient<chromeos::AuthPolicyClient>(bus); InitializeDBusClient<chromeos::BiodClient>(bus); // For device::Fingerprint. InitializeDBusClient<chromeos::CdmFactoryDaemonClient>(bus); InitializeDBusClient<chromeos::CiceroneClient>(bus); // ConciergeClient depends on CiceroneClient. InitializeDBusClient<chromeos::ConciergeClient>(bus); InitializeDBusClient<chromeos::CrasAudioClient>(bus); InitializeDBusClient<chromeos::CrosHealthdClient>(bus); InitializeDBusClient<chromeos::CryptohomeMiscClient>(bus); InitializeDBusClient<chromeos::CryptohomePkcs11Client>(bus); InitializeDBusClient<chromeos::CupsProxyClient>(bus); InitializeDBusClient<chromeos::DlcserviceClient>(bus); InitializeDBusClient<chromeos::DlpClient>(bus); InitializeDBusClient<chromeos::FederatedClient>(bus); chromeos::hermes_clients::Initialize(bus); InitializeDBusClient<chromeos::InstallAttributesClient>(bus); InitializeDBusClient<chromeos::IpPeripheralServiceClient>(bus); InitializeDBusClient<chromeos::KerberosClient>(bus); InitializeDBusClient<chromeos::MachineLearningClient>(bus); InitializeDBusClient<chromeos::MediaAnalyticsClient>(bus); InitializeDBusClient<chromeos::MissiveClient>(bus); InitializeDBusClient<chromeos::OsInstallClient>(bus); InitializeDBusClient<chromeos::PciguardClient>(bus); InitializeDBusClient<chromeos::PermissionBrokerClient>(bus); InitializeDBusClient<chromeos::PowerManagerClient>(bus); InitializeDBusClient<chromeos::ResourcedClient>(bus); InitializeDBusClient<chromeos::SeneschalClient>(bus); InitializeDBusClient<chromeos::SessionManagerClient>(bus); InitializeDBusClient<chromeos::SystemClockClient>(bus); InitializeDBusClient<chromeos::SystemProxyClient>(bus); InitializeDBusClient<chromeos::TpmManagerClient>(bus); InitializeDBusClient<chromeos::TypecdClient>(bus); InitializeDBusClient<chromeos::U2FClient>(bus); InitializeDBusClient<chromeos::UserDataAuthClient>(bus); InitializeDBusClient<chromeos::UpstartClient>(bus); // Initialize the device settings service so that we'll take actions per // signals sent from the session manager. This needs to happen before // g_browser_process initializes BrowserPolicyConnector. chromeos::DeviceSettingsService::Initialize(); chromeos::InstallAttributes::Initialize(); } void InitializeFeatureListDependentDBus() { using chromeos::InitializeDBusClient; dbus::Bus* bus = chromeos::DBusThreadManager::Get()->GetSystemBus(); if (base::FeatureList::IsEnabled(floss::features::kFlossEnabled)) { InitializeDBusClient<floss::FlossDBusManager>(bus); } else { InitializeDBusClient<bluez::BluezDBusManager>(bus); } #if BUILDFLAG(PLATFORM_CFM) if (base::FeatureList::IsEnabled(chromeos::cfm::features::kMojoServices)) { InitializeDBusClient<chromeos::CfmHotlineClient>(bus); } #endif if (ash::features::IsShimlessRMAFlowEnabled()) { InitializeDBusClient<chromeos::RmadClient>(bus); } InitializeDBusClient<chromeos::WilcoDtcSupportdClient>(bus); } void ShutdownDBus() { // Feature list-dependent D-Bus clients are shut down first because we try to // shut down in reverse order of initialization (in case of dependencies). chromeos::WilcoDtcSupportdClient::Shutdown(); #if BUILDFLAG(PLATFORM_CFM) if (base::FeatureList::IsEnabled(chromeos::cfm::features::kMojoServices)) { chromeos::CfmHotlineClient::Shutdown(); } #endif if (base::FeatureList::IsEnabled(floss::features::kFlossEnabled)) { floss::FlossDBusManager::Shutdown(); } else { bluez::BluezDBusManager::Shutdown(); } // Other D-Bus clients are shut down, also in reverse order of initialization. chromeos::UpstartClient::Shutdown(); chromeos::UserDataAuthClient::Shutdown(); chromeos::U2FClient::Shutdown(); chromeos::TypecdClient::Shutdown(); chromeos::TpmManagerClient::Shutdown(); chromeos::SystemProxyClient::Shutdown(); chromeos::SystemClockClient::Shutdown(); chromeos::SessionManagerClient::Shutdown(); chromeos::SeneschalClient::Shutdown(); chromeos::ResourcedClient::Shutdown(); if (ash::features::IsShimlessRMAFlowEnabled()) { chromeos::RmadClient::Shutdown(); } chromeos::PowerManagerClient::Shutdown(); chromeos::PermissionBrokerClient::Shutdown(); chromeos::PciguardClient::Shutdown(); chromeos::OsInstallClient::Shutdown(); chromeos::MissiveClient::Shutdown(); chromeos::MediaAnalyticsClient::Shutdown(); chromeos::MachineLearningClient::Shutdown(); chromeos::KerberosClient::Shutdown(); chromeos::IpPeripheralServiceClient::Shutdown(); chromeos::InstallAttributesClient::Shutdown(); chromeos::hermes_clients::Shutdown(); chromeos::FederatedClient::Shutdown(); chromeos::DlcserviceClient::Shutdown(); chromeos::DlpClient::Shutdown(); chromeos::CupsProxyClient::Shutdown(); chromeos::CryptohomePkcs11Client::Shutdown(); chromeos::CryptohomeMiscClient::Shutdown(); chromeos::CrosHealthdClient::Shutdown(); chromeos::CrasAudioClient::Shutdown(); chromeos::ConciergeClient::Shutdown(); chromeos::CiceroneClient::Shutdown(); chromeos::CdmFactoryDaemonClient::Shutdown(); chromeos::BiodClient::Shutdown(); chromeos::AuthPolicyClient::Shutdown(); chromeos::AttestationClient::Shutdown(); chromeos::ArcQuotaClient::Shutdown(); chromeos::ArcCameraClient::Shutdown(); chromeos::DBusThreadManager::Shutdown(); chromeos::SystemSaltGetter::Shutdown(); } } // namespace ash