blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
0bafafd0826861b7496a903054ef1e369a24c058
9012f534bb271c30750f73da81252dfa62def9be
/JuneCC3.cpp
8ad79e0798fd9de2c57c2ef3fe866c4c150fd84e
[]
no_license
akulkanojia2414/Spoj_questions
a90d08cc3cb4dc943e0dedcf9bf17c14e1215ed6
14742ea8efa17927e32d565a0f02b09d246264a7
refs/heads/master
2021-01-18T13:58:30.917482
2015-01-14T09:11:22
2015-01-14T09:11:22
23,980,064
0
0
null
null
null
null
UTF-8
C++
false
false
1,306
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <utility> #include <map> #include <vector> #include <list> #include <string> #include <set> #include <queue> #include <ctime> #include <fstream> #include <sstream> #include <cmath> #include <limits> using namespace std; char a[100000]; bool num_visited[10] ={0}; vector<long long> vec[10]; int ctr[100000] = {0}; bool visit[100000] = {0}; int len,cur,temp,i; int main() { queue<int> q; scanf("%s",a); len = strlen(a); for( i=0;i<len;i++) { vec[a[i]-'0'].push_back(i); } q.push(0); visit[0] = true; while(!q.empty()) { cur = q.front(); q.pop(); //cout<<cur<<endl; //if(visit[cur]==true) goto again; if(cur == len-1) break; temp = vec[a[cur]-'0'].size(); if(visit[cur+1]==false&&cur!=len-1){ visit[cur+1] = true; q.push(cur+1); ctr[cur+1] =ctr[cur]+1;} if(cur!=0&&visit[cur-1]==false){visit[cur-1]=true; q.push(cur-1); ctr[cur-1] = ctr[cur]+1;} //if(num_visited[a[cur]-'0']==false){ for(i =0;i<temp;i++) { if(visit[vec[a[cur]-'0'][i]]==false) {visit[vec[a[cur]-'0'][i]] = true; q.push(vec[a[cur]-'0'][i]); ctr[vec[a[cur]-'0'][i]] = ctr[cur]+1;} //} //q.push(cur); } num_visited[a[cur]-'0'] = true; } //124 q.clear(); printf("%d",ctr[len-1]); }
[ "akulkanojia2414@gmail.com" ]
akulkanojia2414@gmail.com
eb818170b5a96f8b27411b53aebf140017c4b893
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.h
0d7fc485dc7c9c93e574608b4f1b934d990501ca
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
2,784
h
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 2000 Simon Hausmann <hausmann@kde.org> * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef LayoutEmbeddedObject_h #define LayoutEmbeddedObject_h #include "core/layout/LayoutPart.h" namespace blink { class TextRun; // LayoutObject for embeds and objects, often, but not always, rendered via plugins. // For example, <embed src="foo.html"> does not invoke a plugin. class LayoutEmbeddedObject : public LayoutPart { public: LayoutEmbeddedObject(Element*); ~LayoutEmbeddedObject() override; enum PluginAvailability { PluginAvailable, PluginMissing, PluginBlockedByContentSecurityPolicy, }; void setPluginAvailability(PluginAvailability); bool showsUnavailablePluginIndicator() const; const char* name() const override { return "LayoutEmbeddedObject"; } const String& unavailablePluginReplacementText() const { return m_unavailablePluginReplacementText; } private: void paintContents(const PaintInfo&, const LayoutPoint&) const final; void paintReplaced(const PaintInfo&, const LayoutPoint&) const final; void paint(const PaintInfo&, const LayoutPoint&) const final; void layout() final; PaintInvalidationReason invalidatePaintIfNeeded(const PaintInvalidationState&) final; bool isOfType(LayoutObjectType type) const override { return type == LayoutObjectEmbeddedObject || LayoutPart::isOfType(type); } LayoutReplaced* embeddedReplacedContent() const final; PaintLayerType layerTypeRequired() const final; ScrollResult scroll(ScrollGranularity, const FloatSize&) final; CompositingReasons additionalCompositingReasons() const override; PluginAvailability m_pluginAvailability = PluginAvailable; String m_unavailablePluginReplacementText; }; DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutEmbeddedObject, isEmbeddedObject()); } // namespace blink #endif // LayoutEmbeddedObject_h
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
e9f3a1626afacd0b667d0d1f79c005d20021e582
1e68fb42e7ce3643398f8b1b6563f9892d329e0b
/dsa/connected components in undirected graph.cpp
5090b3abd906f35b606406a809dac72923b7d510
[]
no_license
anonymoushey/DSA_COMPARCH_PROGRAMMING-
cf4906341517597f4f7e5de4cf6abf99cc300b61
f955b173ffb16b785c92fb5e44372ef104ca0620
refs/heads/master
2020-12-04T04:31:29.716813
2020-01-03T20:12:51
2020-01-03T20:12:51
231,613,130
0
0
null
null
null
null
UTF-8
C++
false
false
1,724
cpp
// C++ program to print connected components in // an undirected graph #include<iostream> #include <list> using namespace std; // Graph class represents a undirected graph // using adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency lists list<int> *adj; // A function used by DFS void DFSUtil(int v, bool visited[]); public: Graph(int V); // Constructor void addEdge(int v, int w); void connectedComponents(); }; // Method to print connected components in an // undirected graph void Graph::connectedComponents() { // Mark all the vertices as not visited bool *visited = new bool[V]; for(int v = 0; v < V; v++) visited[v] = false; for (int v=0; v<V; v++) { if (visited[v] == false) { // print all reachable vertices // from v DFSUtil(v, visited); cout << "\n"; } } } void Graph::DFSUtil(int v, bool visited[]) { // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) if(!visited[*i]) DFSUtil(*i, visited); } Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } // method to add an undirected edge void Graph::addEdge(int v, int w) { adj[v].push_back(w); adj[w].push_back(v); } // Drive program to test above int main() { // Create a graph given in the above diagram Graph g(5); // 5 vertices numbered from 0 to 4 g.addEdge(1, 0); g.addEdge(2, 3); g.addEdge(3, 4); cout << "Following are connected components \n"; g.connectedComponents(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
7f17956c4f4927de5d024fbc4a88ccb6f8ee47cd
e6b96681b393ae335f2f7aa8db84acc65a3e6c8d
/atcoder.jp/arc022/arc022_1/Main.cpp
7bdf6c6577dae19ec96f0c36f1eaabadb3fd3818
[]
no_license
okuraofvegetable/AtCoder
a2e92f5126d5593d01c2c4d471b1a2c08b5d3a0d
dd535c3c1139ce311503e69938611f1d7311046d
refs/heads/master
2022-02-21T15:19:26.172528
2021-03-27T04:04:55
2021-03-27T04:04:55
249,614,943
0
0
null
null
null
null
UTF-8
C++
false
false
3,274
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> P; #define eps 1e-9 #define INF 2000000000 // 2e9 #define LLINF 2000000000000000000ll // 2e18 (llmax:9e18) #define all(x) (x).begin(), (x).end() #define sq(x) ((x) * (x)) #ifndef LOCAL #define dmp(...) ; #else #define dmp(...) \ cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl #endif // ---------------- Utility ------------------ template <class T> bool chmin(T &a, const T &b) { if (a <= b) return false; a = b; return true; } template <class T> bool chmax(T &a, const T &b) { if (a >= b) return false; a = b; return true; } template <class T> using MaxHeap = priority_queue<T>; template <class T> using MinHeap = priority_queue<T, vector<T>, greater<T>>; template <class T> vector<T> vect(int len, T elem) { return vector<T>(len, elem); } // ----------------- Input ------------------- template <class T, class U> istream &operator>>(istream &is, pair<T, U> &p) { return is >> p.first >> p.second; } template <class T> istream &operator>>(istream &is, vector<T> &vec) { for (int i = 0; i < vec.size(); i++) is >> vec[i]; return is; } // ----------------- Output ------------------ template <class T, class U> ostream &operator<<(ostream &os, const pair<T, U> &p) { return os << p.first << ',' << p.second; } template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { for (const T &e : v) os << e << " "; return os; } template <class T> ostream &operator<<(ostream &os, const deque<T> &d) { for (const T &e : d) os << e << " "; return os; } template <class T> ostream &operator<<(ostream &os, const set<T> &s) { os << "{ "; for (const T &e : s) os << e << " "; return os << "}"; } template <class T, class U> ostream &operator<<(ostream &os, const map<T, U> &m) { os << "{ "; for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) "; return os << "}"; } void dump_str_rec(ostringstream &) {} template <class Head, class... Tail> void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) { oss << ", " << head; dump_str_rec(oss, forward<Tail>(tail)...); } template <class T, class... U> string dump_str(T &&arg, U &&... args) { ostringstream oss; oss << arg; dump_str_rec(oss, forward<U>(args)...); return oss.str(); } // --------------- Fast I/O ------------------ void fastio() { cin.tie(0); ios::sync_with_stdio(0); cout << fixed << setprecision(20); } // ------------ End of template -------------- #define endl "\n" void solve() { string s; cin >> s; for (int i = 0; i < s.size(); i++) s[i] = toupper(s[i]); for (int i = 0; i < s.size(); i++) { for (int j = i + 1; j < s.size(); j++) { for (int k = j + 1; k < s.size(); k++) { if (s[i] == 'I' && s[j] == 'C' && s[k] == 'T') { cout << "YES" << endl; return; } } } } cout << "NO" << endl; return; } int main() { fastio(); solve(); // while (solve()) {} // int t; cin >> t; while(t--)solve(); // int t; cin >> t; // for(int i=1;i<=t;i++){ // cout << "Case #" << i << ": "; // solve(); // } return 0; }
[ "okuraofvegetable@gmail.com" ]
okuraofvegetable@gmail.com
63c0708f75a6d902616a3513c2d5a36d84b4d518
0dc9c38042c809acf28b8eff086a615026520705
/src/OpenLoco/Paint/Paint.cpp
2c4a056df99014b91a2abc268ba2e893a8c7ddec
[ "MIT" ]
permissive
guTheKing/OpenLoco
6f568af38bc4574ccdb3047eb57f3a61c5155e35
4914cbd2e3b818a526321e28c57407693c2b476e
refs/heads/master
2023-04-24T17:03:42.188226
2021-05-05T14:34:32
2021-05-05T14:34:32
364,663,985
0
0
null
null
null
null
UTF-8
C++
false
false
21,731
cpp
#include "Paint.h" #include "../Graphics/Gfx.h" #include "../Interop/Interop.hpp" #include "../Map/Tile.h" #include "../StationManager.h" #include "../TownManager.h" #include "../Ui.h" #include "../Ui/WindowManager.h" #include "PaintEntity.h" using namespace OpenLoco::Interop; using namespace OpenLoco::Ui::ViewportInteraction; namespace OpenLoco::Paint { PaintSession _session; void PaintSession::setEntityPosition(const Map::Pos2& pos) { _spritePositionX = pos.x; _spritePositionY = pos.y; } loco_global<int32_t[4], 0x4FD120> _4FD120; loco_global<int32_t[4], 0x4FD130> _4FD130; loco_global<int32_t[4], 0x4FD140> _4FD140; loco_global<int32_t[4], 0x4FD200> _4FD200; // 0x004FD120 void PaintSession::addToStringPlotList(uint32_t amount, string_id stringId, uint16_t y, uint16_t z, const int8_t* y_offsets, int16_t offset_x) { registers regs; regs.bx = stringId; regs.edi = reinterpret_cast<int32_t>(y_offsets); regs.si = offset_x; regs.eax = amount; regs.cx = y; regs.dx = z; call(_4FD120[currentRotation], regs); } // 0x004FD120 void PaintSession::addToStringPlotList(uint32_t amount, string_id stringId, uint16_t y, uint16_t z, const int8_t* y_offsets, int16_t offset_x, uint16_t colour) { registers regs; regs.bx = stringId; regs.edi = reinterpret_cast<int32_t>(y_offsets); regs.si = offset_x; regs.eax = amount; regs.cx = y; regs.dx = z; addr<0xE3F0A8, uint16_t>() = colour; call(_4FD120[currentRotation], regs); } // 0x004FD130 void PaintSession::addToPlotListAsParent(uint32_t imageId, const Map::Pos3& offset, const Map::Pos3& boundBoxSize) { registers regs; regs.ebx = imageId; regs.al = offset.x; regs.cl = offset.y; regs.dx = offset.z; regs.di = boundBoxSize.x; regs.si = boundBoxSize.y; regs.ah = boundBoxSize.z; call(_4FD130[currentRotation], regs); } // 0x004FD140 void PaintSession::addToPlotListAsParent(uint32_t imageId, const Map::Pos3& offset, const Map::Pos3& boundBoxOffset, const Map::Pos3& boundBoxSize) { registers regs; regs.ebx = imageId; regs.al = offset.x; regs.cl = offset.y; regs.dx = offset.z; regs.di = boundBoxSize.x; regs.si = boundBoxSize.y; regs.ah = boundBoxSize.z; addr<0xE3F0A0, int16_t>() = boundBoxOffset.x; addr<0xE3F0A2, int16_t>() = boundBoxOffset.y; addr<0xE3F0A4, uint16_t>() = boundBoxOffset.z; call(_4FD140[currentRotation], regs); } // 0x004FD200 void PaintSession::addToPlotList4FD200(uint32_t imageId, const Map::Pos3& offset, const Map::Pos3& boundBoxOffset, const Map::Pos3& boundBoxSize) { registers regs; regs.ebx = imageId; regs.al = offset.x; regs.cl = offset.y; regs.dx = offset.z; regs.di = boundBoxSize.x; regs.si = boundBoxSize.y; regs.ah = boundBoxSize.z; addr<0xE3F0A0, int16_t>() = boundBoxOffset.x; addr<0xE3F0A2, int16_t>() = boundBoxOffset.y; addr<0xE3F0A4, uint16_t>() = boundBoxOffset.z; call(_4FD200[currentRotation], regs); } // 0x0045E779 void PaintSession::attachToPrevious(uint32_t imageId, const Map::Pos2& offset) { registers regs; regs.ebx = imageId; regs.ax = offset.x; regs.cx = offset.y; call(0x0045E779, regs); } void PaintSession::init(Gfx::drawpixelinfo_t& dpi, const uint16_t viewportFlags) { _dpi = &dpi; _nextFreePaintStruct = &_paintEntries[0]; _endOfPaintStructArray = &_paintEntries[3998]; _lastPS = nullptr; for (auto& quadrant : _quadrants) { quadrant = nullptr; } _quadrantBackIndex = -1; _quadrantFrontIndex = 0; _lastPaintString = 0; _paintStringHead = 0; } // 0x0045A6CA PaintSession* allocateSession(Gfx::drawpixelinfo_t& dpi, uint16_t viewportFlags) { _session.init(dpi, viewportFlags); return &_session; } void registerHooks() { registerHook( 0x004622A2, [](registers& regs) -> uint8_t { registers backup = regs; PaintSession session; session.generate(); regs = backup; return 0; }); } // 0x00461CF8 static void paintTileElements(PaintSession& session, const Map::Pos2& loc) { registers regs{}; regs.eax = loc.x; regs.ecx = loc.y; call(0x00461CF8, regs); } // 0x004617C6 static void paintTileElements2(PaintSession& session, const Map::Pos2& loc) { registers regs{}; regs.eax = loc.x; regs.ecx = loc.y; call(0x004617C6, regs); } struct GenerationParameters { Map::Pos2 mapLoc; uint16_t numVerticalQuadrants; std::array<Map::Pos2, 5> additionalQuadrants; Map::Pos2 nextVerticalQuadrant; }; template<uint8_t rotation> GenerationParameters generateParameters(Gfx::drawpixelinfo_t* context) { // TODO: Work out what these constants represent uint16_t numVerticalQuadrants = (context->height + (rotation == 0 ? 1040 : 1056)) >> 5; auto mapLoc = Ui::viewportCoordToMapCoord(static_cast<int16_t>(context->x & 0xFFE0), static_cast<int16_t>((context->y - 16) & 0xFFE0), 0, rotation); if constexpr (rotation & 1) { mapLoc.y -= 16; } mapLoc.x &= 0xFFE0; mapLoc.y &= 0xFFE0; constexpr uint8_t rotOrder[] = { 0, 3, 2, 1 }; const auto direction = rotOrder[rotation]; constexpr std::array<Map::Pos2, 5> additionalQuadrants = { Math::Vector::rotate(Map::Pos2{ -32, 32 }, direction), Math::Vector::rotate(Map::Pos2{ 0, 32 }, direction), Math::Vector::rotate(Map::Pos2{ 32, 0 }, direction), Math::Vector::rotate(Map::Pos2{ 32, -32 }, direction), Math::Vector::rotate(Map::Pos2{ -32, 64 }, direction), }; constexpr auto nextVerticalQuadrant = Math::Vector::rotate(Map::Pos2{ 32, 32 }, direction); return { mapLoc, numVerticalQuadrants, additionalQuadrants, nextVerticalQuadrant }; } void PaintSession::generateTilesAndEntities(GenerationParameters&& p) { for (; p.numVerticalQuadrants > 0; --p.numVerticalQuadrants) { paintTileElements(*this, p.mapLoc); paintEntities(*this, p.mapLoc); auto loc1 = p.mapLoc + p.additionalQuadrants[0]; paintTileElements2(*this, loc1); paintEntities(*this, loc1); auto loc2 = p.mapLoc + p.additionalQuadrants[1]; paintTileElements(*this, loc2); paintEntities(*this, loc2); auto loc3 = p.mapLoc + p.additionalQuadrants[2]; paintTileElements2(*this, loc3); paintEntities(*this, loc3); auto loc4 = p.mapLoc + p.additionalQuadrants[3]; paintEntities2(*this, loc4); auto loc5 = p.mapLoc + p.additionalQuadrants[4]; paintEntities2(*this, loc5); p.mapLoc += p.nextVerticalQuadrant; } } // 0x004622A2 void PaintSession::generate() { if ((addr<0x00525E28, uint32_t>() & (1 << 0)) == 0) return; currentRotation = Ui::WindowManager::getCurrentRotation(); switch (currentRotation) { case 0: generateTilesAndEntities(generateParameters<0>(getContext())); break; case 1: generateTilesAndEntities(generateParameters<1>(getContext())); break; case 2: generateTilesAndEntities(generateParameters<2>(getContext())); break; case 3: generateTilesAndEntities(generateParameters<3>(getContext())); break; } } template<uint8_t> static bool checkBoundingBox(const PaintStructBoundBox& initialBBox, const PaintStructBoundBox& currentBBox) { return false; } template<> bool checkBoundingBox<0>(const PaintStructBoundBox& initialBBox, const PaintStructBoundBox& currentBBox) { if (initialBBox.zEnd >= currentBBox.z && initialBBox.yEnd >= currentBBox.y && initialBBox.xEnd >= currentBBox.x && !(initialBBox.z < currentBBox.zEnd && initialBBox.y < currentBBox.yEnd && initialBBox.x < currentBBox.xEnd)) { return true; } return false; } template<> bool checkBoundingBox<1>(const PaintStructBoundBox& initialBBox, const PaintStructBoundBox& currentBBox) { if (initialBBox.zEnd >= currentBBox.z && initialBBox.yEnd >= currentBBox.y && initialBBox.xEnd < currentBBox.x && !(initialBBox.z < currentBBox.zEnd && initialBBox.y < currentBBox.yEnd && initialBBox.x >= currentBBox.xEnd)) { return true; } return false; } template<> bool checkBoundingBox<2>(const PaintStructBoundBox& initialBBox, const PaintStructBoundBox& currentBBox) { if (initialBBox.zEnd >= currentBBox.z && initialBBox.yEnd < currentBBox.y && initialBBox.xEnd < currentBBox.x && !(initialBBox.z < currentBBox.zEnd && initialBBox.y >= currentBBox.yEnd && initialBBox.x >= currentBBox.xEnd)) { return true; } return false; } template<> bool checkBoundingBox<3>(const PaintStructBoundBox& initialBBox, const PaintStructBoundBox& currentBBox) { if (initialBBox.zEnd >= currentBBox.z && initialBBox.yEnd < currentBBox.y && initialBBox.xEnd >= currentBBox.x && !(initialBBox.z < currentBBox.zEnd && initialBBox.y >= currentBBox.yEnd && initialBBox.x < currentBBox.xEnd)) { return true; } return false; } template<uint8_t _TRotation> static PaintStruct* arrangeStructsHelperRotation(PaintStruct* psNext, const uint16_t quadrantIndex, const uint8_t flag) { PaintStruct* ps = nullptr; do { ps = psNext; psNext = psNext->nextQuadrantPS; if (psNext == nullptr) return ps; } while (quadrantIndex > psNext->quadrantIndex); // Cache the last visited node so we don't have to walk the whole list again auto* psCache = ps; auto* psTemp = ps; do { ps = ps->nextQuadrantPS; if (ps == nullptr) break; if (ps->quadrantIndex > quadrantIndex + 1) { ps->quadrantFlags = QuadrantFlags::bigger; } else if (ps->quadrantIndex == quadrantIndex + 1) { ps->quadrantFlags = QuadrantFlags::next | QuadrantFlags::identical; } else if (ps->quadrantIndex == quadrantIndex) { ps->quadrantFlags = flag | QuadrantFlags::identical; } } while (ps->quadrantIndex <= quadrantIndex + 1); ps = psTemp; while (true) { while (true) { psNext = ps->nextQuadrantPS; if (psNext == nullptr) return psCache; if (psNext->quadrantFlags & QuadrantFlags::bigger) return psCache; if (psNext->quadrantFlags & QuadrantFlags::identical) break; ps = psNext; } psNext->quadrantFlags &= ~QuadrantFlags::identical; psTemp = ps; const PaintStructBoundBox& initialBBox = psNext->bounds; while (true) { ps = psNext; psNext = psNext->nextQuadrantPS; if (psNext == nullptr) break; if (psNext->quadrantFlags & QuadrantFlags::bigger) break; if (!(psNext->quadrantFlags & QuadrantFlags::next)) continue; const PaintStructBoundBox& currentBBox = psNext->bounds; const bool compareResult = checkBoundingBox<_TRotation>(initialBBox, currentBBox); if (compareResult) { ps->nextQuadrantPS = psNext->nextQuadrantPS; PaintStruct* ps_temp2 = psTemp->nextQuadrantPS; psTemp->nextQuadrantPS = psNext; psNext->nextQuadrantPS = ps_temp2; psNext = ps; } } ps = psTemp; } } static PaintStruct* arrangeStructsHelper(PaintStruct* psNext, uint16_t quadrantIndex, uint8_t flag, uint8_t rotation) { switch (rotation) { case 0: return arrangeStructsHelperRotation<0>(psNext, quadrantIndex, flag); case 1: return arrangeStructsHelperRotation<1>(psNext, quadrantIndex, flag); case 2: return arrangeStructsHelperRotation<2>(psNext, quadrantIndex, flag); case 3: return arrangeStructsHelperRotation<3>(psNext, quadrantIndex, flag); } return nullptr; } // 0x0045E7B5 void PaintSession::arrangeStructs() { _paintHead = _nextFreePaintStruct; _nextFreePaintStruct++; PaintStruct* ps = &(*_paintHead)->basic; ps->nextQuadrantPS = nullptr; uint32_t quadrantIndex = _quadrantBackIndex; if (quadrantIndex == std::numeric_limits<uint32_t>::max()) { return; } do { PaintStruct* psNext = _quadrants[quadrantIndex]; if (psNext != nullptr) { ps->nextQuadrantPS = psNext; do { ps = psNext; psNext = psNext->nextQuadrantPS; } while (psNext != nullptr); } } while (++quadrantIndex <= _quadrantFrontIndex); PaintStruct* psCache = arrangeStructsHelper( &(*_paintHead)->basic, _quadrantBackIndex & 0xFFFF, QuadrantFlags::next, currentRotation); quadrantIndex = _quadrantBackIndex; while (++quadrantIndex < _quadrantFrontIndex) { psCache = arrangeStructsHelper(psCache, quadrantIndex & 0xFFFF, 0, currentRotation); } } static bool isSpriteInteractedWithPaletteSet(Gfx::drawpixelinfo_t* dpi, uint32_t imageId, const Gfx::point_t& coords, const Gfx::PaletteMap& paletteMap) { static loco_global<const uint8_t*, 0x0050B860> _paletteMap; static loco_global<bool, 0x00E40114> _interactionResult; _paletteMap = paletteMap.data(); registers regs{}; regs.ebx = imageId; regs.edi = reinterpret_cast<int32_t>(dpi); regs.cx = coords.x; regs.dx = coords.y; call(0x00447A5F, regs); return _interactionResult; } // 0x00447A0E static bool isSpriteInteractedWith(Gfx::drawpixelinfo_t* dpi, uint32_t imageId, const Gfx::point_t& coords) { static loco_global<bool, 0x00E40114> _interactionResult; static loco_global<uint32_t, 0x00E04324> _interactionFlags; _interactionResult = false; auto paletteMap = Gfx::PaletteMap::getDefault(); imageId &= ~Gfx::ImageIdFlags::translucent; if (imageId & Gfx::ImageIdFlags::remap) { _interactionFlags = Gfx::ImageIdFlags::remap; int32_t index = (imageId >> 19) & 0x7F; if (imageId & Gfx::ImageIdFlags::remap2) { index &= 0x1F; } if (auto pm = Gfx::getPaletteMapForColour(index)) { paletteMap = *pm; } } else { _interactionFlags = 0; } return isSpriteInteractedWithPaletteSet(dpi, imageId, coords, paletteMap); } // 0x0045EDFC static bool isPSSpriteTypeInFilter(const InteractionItem spriteType, uint32_t filter) { constexpr uint32_t interactionItemToFilter[] = { 0, InteractionItemFlags::surface, InteractionItemFlags::surface, InteractionItemFlags::entity, InteractionItemFlags::track, InteractionItemFlags::trackExtra, InteractionItemFlags::signal, InteractionItemFlags::station, InteractionItemFlags::station, InteractionItemFlags::station, InteractionItemFlags::station, InteractionItemFlags::water, InteractionItemFlags::tree, InteractionItemFlags::wall, InteractionItemFlags::townLabel, InteractionItemFlags::stationLabel, InteractionItemFlags::roadAndTram, InteractionItemFlags::roadAndTramExtra, 0, InteractionItemFlags::building, InteractionItemFlags::industry, InteractionItemFlags::headquarterBuilding }; if (spriteType == InteractionItem::noInteraction || spriteType == InteractionItem::bridge) // 18 as a type seems to not exist. return false; uint32_t mask = interactionItemToFilter[static_cast<size_t>(spriteType)]; if (filter & mask) { return false; } return true; } // 0x0045ED91 [[nodiscard]] InteractionArg PaintSession::getNormalInteractionInfo(const uint32_t flags) { InteractionArg info{}; for (auto* ps = (*_paintHead)->basic.nextQuadrantPS; ps != nullptr; ps = ps->nextQuadrantPS) { auto* tempPS = ps; auto* nextPS = ps; while (nextPS != nullptr) { ps = nextPS; if (isSpriteInteractedWith(getContext(), ps->imageId, { ps->x, ps->y })) { if (isPSSpriteTypeInFilter(ps->type, flags)) { info = { *ps }; } } nextPS = ps->children; } for (auto* attachedPS = ps->attachedPS; attachedPS != nullptr; attachedPS = attachedPS->next) { if (isSpriteInteractedWith(getContext(), attachedPS->imageId, { static_cast<int16_t>(attachedPS->x + ps->x), static_cast<int16_t>(attachedPS->y + ps->y) })) { if (isPSSpriteTypeInFilter(ps->type, flags)) { info = { *ps }; } } } ps = tempPS; } return info; } // 0x0048DDE4 [[nodiscard]] InteractionArg PaintSession::getStationNameInteractionInfo(const uint32_t flags) { InteractionArg interaction{}; if (flags & InteractionItemFlags::stationLabel) { return interaction; } auto rect = (*_dpi)->getDrawableRect(); for (auto& station : StationManager::stations()) { if (station.empty()) { continue; } if (station.flags & StationFlags::flag_5) { continue; } if (!station.labelFrame.contains(rect, (*_dpi)->zoom_level)) { continue; } interaction.type = InteractionItem::stationLabel; interaction.value = station.id(); interaction.pos.x = station.x; interaction.pos.y = station.y; } return interaction; } // 0x0049773D [[nodiscard]] InteractionArg PaintSession::getTownNameInteractionInfo(const uint32_t flags) { InteractionArg interaction{}; if (flags & InteractionItemFlags::townLabel) { return interaction; } auto rect = (*_dpi)->getDrawableRect(); for (auto& town : TownManager::towns()) { if (town.empty()) { continue; } if (!town.labelFrame.contains(rect, (*_dpi)->zoom_level)) { continue; } interaction.type = InteractionItem::townLabel; interaction.value = town.id(); interaction.pos.x = town.x; interaction.pos.y = town.y; } return interaction; } }
[ "noreply@github.com" ]
noreply@github.com
13905b0c206805e88bcc4cdf7377e041b4c21465
5584ed962e2da2e3001ff4ab99bcb6594b8bf0e1
/src/utils.cpp
54263b6daf4343cae7befa7f7157b73fb068294a
[ "MIT" ]
permissive
ICRA-2020/miccol-Experiments
a9ed20a25b17516f7fd6a7f01694a8d88c4b203e
458823500e83912c635c8e3bf31ad602af7fe8e2
refs/heads/master
2022-02-20T08:28:22.689476
2019-10-03T07:34:45
2019-10-03T07:34:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,625
cpp
#include <utils.h> #include <iostream> #include <definitions.h> #include <math.h> /* log2 */ #include <chrono> #include <random> #include <thread> #include <sstream> #include <fstream> using namespace std; void printState(bstate state) { if (state.rows() > 0) { for (int i = 0; i < state.size(); i++ ) { cout << state(i) << " "; } } cout << endl; } string bstate_to_string(bstate state) { std::ostringstream strs; if (state.rows() > 0) { for (int i = 0; i < state.size(); i++ ) { strs << state[i] << " "; } } return strs.str(); } float entropy(bstate state) { float entropy = 0.0; for (int i = 0; i < state.size(); i++ ) { if(state[i] > 0) entropy -= state[i]*log(state[i]); } return entropy; } int draw(std::vector<float> probabilities) { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine gen(seed); std::discrete_distribution<int> distribution(probabilities.begin(), probabilities.end()); return distribution(gen); } int generateRandomNumber(int max) { std::this_thread::sleep_for(std::chrono::nanoseconds(100)); unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::uniform_int_distribution<int> dis(0, max - 1); return dis(generator); } bool bstateCompare(bstate bstate_i, bstate bstate_j, double epsilon) { // bstate have fixed lengh for(int i = 0; i< bstate_i.size(); i++) { if(std::abs(bstate_i[i] - bstate_j[i]) > epsilon) { return false; } } return true; } vector < vector < int >> genperms (int n, int m) { vector < vector < int >>perms; vector < int >curr (n, 1); perms.push_back (curr); while (true) { int change = 0; for (int i = n - 1; i >= 0; i--) { if (curr[i] < m) { curr[i]++; for (int j = i + 1; j < n; j++) { curr[j] = 1; } change = 1; perms.push_back (curr); break; //try to change again } } if (change == 0) break; //if we couldnt make a change we are done } return perms; } std::vector<std::vector<bool>> get_all_observations(int n_of_objects) { std::vector<std::vector<bool>> to_return; vector < vector < int >>res = genperms (n_of_objects, 2); for (auto r:res) { std::vector<bool> single_obs; for (auto i:r) { single_obs.push_back(i==1); } to_return.push_back(single_obs); } return to_return; }
[ "miccol@kth.se" ]
miccol@kth.se
638c2675225095e285c42335df3aabe7fdf71b0c
63192d866e373a0e6efc33c289222b079bbd50b7
/src/gui.cpp
b56527940a9abf3a59bd7d6c005c75dbdc613277
[ "MIT" ]
permissive
EranGoldman/FancyWatchOS
25411261960f15d33465e16f6b574e67e63b4925
00e04d792dcbd53d6ae959db7a0c9a4f901e65fb
refs/heads/master
2023-02-12T22:37:40.815940
2021-01-13T13:26:18
2021-01-13T13:26:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,626
cpp
#include "gui.h" bool Uint8Rect::Contains(uint8_t px, uint8_t py) { return px < x + w && px >= x && py < y + h && py >= y; } Widget::Widget(uint8_t x, uint8_t y, uint8_t w, uint8_t h) { rect.x = x; rect.y = y; rect.w = w; rect.h = h; } void Button::HandleEvent(Event& e) { // Only register one finger. if (e.type & (EVENT_TOUCH_BEGIN | EVENT_TOUCH_CHANGE | EVENT_TOUCH_END) && e.touch.touchID == 0) { switch (e.type) { case EVENT_TOUCH_CHANGE: { if (pressed) { OnDrag(Vector2((float)e.touch.x, (float)e.touch.y)); } if (strictPress) { break; } } case EVENT_TOUCH_BEGIN: { pressed = rect.Contains(e.touch.x, e.touch.y); if (pressed && !wasPressed) { OnPointerDown(Vector2((float)e.touch.x, (float)e.touch.y)); } break; } case EVENT_TOUCH_END: { if (pressed) { pressed = false; OnPointerUp(Vector2((float)e.touch.x, (float)e.touch.y)); if (rect.Contains(e.touch.x, e.touch.y)) { OnClick(); } } break; } default: { break; } } } } void Button::Render(Display& display, const Vector2& offset) { if (wasPressed != pressed && shape != SHAPETYPE_INVISIBLE) { switch (shape) { case SHAPETYPE_RECT: display.GetTFT()->fillRect((int32_t)rect.x + (int32_t)offset.x, (int32_t)rect.y + (int32_t)offset.y, rect.w, rect.h, pressed ? colorPressed : colorNormal); break; case SHAPETYPE_RECT_ROUNDED: display.GetTFT()->fillRoundRect(((int32_t)rect.x + (int32_t)offset.x) - radius, ((int32_t)rect.y + (int32_t)offset.y) - radius, rect.w, rect.h, radius, pressed ? colorPressed : colorNormal); break; case SHAPETYPE_CIRCLE: display.GetTFT()->fillCircle((int32_t)rect.x + (int32_t)offset.x, (int32_t)rect.y + (int32_t)offset.y, radius, pressed ? colorPressed : colorNormal); break; case SHAPETYPE_ELLIPSE: display.GetTFT()->fillEllipse((int32_t)rect.x + (int32_t)offset.x, (int32_t)rect.y + (int32_t)offset.y, rect.w, rect.h, pressed ? colorPressed : colorNormal); break; default: break; } wasPressed = pressed; } } bool Button::IsPressed() { return pressed; } // // Text // void Text::Render(Display& display, const Vector2& offset) { if (refresh) { refresh = false; TFT_eSPI* tft = display.GetTFT(); tft->setTextWrap(wrapText); tft->setTextDatum(datum); tft->setTextFont(textFont); tft->setTextSize(textSize); tft->setTextColor(fg); width = tft->textWidth(text.c_str()); // TODO: account for wrapping. height = tft->fontHeight(); // Clear old text area tft->fillRect((int32_t)oldArea.x + (int32_t)offset.x, (int32_t)oldArea.y + (int32_t)offset.y, oldArea.w > 0 ? oldArea.w : width, oldArea.h > 0 ? oldArea.h : height, bg); uint8_t x, y; GetDatumOffset(width, height, &x, &y); // True position is based on the datum. oldArea.x = rect.x - x; oldArea.y = rect.y - y; oldArea.w = width; oldArea.h = height; tft->drawString(text.c_str(), (int32_t)rect.x + (int32_t)offset.x, (int32_t)rect.y + (int32_t)offset.x, textFont); } } void Text::SetText(const char* text) { this->text = text; // It's up to the caller to be smart about setting text, assume there is a change. refresh = true; } const char* Text::GetText() { return text.c_str(); } void Text::SetColor(uint16_t color) { refresh |= color != fg; fg = color; } uint16_t Text::GetColor() { return fg; } void Text::SetClearColor(uint16_t color) { refresh |= color != bg; bg = color; } uint16_t Text::GetClearColor() { return bg; } void Text::SetWrap(bool wrap) { refresh |= wrap != wrapText; wrapText = wrap; } bool Text::IsWrapped() { return wrapText; } void Text::SetDatum(uint8_t datum) { refresh |= datum != this->datum; this->datum = datum; } uint8_t Text::GetDatum() { return datum; } void Text::SetSize(uint8_t size) { refresh |= textSize != size; textSize = size; } uint8_t Text::GetSize() { return textSize; } void Text::SetFont(uint8_t selectFont) { refresh |= selectFont != textFont; textFont = selectFont; } uint8_t Text::GetFont() { return textFont; } void Text::GetDatumOffset(uint8_t width, uint8_t height, uint8_t* x, uint8_t* y) { /** // These enumerate the text plotting alignment (reference datum point) #define TL_DATUM 0 // Top left (default) #define TC_DATUM 1 // Top centre #define TR_DATUM 2 // Top right #define ML_DATUM 3 // Middle left #define CL_DATUM 3 // Centre left, same as above #define MC_DATUM 4 // Middle centre #define CC_DATUM 4 // Centre centre, same as above #define MR_DATUM 5 // Middle right #define CR_DATUM 5 // Centre right, same as above #define BL_DATUM 6 // Bottom left #define BC_DATUM 7 // Bottom centre #define BR_DATUM 8 // Bottom right // These aren't supported... #define L_BASELINE 9 // Left character baseline (Line the 'A' character would sit on) #define C_BASELINE 10 // Centre character baseline #define R_BASELINE 11 // Right character baseline */ switch (datum) { default: case TL_DATUM: *x = 0; *y = 0; break; case TC_DATUM: *x = width / 2; *y = 0; break; case TR_DATUM: *x = width; *y = 0; break; case ML_DATUM: *x = 0; *y = height / 2; break; case MC_DATUM: *x = width / 2; *y = height / 2; break; case MR_DATUM: *x = width; *y = height / 2; break; case BL_DATUM: *x = 0; *y = height; break; case BC_DATUM: *x = width / 2; *y = height; break; case BR_DATUM: *x = width; *y = height; break; } }
[ "timlanesoftware@gmail.com" ]
timlanesoftware@gmail.com
d07ff4eaa8933c2d606862571ffb133809ff4b74
9b91660a4988a9f6c860e7ed4e8bfd4ccc753a0e
/AUT2016/LOG2410/tp5/TP5-A16/Code/VisiteurCalculVolumeLiquide.h
dbaca579d88ce293bab746b4d93a0680f5fe4551
[ "MIT" ]
permissive
KevPantelakis/turbo-giggle
2be8b6f97e19d14aa3f6a57839e199b8ae53c7cd
cb3c089f9284fe4b2b20917c3301054812d32e4b
refs/heads/master
2020-12-25T14:23:37.463935
2017-04-08T19:46:28
2017-04-08T19:46:28
67,129,072
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
h
/////////////////////////////////////////////////////////// // VisiteurCalculVolumeLiquide.h // Implementation of the Class VisiteurCalculVolumeLiquide // Created on: 10-nov.-2016 // Original author: francois /////////////////////////////////////////////////////////// #if !defined(class_VisiteurCalculVolumeLiquide__INCLUDED_) #define class_VisiteurCalculVolumeLiquide__INCLUDED_ #include "VisiteurSansEffet.h" class VisiteurCalculVolumeLiquide : public VisiteurSansEffet { private: float _volumeTotal; public: VisiteurCalculVolumeLiquide(); virtual ~VisiteurCalculVolumeLiquide() {}; // Methode de traitement des elements concrets des circuits liquides virtual void traiterBouilloire(Bouilloire* _bouil); virtual void traiterPompe(Pompe* _pomp); virtual void traiterReservoir(Reservoir* _reserv); virtual void traiterTuyau(Tuyau* _tuy); // Methode d'acces au volume total virtual float getVolumeTotal() const { return _volumeTotal; }; virtual void resetVolumeTotal() { _volumeTotal = 0; } }; #endif // class_VisiteurCalculVolumeLiquide__INCLUDED_#pragma once
[ "kev.pantelakis@gmail.com" ]
kev.pantelakis@gmail.com
d325c91ff00c9dcd345595ca79b7909927e6ec9f
5793887005d7507a0a08dc82f389d8b8849bc4ed
/vendor/mediatek/proprietary/hardware/mtkcam/legacy/include/mtkcam/metadata/mtk_metadata_types.h
cdfe4ba4314679c20823da1b51aa111965eb584d
[]
no_license
wangbichao/dual_camera_x
34b0e70bf2dc294c7fa077c637309498654430fa
fa4bf7e6d874adb7cf4c658235a8d24399f29f30
refs/heads/master
2020-04-05T13:40:56.119933
2017-07-10T13:57:33
2017-07-10T13:57:33
94,966,927
3
0
null
null
null
null
UTF-8
C++
false
false
4,382
h
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ #include <common.h> #include <utils/common.h> /****************************************************************************** * ******************************************************************************/ namespace NSCam { /****************************************************************************** * Type Info Utility ******************************************************************************/ enum MTK_TYPE_ENUM { TYPE_UNKNOWN = -1, TYPE_MUINT8, //= TYPE_BYTE, // Unsigned 8-bit integer (uint8_t) TYPE_MINT32, //= TYPE_INT32, // Signed 32-bit integer (int32_t) TYPE_MFLOAT,// = TYPE_FLOAT, // 32-bit float (float) TYPE_MINT64,// = TYPE_INT64, // Signed 64-bit integer (int64_t) TYPE_MDOUBLE,// = TYPE_DOUBLE, // 64-bit float (double) TYPE_MRational, //= TYPE_RATIONAL,// A 64-bit fraction (camera_metadata_rational_t) // -- MTK -- // TYPE_MPoint, TYPE_MSize, TYPE_MRect, TYPE_IMetadata, TYPE_Memory, NUM_MTYPES // Number of type fields }; /****************************************************************************** * ******************************************************************************/ template <typename _T> struct Type2TypeEnum{}; template <> struct Type2TypeEnum<MUINT8 >{ enum { typeEnum = TYPE_MUINT8 }; }; template <> struct Type2TypeEnum<MINT32 >{ enum { typeEnum = TYPE_MINT32 }; }; template <> struct Type2TypeEnum<MFLOAT >{ enum { typeEnum = TYPE_MFLOAT }; }; template <> struct Type2TypeEnum<MINT64 >{ enum { typeEnum = TYPE_MINT64 }; }; template <> struct Type2TypeEnum<MDOUBLE >{ enum { typeEnum = TYPE_MDOUBLE }; }; template <> struct Type2TypeEnum<MRational>{ enum { typeEnum = TYPE_MRational };}; template <> struct Type2TypeEnum<MPoint >{ enum { typeEnum = TYPE_MPoint }; }; template <> struct Type2TypeEnum<MSize >{ enum { typeEnum = TYPE_MSize }; }; template <> struct Type2TypeEnum<MRect >{ enum { typeEnum = TYPE_MRect }; }; template <> struct Type2TypeEnum<IMetadata>{ enum { typeEnum = TYPE_IMetadata };}; template <> struct Type2TypeEnum<IMetadata::Memory>{ enum { typeEnum = TYPE_Memory };}; };
[ "wangbichao@live.com" ]
wangbichao@live.com
adf97f68dbde9569fe72a9c2205f4c331efa83f0
b286f4b45a2a881decd0ac935a1d9491b026c1bf
/QuadraticAssignmentProblem/SVD/src/squaresvd.cpp
9e3bc46e2776a205d40d40296dc92083f731f730
[]
no_license
Hydra5/Quadratic-Assignment-Problem-Solver
eb0507fec6a2a90bf086c167a6afc8fb85e7fde7
566d5392666bf0868353493b2c7776dcb6d45e03
refs/heads/main
2023-08-26T09:09:41.447352
2021-10-09T17:17:31
2021-10-09T17:17:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,926
cpp
#include "QuadraticAssignmentProblem/SVD/squaresvd.h" #include "QuadraticAssignmentProblem/Matrices/squarematrix.h" double QAPSolver::internal::SquareSVD::TraceNorm() { double total = 0; int num_singular_values = m_singularValues_.size(); for (int i = 0; i < num_singular_values; i++) { total += m_singularValues_[i]; } return total; } // SVD Algorithm based on Eigen's Jacobi SVD QAPSolver::internal::SquareSVD::SquareSVD(QAPSolver::SquareMatrix m_workMatrix, int size) : m_singularValues_(size) { // using // static constexpr double precision = 2 * std::numeric_limits<double>::epsilon(); // causes infinite loop on some inputs static constexpr double precision = 2* std::numeric_limits<double>::epsilon(); static constexpr double considerAsZero = (std::numeric_limits<double>::min)(); // Scaling factor double scale = m_workMatrix.MaxAbsOfEntries(); if (scale == 0) { scale = 1; } m_workMatrix.ScaleBy(1.0 / scale); double maxDiagEntry = m_workMatrix.MaxAbsOfDiagonal(); bool finished = false; while (!finished) { finished = true; for (int p = 1; p < size; ++p) { for (int q = 0; q < p; ++q) { double threshold = std::max<double>(considerAsZero, precision * maxDiagEntry); if ((std::abs(m_workMatrix(p, q)) > threshold) || (std::abs(m_workMatrix(q, p)) > threshold)) { finished = false; JacobiRotation j_left, j_right; real_2x2_jacobi_svd(m_workMatrix, p, q, &j_left, &j_right); m_workMatrix.applyOnTheLeft(p, q, j_left); m_workMatrix.applyOnTheRight(p, q, j_right); // keep track of the largest diagonal coefficient maxDiagEntry = std::max<double>(maxDiagEntry, std::max<double>(abs(m_workMatrix(p, p)), abs(m_workMatrix(q, q)))); } } } } for (int i = 0; i < size; ++i) { m_singularValues_[i] = std::abs(m_workMatrix(i, i) * scale); } }
[ "noreply@github.com" ]
noreply@github.com
04ff49e8a9f334ab6ebe88a3fbdf82e91ff46293
4e758f77179b2bc2373499dd9b7c1281feedef2c
/src/ArraySandpileSeq1.cpp
781cec16c96e2fdac5080fc25821f68e08c9472b
[]
no_license
hjurin/abelianSandpile
c4768190167c15ce8747810c405f8a851e3d4635
84fcece49bf41145d4eb1955729cbf67795bcd49
refs/heads/master
2021-01-13T10:27:41.406284
2016-12-02T17:42:21
2016-12-02T17:42:21
72,246,371
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
#include "ArraySandpileSeq1.hpp" #include <cstring> ArraySandpileSeq1::ArraySandpileSeq1(int size, int globalHeight, int peakHeight) : ArraySandpile(size, globalHeight, peakHeight), stable(false) { } ArraySandpileSeq1::~ArraySandpileSeq1() { } void ArraySandpileSeq1::compute(int nbSteps) { int x, y, i; while (nbSteps > 0 && !stable) { stable = true; memcpy(grid2, grid1, s*s * sizeof(int)); // Note that cells of the borders never topple for (y = 1; y < s-1; y++) { for (x = 1; x < s-1; x++) { i = s*y + x; if (grid1[i] >= 4) { stable = 0; grid2[i] -= 4; grid2[i-s] += 1; grid2[i+1] += 1; grid2[i+s] += 1; grid2[i-1] += 1; } } } nextStep(); nbSteps--; } } bool ArraySandpileSeq1::isStable() { return stable; } bool ArraySandpileSeq1::isOMPable() { return false; }
[ "vsaintguilh@enseirb-matmeca.fr" ]
vsaintguilh@enseirb-matmeca.fr
58d2261f427cbec7a63259d47c92150f5919de43
74473b2b023d3638b44dce64d1a2303cc2e6cfef
/Programare Procedurala/Descompunere F.Primi.cpp
2cfb110657bee4952eadcc79bd93327ad7493cce
[]
no_license
marrusian/C
c022c0d54295f238aab2aec814d0e5e5b4d551b4
a37bcbaf7d5ca4e681bee7c83b530e7251b3ee37
refs/heads/master
2021-01-10T07:19:08.066006
2016-03-08T14:46:48
2016-03-08T14:46:48
53,412,823
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
#include<iostream> int main(void) { using namespace std; // n = numar; d = divizor; p = putere; int n = 0, d = 2, p = 0; cout << "Introduceti numar: "; cin >> n; while(n > 1) { while(n%d == 0) { p++; n /= d; } if(p) { cout << d << " la puterea a " << p << "\n"; p = 0; } d++; } return 0; }
[ "marru.gw@hotmail.com" ]
marru.gw@hotmail.com
ad19f71b76f185eaac5bc83c957e13b82cf2a985
eca37fcbdcbd4bad997d89660f1b11f86d3fc790
/Classes/Botnet/BotnetInterface.h
3c1ca58b60f19562505d95731fe679e308e3fdde
[]
no_license
regras/simbo
bc31495e963a1c642e22144eba354c2e5ea5a5ab
db68fce0f10d78224fe9d65ce0b359908510478f
refs/heads/master
2021-01-20T18:20:51.712331
2017-07-31T19:43:15
2017-07-31T19:43:15
63,374,699
0
1
null
null
null
null
ISO-8859-1
C++
false
false
2,884
h
// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // #ifndef __INET_BOTNETINTERFACE_H_ #define __INET_BOTNETINTERFACE_H_ #include "inet/common/INETDefs.h" #include "inet/networklayer/common/L3Address.h" #include "inet/transportlayer/contract/tcp/TCPSocket.h" #include "inet/applications/simbo/Modulos/BotnetApp/BotnetApp.h" #include "inet/applications/simbo/Classes/Topologia/Topologia.h" namespace inet { class INET_API BotnetInterface { public: BotnetInterface(BotnetApp *){}; BotnetInterface(){}; virtual ~BotnetInterface(){}; //BotnetApp *obj; Topologia topologia; std::vector<CellTopo> subBotnet; //fixme: em desenvolvimento. std::vector<CellTopo>::iterator it; //fixme: em desenvolvimento. int maxNumDropOut; //fixme:Em deenvolvimento. Tempo máximo para um bot ser considerado desconectado da botnet pelos CC ou botmaster. //Ciclo tradicional virtual void inicia(){} virtual void prospectaTopologia(){} virtual bool terminoProspectaTopologia(){return false;} virtual bool verificaProspectaTopologia(){return true;} virtual void prospectaSuperficies(){} virtual int prospectaSuperficie(L3Address){return 0;} virtual bool terminoProspectaSuperficie(){return false;} virtual bool verificaProspectaSuperficie(){return true;} virtual void invadeSistemas(){} virtual TCPSocket * invadeSistema(L3Address){return NULL;} virtual bool terminoInvadeSistemas(){return false;} virtual bool verificaInvadeSistemas(){return true;} virtual int isSetTimerAliveFeedback(){return 3;} //Regula de quanto em quanto tempo o bot vai enviar notificação de vida para o centro de comando ou botmaster. virtual void finaliza(){} //Sinais externos virtual bool infectaApp(int vulnerabilidade, void *ip){return true;} virtual bool aliveFeedback(int connId){return false;} virtual bool recebeComando(void *){return false;} //Ciclo de comandos virtual bool repassaComando(){return false;} virtual bool executaComando(){return false;} //Auxiliares virtual bool verificaIdConexoesAbertas(int connId){return false;} virtual TCPSocket * getConexoesAberta(int connId){return NULL;} }; } /* namespace inet */ #endif /* __INET_BOTNET_H_ */
[ "felipebalabanian@gmail.com" ]
felipebalabanian@gmail.com
a68e100723ba0c9fd9d64190ffec1e1a63e90539
5e00242dc035fdab6aa6bbb40c6d7e6c119ad8e6
/Vault/SPOJ Problems/P164PROB.cpp
ccb69fdb97a0731043f5c25f438c1e8532275823
[]
no_license
AkiLotus/AkikazeCP
39b9c649383dcb7c71962a161e830b9a9a54a4b3
064db52198873bf61872ea66235d66b97fcde80e
refs/heads/master
2023-07-15T09:53:36.520644
2021-09-03T09:54:06
2021-09-03T09:54:06
141,382,884
9
1
null
null
null
null
UTF-8
C++
false
false
2,458
cpp
/** Template by Akikaze (秋風) - formerly proptit_4t41. Code written by a random fan of momocashew and Chiho. **/ #include <bits/stdc++.h> using namespace std; /** -----BASIC MACROES----- **/ #define endl '\n' #define i64 long long #define ld long double #define pub push_back #define mp make_pair #define fi first #define se second const long long MOD = 1000000007LL, INF = 1e9, LINF = 1e18; const long double PI = 3.141592653589793116, EPS = 1e-9, GOLD = ((1+sqrt(5))/2); typedef vector<i64> vi; typedef vector<ld> vd; typedef vector<string> vs; typedef vector<bool> vb; typedef pair<i64, i64> pii; typedef pair<i64, pii> pip; typedef pair<pii, i64> ppi; /** -----BIT CONTROLS----- **/ template<class T> int getbit(T s, int i) { return (s >> 1) & 1; } template<class T> T onbit(T s, int i) { return s | (T(1) << i); } template<class T> T offbit(T s, int i) { return s & (~(T(1) << i)); } template<class T> int cntbit(T s) { return __builtin_popcount(s); } /** -----IDEAS/ALGORITHMS----- -------------------------- **/ /** -----CUSTOM TYPEDEFS/DEFINES----- **/ /** -----GLOBAL VARIABLES----- **/ string s; i64 n; /** -----EXTENSIVE FUNCTIONS----- **/ /** -----COMPULSORY FUNCTIONS----- **/ void VarInput() { ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> s; n = s.size(); } void ProSolve() { if (n % 2 == 1) { n++; for (i64 i=0; i<n/2; i++) cout << "4"; for (i64 i=0; i<n/2; i++) cout << "7"; return; } string mx = "", mn = ""; for (i64 i=0; i<n/2; i++) {mx += "4"; mn += "4";} mx += "4"; for (i64 i=0; i<n/2; i++) {mx += "7"; mn += "7";} mx += "7"; i64 ptr1 = 0, ptr2 = n/2; while (ptr1 < n) { if (s[ptr1] < mn[ptr1]) {cout << mn; return;} if (s[ptr1] > mn[ptr1]) { if (ptr2 == n) {cout << mx; return;} swap(mn[min(ptr1, ptr2-1)], mn[ptr2]); ptr2++; if (s[min(ptr1, ptr2-2)] < mn[min(ptr1, ptr2-2)]) {cout << mn; return;} else ptr1 = min(ptr1, ptr2-2); } ptr1++; } if (s <= mn) cout << mn; else cout << mx; } /** -----MAIN FUNCTION----- **/ int main() { #ifdef Akikaze //freopen("FILE.INP", "r", stdin); //freopen("FILE.OUT", "w", stdout); #endif VarInput(); #ifdef Akikaze auto TIME1 = chrono::steady_clock::now(); #endif ProSolve(); #ifdef Akikaze auto TIME2 = chrono::steady_clock::now(); auto DIFF = TIME2 - TIME1; cout << "\n\nTime elapsed: " << fixed << setprecision(18) << chrono::duration<double>(DIFF).count() << " seconds."; #endif return 0; }
[ "duybach.224575@gmail.com" ]
duybach.224575@gmail.com
e4f6ae66f115e868b84f9095a03ed3b2362220c7
e5a2e6154c12550cb1aa8171daa72cfde806a3ae
/LinkedList.h
5914aafb4d0e4dcea0d7dcd44e6308ce1bfd346b
[]
no_license
JesseOsrecak/AzulMilestone2
6176ca3cebd91fe4f39c8c3c158d274dc6e8fdd5
ecdc748e8843af17850a511d38748ba5be562168
refs/heads/master
2022-09-17T13:53:36.593902
2020-06-04T11:13:49
2020-06-04T11:13:49
267,490,854
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
h
/* * Linked List * * Linked list where all nodes are tiles. Is designed to be used with tile collections only. * * Authors: C. Hodgen (s3031209), J. Osrecak (s3782455) */ #ifndef LINKED_LIST_H #define LINKED_LIST_H #include <memory> #include "Node.h" #include "Tile.h" class LinkedList { public: // Constructs an empty linked list LinkedList(); // Deconstructs linked List ~LinkedList(); // Returns the size of the Linked List unsigned int size() const; // Clears the linked list (deletes all nodes) void clear(); // Adds a node to the front of the linked list void addFront(std::shared_ptr<Tile> data); // Returns the tile and removes from the start of the Linked List std::shared_ptr<Tile> deleteFront(); // Add a new node to the back void addBack(std::shared_ptr<Tile> data); // Returns the tile and removes from the end of the Linked List std::shared_ptr<Tile> deleteBack(); // Returns a tile reference at the index Index must not be greater than size. Index 0 = head std::shared_ptr<Tile> get(const unsigned int index) const; private: // Tracks the head of the list std::shared_ptr<Node> head; // Tracks the tail of the list std::shared_ptr<Node> tail; // Tracks the length of the list unsigned int length; }; #endif // LINKED_LIST_H
[ "s3782455@student.rmit.edu.au" ]
s3782455@student.rmit.edu.au
d4c06e2a5fd9812a6682c0c8e41dafd5630ebba3
3be032c14c9b659ba4c1dfd599f8c85257688317
/dist/ios/include/Uno.Runtime.Implementation.ShaderBackends.OpenGL.GLProgram.h
9a8d6b9ac7a97f8c0da7a493b9673dd05d080ffa
[]
no_license
gncvalente/18app
5433674c6f86d204af81290aa61eef07bb897cf5
40968aa4e3e7c044ce14cd2488313dd5a45d9b1b
refs/heads/master
2021-07-21T01:43:39.091532
2017-10-31T12:44:48
2017-10-31T12:44:48
106,106,556
3
0
null
2017-10-07T15:02:43
2017-10-07T15:02:43
null
UTF-8
C++
false
false
2,800
h
// This file was generated based on /usr/local/share/uno/Packages/UnoCore/1.3.2/Source/Uno/Runtime/Implementation/ShaderBackends/OpenGL/GLProgram.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Uno{namespace Collections{struct Dictionary;}}} namespace g{namespace Uno{namespace Runtime{namespace Implementation{namespace ShaderBackends{namespace OpenGL{struct GLCompiledProgram;}}}}}} namespace g{namespace Uno{namespace Runtime{namespace Implementation{namespace ShaderBackends{namespace OpenGL{struct GLProgram;}}}}}} namespace g{ namespace Uno{ namespace Runtime{ namespace Implementation{ namespace ShaderBackends{ namespace OpenGL{ // public sealed extern class GLProgram :7 // { uType* GLProgram_typeof(); void GLProgram__ctor__fn(GLProgram* __this, uString* vsSource, uString* fsSource, int* constCount, int* attribCount, uArray* constAttribAndUniformNames); void GLProgram__get_ConstantCount_fn(GLProgram* __this, int* __retval); void GLProgram__Create_fn(uString* vsSource, uString* fsSource, int* constCount, int* attribCount, uArray* constAttribAndUniformNames, GLProgram** __retval); void GLProgram__GetCompiledProgram_fn(GLProgram* __this, uArray* constStrings, ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLCompiledProgram** __retval); void GLProgram__GetCompiledProgramInternal_fn(GLProgram* __this, uArray* constStrings, ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLCompiledProgram** __retval); void GLProgram__New1_fn(uString* vsSource, uString* fsSource, int* constCount, int* attribCount, uArray* constAttribAndUniformNames, GLProgram** __retval); struct GLProgram : uObject { int _attribCount; uStrong< ::g::Uno::Collections::Dictionary*> _cachedPrograms; uStrong<uArray*> _constAttribAndUniformNames; int _constCount; uStrong<uString*> _fsSource; uStrong< ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLCompiledProgram*> _singleProgram; uStrong<uString*> _vsSource; void ctor_(uString* vsSource, uString* fsSource, int constCount, int attribCount, uArray* constAttribAndUniformNames); int ConstantCount(); ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLCompiledProgram* GetCompiledProgram(uArray* constStrings); ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLCompiledProgram* GetCompiledProgramInternal(uArray* constStrings); static GLProgram* Create(uString* vsSource, uString* fsSource, int constCount, int attribCount, uArray* constAttribAndUniformNames); static GLProgram* New1(uString* vsSource, uString* fsSource, int constCount, int attribCount, uArray* constAttribAndUniformNames); }; // } }}}}}} // ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL
[ "giuseppe.toto@gmail.com" ]
giuseppe.toto@gmail.com
fa0ce24cdaed0fcbdd4d5a615b8e60b99ba9a611
4070c5f93608bfbe6d48a755fd66448abf83029c
/find_details.h
3a862d693660f41526131ad385846a11e279d35d
[]
no_license
ExoDuS997/Socio-Economic-survey-of-Khordha-district-of-Odisha
ae9acdee65625b5382d21f5d76817df477deb5b9
fc40d6b74e069f3db753456313fca94f1896ba8a
refs/heads/master
2020-04-18T23:25:53.394572
2019-06-04T05:11:26
2019-06-04T05:11:26
167,821,287
0
0
null
null
null
null
UTF-8
C++
false
false
9,346
h
namespace find_details { class entity { protected: string block; long unsigned popln; short sex_rat; float lit_rate; long unsigned avg_inc; long unsigned noindus; public: virtual void show_data() = 0; }; class grampanch : public entity //Gram Panchayat class. { string gp_name; string avgeduqual; string inc_src; public: void show_data() { cout<<"----------------------------------------------------------------------------------------------=== DETAILS ===----------------------------------------------------------------------------------------"<<endl; cout<<setw(100)<<"Block name: "<<block<<endl; cout<<endl<<setw(98)<<"Demographics "<<endl; cout<<setw(99)<<"_________________"<<endl; cout<<setw(100)<<"Population: "<<popln<<endl; cout<<setw(100)<<"Sex ratio: "<<sex_rat<<endl; cout<<setw(100)<<"Average educational qualification: "<<avgeduqual<<endl; cout<<setw(100)<<"Literacy rate: "<<lit_rate<<endl; cout<<endl<<setw(95)<<"Economy "<<endl; cout<<setw(99)<<"__________________"<<endl; cout<<setw(100)<<"Income source: "<<inc_src<<endl; cout<<setw(100)<<"Average income: "<<avg_inc<<endl; cout<<setw(100)<<"No. of industries: "<<noindus<<endl; } friend void disp_gram_panch(); friend void disp_gram_panch(string); }g; class blockclass : public entity { public: blockclass() { popln = 0; sex_rat = 0; lit_rate = 0; avg_inc = 0; noindus = 0; } void show_data() { cout<<"----------------------------------------------------------------------------------------------=== DETAILS ===----------------------------------------------------------------------------------------"<<endl; cout<<setw(100)<<"Block name: "<<block<<endl; cout<<endl<<setw(98)<<"Demographics "<<endl; cout<<setw(99)<<"_________________"<<endl; cout<<setw(100)<<"Population: "<<popln<<endl; cout<<setw(100)<<"Sex ratio: "<<sex_rat<<endl; cout<<setw(100)<<"Literacy rate: "<<lit_rate<<endl; cout<<endl<<setw(95)<<"Economy "<<endl; cout<<setw(99)<<"__________________"<<endl; cout<<setw(100)<<"Average income: "<<avg_inc<<endl; cout<<setw(100)<<"No. of industries: "<<noindus<<endl; } friend blockclass operator+(blockclass &, blockclass &); friend blockclass operator/(blockclass &, int); friend void dispblock(); friend void dispblock(string); }bl; blockclass operator+(blockclass & ob1, blockclass &ob2) { blockclass ob3; ob3.block = ob1.block; ob3.popln = ob1.popln+ob2.popln; ob3.sex_rat = ob1.sex_rat+ob2.sex_rat; ob3.lit_rate = ob1.lit_rate+ob2.lit_rate; ob3.avg_inc = ob1.avg_inc+ob2.avg_inc; ob3.noindus = ob1.noindus+ob2.noindus; return ob3; } blockclass operator/(blockclass &ob1, int count) { blockclass ob2; ob2.block = ob1.block; ob2.popln = ob1.popln; ob2.sex_rat = ob1.sex_rat/count; ob2.lit_rate = ob1.lit_rate/count; ob2.avg_inc = ob1.avg_inc/count; ob2.noindus = ob1.noindus; return ob2; } void dispblock() //function to display all the block details { blockclass b1,b2; int i=0,c=0,blnum=0; string line,dummy; string block,popln,sex_rat,lit_rate,avg_inc,noindus; ifstream ifs("ooppro.csv",ios::in); getline(ifs,line,'\n'); int x = 25, y =17; gotoxy(x,y); cout<<"Block"; gotoxy(x+25,y); cout<<("Average Income"); gotoxy(x+50,y); cout<<"Population"; gotoxy(x+75,y); cout<<"Sex Ratio"; gotoxy(x+100,y); cout<<"Literacy Rate"; gotoxy(x+125,y); cout<<"No. of industries"<<endl; y++; gotoxy(x-17,y); cout<<"---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"; getline(ifs,b2.block,','); block = b2.block; while(!ifs.eof()) { blnum++; getline(ifs,dummy,','); getline(ifs,popln,','); getline(ifs,sex_rat,','); getline(ifs,dummy,','); getline(ifs,lit_rate,','); getline(ifs,dummy,','); getline(ifs,avg_inc,','); getline(ifs,noindus); b1.block = b2.block; b2.popln = atoi(popln.c_str()); b2.sex_rat = atoi(sex_rat.c_str()); b2.lit_rate = atof(lit_rate.c_str()); b2.avg_inc = atoi(avg_inc.c_str()); b2.noindus = atoi(noindus.c_str()); b1 = b1+b2; if(!ifs.eof()) getline(ifs,block,','); else break; if(!(block==b2.block)) { b2.block = block; if(blnum!=0) b1 = b1/blnum; y++; gotoxy(x,y); cout<<b1.block; gotoxy(x+25,y); cout<<b1.popln; gotoxy(x+50,y); cout<<b1.sex_rat; gotoxy(x+75,y); cout<<b1.lit_rate; gotoxy(x+100,y); cout<<b1.avg_inc; gotoxy(x+125,y); cout<<b1.noindus<<endl; blnum = 0; b1.popln = b1.sex_rat = b1.lit_rate = b1.avg_inc = b1.noindus = 0; } } ifs.close(); } void dispblock(string user_block) //TO DISPLAY DETAILS OF A SPECIFIC BLOCK { blockclass b1,b2; int i=0,c=0,blnum=0,found =0; string line,dummy; string block,popln,sex_rat,lit_rate,avg_inc,noindus; ifstream ifs("ooppro.csv",ios::in); getline(ifs,line,'\n'); getline(ifs,b2.block,','); block = b2.block; while(!ifs.eof()) { if(!strcmpi(block.c_str(),user_block.c_str())) { found =1; blnum++; getline(ifs,dummy,','); getline(ifs,popln,','); getline(ifs,sex_rat,','); getline(ifs,dummy,','); getline(ifs,lit_rate,','); getline(ifs,dummy,','); getline(ifs,avg_inc,','); getline(ifs,noindus,'\n'); b1.block = b2.block; b2.popln = atoi(popln.c_str()); b2.sex_rat = atoi(sex_rat.c_str()); b2.lit_rate = atof(lit_rate.c_str()); b2.avg_inc = atoi(avg_inc.c_str()); b2.noindus = atoi(noindus.c_str()); b1 = b1+b2; } else { getline(ifs,line,'\n'); } getline(ifs,block,','); b2.block = block; } if(found == 0) { cout<<"Entered block does not exist in the database...."<<endl; } else { b1 = b1/blnum; b1.show_data(); } ifs.close(); } void disp_gram_panch() //TO DISPLAY ENTIRE DATABASE OF GRAM PANCHAYATS { string line; ifstream ifs("ooppro.csv",ios::in); string block,gp_name,popln,sex_rat,avgeduqual,lit_rate,inc_src,avg_inc,noindus; getline(ifs,line,'\n'); int x = 7,y=4; gotoxy(x,y); cout<<"BLOCK"; gotoxy(x+20,y); cout<<"GRAM PANCHAYAT"; gotoxy(x+40,y); cout<<"POPULATION"; gotoxy(x+60,y); cout<<"SEX RATIO"; gotoxy(x+80,y); cout<<"AVG. EDU. QUALIFICATION"; gotoxy(x+110,y); cout<<"LITERACY RATE"; gotoxy(x+130,y); cout<<"INCOME SOURCE"; gotoxy(x+150,y); cout<<"AVERAGE INCOME"; gotoxy(x+170,y); cout<<"NO. OF INDUSTRIES"; y++; gotoxy(x,y); cout<<"---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"; y++; getline(ifs,block,','); getline(ifs,gp_name,','); getline(ifs,popln,','); getline(ifs,sex_rat,','); getline(ifs,avgeduqual,','); getline(ifs,lit_rate,','); getline(ifs,inc_src,','); getline(ifs,avg_inc,','); getline(ifs,noindus,'\n'); while(!ifs.eof()) { g.block = block; g.gp_name = gp_name; g. popln = atoi(popln.c_str()); g.sex_rat = atoi(sex_rat.c_str()); g.avgeduqual = avgeduqual; g.lit_rate = atof(lit_rate.c_str()); g.inc_src = inc_src; g.avg_inc = atoi(avg_inc.c_str()); g.noindus = atoi(noindus.c_str()); gotoxy(x,y); cout<<g.block; gotoxy(x+20,y); cout<<g.gp_name; gotoxy(x+40,y); cout<<g.popln; gotoxy(x+60,y); cout<<g.sex_rat; gotoxy(x+80,y); cout<<g.avgeduqual; gotoxy(x+110,y); cout<<g.lit_rate; gotoxy(x+130,y); cout<<g.inc_src; gotoxy(x+150,y); cout<<g.avg_inc; gotoxy(x+170,y); cout<<g.noindus; y++; gotoxy(x,y); getline(ifs,block,','); getline(ifs,gp_name,','); getline(ifs,popln,','); getline(ifs,sex_rat,','); getline(ifs,avgeduqual,','); getline(ifs,lit_rate,','); getline(ifs,inc_src,','); getline(ifs,avg_inc,','); getline(ifs,noindus,'\n'); } ifs.close(); } void disp_gram_panch(string user_gram_panch) { string line; int found = 0; ifstream ifs("ooppro.csv",ios::in); string block,gp_name,popln,sex_rat,avgeduqual,lit_rate,inc_src,avg_inc,noindus; getline(ifs,line,'\n'); while(!ifs.eof()) { getline(ifs,block,','); getline(ifs,gp_name,','); if(!strcmpi(gp_name.c_str(),user_gram_panch.c_str())) { found = 1; getline(ifs,popln,','); getline(ifs,sex_rat,','); getline(ifs,avgeduqual,','); getline(ifs,lit_rate,','); getline(ifs,inc_src,','); getline(ifs,avg_inc,','); getline(ifs,noindus,'\n'); g.block = block; g.gp_name = gp_name; g. popln = atoi(popln.c_str()); g.sex_rat = atoi(sex_rat.c_str()); g.avgeduqual = avgeduqual; g.lit_rate = atof(lit_rate.c_str()); g.inc_src = inc_src; g.avg_inc = atoi(avg_inc.c_str()); g.noindus = atoi(noindus.c_str()); g.show_data(); } else { getline(ifs,line,'\n'); } } if(found == 0) { cout<<setw(138)<<"!!!! Entered Gram panchyat record doesnot exist in the database..... !!!!"<<endl; } ifs.close(); } }
[ "noreply@github.com" ]
noreply@github.com
844ac510c05017e608c78bfc003bc2b885a1cade
69dd4bd4268e1c361d8b8d95f56b5b3f5264cc96
/GPU Pro5/06_Compute/Object-order Ray Tracing for Fully Dynamic Scenes/External/lean/header/lean/concurrent/semaphore.h
da66e18d5727dbe5986239116a59bb68fb6798a9
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
permissive
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
65c16710d1abb9207fd7e1116290336a64ddfc86
f442622273c6c18da36b61906ec9acff3366a790
refs/heads/master
2022-12-15T00:40:42.931271
2020-09-07T16:48:25
2020-09-07T16:48:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,585
h
/*****************************************************/ /* lean Concurrent (c) Tobias Zirr 2011 */ /*****************************************************/ #pragma once #ifndef LEAN_CONCURRENT_SEMAPHORE #define LEAN_CONCURRENT_SEMAPHORE #include "../lean.h" #include "../tags/noncopyable.h" #include <windows.h> namespace lean { namespace concurrent { /// Implements a semaphore. class semaphore : public noncopyable { private: HANDLE m_semaphore; public: /// Constructs a critical section. Throws a runtime_error on failure. explicit semaphore(long initialCount = 1) : m_semaphore( ::CreateSemaphoreW(NULL, initialCount, LONG_MAX, NULL) ) { LEAN_ASSERT(m_semaphore != NULL); } /// Destructor. ~semaphore() { ::CloseHandle(m_semaphore); } /// Tries to acquire this semaphore, returning false if currenty unavailable. LEAN_INLINE bool try_lock() { return (::WaitForSingleObject(m_semaphore, 0) == WAIT_OBJECT_0); } /// Acquires this semaphore, returning immediately on success, otherwise waiting for the semaphore to become available. LEAN_INLINE void lock() { DWORD result = ::WaitForSingleObject(m_semaphore, INFINITE); LEAN_ASSERT(result == WAIT_OBJECT_0); } /// Releases this semaphore, permitting waiting threads to continue execution. LEAN_INLINE void unlock() { BOOL result = ::ReleaseSemaphore(m_semaphore, 1, NULL); LEAN_ASSERT(result != FALSE); } /// Gets the native handle. LEAN_INLINE HANDLE native_handle() const { return m_semaphore; } }; } // namespace using concurrent::semaphore; } // namespace #endif
[ "IRONKAGE@gmail.com" ]
IRONKAGE@gmail.com
774c326facaaa144d3dd70185feabbf35bc40a61
f8211d24d758f2a4af9244e66a2ac86a1c2031a9
/1197A.cpp
1a9de497e2a825c03c085a7c316e0899bec0a639
[]
no_license
kowshik24/Codeforces
7bdb6a933cda5e27b97b4b5764598cbd91648493
f265752dbade9ef8d06e064ae8009200ec01cbad
refs/heads/main
2022-02-18T23:30:57.415200
2022-02-09T19:43:28
2022-02-09T19:43:28
237,670,218
0
0
null
null
null
null
UTF-8
C++
false
false
442
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int int main() { int q; cin >> q; for(int i=0; i<q; i++) { ll n; cin >> n; ll ar[n]; for(int j=0; j<n; j++) { cin >> ar[j]; } sort(ar,ar+n); ll fx = ar[n-2]-1; cout << min((n-2),fx) << endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
289e0408fa83b98e875711ea05d1f75081f87e74
5ecc58979d277c435fc300f9502eb619fc31891b
/arraypointing.cpp
b9b2c61e10f328a02627584149de60fdedbbb4d0
[]
no_license
Ashu00001/cpp
35b5e974a75609ab97407d7d1772d6c5f858982b
8cc94e35bd4a7c3874d5a3b2adcab6dc2ad093bf
refs/heads/master
2023-05-22T04:00:03.609191
2021-06-11T03:04:59
2021-06-11T03:04:59
293,784,829
0
0
null
null
null
null
UTF-8
C++
false
false
568
cpp
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> using namespace std; int main() { int a[3][3]={1,2,3,4,5,6,7,8,9}; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { cout<<(*(*(a+i)+j))<<endl; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
de9807dc2bf211f1105e693766d3dcb95bea4383
68bec95d10d141e3504259994b7d43a3e4062d82
/other/UCSC Classes/CPP/Assignment4/Final_AirShip_JamesJKim_OLD.cpp
28ef38270c75d01ea2d7300777d9e2447f3edbed
[]
no_license
createdbyjames/dev
7712e044eaa918379065978e17821c825b1c63a6
c90796baf2d83cecbb52a7b0350d5574a52109d8
refs/heads/master
2023-01-23T01:55:24.207216
2023-01-18T19:17:59
2023-01-18T19:17:59
120,493,969
0
0
null
null
null
null
UTF-8
C++
false
false
12,636
cpp
// // AirShip.cpp // // Created by James Kim on 10/30/15. // Copyright © 2015 James J. Kim. All rights reserved. // #include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; enum AIRSHIP_TYPE {AIRPLANE = 0, BALLOON = 1}; //AirShip Type enum ENGINE_TYPE {JET = 0, PROPELLER = 1}; //Engine Type for Airplane Objects enum GAS_TYPE {HELIUM = 0, HYDROGEN = 1}; //Gas Type for Balloon Objects /************************************************************ Function: DataMembers Purpose: Place holder to hold the data that's being read from the file Parameters: none Variables: type: int value to determine if its airplane or balloon name: name of the airplane or balloon maxPassemgers: number of passengers maxCargoWeight: maximum cargo weight gasType: either helium or hydrogen maxRange: maximum range maxAltitude: maximum altitude ************************************************************/ struct DataMembers { int type; const char *name; int maxPassengers; double maxCargoWeight; int engineType; int gasType; double maxRange; double maxAltitude; }; class AirShip { public: void readFile(int argCount, const char *fileName); //Method to read in the file virtual void setData (DataMembers &data) = 0; //Setting the values virtual void showData() = 0; //Display the data AIRSHIP_TYPE getAirShipType() { return (AIRSHIP_TYPE)airShipType; }; //Returns enum type private: const char *fileName; //File name passed in from the CLI argument int getNumberOfRecords(const char *fileName); //Number of records found in the file protected: int airShipType; //Type of AirShip object being held string name; //Name of the object int maxPassengers; //Max Passenger Counts double maxCargoWeight; //Max Cargo Weight }; //Airplane Object class Airplane : public AirShip { public: Airplane() : AirShip() {} //Default constructor void setData (DataMembers &data); //Implementation of setData method from the baseclass void showData(); //Implementaiton of showData method from the baseclass const char* getType(ENGINE_TYPE type); //Returns the engine type from the enum protected: int engineType; //iVar to hold engine type info double maxRange; //iVar to hold the max range }; //Balloon Object class Balloon : public AirShip { public: Balloon() : AirShip() {} //Default constructor void setData (DataMembers &data); //Implementation of setData method from the baseclass void showData(); //Implementaiton of showData method from the baseclass const char* getType(GAS_TYPE type); //Returns the gas type from the enum protected: int gasType; //iVar to hold the gas type double maxAltitude; //iVar to hold the maximum altitude }; /************************************************************ Function: setData (DataMembers &data) Purpose: Holds the data thats read from the database Parameters: DataMembers-enum Variables: name: name of the airplane or balloon maxPassemgers: number of passengers maxCargoWeight: maximum cargo weight gasType: either helium or hydrogen maxRange: maximum range maxAltitude: maximum altitude ************************************************************/ void Airplane::setData (DataMembers &data) { name = data.name; maxPassengers = data.maxPassengers; maxCargoWeight = data.maxCargoWeight; maxRange = data.maxRange; airShipType = AIRSHIP_TYPE(data.type); engineType = ENGINE_TYPE(data.engineType); } /************************************************************ Function: showData() Purpose: Displays the data that's being held in the object Parameters: none Variables: none ************************************************************/ void Airplane::showData() { cout << left << setw(20) << name; cout << left << setw(20) << getType(ENGINE_TYPE(engineType)); cout << left << setw(20) << maxRange; } /************************************************************ Function: setData (DataMembers &data) Purpose: Holds the data thats read from the database Parameters: DataMembers-enum Variables: name: name of the airplane or balloon maxPassemgers: number of passengers maxCargoWeight: maximum cargo weight gasType: either helium or hydrogen maxRange: maximum range maxAltitude: maximum altitude ************************************************************/ void Balloon::setData (DataMembers &data) { name = data.name; maxPassengers = data.maxPassengers; maxCargoWeight = data.maxCargoWeight; maxAltitude = data.maxAltitude; airShipType = AIRSHIP_TYPE(data.type); gasType = GAS_TYPE(data.gasType); } /************************************************************ Function: showData() Purpose: Displays the data that's being held in the object Parameters: none Variables: none ************************************************************/ void Balloon::showData() { cout << left << setw(20) << name; cout << left << setw(20) << getType(GAS_TYPE(gasType)); cout << left << setw(20) << maxAltitude; } /************************************************************ Function: getType(ENGINE_TYPE type) Purpose: Determines what type of engine Parameters: ENGINE_TYPE type Variables: none ************************************************************/ const char* Airplane::getType(ENGINE_TYPE type) { switch (type) { case JET: return "Jet"; break; case PROPELLER: return "Propeller"; break; default: return "No Type"; break; } } /************************************************************ Function: getType(GAS_TYPE type) Purpose: Determines what type of engine Parameters: GAS_TYPE type Variables: none ************************************************************/ const char* Balloon::getType(GAS_TYPE type) { switch (type) { case HELIUM: return "Helium"; break; case HYDROGEN: return "Hydrogen"; break; default: return "No Type"; break; } } /************************************************************ Function: getNumberOfRecords(const char *fileName) Purpose: Opens the file with the fileName that's passed in Parameters: fileName Variables: inputFile: file object tokenRead: token that's read in from the file numberOfRecords: number of lines found in the file ************************************************************/ int AirShip::getNumberOfRecords(const char *fileName) { //create the input stream ifstream inputFile(fileName); //check if the file is open if (!inputFile) { cout << "Can't open the input file !." << endl; exit(1); } char tokenRead[100]; //this is used to read in the value //initialize a value for line count int numberOfRecords = 0; //iterate through each reacord and find out how many lines of records you have while (inputFile.getline(tokenRead, 100)) { //DEBUG - Prints out total number of records //cout << numberOfRecords << ": " << tokenRead << endl; numberOfRecords++; } cout << "Total Records in File: " << numberOfRecords << endl; return numberOfRecords; } /************************************************************ Function: readFile(int argCount, const char *fileName) Purpose: Opens the file Parameters: argCount: argument count from the main mneu fileName: fileName Variables: inputFile: file object tokenRead: token that's read in from the file numberOfRecords: number of lines found in the file ************************************************************/ void AirShip::readFile(int argCount, const char *fileName) { if (argCount != 2) { cout << "Input file was not specified. " << endl; cout << "$> AirShip fileName" << endl; exit(1); } fileName = fileName; //create the input stream ifstream inputFile(fileName); //check if the file is open if (!inputFile) { cout << "Can't open the input file !." << endl; exit(1); } char tokenRead[100]; //this is used to read in the value char d[] = ","; //this is used to delimit by commas //initialize a value for line count int numberOfRecords = getNumberOfRecords(fileName); //create an array of AirShips according to the records found in the file AirShip *ships[numberOfRecords]; //variable to hold the array element int count = 0; while(inputFile.getline(tokenRead, 100) && !inputFile.eof()) { //enum to determine the AirShip type //AIRSHIP_TYPE airshipType; //determine the AirShip type by the first value in the file //airshipType = (AIRSHIP_TYPE)atoi(strtok(tokenRead, d)); struct DataMembers data; data.type = atoi(strtok(tokenRead, d)); switch (data.type) { case AIRPLANE: //cout << "Fucking AirAplane !!!" << endl; ships[count] = new Airplane(); //data.type = atoi(strtok(tokenRead, d)); data.name = strtok(NULL, d); data.maxPassengers = atoi(strtok(NULL, d)); data.maxCargoWeight = atof(strtok(NULL, d)); data.engineType = atoi(strtok(NULL, d)); data.maxRange = stof(strtok(NULL, d)); break; case BALLOON: //cout << "Fucking Baloon !!!" << endl; ships[count] = new Balloon(); //data.type = atoi(strtok(tokenRead, d)); data.name = strtok(NULL, d); data.maxPassengers = atoi(strtok(NULL, d)); data.maxCargoWeight = atof(strtok(NULL, d)); data.gasType = atoi(strtok(NULL, d)); data.maxAltitude = stof(strtok(NULL, d)); break; default: break; } ships[count]->setData(data); count++; memset(tokenRead, '\0', 100); } //print the Airplane Data cout << "Listing of all Airplanes" << endl; cout << left << setw(20) << "Name" << left << setw(20) << "Engine Type" << left << setw(10) << "Maximum Range" << endl; cout << "===============================================================" << endl; for (int i = 0; i < numberOfRecords;i++) { if (ships[i]->getAirShipType() == AIRPLANE) { ships[i]->showData(); cout << "\n"; } } cout << "\n"; //print the Balloon Data cout << "Listing of all Balloons" << endl; cout << left << setw(20) << "Name" << left << setw(20) << "Gas Type" << left << setw(10) << "Maximum Altitude" << endl; cout << "===============================================================" << endl; for (int i = 0; i < numberOfRecords;i++) { if (ships[i]->getAirShipType() == BALLOON) { ships[i]->showData(); cout << "\n"; } } } int main(int argc, const char * argv[]) { AirShip *myShip; myShip->readFile(argc, argv[1]); return 0; }
[ "jamesjkim@apple.com" ]
jamesjkim@apple.com
f78b95f4ca1f09a96d854a508333ddf14462557d
cf7b884da75872a446bd7c0dc76a2e1ab64c2f61
/videoParser/source/h264_parser.cpp
2b669ebf01e85e362e914fdc8c904aa3f6daece1
[]
no_license
tcll321/video_decoder
5726eb623da798835d7f76b38f2a72aa6f5023ef
efb5b77ff0d8d29c4f491bc1bd10e2db1593f42c
refs/heads/master
2020-04-08T07:33:57.043529
2019-10-29T08:13:12
2019-10-29T08:13:12
159,143,197
3
3
null
null
null
null
UTF-8
C++
false
false
9,665
cpp
#include <assert.h> #include <stdint.h> #include "defines.h" #include "AVCodecParser.h" extern "C" { #include "h264.h" #include "get_bits.h" #include "error.h" #include "utils.h" #include "avassert.h" } typedef struct H264ParseContext { ParseContext pc; H264ParamSets ps; // H264DSPContext h264dsp; // H264POCContext poc; // H264SEIContext sei; int is_avc; int nal_length_size; int got_first; int picture_structure; uint8_t parse_history[6]; int parse_history_count; int parse_last_mb; int64_t reference_dts; int last_frame_num, last_picture_structure; } H264ParseContext; int ff_h2645_extract_rbsp(const uint8_t *src, int length, H2645RBSP *rbsp, H2645NAL *nal, int small_padding) { int i, si, di; uint8_t *dst; nal->skipped_bytes = 0; #define STARTCODE_TEST \ if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \ if (src[i + 2] != 3 && src[i + 2] != 0) { \ /* startcode, so we must be past the end */ \ length = i; \ } \ break; \ } #if HAVE_FAST_UNALIGNED #define FIND_FIRST_ZERO \ if (i > 0 && !src[i]) \ i--; \ while (src[i]) \ i++ #if HAVE_FAST_64BIT for (i = 0; i + 1 < length; i += 9) { if (!((~AV_RN64(src + i) & (AV_RN64(src + i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL)) continue; FIND_FIRST_ZERO; STARTCODE_TEST; i -= 7; } #else for (i = 0; i + 1 < length; i += 5) { if (!((~AV_RN32(src + i) & (AV_RN32(src + i) - 0x01000101U)) & 0x80008080U)) continue; FIND_FIRST_ZERO; STARTCODE_TEST; i -= 3; } #endif /* HAVE_FAST_64BIT */ #else for (i = 0; i + 1 < length; i += 2) { if (src[i]) continue; if (i > 0 && src[i - 1] == 0) i--; STARTCODE_TEST; } #endif /* HAVE_FAST_UNALIGNED */ if (i >= length - 1 && small_padding) { // no escaped 0 nal->data = nal->raw_data = src; nal->size = nal->raw_size = length; return length; } else if (i > length) i = length; nal->rbsp_buffer = &rbsp->rbsp_buffer[rbsp->rbsp_buffer_size]; dst = nal->rbsp_buffer; memcpy(dst, src, i); si = di = i; while (si + 2 < length) { // remove escapes (very rare 1:2^22) if (src[si + 2] > 3) { dst[di++] = src[si++]; dst[di++] = src[si++]; } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) { if (src[si + 2] == 3) { // escape dst[di++] = 0; dst[di++] = 0; si += 3; if (nal->skipped_bytes_pos) { nal->skipped_bytes++; if (nal->skipped_bytes_pos_size < nal->skipped_bytes) { nal->skipped_bytes_pos_size *= 2; av_assert0(nal->skipped_bytes_pos_size >= nal->skipped_bytes); av_reallocp_array(&nal->skipped_bytes_pos, nal->skipped_bytes_pos_size, sizeof(*nal->skipped_bytes_pos)); if (!nal->skipped_bytes_pos) { nal->skipped_bytes_pos_size = 0; return AVERROR(ENOMEM); } } if (nal->skipped_bytes_pos) nal->skipped_bytes_pos[nal->skipped_bytes - 1] = di - 1; } continue; } else // next start code goto nsc; } dst[di++] = src[si++]; } while (si < length) dst[di++] = src[si++]; nsc: memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE); nal->data = dst; nal->size = di; nal->raw_data = src; nal->raw_size = si; rbsp->rbsp_buffer_size += si; return si; } static int h264_find_frame_end(H264ParseContext *p, const uint8_t *buf,int buf_size, void *logctx) { return 0; // int i, j; // uint32_t state; // ParseContext *pc = &p->pc; // // int next_avc = p->is_avc ? 0 : buf_size; // state = pc->state; // if (state > 13) // state = 7; // // for (i = 0; i < buf_size; i++) { // if (i >= next_avc) { // int nalsize = 0; // i = next_avc; // for (j = 0; j < p->nal_length_size; j++) // nalsize = (nalsize << 8) | buf[i++]; // if (nalsize <= 0 || nalsize > buf_size - i) { // return buf_size; // } // next_avc = i + nalsize; // state = 5; // } // // if (state == 7) { // if (i < next_avc) // state = 2; // } // else if (state <= 2) { // if (buf[i] == 1) // state ^= 5; // 2->7, 1->4, 0->5 // else if (buf[i]) // state = 7; // else // state >>= 1; // 2->1, 1->0, 0->0 // } // else if (state <= 5) { // int nalu_type = buf[i] & 0x1F; // if (nalu_type == H264_NAL_SEI || nalu_type == H264_NAL_SPS || // nalu_type == H264_NAL_PPS || nalu_type == H264_NAL_AUD) { // if (pc->frame_start_found) { // i++; // goto found; // } // } // else if (nalu_type == H264_NAL_SLICE || nalu_type == H264_NAL_DPA || // nalu_type == H264_NAL_IDR_SLICE) { // state += 8; // continue; // } // state = 7; // } // else { // unsigned int mb, last_mb = p->parse_last_mb; // GetBitContext gb; // p->parse_history[p->parse_history_count++] = buf[i]; // // init_get_bits(&gb, p->parse_history, 8 * p->parse_history_count); // mb = get_ue_golomb_long(&gb); // if (get_bits_left(&gb) > 0 || p->parse_history_count > 5) { // p->parse_last_mb = mb; // if (pc->frame_start_found) { // if (mb <= last_mb) { // i -= p->parse_history_count - 1; // p->parse_history_count = 0; // goto found; // } // } // else // pc->frame_start_found = 1; // p->parse_history_count = 0; // state = 7; // } // } // } // pc->state = state; // if (p->is_avc) // return next_avc; // return END_NOT_FOUND; // // found: // pc->state = 7; // pc->frame_start_found = 0; // if (p->is_avc) // return next_avc; // return i - (state & 5); } /** * Parse NAL units of found picture and decode some basic information. * * @param s parser context. * @param avctx codec context. * @param buf buffer with field/frame data. * @param buf_size size of the buffer. */ static inline int parse_nal_units(H264ParseContext* p, const uint8_t * const buf, int buf_size) { H2645RBSP rbsp = { NULL }; H2645NAL nal = { NULL }; int buf_index, next_avc; int state = -1, got_reset = 0; int ret; av_fast_padded_malloc(&rbsp.rbsp_buffer, (unsigned int*)&rbsp.rbsp_buffer_alloc_size, buf_size); if (!rbsp.rbsp_buffer) return AVERROR(ENOMEM); buf_index = 0; next_avc = 0; for (;;) { const SPS *sps; int src_length, consumed, nalsize = 0; if (buf_index >= next_avc) { nalsize = get_nalsize(p->nal_length_size, buf, buf_size, &buf_index); if (nalsize < 0) break; next_avc = buf_index + nalsize; } else { buf_index = find_start_code(buf, buf_size, buf_index, next_avc); if (buf_index >= buf_size) break; if (buf_index >= next_avc) continue; } src_length = next_avc - buf_index; state = buf[buf_index]; switch (state & 0x1f) { case H264_NAL_SLICE: case H264_NAL_IDR_SLICE: // Do not walk the whole buffer just to decode slice header if ((state & 0x1f) == H264_NAL_IDR_SLICE || ((state >> 5) & 0x3) == 0) { /* IDR or disposable slice * No need to decode many bytes because MMCOs shall not be present. */ if (src_length > 60) src_length = 60; } else { /* To decode up to MMCOs */ if (src_length > 1000) src_length = 1000; } break; } consumed = ff_h2645_extract_rbsp(buf + buf_index, src_length, &rbsp, &nal, 1); if (consumed < 0) break; buf_index += consumed; ret = init_get_bits8(&nal.gb, nal.data, nal.size); if (ret < 0) goto fail; get_bits1(&nal.gb); nal.ref_idc = get_bits(&nal.gb, 2); nal.type = get_bits(&nal.gb, 5); switch (nal.type) { case H264_NAL_SPS: ff_h264_decode_seq_parameter_set(&nal.gb, &p->ps, 0); break; case H264_NAL_PPS: ff_h264_decode_picture_parameter_set(&nal.gb, &p->ps, nal.size_bits); break; case H264_NAL_SEI: // ff_h264_sei_decode(&p->sei, &nal.gb, &p->ps, avctx); break; case H264_NAL_IDR_SLICE: break; // s->key_frame = 1; // p->poc.prev_frame_num = 0; // p->poc.prev_frame_num_offset = 0; // p->poc.prev_poc_msb = // p->poc.prev_poc_lsb = 0; av_freep(&rbsp.rbsp_buffer); return 0; /* no need to evaluate the rest */ } } fail: av_freep(&rbsp.rbsp_buffer); return -1; } static int h264_parse(const uint8_t *buf, int buf_size, VideoInfo * info) { H264ParseContext parseContext; int ret = parse_nal_units(&parseContext, buf, buf_size); info->codeWidth = 16 * parseContext.ps.sps->mb_width; info->codeHeight = 16 * parseContext.ps.sps->mb_height; info->width = info->codeWidth - (parseContext.ps.sps->crop_right + parseContext.ps.sps->crop_left); info->height = info->codeHeight - (parseContext.ps.sps->crop_top + parseContext.ps.sps->crop_bottom); if (info->width <= 0 || info->height <= 0) { info->width = info->codeWidth; info->height = info->codeHeight; } return ret; } static int h264_split(const uint8_t *buf, int buf_size) { return 0; } static void h264_close() { } static int init() { return 0; } AVCodecParser ff_h264_parser = { { AV_CODEC_TYPE_H264 }, init, h264_parse, h264_close, h264_split, }; // AVCodecParser ff_h264_parser = { // .codec_ids = { AV_CODEC_TYPE_H264 }, // .parser_init = init, // .parser_parse = h264_parse, // .parser_close = h264_close, // .split = h264_split, // };
[ "liuchuntao@accusyschina.com" ]
liuchuntao@accusyschina.com
10bb22425e28bae19f6390af551b2b56737a86f3
a80fba11bd00fbf94514dfb758cad3dd1d76b9be
/Source/Sokoban/TPPawn.h
3d077c09e531fd819a6b93f85df4356b8ef0b01b
[]
no_license
KovarnaKocici/Sokoban_3D
4aecbfab6febbb096b9df701bc06c92f2d554489
006d4b90a4583a0d3dc4d4f56cf0c35efb5116b4
refs/heads/master
2020-05-09T14:12:24.943479
2019-05-18T16:52:46
2019-05-18T16:52:46
181,185,782
0
0
null
null
null
null
UTF-8
C++
false
false
1,444
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "GridPossession.h" #include "Block.h" #include "TPPawn.generated.h" UCLASS() class SOKOBAN_API ATPPawn : public AGridPossession { GENERATED_BODY() public: // Sets default values for this pawn's properties ATPPawn(const FObjectInitializer &ObjectInitializer); UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Components) class USpringArmComponent* SpringArmComponent; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Components) class UCameraComponent* CameraComponent; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) bool IsPushing = false; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Components) class UTPPlayerMovementComponent* MovementComponent; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; //ConstructionScript virtual void OnConstruction(const FTransform & Transform) override; virtual UPawnMovementComponent* GetMovementComponent() const override; void Push(ABlock* Block); UFUNCTION(BlueprintCallable) void OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); };
[ "e.beirak@coworking.local" ]
e.beirak@coworking.local
ff817aad074769812b599af4e84fbaeb13335283
29792c63c345f87474136c8df87beb771f0a20a8
/vcmp/game/hooks.cpp
ef7ee11935893662a763cfa730f9be5804e2c0b7
[]
no_license
uvbs/jvcmp
244ba6c2ab14ce0a757f3f6044b5982287b01fae
57225e1c52085216a0a4a9c4e33ed324c1c92d39
refs/heads/master
2020-12-29T00:25:39.180996
2009-06-24T14:52:39
2009-06-24T14:52:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,018
cpp
// File Author: kyeman #include "../main.h" #include "game.h" #include "util.h" #include "keystuff.h" extern CNetGame* pNetGame; extern CGame* pGame; extern DWORD dwGameLoop; extern DWORD dwRenderLoop; #define NUDE void _declspec(naked) //----------------------------------------------------------- PED_TYPE *_pPlayer; VEHICLE_TYPE *_pVehicle; DWORD *_pEntity; int _iWeapon; float _fUnk; int _iPedPieces; BYTE _byteUnk; DWORD dwStackFrame; DWORD dwCurPlayerActor=0; BYTE byteCurPlayer=0; BYTE byteInternalPlayer=0; DWORD dwCameraMode=0; DWORD dwRGBARadar=0; int iRadarColor1=0; BYTE byteSavedCameraMode; BYTE *pbyteCameraMode = (BYTE *)0x7E481C; BYTE *pbyteCurrentPlayer = (BYTE *)0xA10AFB; BYTE byteUnkSave; BOOL bUsePassenger=FALSE; BOOL bIsPlayer=FALSE; VEHICLE_TYPE *ObjectiveVehicle; extern GTA_CONTROLSET *pGcsInternalKeys; // CHEATING STUFF DWORD GetMemSum(BYTE * mem, int size); BOOL bIsACheater=FALSE; BOOL bHasCheaterBeenPunished=FALSE; BOOL bHasSamplesOfPlayerData=FALSE; DWORD dwSuspectedCheat=0; DWORD dwStoredPlayerDataSum[2]; float fStoredPlayerHealth=0.0f; float fStoredPlayerArmour=0.0f; float fCheaterFlingSpeed = 0.0f; //----------------------------------------------------------- BYTE PreGameProcess_HookJmpCode[] = {0xFF,0x25,0x77,0x5D,0x4A,0x00}; //4A5D77 BYTE PedSetObjective_HookJmpCode[] = {0xFF,0x25,0x75,0x11,0x40,0x00,0x90,0x90,0x90}; BYTE RadarTranslateColor_HookJmpCode[] = {0xFF,0x25,0x44,0x30,0x4C,0x00,0x90}; // 4C3044 BYTE EnterCarAnimCallback_HookJmpCode[] = {0xFF,0x25,0xD8,0x28,0x51,0x00,0x90,0x90}; // 5128D8 BYTE HookedRand_HookJmpCode[] = {0xFF,0x25,0xE8,0x99,0x64,0x00,0x90,0x90}; // 6499E8 BYTE InflictDamage_HookJmpCode[] = {0xFF,0x25,0x15,0x5B,0x52,0x00}; // 525B15 BYTE InTheGame_HookJmpCode[] = {0xFF,0x25,0x3c,0x5c,0x4a,0x00}; //4A5C3C //----------------------------------------------------------- void DoCheatEntryChecking() { if( pNetGame && pNetGame->GetPlayerPool()->GetLocalPlayer()->IsActive() && bHasSamplesOfPlayerData ) { if(dwSuspectedCheat == 15) { bIsACheater = TRUE; } if(fStoredPlayerHealth != GamePool_FindPlayerPed()->fHealth) { dwSuspectedCheat++; return; } if(fStoredPlayerArmour != GamePool_FindPlayerPed()->fArmour) { dwSuspectedCheat++; return; } if(dwStoredPlayerDataSum[1] != GetMemSum((BYTE *)GamePool_FindPlayerPed()+1032,192)) { dwSuspectedCheat++; return; } } else { dwSuspectedCheat = 0; } } //----------------------------------------------------------- void DoCheatExitStoring() { if(pNetGame) { if(pNetGame->GetPlayerPool()->GetLocalPlayer()->IsActive()) { dwStoredPlayerDataSum[1] = GetMemSum((BYTE *)GamePool_FindPlayerPed()+1032,192); fStoredPlayerHealth = GamePool_FindPlayerPed()->fHealth; fStoredPlayerArmour = GamePool_FindPlayerPed()->fArmour; bHasSamplesOfPlayerData = TRUE; } else { bHasSamplesOfPlayerData = FALSE; } } } //----------------------------------------------------------- NUDE PreGameProcessHook() { _asm mov dwStackFrame, esp _asm pushad _asm mov edx, dwGameLoop ; upcalls our main game loop handler _asm call edx DoCheatExitStoring(); _asm popad _asm mov esp, dwStackFrame _asm push ebx _asm sub esp, 112 _asm push 0 _asm mov edx, ADDR_PRE_GAME_PROCESS ; back into the real proc _asm add edx, 6 _asm jmp edx } //----------------------------------------------------------- NUDE InTheGameHook() { _asm pushad DoCheatEntryChecking(); _asm popad _asm mov edx, 0x4A5D80 _asm call edx _asm pop ecx _asm mov edx, 0x4A5BE6 _asm jmp edx } //----------------------------------------------------------- DWORD GetMemSum(BYTE * mem, int size) { int x=0; DWORD ret=0; while(x!=size) { ret+=mem[x]; x++; } return ret; } //----------------------------------------------------------- void _stdcall DoOnFootWorldBoundsStuff() { if(pNetGame) { CLocalPlayer *pLocalPlayer = pNetGame->GetPlayerPool()->GetLocalPlayer(); CPlayerPed *pPlayerPed = pGame->FindPlayerPed(); // Make sure they don't leave their worldy confines. if(pLocalPlayer->IsActive() && !pPlayerPed->IsInVehicle()) { if(pPlayerPed->EnforceWorldBoundries( pNetGame->m_WorldBounds[0],pNetGame->m_WorldBounds[1], pNetGame->m_WorldBounds[2],pNetGame->m_WorldBounds[3])) { pGcsInternalKeys->wKeys1[KEY_ONFOOT_JUMP] = 0xFF; pGcsInternalKeys->wKeys2[KEY_ONFOOT_JUMP] = 0x00; pPlayerPed->SetArmedWeapon(0); //pGame->DisplayTextMessage("Stay within the world boundries"); } } } } //----------------------------------------------------------- // A hook function that switches keys for // CPlayerPed::ProcessControl(void) NUDE CPlayerPed_ProcessControl_Hook() { _asm mov dwCurPlayerActor, ecx _asm pushad byteInternalPlayer = *pbyteCurrentPlayer; byteCurPlayer = FindPlayerNumFromPedPtr(dwCurPlayerActor); if( dwCurPlayerActor && byteCurPlayer != 0 && byteInternalPlayer == 0 ) { // key switching GameStoreLocalPlayerKeys(); // remember local player's keys GameSetRemotePlayerKeys(byteCurPlayer); // set remote player's keys // save the internal cammode. byteSavedCameraMode = *pbyteCameraMode; *pbyteCameraMode = 4; // onfoot mouse looking mode. // aim switching GameStoreLocalPlayerAim(); GameSetRemotePlayerAim(byteCurPlayer); *pbyteCurrentPlayer = byteCurPlayer; // Set the internal player to the passed actor // call the internal CPlayerPed[]::Process _asm popad _asm mov edx, 0x537270 _asm call edx _asm pushad // restore the camera mode. *pbyteCameraMode = byteSavedCameraMode; // restore the local player's keys and the internal ID. *pbyteCurrentPlayer = 0; GameSetLocalPlayerKeys(); GameSetLocalPlayerAim(); } else // it's the local player { if(!bIsACheater) { DoOnFootWorldBoundsStuff(); } else { if(!_pPlayer->byteIsInVehicle) { pGcsInternalKeys->wKeys1[KEY_ONFOOT_JUMP] = 0xFF; pGcsInternalKeys->wKeys2[KEY_ONFOOT_JUMP] = 0x00; _pPlayer = (PED_TYPE *)dwCurPlayerActor; _pPlayer->entity.vecMoveSpeed.Z = fCheaterFlingSpeed; fCheaterFlingSpeed+=0.025f; } else { _pPlayer->byteIsInVehicle = 0; } } _asm popad _asm mov edx, 0x537270 _asm call edx _asm pushad } _asm popad _asm ret } //----------------------------------------------------------- // Hook that replaces CBike::ProcessControl(void) NUDE CBike_ProcessControl_Hook() { _asm mov _pVehicle, ecx // store the CBike pointer. _asm pushad byteInternalPlayer = *pbyteCurrentPlayer; if( (_pVehicle->pDriver) && (_pVehicle->pDriver != GamePool_FindPlayerPed()) && (byteInternalPlayer==0) ) // not player's car { // get the current driver's player number byteCurPlayer = FindPlayerNumFromPedPtr((DWORD)_pVehicle->pDriver); GameStoreLocalPlayerKeys(); // save local player keys GameSetRemotePlayerKeys(byteCurPlayer); // set remote player keys. *pbyteCurrentPlayer = byteCurPlayer; // set internal ID to this remote player // call CBike::ProcessControl(void) _asm popad _asm mov eax, 0x60E3E0 _asm call eax _asm pushad // restore local player keys and internal ID. *pbyteCurrentPlayer = 0; GameSetLocalPlayerKeys(); } else { _asm popad _asm mov eax, 0x60E3E0 _asm call eax _asm pushad } _asm popad _asm ret } //----------------------------------------------------------- // Hook that replaces CBoat::ProcessControl(void) NUDE CBoat_ProcessControl_Hook() { _asm mov _pVehicle, ecx // store the CBoat pointer. _asm pushad byteInternalPlayer = *(BYTE *)0xA10AFB; if( (_pVehicle->pDriver) && (_pVehicle->pDriver != GamePool_FindPlayerPed()) && (byteInternalPlayer==0) ) // not player's car { // get the current driver's player number byteCurPlayer = FindPlayerNumFromPedPtr((DWORD)_pVehicle->pDriver); GameStoreLocalPlayerKeys(); // save local player keys GameSetRemotePlayerKeys(byteCurPlayer); // set remote player keys. *pbyteCurrentPlayer = byteCurPlayer; // set internal ID to this remote player // call CBoat::ProcessControl(void) _asm popad _asm mov eax, 0x59FE90 _asm call eax _asm pushad // restore local player keys and internal ID. *pbyteCurrentPlayer = 0; GameSetLocalPlayerKeys(); } else { _asm popad _asm mov eax, 0x59FE90 _asm call eax _asm pushad } _asm popad _asm ret } //----------------------------------------------------------- // Hook for CAutomobile::ProcessControl(void) NUDE CAutomobile_ProcessControl_Hook() { _asm mov _pVehicle, ecx _asm pushad byteInternalPlayer = *(BYTE *)0xA10AFB; if( (_pVehicle->pDriver) && (_pVehicle->pDriver != GamePool_FindPlayerPed()) && (byteInternalPlayer==0) ) // not player's car { // get the current driver's player number byteCurPlayer = FindPlayerNumFromPedPtr((DWORD)_pVehicle->pDriver); GameStoreLocalPlayerKeys(); // save local player keys GameSetRemotePlayerKeys(byteCurPlayer); // set remote player keys. *pbyteCurrentPlayer = byteCurPlayer; // set internal ID to this remote player // call CAutomobile::ProcessControl(void) _asm popad _asm mov edi, 0x593030 _asm call edi _asm pushad // restore local player keys and internal ID. *pbyteCurrentPlayer = 0; GameSetLocalPlayerKeys(); } else { _asm popad _asm mov edi, 0x593030 _asm call edi _asm pushad } _asm popad _asm ret } //----------------------------------------------------------- void _stdcall DoEnterVehicleNotification(BOOL bPassenger) { /* if(pNetGame) { ObjectiveVehicle = (VEHICLE_TYPE *)_pVehicle; pNetGame->GetPlayerPool()->GetLocalPlayer() ->SendEnterVehicleNotification(pNetGame->GetVehiclePool() ->FindIDFromGtaPtr(ObjectiveVehicle),bPassenger); }*/ } //----------------------------------------------------------- void _stdcall DoExitVehicleNotification() { /* if(pNetGame) { ObjectiveVehicle = (VEHICLE_TYPE *)_pVehicle; if(ObjectiveVehicle->pDriver != GamePool_FindPlayerPed()) { pNetGame->GetPlayerPool()->GetLocalPlayer() ->SendExitVehicleNotification(pNetGame->GetVehiclePool() ->FindIDFromGtaPtr(ObjectiveVehicle)); } }*/ } //----------------------------------------------------------- // Hooks CPed::SetObjective(enum eObjective) NUDE CPed_SetObjective_Hook() { } //----------------------------------------------------------- NUDE RadarTranslateColor() { _asm mov eax, [esp+4] _asm mov iRadarColor1, eax TranslateColorCodeToRGBA(iRadarColor1); // return will still be in eax. _asm ret } //----------------------------------------------------------- NUDE CantFindFuckingAnim() { _asm mov eax, [esp+4] _asm test eax, eax _asm jnz its_ok _asm ret ; was 0, so foobarred its_ok: _asm mov edx, 0x405AC0 _asm add edx, 4 } //----------------------------------------------------------- // ok, this bullshit procedure don't check the fucking // vehicle pointer for 0 and caused the widely hated 5128fb crash. NUDE EnterCarAnimCallback_Hook() { _asm mov edx, [esp+4] _asm mov eax, [esp+8] _asm mov _pPlayer, eax _asm pushad if( _pPlayer->pVehicle == 0 && _pPlayer != GamePool_FindPlayerPed()) { _asm popad _asm ret } _asm popad _asm mov ebp, 0x5128E0 _asm add ebp, 8 _asm jmp ebp } //----------------------------------------------------------- // The rand() function in GTA is hooked and we can // control the seed this way. NUDE HookedRand_Hook() { rand(); _asm ret } //----------------------------------------------------------- #define NO_TEAM 255 //----------------------------------------------------------- NUDE CPed_InflictDamageHook() { _asm mov dwStackFrame, esp _asm mov _pPlayer, ecx _asm mov eax, [esp+4] _asm mov _pEntity, eax _asm mov eax, [esp+8] _asm mov _iWeapon, eax _asm mov eax, [esp+12] _asm mov _fUnk, eax _asm mov eax, [esp+16] _asm mov _iPedPieces, eax _asm mov al, [esp+20] _asm mov _byteUnk, al _asm pushad if(pNetGame) { /*if(IsFriendlyFire(_pPlayer,_pEntity,_iWeapon,_fUnk,_iPedPieces,_byteUnk)) { _asm popad _asm mov esp, dwStackFrame _asm xor al, al _asm retn 0x14 }*/ /* if(_pPlayer == GamePool_FindPlayerPed()) { fLastDamageAmount = _fUnk; fLastHealth = _pPlayer->fHealth - fLastDamageAmount; bLastDamageProcessed = FALSE; }*/ } _asm popad _asm mov esp, dwStackFrame _asm fld ds:[0x694170] _asm mov edx, 0x525B20 _asm add edx, 6 _asm jmp edx } //----------------------------------------------------------- void InstallMethodHook(DWORD dwInstallAddress,DWORD dwHookFunction) { DWORD dwVP, dwVP2; VirtualProtect((LPVOID)dwInstallAddress,4,PAGE_EXECUTE_READWRITE,&dwVP); *(PDWORD)dwInstallAddress = (DWORD)dwHookFunction; VirtualProtect((LPVOID)dwInstallAddress,4,dwVP,&dwVP2); } //----------------------------------------------------------- void InstallHook( DWORD dwInstallAddress, DWORD dwHookFunction, DWORD dwHookStorage, BYTE * pbyteJmpCode, int iJmpCodeSize ) { DWORD dwVP, dwVP2; // Install the pointer to procaddr. VirtualProtect((PVOID)dwHookStorage,4,PAGE_EXECUTE_READWRITE,&dwVP); *(PDWORD)dwHookStorage = (DWORD)dwHookFunction; VirtualProtect((PVOID)dwHookStorage,4,dwVP,&dwVP2); // Install the Jmp code. VirtualProtect((PVOID)dwInstallAddress,iJmpCodeSize,PAGE_EXECUTE_READWRITE,&dwVP); memcpy((PVOID)dwInstallAddress,pbyteJmpCode,iJmpCodeSize); VirtualProtect((PVOID)dwInstallAddress,iJmpCodeSize,dwVP,&dwVP2); } //----------------------------------------------------------- void GameInstallHooks() { //InstallHook(0x6499F0,(DWORD)HookedRand_Hook,0x6499E8,HookedRand_HookJmpCode, //sizeof(HookedRand_HookJmpCode)); // Below is the Render2DStuff hook, don't be confused by the poor naming. InstallHook(ADDR_PRE_GAME_PROCESS,(DWORD)PreGameProcessHook, ADDR_PRE_GAME_PROCESS_STORAGE,PreGameProcess_HookJmpCode, sizeof(PreGameProcess_HookJmpCode)); InstallHook(0x4A5BE0,(DWORD)InTheGameHook,0x4A5C3C,InTheGame_HookJmpCode, sizeof(InTheGame_HookJmpCode)); // Install CPlayerPed::ProcessControl hook. InstallMethodHook(0x694D90,(DWORD)CPlayerPed_ProcessControl_Hook); // Install CBike::ProcessControl hook. InstallMethodHook(0x6D7B54,(DWORD)CBike_ProcessControl_Hook); // Install CBoat::ProcessControl hook. InstallMethodHook(0x69B0D4,(DWORD)CBoat_ProcessControl_Hook); // Install CAutomobile::ProcessControl hook. InstallMethodHook(0x69ADB0,(DWORD)CAutomobile_ProcessControl_Hook); /* Install CPed::SetObjective() hook. InstallHook(ADDR_SET_OBJECTIVE,(DWORD)CPed_SetObjective_Hook, ADDR_SET_OBJECTIVE_STORAGE,PedSetObjective_HookJmpCode,sizeof(PedSetObjective_HookJmpCode));*/ // Install Hook for RadarTranslateColor //InstallHook(0x4C3050,(DWORD)RadarTranslateColor,0x4C3044, //RadarTranslateColor_HookJmpCode,sizeof(RadarTranslateColor_HookJmpCode)); //InstallHook(0x525B20,(DWORD)CPed_InflictDamageHook,0x525B15, // InflictDamage_HookJmpCode,sizeof(InflictDamage_HookJmpCode)); // Install Hook for enter car animation callback.. // Update: Causing even more problems. InstallHook(0x5128E0,(DWORD)EnterCarAnimCallback_Hook,0x5128D8, EnterCarAnimCallback_HookJmpCode,sizeof(EnterCarAnimCallback_HookJmpCode)); /* Hook/patch code to get around 0x405AC5 animation bug InstallHook(0x405AC0,(DWORD)CantFindFuckingAnim,0x405A95, CantFindFuckingAnim_HookJmpCode,sizeof(CantFindFuckingAnim_HookJmpCode));*/ } //-----------------------------------------------------------
[ "jacks.mini.net@43d76e2e-6035-11de-a55d-e76e375ae706" ]
jacks.mini.net@43d76e2e-6035-11de-a55d-e76e375ae706
395b14434be56a72e4c991bf2d6fe6e05fd1cdcd
d8dbc61ea3dc6f6c2a43dec5241dd68f111ecb9f
/src/PaContext.cc
2801bd58f2bcfa9892242802b0f02266f0affec7
[ "MIT", "Apache-2.0" ]
permissive
gweltaz-calori/naudiodon
868abf5bd8a881a89bc44b579eb6c6c4a2941cff
8b557ea53d5b19f4e12b5967d5fce5c973b3e551
refs/heads/master
2023-07-03T14:57:47.034760
2021-08-12T09:16:11
2021-08-12T09:16:11
395,261,587
0
1
null
null
null
null
UTF-8
C++
false
false
11,011
cc
/* Copyright 2019 Streampunk Media Ltd. 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 "PaContext.h" #include "Params.h" #include "Chunks.h" #include <portaudio.h> #include <thread> namespace streampunk { int PaCallback(const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { PaContext *paContext = (PaContext *)userData; double inTimestamp = timeInfo->inputBufferAdcTime > 0.0 ? timeInfo->inputBufferAdcTime : paContext->getCurTime() - paContext->getInLatency(); // approximation for timestamp of first sample double outTimestamp = timeInfo->outputBufferDacTime; paContext->checkStatus(statusFlags); // printf("PaCallback output %p, frameCount %d\n", output, frameCount); int inRetCode = paContext->hasInput() && paContext->readPaBuffer(input, frameCount, inTimestamp) ? paContinue : paComplete; int outRetCode = paContext->hasOutput() && paContext->fillPaBuffer(output, frameCount) ? paContinue : paComplete; return ((inRetCode == paComplete) && (outRetCode == paComplete)) ? paComplete : paContinue; } PaContext::PaContext(napi_env env, napi_value inOptions, napi_value outOptions) : mInOptions(checkOptions(env, inOptions) ? std::make_shared<AudioOptions>(env, inOptions) : std::shared_ptr<AudioOptions>()), mOutOptions(checkOptions(env, outOptions) ? std::make_shared<AudioOptions>(env, outOptions) : std::shared_ptr<AudioOptions>()), mInChunks(new Chunks(mInOptions ? mInOptions->maxQueue() : 0)), mOutChunks(new Chunks(mOutOptions ? mOutOptions->maxQueue() : 0)), mStream(nullptr) { PaError errCode = Pa_Initialize(); if (errCode != paNoError) { std::string err = std::string("Could not initialize PortAudio: ") + Pa_GetErrorText(errCode); napi_throw_error(env, nullptr, err.c_str()); return; } if (!mInOptions && !mOutOptions) { napi_throw_error(env, nullptr, "Input and/or Output options must be specified"); return; } if (mInOptions && mOutOptions && (mInOptions->sampleRate() != mOutOptions->sampleRate())) { napi_throw_error(env, nullptr, "Input and Output sample rates must match"); return; } printf("%s\n", Pa_GetVersionInfo()->versionText); if (mInOptions) printf("Input %s\n", mInOptions->toString().c_str()); if (mOutOptions) printf("Output %s\n", mOutOptions->toString().c_str()); double sampleRate; PaStreamParameters inParams; memset(&inParams, 0, sizeof(PaStreamParameters)); if (mInOptions) setParams(env, /*isInput*/true, mInOptions, inParams, sampleRate); PaStreamParameters outParams; memset(&outParams, 0, sizeof(PaStreamParameters)); if (mOutOptions) setParams(env, /*isInput*/false, mOutOptions, outParams, sampleRate); uint32_t framesPerBuffer = paFramesPerBufferUnspecified; #ifdef __arm__ framesPerBuffer = 256; #endif uint32_t inFramesPerBuffer = mInOptions ? mInOptions->framesPerBuffer() : 0; uint32_t outFramesPerBuffer = mOutOptions ? mOutOptions->framesPerBuffer() : 0; if (!((0 == inFramesPerBuffer) && (0 == outFramesPerBuffer))) framesPerBuffer = std::max<uint32_t>(inFramesPerBuffer, outFramesPerBuffer); errCode = Pa_IsFormatSupported(mInOptions ? &inParams : NULL, mOutOptions ? &outParams : NULL, sampleRate); if (errCode != paFormatIsSupported) { std::string err = std::string("Format not supported: ") + Pa_GetErrorText(errCode); napi_throw_error(env, nullptr, err.c_str()); return; } errCode = Pa_OpenStream(&mStream, mInOptions ? &inParams : NULL, mOutOptions ? &outParams : NULL, sampleRate, framesPerBuffer, paNoFlag, PaCallback, this); if (errCode != paNoError) { std::string err = std::string("Could not open stream: ") + Pa_GetErrorText(errCode); napi_throw_error(env, nullptr, err.c_str()); return; } const PaStreamInfo *streamInfo = Pa_GetStreamInfo(mStream); mInLatency = streamInfo->inputLatency; } void PaContext::start(napi_env env) { PaError errCode = Pa_StartStream(mStream); if (errCode != paNoError) { std::string err = std::string("Could not start stream: ") + Pa_GetErrorText(errCode); napi_throw_error(env, nullptr, err.c_str()); return; } } void PaContext::stop(eStopFlag flag) { if (eStopFlag::ABORT == flag) Pa_AbortStream(mStream); else Pa_StopStream(mStream); Pa_CloseStream(mStream); Pa_Terminate(); } std::shared_ptr<Chunk> PaContext::pullInChunk(uint32_t numBytes, bool &finished) { std::shared_ptr<Memory> result = Memory::makeNew(numBytes); finished = false; double timeStamp = 0.0; uint32_t bytesRead = fillBuffer(result->buf(), numBytes, timeStamp, mInChunks, finished, /*isInput*/true); if (bytesRead != numBytes) { if (0 == bytesRead) result = std::shared_ptr<Memory>(); else { std::shared_ptr<Memory> trimResult = Memory::makeNew(bytesRead); memcpy(trimResult->buf(), result->buf(), bytesRead); result = trimResult; } } return std::make_shared<Chunk>(result, timeStamp); } void PaContext::pushOutChunk(std::shared_ptr<Chunk> chunk) { mOutChunks->push(chunk); } void PaContext::checkStatus(uint32_t statusFlags) { if (statusFlags) { std::string err = std::string("portAudio status - "); if (statusFlags & paInputUnderflow) err += "input underflow "; if (statusFlags & paInputOverflow) err += "input overflow "; if (statusFlags & paOutputUnderflow) err += "output underflow "; if (statusFlags & paOutputOverflow) err += "output overflow "; if (statusFlags & paPrimingOutput) err += "priming output "; std::lock_guard<std::mutex> lk(m); mErrStr = err; } } bool PaContext::getErrStr(std::string& errStr, bool isInput) { std::lock_guard<std::mutex> lk(m); std::shared_ptr<AudioOptions> options = isInput ? mInOptions : mOutOptions; if (options->closeOnError()) // propagate the error back to the stream handler errStr = mErrStr; else if (mErrStr.length()) printf("AudioIO: %s\n", mErrStr.c_str()); mErrStr.clear(); return !errStr.empty(); } void PaContext::quit() { if (mInOptions) mInChunks->quit(); if (mOutOptions) { mOutChunks->quit(); mOutChunks->waitDone(); } // wait for next PaCallback to run std::this_thread::sleep_for(std::chrono::milliseconds(20)); } bool PaContext::readPaBuffer(const void *srcBuf, uint32_t frameCount, double inTimestamp) { uint32_t bytesAvailable = frameCount * mInOptions->channelCount() * mInOptions->sampleBits() / 8; std::shared_ptr<Memory> chunk = Memory::makeNew(bytesAvailable); memcpy(chunk->buf(), srcBuf, bytesAvailable); mInChunks->push(std::make_shared<Chunk>(chunk, inTimestamp)); return true; } bool PaContext::fillPaBuffer(void *dstBuf, uint32_t frameCount) { uint32_t bytesRemaining = frameCount * mOutOptions->channelCount() * mOutOptions->sampleBits() / 8; bool finished = false; double timeStamp = 0.0; fillBuffer((uint8_t *)dstBuf, bytesRemaining, timeStamp, mOutChunks, finished, /*isInput*/false); return !finished; } double PaContext::getCurTime() const { return Pa_GetStreamTime(mStream); } // private uint32_t PaContext::fillBuffer(uint8_t *buf, uint32_t numBytes, double &timeStamp, std::shared_ptr<Chunks> chunks, bool &finished, bool isInput) { uint32_t bufOff = 0; timeStamp = 0.0; while (numBytes) { if (!chunks->curBuf() || (chunks->curBuf() && (chunks->curBytes() == chunks->curOffset()))) { chunks->waitNext(); if (!chunks->curBuf()) { printf("Finishing %s - %d bytes not available to fill the last buffer\n", isInput ? "input" : "output", numBytes); memset(buf + bufOff, 0, numBytes); finished = true; break; } } if ((0 == bufOff) && isInput) { // offset the chunk timestamp by the chunk offset double timeOffset = (double)chunks->curOffset() / mInOptions->channelCount() / (mInOptions->sampleBits() / 8) / mInOptions->sampleRate(); timeStamp = chunks->curTs() + timeOffset; } uint32_t curBytes = std::min<uint32_t>(numBytes, chunks->curBytes() - chunks->curOffset()); void *srcBuf = chunks->curBuf() + chunks->curOffset(); memcpy(buf + bufOff, srcBuf, curBytes); bufOff += curBytes; chunks->incOffset(curBytes); numBytes -= curBytes; } return bufOff; } void PaContext::setParams(napi_env env, bool isInput, std::shared_ptr<AudioOptions> options, PaStreamParameters &params, double &sampleRate) { int32_t deviceID = (int32_t)options->deviceID(); if ((deviceID >= 0) && (deviceID < Pa_GetDeviceCount())) params.device = (PaDeviceIndex)deviceID; else params.device = isInput ? Pa_GetDefaultInputDevice() : Pa_GetDefaultOutputDevice(); if (params.device == paNoDevice) { napi_throw_error(env, nullptr, "No default device"); return; } printf("%s device name is %s\n", isInput?"Input":"Output", Pa_GetDeviceInfo(params.device)->name); params.channelCount = options->channelCount(); int maxChannels = isInput ? Pa_GetDeviceInfo(params.device)->maxInputChannels : Pa_GetDeviceInfo(params.device)->maxOutputChannels; if (params.channelCount > maxChannels) { napi_throw_error(env, nullptr, "Channel count exceeds maximum number of channels for device"); return; } uint32_t sampleFormat = options->sampleFormat(); switch(sampleFormat) { case 1: params.sampleFormat = paFloat32; break; case 8: params.sampleFormat = paInt8; break; case 16: params.sampleFormat = paInt16; break; case 24: params.sampleFormat = paInt24; break; case 32: params.sampleFormat = paInt32; break; default: { napi_throw_error(env, nullptr, "Invalid sampleFormat"); return; } } params.suggestedLatency = isInput ? Pa_GetDeviceInfo(params.device)->defaultLowInputLatency : Pa_GetDeviceInfo(params.device)->defaultLowOutputLatency; params.hostApiSpecificStreamInfo = NULL; sampleRate = (double)options->sampleRate(); #ifdef __arm__ params.suggestedLatency = isInput ? Pa_GetDeviceInfo(params.device)->defaultHighInputLatency : Pa_GetDeviceInfo(params.device)->defaultHighOutputLatency; #endif } } // namespace streampunk
[ "scriptorian@streampunk.media" ]
scriptorian@streampunk.media
9937fc35058ef2fd921a12adeaa26f963d308906
dc1c3b453eec10b80469554a6a552b50988ea090
/ElDorito/Source/Blam/Math/RealPoint2D.hpp
55f5003e84e215a9ddd40ab3af1fa613319bbfba
[]
no_license
unk-1/ElDorito
7a272c5341c51fbbd6bce9fc379c72bc3984e2c0
634bcffbfb0f97e703670a74c92618118803b9db
refs/heads/master
2021-01-17T10:15:39.115479
2017-04-29T20:10:40
2017-04-29T20:10:40
84,011,513
6
1
null
2017-03-05T23:51:05
2017-03-05T23:51:05
null
UTF-8
C++
false
false
1,448
hpp
#pragma once namespace Blam { namespace Math { struct RealPoint2D { float X; float Y; RealPoint2D(); RealPoint2D(const float x, const float y); bool operator==(const RealPoint2D &other) const; bool operator!=(const RealPoint2D &other) const; explicit operator const float *() const; RealPoint2D &operator+=(const RealPoint2D &other); RealPoint2D &operator+=(const float other); RealPoint2D operator+(const RealPoint2D &other) const; RealPoint2D operator+(const float other) const; friend RealPoint2D operator+(const float a, const RealPoint2D &b); RealPoint2D &operator-=(const RealPoint2D &other); RealPoint2D &operator-=(const float other); RealPoint2D operator-(const RealPoint2D &other) const; RealPoint2D operator-(const float other) const; friend RealPoint2D operator-(const float a, const RealPoint2D &b); RealPoint2D &operator*=(const RealPoint2D &other); RealPoint2D &operator*=(const float other); RealPoint2D operator*(const RealPoint2D &other) const; RealPoint2D operator*(const float other) const; friend RealPoint2D operator*(const float a, const RealPoint2D &b); RealPoint2D &operator/=(const RealPoint2D &other); RealPoint2D &operator/=(const float other); RealPoint2D operator/(const RealPoint2D &other) const; RealPoint2D operator/(const float other) const; friend RealPoint2D operator/(const float a, const RealPoint2D &b); }; } }
[ "camden.smallwood@gmail.com" ]
camden.smallwood@gmail.com
cfbc4bd3533fe1f4c2a736f3f37239dff1ec0f63
063125a1b6bcc7bded7fa32249c020aeb20adac5
/include/gptValue.hpp
71b4fecc4a0ebf6220f1323932063c97c81475d1
[ "BSD-3-Clause" ]
permissive
Galfurian/GnuplotTracer
e71ef1f61546f992207164b27c32a6f33c399b94
b31db32f9e201616729d0f7bbfbd519ac9ffcc0f
refs/heads/master
2022-01-16T11:06:40.409556
2019-05-24T07:58:57
2019-05-24T07:58:57
107,656,129
0
0
null
null
null
null
UTF-8
C++
false
false
2,995
hpp
/// @file gptValue.hpp /// @author Enrico Fraccaroli /// @date Oct 20 2017 /// @copyright /// Copyright (c) 2017 Enrico Fraccaroli <enrico.fraccaroli@univr.it> #pragma once #include <algorithm> // std::move #include <cassert> // assert #include <iostream> #include <vector> /// @brief Abstract class for storing pointers to traced variables. class GPTVariable { protected: /// The name of the trace. std::string name; /// The format used to print the trace. std::string format; /// The width of the line. unsigned int lineWidth; public: /// @brief Constructor. /// @param _name The name of the trace. /// @param _format The format used to print the trace. /// @param _lineWidth The width of the line. explicit GPTVariable(std::string _name, std::string _format, const unsigned int & _lineWidth) : name(std::move(_name)), format(std::move(_format)), lineWidth(_lineWidth) { // Nothing to do. } /// @brief Destructor. virtual ~GPTVariable() = default; /// @brief Provides the name. inline std::string getName() const { return name; } /// @brief Provides the format. inline std::string getFormat() const { return format; } /// @brief Provides the width of the line. inline unsigned int getLineWidth() const { return lineWidth; } /// @brief Samples the value from the traced variable. virtual void sampleValue() = 0; /// @brief Checks if there are values. virtual bool empty() = 0; /// @brief Provides the number of stored values. virtual size_t size() = 0; /// @brief Provides the sampled value at the given position inside the /// vector of sampled values. /// @param pos The position inside the sampling vector. /// @return The sampled value. virtual double get(const size_t & pos) = 0; }; /// @brief Generalized class for storing pointers to traced variables. template<typename T> class GPTGenericVariable : public GPTVariable { private: /// The traced variable. T * variable; /// The sampled values. std::vector<T> values; public: /// @brief Constructor. GPTGenericVariable(T * _variable, const std::string & _name, const std::string & _format, const unsigned int & _lineWidth) : GPTVariable(_name, _format, _lineWidth), variable(_variable) { // Nothing to do. } inline void sampleValue() override { assert(variable); values.emplace_back(*variable); } inline bool empty() override { return values.empty(); } inline size_t size() override { return values.size(); } inline double get(const size_t & pos) override { assert(pos < this->size()); return values[pos]; } };
[ "enry.frak@gmail.com" ]
enry.frak@gmail.com
734b1f11a82c6fb00564e3fb69f4127d11bfe60f
f7936cf3e2abb8939e9bb1aadb7d88e1eb0f0377
/Programmers/카카오/괄호 변환.cpp
0840d4bbcb74639284a9900c34bd19c136cc5b84
[]
no_license
raeyoungii/BOJ
b30f599ddcd663ee765d98f1a3ef23b5976e2ab7
cb8f6ad8545ea6810dc08e39e2f365ca0e637bd8
refs/heads/master
2023-06-14T04:23:32.087035
2021-07-02T16:43:06
2021-07-02T16:43:06
329,713,517
0
0
null
null
null
null
UTF-8
C++
false
false
1,019
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const char nl = '\n'; bool check(string& u) { stack<char> s; for (char& ch : u) { if (ch == '(') s.push(ch); else if (!s.empty()) s.pop(); else return false; } if (!s.empty()) return false; return true; } string f(string& p) { if (p.empty()) return p; int tmp = 0, idx = 0; for (char& ch : p) { if (ch == '(') tmp++; else tmp--; idx++; if (!tmp) break; } string u = p.substr(0, idx); string v = p.substr(idx, p.size()); if (check(u)) { return u + f(v); } u.erase(u.begin()); u.pop_back(); for (char& ch : u) { if (ch == '(') ch = ')'; else ch = '('; } return "(" + f(v) + ")" + u; } string solution(string p) { string answer = f(p); return answer; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string p = ")("; cout << solution(p) << nl; return 0; }
[ "skepo@naver.com" ]
skepo@naver.com
db148c512967d80468a3d637f2f08b1cfcdc4f2b
3d252d03739ca4a5b13d283ff94f5db130c889fc
/Chess/Chess.cpp
2601bc4010cbe8e065763c7fb83e7930f2dd8c8d
[]
no_license
zBaitu/Chess
1b9e577fa519771d2da69c486bdfce22257ce9df
d3a1014fd4611c3acbd137c6835bf742219ea405
refs/heads/master
2023-04-19T00:05:33.931187
2021-05-10T16:37:41
2021-05-10T16:37:41
366,079,078
0
0
null
null
null
null
GB18030
C++
false
false
3,569
cpp
// Chess.cpp : 定义应用程序的类行为。 // #include "stdafx.h" #include "Chess.h" #include "MainFrm.h" #include "ChessDoc.h" #include "ChessView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CChessApp BEGIN_MESSAGE_MAP(CChessApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CChessApp::OnAppAbout) // 基于文件的标准文档命令 ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) END_MESSAGE_MAP() // CChessApp 构造 CChessApp::CChessApp() { // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的一个 CChessApp 对象 CChessApp theApp; // CChessApp 初始化 BOOL CChessApp::InitInstance() { // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); // 初始化 OLE 库 if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); LoadStdProfileSettings(4); // 加载标准 INI 文件选项(包括 MRU) // 注册应用程序的文档模板。文档模板 // 将用作文档、框架窗口和视图之间的连接 CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CChessDoc), RUNTIME_CLASS(CMainFrame), // 主 SDI 框架窗口 RUNTIME_CLASS(CChessView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // 分析标准外壳命令、DDE、打开文件操作的命令行 CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // 调度在命令行中指定的命令。如果 // 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。 if (!ProcessShellCommand(cmdInfo)) return FALSE; // 唯一的一个窗口已初始化,因此显示它并对其进行更新 m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // 仅当具有后缀时才调用 DragAcceptFiles // 在 SDI 应用程序中,这应在 ProcessShellCommand 之后发生 return TRUE; } // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // 用于运行对话框的应用程序命令 void CChessApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CChessApp 消息处理程序
[ "zbaitu@gmail.com" ]
zbaitu@gmail.com
0e2517fd6020a4e2269a6bdbc5c5f3d789bc22df
9f5aa407a9ee07caa5b3b473567910a2c22024e6
/OP/dijkstra.h
2884a70ef8022f5f161affc745a85581738d1ac3
[]
no_license
damnhe/shopbot
49d986e8d81475b9294aaf3f45b48a55544e2d9a
cfe216d2063537345a418382fa2df091491d9529
refs/heads/master
2020-12-24T13:07:29.805359
2013-05-09T21:03:36
2013-05-09T21:03:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
#ifndef graphAlgorithm_dijkstra_h #define graphAlgorithm_dijkstra_h #include "Vertex.h" #include "LeftistHeap.h" #include <iostream> using namespace std; class graphMani{ public: graphMani(); void dijkstraAlgo(vector<Vertex> &,int); void printPath(float, vector<Vertex>, int,int); int numberOfOperationsItTook(){return this->numberOfOperations;}; private: int numberOfOperations; }; #endif
[ "J-N@John-Nicholas.Net" ]
J-N@John-Nicholas.Net
c3b13b0498591da044110b32982df85f78c71445
5e6637b14fa372049196b4fdbea0bd03ef6180cb
/例子/函数递归.cpp
6498ec924b69a7c40a1130925a567bd883110f7c
[]
no_license
dangfugui/note-C
de1d9ad34b7ad5e804f41093a6fade408ac56ef5
0cfce2b3f06749312ef22e965bf29f6ed1783f0a
refs/heads/master
2020-06-23T13:41:00.370822
2016-09-10T14:24:26
2016-09-10T14:24:26
67,228,867
0
0
null
null
null
null
UTF-8
C++
false
false
192
cpp
#include<stdio.h> int and(int a) { if (a==1||a==2) { return 1; } else { return and(a-2)+and(a-1); } } main() { int x; scanf("%d",&x); printf("%d\n",and(x)); }
[ "dangfugui@163.com" ]
dangfugui@163.com
2b5514acfddddd8711c8cf603bd5229ead8c0dc0
9824d607fab0a0a827abff255865f320e2a7a692
/界面资源/[XTreme.Toolkit.9.6.MFC].Xtreme.Toolkit.Pro.v9.60/Samples/GUI_Samples/GUI_Eclipse/GUI_EclipseDoc.h
ab37f6a22a93aa5dcc8d9502430e9c369c140cc0
[]
no_license
tuian/pcshare
013b24af954b671aaf98604d6ab330def675a561
5d6455226d9720d65cfce841f8d00ef9eb09a5b8
refs/heads/master
2021-01-23T19:16:44.227266
2014-09-18T02:31:05
2014-09-18T02:31:05
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,111
h
// GUI_EclipseDoc.h : interface of the CGUI_EclipseDoc class // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // ©1998-2005 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_GUI_ECLIPSEDOC_H__39D8EA55_2CD2_4D09_8504_E2A6A1DAEAAD__INCLUDED_) #define AFX_GUI_ECLIPSEDOC_H__39D8EA55_2CD2_4D09_8504_E2A6A1DAEAAD__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CGUI_EclipseDoc : public CDocument { protected: // create from serialization only CGUI_EclipseDoc(); DECLARE_DYNCREATE(CGUI_EclipseDoc) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CGUI_EclipseDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); //}}AFX_VIRTUAL // Implementation public: virtual ~CGUI_EclipseDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CGUI_EclipseDoc) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_GUI_ECLIPSEDOC_H__39D8EA55_2CD2_4D09_8504_E2A6A1DAEAAD__INCLUDED_)
[ "sincoder@vip.qq.com" ]
sincoder@vip.qq.com
27a0e934d91c14efa6c23fe49bf843e1ce1fafcd
9e49dd158d2a352379c7a33572c61692c05103eb
/src/shaderparam/shaderparam.h
3574e782a25d4f45545360b6ac0b063de70ed69e
[]
no_license
WowVeryLogin/OpenGLBoxes
38db4eb15cf7b704f503de7a122be0fa88b94de5
c7779ea9b468297196cf224e4c9e484498f14c1a
refs/heads/master
2020-07-30T08:29:59.924840
2019-09-22T14:02:49
2019-09-22T14:02:49
210,155,809
0
0
null
null
null
null
UTF-8
C++
false
false
612
h
#ifndef SHADERPARAM_H #define SHADERPARAM_H #include <GL/glew.h> #include <glm/gtc/type_ptr.hpp> #include <string> class ShaderParam { public: ShaderParam() {}; virtual ~ShaderParam() {}; virtual void pass(GLuint prog) = 0; }; template<class Data> class Param : public ShaderParam { public: Param() {}; Param(std::string&& name, Data&& data) : data(data), name(name) {}; private: GLuint location(GLuint prog) { return glGetUniformLocation(prog, name.c_str()); } Data data; std::string name; void pass(GLuint); }; #endif
[ "davidovdd92@mail.ru" ]
davidovdd92@mail.ru
5165a8a3d2eed3277f2e821c7ba3d4ab3fdade5f
4abb82f121c49b2d4051438b326a962a0062fa14
/Source/Battery_Collector/FootStepNotify.h
b22deb4b9b5848661bcb2a312be7de03d0c6e3e7
[]
no_license
hallazie/AnotherDogBitestheDust
cdba272bc4e96e155c8dfdff80069ad47fe9e0ab
1cf739595d496ae19017adddb0c4282620bca29f
refs/heads/main
2023-01-28T09:10:01.610644
2020-12-12T15:18:25
2020-12-12T15:18:25
304,085,043
0
0
null
null
null
null
UTF-8
C++
false
false
577
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Animation/AnimNotifies/AnimNotifyState.h" #include "FootStepNotify.generated.h" /** * */ UCLASS() class BATTERY_COLLECTOR_API UFootStepNotify : public UAnimNotifyState { GENERATED_BODY() public: virtual void NotifyBegin(USkeletalMeshComponent* MeshComp, UAnimSequenceBase* Animation, float TotalDuration) override; virtual void NotifyEnd(USkeletalMeshComponent* MeshComp, UAnimSequenceBase* Animation) override; };
[ "hallazie@outlook.com" ]
hallazie@outlook.com
0e5e3884dfb553ed28002e4af84b15a8eb934e6a
45a26f28a29ab6dd9d3bcf315117d814f50808b1
/src/AppleMacRISC4PE/AppleMacRISC4PE-112.1.17/IOPlatformPlugins/PowerMac7_2_PlatformPlugin/PowerMac7_2_PCIPowerSensor.cpp
541dbecafae3f136b475407715bbc1b807975a51
[]
no_license
zeborrego/opensource.apple.com
0eb9161029ce8440dbdc4b5157b3927a6e381f8d
88cbaab4a42e97cbbfe6b660f2f0945536821be6
refs/heads/master
2021-07-06T17:16:28.241638
2017-10-02T11:58:56
2017-10-02T11:58:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,219
cpp
/* * Copyright (c) 2003-2004 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Copyright (c) 2003-2004 Apple Computer, Inc. All rights reserved. * * */ #include "PowerMac7_2_PCIPowerSensor.h" #define super IOPlatformSensor OSDefineMetaClassAndStructors(PowerMac7_2_PCIPowerSensor, IOPlatformSensor) SensorValue PowerMac7_2_PCIPowerSensor::applyCurrentValueTransform( SensorValue hwReading ) const { SensorValue pluginReading; pluginReading.sensValue = (((UInt32)hwReading.sensValue) << 12) / 40; return pluginReading; } /* XXX the inverse transform is not used, and has not been for a long time... since PID started XXX working. At that point, this class was changed so that instead of inheriting from XXX IOPlatformStateSensor, it inherits from IOPlatformSensor. This method was never removed. XXX I've updated it in line with the change in the value transform functions, but I'm leaving XXX the code commented out because it's not used and shouldn't be here. SensorValue PowerMac7_2_PCIPowerSensor::applyCurrentValueInverseTransform( SensorValue pluginReading ) const { SensorValue hwReading; hwReading.sensValue = (SInt32)((((UInt32)pluginReading.sensValue) * 40) >> 12); return hwReading; } */
[ "mattl@cnuk.org" ]
mattl@cnuk.org
8bfc334fdeeb067f4dd28a9c2535fe79af5e647b
bea7302f72c2f261590544e16b862941f9424838
/Лаба 4 - Стек/TSD-4-STACK/liststack.h
7d9a29f1ec9f2cdb21573426eb14a84cf7652f35
[]
no_license
idenx/Semestr2_TSD
b3bcb88e7b8afc66deb018d48f1c2f36a36ef5b7
b7e4cc8a6681d3bbfe206de6c09f358c6cf30c98
refs/heads/master
2021-01-10T20:38:38.676190
2012-08-04T10:42:49
2012-08-04T10:42:49
5,294,588
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
4,088
h
#ifndef LISTSTACK_H #define LISTSTACK_H #include "stack.h" #include "error.h" template<class T> struct TList { T data; TList* next; }; template<class T> class ListStack : public Stack<T> { public: inline ListStack(); T Pop(); T Top(); void Push(const T &data); bool isEmpty(); inline QString *getLog(); void Free(); int Length(); void Clear(); QString getFreeAddresses(); QString getBusyAddresses(); bool canPush(const T &data, int MaxElements, int MaxAddress); private: TList<T> *Begin; TList<T> *Head; QString Log; QString FreeAddresses; }; template<class T> inline ListStack<T>::ListStack() { Begin = 0; Head = 0; Log = "Создание стека в виде списка"; FreeAddresses = ""; } template<class T> void ListStack<T>::Free() { QString Addresses = ""; TList<T> *temp = Head; while (temp != 0) { Addresses.append(QString::number((int) temp, 16)); this->FreeAddresses.append(QString::number((int) temp, 16)); temp = temp->next; if (temp != 0) { Addresses.append(", "); this->FreeAddresses.append("\n"); } } while (Head != 0) { temp = Head; Head = Head->next; delete temp; } this->Log = (QString) "Освобождение памяти по адресам: " + Addresses; } template<class T> bool ListStack<T>::isEmpty() { bool Result = (Head == 0); return Result; } template<class T> void ListStack<T>::Clear() { this->Free(); } template<class T> int ListStack<T>::Length() { TList<T> *Counter = this->Head; int Length = 0; while (Counter != 0) { Length++; Counter = Counter->next; } return Length; } template<class T> QString ListStack<T>::getFreeAddresses() { return (this->FreeAddresses); } template<class T> bool ListStack<T>::canPush(const T &data, int MaxElements, int MaxAddress) { if (this->Length() >= MaxElements) return false; this->Push(data); int HeadAddress = (int)(this->Head); if (HeadAddress > MaxAddress) { this->Pop(); return false; } return true; } template<class T> QString ListStack<T>::getBusyAddresses() { QString BusyAddresses = ""; TList<T> *temp = Head; while (temp != 0) { BusyAddresses.append(QString::number((int) temp, 16)); temp = temp->next; if (temp != 0) BusyAddresses.append("\n"); } return BusyAddresses; } template<class T> T ListStack<T>::Pop() { if (isEmpty()) { Error error((QString) "Стек пуст!"); throw error; } else { T toReturn = Head->data; TList<T> *toDelete = Head; this->FreeAddresses += QString::number((int) Head, 16) + "\n"; Log = "Удаление элемента '" + (QString) (Head->data) + "' из вершины стека по адресу " + QString::number((int) Head, 16) + " с освобождением памяти"; Head = Head->next; if (Head == 0) Begin = 0; delete toDelete; return toReturn; } } template<class T> T ListStack<T>::Top() { if (isEmpty()) { Error error((QString) "Стек пуст!"); throw error; } else { Log = "Доступ к элементу '" + (QString) (Head->data) + "' на вершине стека (без удаления) по адресу " + QString::number((int) Head, 16); return Head->data; } } template<class T> void ListStack<T>::Push(const T &data) { TList<T> *toAdd = new TList<T>; toAdd->data = data; toAdd->next = Head; if (Head == 0) Begin = toAdd; Head = toAdd; Log = "Добавление элемента '" + (QString) (data) + "' по адресу " + QString::number((int) Head, 16) + " с выделением памяти"; } template<class T> inline QString *ListStack<T>::getLog() { return &(this->Log); } #endif // LISTSTACK_H
[ "idenx@ya.ru" ]
idenx@ya.ru
6b508a5f7296763e4a42f0aff05f780b11f6f73f
ef204cdcda3a3c2c4d5ee9ff9b000b57dcb7e3f3
/MatrixMultiplication/strassen_matrix_multiplication.cpp
5c2b8685d113664d4e80f11b294cc0c312de51a4
[]
no_license
sagarbhathwar/AdvancedAlgorithms
ffd8c13034f242bdafdfc8300a29c3e8ef8f5a90
1736108306b6642cbd5670fcbf4a6453f85a43b4
refs/heads/master
2020-12-07T06:22:09.868483
2016-10-14T04:23:53
2016-10-14T04:23:53
67,332,480
0
0
null
null
null
null
UTF-8
C++
false
false
6,848
cpp
//Compiled with "g++ -std=c++14 -O3 <filename.cpp>" #include <vector> #include <cassert> #include <iostream> #include <iomanip> #include <chrono> #define BLOCK_SIZE 8 template <typename T> class Matrix { private: std::vector<std::vector<T>> matrix_; int n_rows_; int n_cols_; public: Matrix(int n_rows, int n_cols); Matrix() {} template <typename T_> friend std::istream& operator>>(std::istream& is, Matrix<T_>& matrix); template <typename T_> friend std::ostream& operator<<(std::ostream& os, const Matrix<T_>& matrix); static Matrix<T> strassen_multiplication(const Matrix<T>& A, const Matrix<T>& B); Matrix<T> transpose() const; Matrix<T> operator*(const Matrix<T>& other) const; Matrix<T> operator+(const Matrix<T>& other) const; Matrix<T> operator-(const Matrix<T>& other) const; std::vector<T>& operator[](int i); T& operator()(int i, int j); const T& operator()(int i, int j) const; }; template<typename T> Matrix<T>::Matrix(int n_rows, int n_cols) { matrix_ = std::vector<std::vector<T>>(n_rows, std::vector<T>(n_cols)); n_rows_ = n_rows; n_cols_ = n_cols; } template <typename T> std::istream& operator>>(std::istream& is, Matrix<T>& matrix) { for (int i = 0; i < matrix.matrix_.size(); ++i) { for (int j = 0; j < matrix.matrix_[i].size(); ++j) { is >> matrix.matrix_[i][j]; } } return is; } template <typename T> std::ostream& operator<<(std::ostream& os, const Matrix<T>& matrix) { for (int i = 0; i < matrix.matrix_.size(); ++i) { for (int j = 0; j < matrix.matrix_[i].size(); ++j) { os << matrix.matrix_[i][j] << ' '; } os << std::endl; } return os; } template <typename T> Matrix<T> Matrix<T>::operator+(const Matrix<T>& other) const { assert(this->n_cols_ == other.n_cols_ && this->n_rows_ == other.n_rows_); Matrix<T> result(this->n_rows_, this->n_cols_); for (int i = 0; i < this->n_rows_; ++i) { for (int j = 0; j < this->n_cols_; ++j) { result[i][j] = this->matrix_[i][j] + other.matrix_[i][j]; } } return result; } template <typename T> Matrix<T> Matrix<T>::operator-(const Matrix<T>& other) const { assert(this->n_cols_ == other.n_cols_ && this->n_rows_ == other.n_rows_); Matrix<T> result(this->n_rows_, this->n_cols_); for (int i = 0; i < this->n_rows_; ++i) { for (int j = 0; j < this->n_cols_; ++j) { result[i][j] = this->matrix_[i][j] - other.matrix_[i][j]; } } return result; } template <typename T> Matrix<T> Matrix<T>::operator*(const Matrix<T>& other) const { assert(this->n_cols_ == other.n_rows_); Matrix<T> result(this->n_rows_, other.n_cols_); Matrix<T> transpose_of_B = other.transpose(); for (int i = 0; i < this->n_rows_; ++i) { for (int j = 0; j < other.n_cols_; ++j) { T total = 0; for (int k = 0; k < this->n_cols_; ++k) { total += this->matrix_[i][k] * transpose_of_B.matrix_[j][k]; } result.matrix_[i][j] = total; } } return result; } template <typename T> T& Matrix<T>::operator()(int i, int j) { return matrix_[i][j]; } template <typename T> const T& Matrix<T>::operator()(int i, int j) const { return matrix_[i][j]; } template<typename T> std::vector<T>& Matrix<T>::operator[](int i) { return this->matrix_[i]; } template <typename T> Matrix<T> Matrix<T>::transpose() const { Matrix<T> transpose_matrix(n_cols_, n_rows_); for(int i = 0; i < n_rows_; ++i) { for(int j = 0; j < n_cols_; ++j) { transpose_matrix.matrix_[i][j] = this->matrix_[j][i]; } } return transpose_matrix; } template <typename T> Matrix<T> Matrix<T>::strassen_multiplication(const Matrix<T>& A, const Matrix<T>& B) { int n = A.n_rows_; if(n <= BLOCK_SIZE) { return A * B; } else { Matrix<T> a00(n / 2, n / 2), b00(n / 2, n / 2), a01(n / 2, n / 2), b01(n / 2, n / 2), a10(n / 2, n / 2), b10(n / 2, n / 2), a11(n / 2, n / 2), b11(n / 2, n / 2); for(int i = 0; i < n / 2; ++i) { a00.matrix_[i] = std::vector<T>(A.matrix_[i].begin(), A.matrix_[i].begin() + n / 2); b00.matrix_[i] = std::vector<T>(B.matrix_[i].begin(), B.matrix_[i].begin() + n / 2); a01.matrix_[i] = std::vector<T>(A.matrix_[i].begin() + n / 2, A.matrix_[i].end()); b01.matrix_[i] = std::vector<T>(B.matrix_[i].begin() + n / 2, B.matrix_[i].end()); } for(int i = n / 2; i < n; ++i) { a10.matrix_[i - n / 2] = std::vector<T>(A.matrix_[i].begin(), A.matrix_[i].begin() + n / 2); b10.matrix_[i - n / 2] = std::vector<T>(B.matrix_[i].begin(), B.matrix_[i].begin() + n / 2); a11.matrix_[i - n / 2] = std::vector<T>(A.matrix_[i].begin() + n / 2, A.matrix_[i].end()); b11.matrix_[i - n / 2] = std::vector<T>(B.matrix_[i].begin() + n / 2, B.matrix_[i].end()); } Matrix<T> m1 = strassen_multiplication(a00 + a11, b00 + b11); Matrix<T> m2 = strassen_multiplication(a10 + a11, b00); Matrix<T> m3 = strassen_multiplication(a00, b01 - b11); Matrix<T> m4 = strassen_multiplication(a11, b10 - b00); Matrix<T> m5 = strassen_multiplication(a00 + a01, b11); Matrix<T> m6 = strassen_multiplication(a10 - a00, b00 + b01); Matrix<T> m7 = strassen_multiplication(a01 - a11, b10 + b11); Matrix<T> C00 = m1 + m4 - m5 + m7; Matrix<T> C01 = m3 + m5; Matrix<T> C10 = m2 + m4; Matrix<T> C11 = m1 + m3 - m2 + m6; Matrix<T> C(n, n); for (int i = 0; i < n / 2; ++i) for (int j = 0; j < n / 2; ++j) C(i, j) = C00(i, j); for (int i = 0; i < n / 2; ++i) for (int j = n / 2; j < n; ++j) C(i, j) = C01(i, j - n / 2); for (int i = n / 2; i < n; ++i) for (int j = 0; j < n / 2; ++j) C(i, j) = C10(i - n / 2, j); for (int i = n / 2; i < n; ++i) for (int j = n / 2; j < n; ++j) C(i, j) = C11(i - n / 2, j - n / 2); return C; } } int main() { int n; std::cin >> n; Matrix<float> A(n, n), B(n , n); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { std::cin >> A(i, j); } } for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { std::cin >> B(i, j); } } std::cout << std::fixed << std::setprecision(6); auto t1 = std::chrono::high_resolution_clock::now(); auto C1 = Matrix<float>::strassen_multiplication(A, B); auto t2 = std::chrono::high_resolution_clock::now(); std::cout << double((t2 - t1).count()) / (1000000000) << std::endl; }
[ "sagarbhathwar@gmail.com" ]
sagarbhathwar@gmail.com
3424cc50dc63286aeec289a4c66647e94c09cdb9
b1a8b4515064081a2571a21cef3aab597e2566c4
/core/unit_tests/gen12lp/image_surface_state_tests_gen12lp.cpp
8b02b132671853306ce189cd498e9436f4a3808b
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
KamilKoprykIntel/compute-runtime
379e9bc66e34b6cbda4b9a1ef7d1cd0da58d9ca2
8ece440625dc178b6f836ea455d8daccda5cdcc0
refs/heads/master
2021-01-08T04:01:29.178394
2020-02-19T19:17:21
2020-02-20T11:10:21
241,906,088
0
0
MIT
2020-02-20T14:32:41
2020-02-20T14:32:40
null
UTF-8
C++
false
false
2,728
cpp
/* * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "core/unit_tests/image/image_surface_state_fixture.h" using ImageSurfaceStateTestsGen12LP = ImageSurfaceStateTests; GEN12LPTEST_F(ImageSurfaceStateTestsGen12LP, givenGmmWithMediaCompressedWhenSetFlagsForMediaCompressionThenAuxiliarySurfaceNoneIsSetAndMemoryCompressionEnable) { auto size = sizeof(typename TGLLPFamily::RENDER_SURFACE_STATE); auto surfaceState = std::make_unique<char[]>(size); auto castSurfaceState = reinterpret_cast<typename TGLLPFamily::RENDER_SURFACE_STATE *>(surfaceState.get()); castSurfaceState->setAuxiliarySurfaceMode(TGLLPFamily::RENDER_SURFACE_STATE::AUXILIARY_SURFACE_MODE::AUXILIARY_SURFACE_MODE_AUX_CCS_E); mockGmm.gmmResourceInfo->getResourceFlags()->Info.MediaCompressed = false; setFlagsForMediaCompression<TGLLPFamily>(castSurfaceState, &mockGmm); EXPECT_EQ(castSurfaceState->getAuxiliarySurfaceMode(), TGLLPFamily::RENDER_SURFACE_STATE::AUXILIARY_SURFACE_MODE::AUXILIARY_SURFACE_MODE_AUX_CCS_E); EXPECT_EQ(castSurfaceState->getMemoryCompressionEnable(), false); mockGmm.gmmResourceInfo->getResourceFlags()->Info.MediaCompressed = true; setFlagsForMediaCompression<TGLLPFamily>(castSurfaceState, &mockGmm); EXPECT_EQ(castSurfaceState->getAuxiliarySurfaceMode(), TGLLPFamily::RENDER_SURFACE_STATE::AUXILIARY_SURFACE_MODE::AUXILIARY_SURFACE_MODE_AUX_NONE); EXPECT_EQ(castSurfaceState->getMemoryCompressionEnable(), true); } GEN12LPTEST_F(ImageSurfaceStateTestsGen12LP, givenGmmWhenSetClearColorParamsThenClearValueAddressEnable) { auto size = sizeof(typename TGLLPFamily::RENDER_SURFACE_STATE); auto surfaceState = std::make_unique<char[]>(size); auto castSurfaceState = reinterpret_cast<typename TGLLPFamily::RENDER_SURFACE_STATE *>(surfaceState.get()); mockGmm.gmmResourceInfo->getResourceFlags()->Gpu.IndirectClearColor = true; setClearColorParams<TGLLPFamily>(castSurfaceState, &mockGmm); EXPECT_EQ(castSurfaceState->getClearValueAddressEnable(), true); } GEN12LPTEST_F(ImageSurfaceStateTestsGen12LP, givenGmmWithMediaCompressedWhenSetMipTailStartLodThenMipTailStartLodIsSet) { auto size = sizeof(typename FamilyType::RENDER_SURFACE_STATE); auto surfaceState = std::make_unique<char[]>(size); auto castSurfaceState = reinterpret_cast<typename FamilyType::RENDER_SURFACE_STATE *>(surfaceState.get()); setMipTailStartLod<FamilyType>(castSurfaceState, nullptr); EXPECT_EQ(castSurfaceState->getMipTailStartLod(), 0u); setMipTailStartLod<FamilyType>(castSurfaceState, &mockGmm); EXPECT_EQ(castSurfaceState->getMipTailStartLod(), mockGmm.gmmResourceInfo->getMipTailStartLodSurfaceState()); }
[ "ocldev@intel.com" ]
ocldev@intel.com
23874ae9db9b6ba46286d87517dd373b929ccf94
2b79dd853f40ceb9291db8048805e1d5056eae57
/numbersToMonths.cpp
9b3ed7a596ecbb9c116bf60ae4bb9db5f899f71e
[]
no_license
ArginAslanian/008-Numbers-To-Months
7282510481f7b908614b1b1f3cfbb5f6f37bb8f3
99d2ef7add950536e43ee9932144091e28076b40
refs/heads/master
2021-08-29T20:01:58.340732
2017-12-14T21:40:06
2017-12-14T21:40:06
114,298,848
0
0
null
null
null
null
UTF-8
C++
false
false
3,126
cpp
/** * Programmer: Argin Aslanian * Purpose: This program will display the name of a month in either Italian or English * given the number of the month by the user. * * A map with a key of string and value of a map with a key of int and a value of string is created. * The key of the map is the language. * The value of the map is another map, with a key that is the number of the month, and a value * that is the name of the month, in that language. * * Constraints & Assumptions. * 1. The user will enter either 'English' or 'Italian'. * 2. The user will enter numbers ONLY between 1 and 12. * 3. If the user enters another value, display appropriate message. */ #include <iostream> #include <map> using namespace std; int main() { //Create the map. map<string, map<int, string>> months = { {"Italian", { {1, "Gennaio"}, {2, "Febbraio"}, {3, "Marzo"}, {4, "Aprile"}, {5, "Maggio"}, {6, "Giugno"}, {7, "Luglio"}, {8, "Agosto"}, {9, "Settembre"}, {10, "Ottobre"}, {11, "Novembre"}, {12, "Dicembre"} } }, {"English", { {1, "January"}, {2, "February"}, {3, "March"}, {4, "April"}, {5, "May"}, {6, "June"}, {7, "July"}, {8, "August"}, {9, "September"}, {10, "October"}, {11, "November"}, {12, "December"} } } }; //Declare variables. string lang; int num; //Get language. cout << "Choose Language: Italian or English? " << endl; cin >> lang; //Get number of the month. cout << "Choose the number of the month: " << endl; cin >> num; //Check if the language entered exists in the map. if (months.count(lang) > 0) { //If it does, check if the number of the month entered exists in the map. if (months[lang].count(num) > 0) { //If it does, display to the user. cout << "Month number " << num << " in " << lang << " is " << months[lang][num] << "." << endl; } else { //If the number of the month does not exist, display appropriate message. cout << "Error: You entered an invalid value. " << endl; } } else { //If the language entered did not exist, display appropriate message. cout << "Error: You entered an unsupported language for this program. " << endl; } return 0; }
[ "33509814+ArginAslanian@users.noreply.github.com" ]
33509814+ArginAslanian@users.noreply.github.com
fef836b5cddad182aded0c6db4a5f1dede5bedd0
7d7f8c987297fa43515e713ef08643bedb588e73
/ccdb/src/Tests/test_NoMySqlUserAPI.cc
b96b099bd9f7535e55e65e57d5e41bfde159874a
[]
no_license
lendackya/Add-PMT-Files
ccce48ab538427ecf5fa519c379c34aa2508b915
b4533bb905a694a25da37842552b1250196762f1
refs/heads/master
2021-01-13T12:51:34.460757
2020-07-23T16:24:09
2020-07-23T16:24:09
78,468,358
0
1
null
2020-07-23T12:07:48
2017-01-09T20:57:29
C
UTF-8
C++
false
false
6,956
cc
#pragma warning(disable:4800) #include "Tests/catch.hpp" #include "Tests/tests.h" #include "CCDB/Console.h" #include "CCDB/SQLiteCalibration.h" #include "CCDB/Providers/SQLiteDataProvider.h" #include "CCDB/Helpers/PathUtils.h" #include "CCDB/CalibrationGenerator.h" using namespace std; using namespace ccdb; /** ********************************************************************* * @brief Test of CCDB USER API work * * @return true if test passed */ TEST_CASE("CCDB/UserAPI/SQLite","tests") { bool result; DataProvider *prov = new SQLiteDataProvider(); if(!prov->Connect(TESTS_SQLITE_STRING)) return; //U S I N G U S E R A P I D I R E C T L Y //---------------------------------------------------- SQLiteCalibration *calib = new SQLiteCalibration(100); result = false; REQUIRE_NOTHROW(result = calib->Connect(TESTS_SQLITE_STRING)); REQUIRE(result); REQUIRE(calib->GetConnectionString() == TESTS_SQLITE_STRING); //get data as table of strings //---------------------------------------------------- vector<vector<string> > tabledValues; REQUIRE_NOTHROW(result = calib->GetCalib(tabledValues, "/test/test_vars/test_table")); REQUIRE(tabledValues.size()>0); REQUIRE(tabledValues.size()==2); REQUIRE(tabledValues[0].size()==3); //test of disconnect and reconnect function //---------------------------------------------------- REQUIRE_NOTHROW(calib->Disconnect()); REQUIRE_NOTHROW(calib->Reconnect()); //test of getting data without / in the beginning //---------------------------------------------------- tabledValues.clear(); REQUIRE_NOTHROW(result = calib->GetCalib(tabledValues, "test/test_vars/test_table")); REQUIRE(result); REQUIRE(tabledValues.size()>0); //test of getting data without / in the beginning //---------------------------------------------------- vector<map<string, string> > vectorOfMapsdValues; REQUIRE_NOTHROW(result = calib->GetCalib(vectorOfMapsdValues, "test/test_vars/test_table")); REQUIRE(result); REQUIRE(vectorOfMapsdValues.size()>0); vectorOfMapsdValues.clear(); REQUIRE_NOTHROW(result = calib->GetCalib(vectorOfMapsdValues, "test/test_vars/test_table")); REQUIRE(result); REQUIRE(vectorOfMapsdValues.size()>0); //test of get all namepaths //---------------------------------------------------- vector<string> paths; REQUIRE_NOTHROW(calib->GetListOfNamepaths(paths)); REQUIRE(paths.size()>0); } TEST_CASE("CCDB/UserAPI/SQLite_CalibrationGenerator","Use universal generator to get calibrations") { bool result; CalibrationGenerator* gen = new CalibrationGenerator(); Calibration* sqliteCalib = gen->MakeCalibration(TESTS_SQLITE_STRING, 100, "default"); REQUIRE(static_cast<SQLiteCalibration*>(sqliteCalib)!=NULL); REQUIRE(sqliteCalib->IsConnected()); vector<vector<string> > tabledValues; REQUIRE_NOTHROW(result = sqliteCalib->GetCalib(tabledValues, "/test/test_vars/test_table")); REQUIRE(result); REQUIRE(tabledValues.size()>0); REQUIRE(tabledValues.size()==2); REQUIRE(tabledValues[0].size()==3); //ask for vector vector<vector<int> > tabledDoubleValues; REQUIRE_NOTHROW(result = sqliteCalib->GetCalib(tabledDoubleValues, "/test/test_vars/test_table2::test")); REQUIRE(result); REQUIRE(tabledDoubleValues.size()>0); REQUIRE(tabledDoubleValues.size()==1); REQUIRE(tabledDoubleValues[0].size()==3); REQUIRE(tabledDoubleValues[0][0]==10); REQUIRE(tabledDoubleValues[0][1]==20); REQUIRE(tabledDoubleValues[0][2]==30); vector<int> lineOfIntValues; REQUIRE_NOTHROW(result = sqliteCalib->GetCalib(lineOfIntValues, "/test/test_vars/test_table2:0:test:2012-09-30 23-48-42")); REQUIRE(result); REQUIRE(lineOfIntValues.size()==3); REQUIRE(lineOfIntValues[0]==10); REQUIRE(lineOfIntValues[1]==20); REQUIRE(lineOfIntValues[2]==30); //Get Type table through the Provider() ConstantsTypeTable* table = sqliteCalib->GetProvider()->GetConstantsTypeTable("/test/test_vars/test_table2", true); REQUIRE(table->GetColumns()[0]->GetType() == ConstantsTypeColumn::cIntColumn); Calibration* sqliteCalib2 = gen->MakeCalibration(TESTS_SQLITE_STRING, 100, "default"); REQUIRE(sqliteCalib == sqliteCalib2); REQUIRE(CalibrationGenerator::CheckOpenable(TESTS_SQLITE_STRING)); REQUIRE_FALSE(CalibrationGenerator::CheckOpenable("abra_kadabra://protocol")); //=== Default time === SECTION("Default Time SQLite", "Test that test vars are opened with default date") { ContextParseResult res = PathUtils::ParseContext("variation=default calibtime=2012-08"); Calibration* sqliteCalib = gen->MakeCalibration(TESTS_SQLITE_STRING, 100, res.Variation, res.ConstantsTime); REQUIRE_NOTHROW(result = sqliteCalib->GetCalib(tabledValues, "/test/test_vars/test_table")); REQUIRE(result); REQUIRE(tabledValues.size()>0); REQUIRE(tabledValues.size()==2); REQUIRE(tabledValues[0].size()==3); REQUIRE(tabledValues[0][0]=="1.11"); //No such calibration exist in mc variation, but constants should fallback to default varitaion res = PathUtils::ParseContext("variation=subtest calibtime=2012-11"); sqliteCalib = gen->MakeCalibration(TESTS_SQLITE_STRING, 100, res.Variation, res.ConstantsTime); REQUIRE_NOTHROW(result = sqliteCalib->GetCalib(tabledValues, "/test/test_vars/test_table")); REQUIRE(result); REQUIRE(tabledValues.size()>0); REQUIRE(tabledValues.size()==2); REQUIRE(tabledValues[0].size()==3); REQUIRE(tabledValues[0][0]=="10"); //No such calibration exist in test variation run 100, but constants should fallback to variation res = PathUtils::ParseContext("variation=test"); sqliteCalib = gen->MakeCalibration(TESTS_SQLITE_STRING, 100, res.Variation); REQUIRE_NOTHROW(result = sqliteCalib->GetCalib(tabledValues, "/test/test_vars/test_table")); REQUIRE(result); REQUIRE(tabledValues.size()>0); REQUIRE(tabledValues.size()==2); REQUIRE(tabledValues[0].size()==3); REQUIRE(tabledValues[0][0]=="2.2"); //Error regression test for bug with absent column names. Filling map will test the column names are OK vector<map<string, string> > tableMapValues; REQUIRE_NOTHROW(result = sqliteCalib->GetCalib(tableMapValues, "/test/test_vars/test_table")); } SECTION("Get Assignment test", "Test all elements of getting data through get assignment") { Assignment *a; REQUIRE_NOTHROW(a = sqliteCalib->GetAssignment("/test/test_vars/test_table2:0:test")); REQUIRE(result); REQUIRE(a->GetValueType(0) == ConstantsTypeColumn::cIntColumn); REQUIRE(a->GetValueType("c3") == ConstantsTypeColumn::cIntColumn); REQUIRE(a->GetValue(1) == "20"); REQUIRE(a->GetValue(0, 1) == "20"); REQUIRE(a->GetValue("c1") == "10"); REQUIRE(a->GetValue(0, "c3") == "30"); REQUIRE(a->GetValueInt(1) == 20); REQUIRE(a->GetValueInt(0, 1) == 20); REQUIRE(a->GetValueInt("c1") == 10); REQUIRE(a->GetValueInt(0, "c3") == 30); REQUIRE(a->GetValueDouble(2) > 29); } }
[ "lendackya@gmail.com" ]
lendackya@gmail.com
b37860c9c54f99082e5b147bd4984adcd7f983d5
f70fd72a5ded8bcdb81da24af20ddbbd21973182
/Firmware/communication/ascii_protocol.hpp
145ee5e5c9ec64b6cc52a55d407ce86e36d61055
[ "MIT" ]
permissive
Wetmelon/ODrive
f0d4c6b77356581310e578512fd9b47790e6bf37
b917896daca15b5631297a963a722ac6bf456959
refs/heads/master
2021-11-08T20:46:20.276050
2020-10-28T04:40:42
2020-10-28T04:40:42
84,619,177
20
25
MIT
2020-11-26T12:26:25
2017-03-11T02:56:43
C
UTF-8
C++
false
false
850
hpp
#ifndef __ASCII_PROTOCOL_H #define __ASCII_PROTOCOL_H /* Includes ------------------------------------------------------------------*/ #include <fibre/protocol.hpp> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported variables --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ void ASCII_protocol_parse_stream(const uint8_t* buffer, size_t len, StreamSink& response_channel); #endif /* __ASCII_PROTOCOL_H */
[ "samuel.sadok@bluewin.ch" ]
samuel.sadok@bluewin.ch
c024af4e1fa342ce0ef1037bf982158097d817cf
8a2cf1681445d6ab3259a9ec07ec5044fcf388d5
/BuildFre_elementIcon.cpp
db6858a4b42a7aa1b2945dc655031d608588347c
[]
no_license
ChongMingWei/RoyalBattle
28ae2cfe8f743e50bd14217a0d48726208543222
a195e9c9e1647271dc4966ec51d289da2e348519
refs/heads/master
2021-01-01T06:07:18.997623
2017-06-11T07:05:10
2017-06-11T07:05:10
97,360,324
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
#include "BuildFire_elementIcon.h" #include "Game.h" extern Game * game; BuildFire_elementIcon::BuildFire_elementIcon(QGraphicsItem *parent):QGraphicsPixmapItem(parent) { setPixmap(QPixmap(":/image/championicon/fire_element_icon.png")); } void BuildFire_elementIcon::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(!game->summon_fire_element) { //game->setCursor(QString(":/image/archer.png")); game->summon_fire_element = new Fire_element(); } }
[ "29A7882zz@gmail.com" ]
29A7882zz@gmail.com
ae7ef25d4e2abcf714cf00b3073f1c68a7bd0209
258a8d35efb2f35aca22de0ed8391010ad31efbb
/segmentsFitting2D/segmentsFitting2D/selectable.cpp
71f9bbfb4e3ddb92104d05b9242eb3dc88e9034e
[]
no_license
hatsil/thesis
b8c88a0ebab1462156cde10a674f35449b1bc9e8
ae26983ed69e3863287be8188a66c5ef3971b3d0
refs/heads/master
2020-03-26T09:35:33.730729
2018-10-09T13:08:48
2018-10-09T13:08:48
144,754,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,470
cpp
/* * pressable.cpp * * Created on: 13 Sep 2018 * Author: hatsil */ #include "selectable.hpp" #include "selectableDelegate.hpp" namespace thesis { static uint pickingColorSingleton = 1; Selectable::Selectable(): Drawable(), pickingColor(pickingColorSingleton), pickingColorVec(convertPickingColor(pickingColorSingleton)), selectableDelegate(nullptr) { ++pickingColorSingleton; } Selectable::~Selectable() {} void Selectable::leftPosition(double, double) {} void Selectable::resign() {} void Selectable::rightPress() {} void Selectable::rightRelease() {} void Selectable::rightPosition(double, double) {} void Selectable::middlePress() {} void Selectable::middleRelease() {} bool Selectable::mark() { return false; } bool Selectable::unmark() { return false; } bool Selectable::isRemovable() const { return false; } void Selectable::position(double, double) {} void Selectable::setDelegate(SelectableDelegate* selectableDelegate) { this->selectableDelegate = selectableDelegate; selectableDelegate->addSelectable(this); } bool SelectablePtrComp::operator()(Selectable* const & lhs, Selectable* const & rhs) const { return lhs->pickingColor < rhs->pickingColor; } bool SelectablePtrComp::operator()(Selectable* const & lhs, const uint& rhs) const { return lhs->pickingColor < rhs; } bool SelectablePtrComp::operator()(const uint& lhs, Selectable* const & rhs) const { return lhs < rhs->pickingColor; } } /* namespace thesis */
[ "tsahisa@post.bgu.ac.il" ]
tsahisa@post.bgu.ac.il
1aadfeac4a9d799542d4d9d1a38850f3c180f959
d06bc963456f5403402389944917a1ee722dec62
/Codechef/MAY17/SANDWICH3.cpp
254686c8ff25ffe3d8c9ecd3a7eebcfb1255e43a
[]
no_license
hackboxlive/CP
4ec6a8d0581d71ef103e47ad08e5a5ce93f20ff5
4110a37ec88aac85295802892876ad42779c60a8
refs/heads/master
2021-06-16T03:34:37.321378
2020-11-24T21:22:48
2020-11-24T21:22:48
95,323,963
3
2
null
2018-01-21T08:19:18
2017-06-24T21:33:12
C++
UTF-8
C++
false
false
5,684
cpp
// This is a collection of useful code for solving problems that // involve modular linear equations. Note that all of the // algorithms described here work on nonnegative integers. #include <iostream> #include <vector> #include <algorithm> #include <cstdio> using namespace std; typedef vector<int> VI; typedef pair<int,int> PII; vector<VI> facts1; vector<VI> facts2; vector<PII> factors; void print_vector(VI v) { for (int i = 0; i < v.size(); ++i) { printf(" %d", v[i]); } printf("\n"); } // return a % b (positive value) int mod(int a, int b) { return ((a%b)+b)%b; } // computes gcd(a,b) int gcd(int a, int b) { int tmp; while(b){a%=b; tmp=a; a=b; b=tmp;} return a; } // computes lcm(a,b) int lcm(int a, int b) { return a/gcd(a,b)*b; } // returns d = gcd(a,b); finds x,y such that d = ax + by int extended_euclid(int a, int b, int &x, int &y) { int xx = y = 0; int yy = x = 1; while (b) { int q = a/b; int t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y-q*yy; y = t; } return a; } // finds all solutions to ax = b (mod n) VI modular_linear_equation_solver(int a, int b, int n) { int x, y; VI solutions; int d = extended_euclid(a, n, x, y); if (!(b%d)) { x = mod (x*(b/d), n); for (int i = 0; i < d; i++) solutions.push_back(mod(x + i*(n/d), n)); } return solutions; } // computes b such that ab = 1 (mod n), returns -1 on failure int mod_inverse(int a, int n) { int x, y; int d = extended_euclid(a, n, x, y); if (d > 1) return -1; return mod(x,n); } // Chinese remainder theorem (special case): find z such that // z % x = a, z % y = b. Here, z is unique modulo M = lcm(x,y). // Return (z,M). On failure, M = -1. PII chinese_remainder_theorem(int x, int a, int y, int b) { int s, t; int d = extended_euclid(x, y, s, t); if (a%d != b%d) return make_pair(0, -1); return make_pair(mod(s*b*x+t*a*y,x*y)/d, x*y/d); } // Chinese remainder theorem: find z such that // z % x[i] = a[i] for all i. Note that the solution is // unique modulo M = lcm_i (x[i]). Return (z,M). On // failure, M = -1. Note that we do not require the a[i]'s // to be relatively prime. PII chinese_remainder_theorem(const VI &x, const VI &a) { PII ret = make_pair(a[0], x[0]); for (int i = 1; i < x.size(); i++) { ret = chinese_remainder_theorem(ret.second, ret.first, x[i], a[i]); if (ret.second == -1) break; } return ret; } // computes x and y such that ax + by = c; on failure, x = y =-1 void linear_diophantine(int a, int b, int c, int &x, int &y) { int d = gcd(a,b); if (c%d) { x = y = -1; } else { x = c/d * mod_inverse(a/d, b/d); y = (c-a*x)/b; } } // compute a^b % m int power_mod(int a, int b, int m) { if (b == 0) { return 1; } else if (b == 1) { return a % m; } else { int tmp = power_mod(a, b >> 1, m); if (b % 2 == 0) { return tmp * tmp % m; } else { return tmp * tmp * a % m; } } } // compute n! = a * p^e, return (a, e), p is a prime PII fact_mod(int n, int p, const VI& facts) { if (n == 0) return make_pair(1, 0); PII tmp = fact_mod(n / p, p, facts); int a = tmp.first; int e = tmp.second; e += n / p; if (n / p % 2 != 0) return make_pair(a * (p - facts[n % p]) %p, e); else return make_pair(a * facts[n % p] % p, e); } // compute n!! (mod m), m is of type p^a, where p is a prime int n_fact_fact(int n, int m, int p, const VI& facts) { if (n == 0 || n == 1) { return 1; } else if (n < m) { return facts[n] * n_fact_fact(n / p, m, p, facts) % m; } else { int a = facts[m - 1]; int b = facts[n % m]; int c = n_fact_fact(n / p, m, p, facts); return power_mod(a, n / m, m) * b * c % m; } } int power(int a, int i) { if (i == 0) { return 1; } else if (i == 1) { return a; } else { int tmp = power(a, i >> 1); if (i % 2 == 0) return tmp * tmp; else return tmp * tmp * a; } } int comb_mod2(int n, int r, int m, PII pa, const VI facts, const VI& tmp) { int p, a; p = pa.first; a = pa.second; int b = a; while (b > 0) { PII t1 = fact_mod(n, p, tmp); PII t2 = fact_mod(r, p, tmp); PII t3 = fact_mod(n - r, p, tmp); int e1, e2, e3; e1 = t1.second; e2 = t2.second; e3 = t3.second; if (e1 >= e2 + e3 + a) return 0; if (e1 >= e2 + e3 + b) break; b = b - 1; } int m1 = n_fact_fact(n, m, p, facts); int m2 = n_fact_fact(r, m, p ,facts); int m3 = n_fact_fact(n - r, m, p, facts); return power(p, b) * m1 * mod_inverse(m2, m) * \ mod_inverse(m3, m) % m; } int solve(int n, int r) { VI xs(4, 0); VI as(4, 0); for (int i = 0; i < factors.size(); ++i) { xs[i] = power(factors[i].first, factors[i].second); as[i] = comb_mod2(n, r, xs[i], factors[i], facts1[i], facts2[i]); } return chinese_remainder_theorem(xs, as).first; } VI gen_fact(int m) { VI ret(m, 1); ret.push_back(1); for (int i = 1; i < m; ++i) { if (gcd(i, m) == 1) ret[i] = ret[i - 1] * i % m; else ret[i] = ret[i - 1]; } return ret; } void init() { factors.push_back(make_pair(3, 3)); factors.push_back(make_pair(11, 1)); factors.push_back(make_pair(13, 1)); factors.push_back(make_pair(37, 1)); for(int i = 0; i < 4; ++i) { int p = factors[i].first; int a = factors[i].second; facts1.push_back(gen_fact(power(p, a))); facts2.push_back(gen_fact(p)); } } int main() { int T, n, r; init(); scanf("%d", &T); for (int i = 0; i < T; ++i) { scanf("%d %d", &n, &r); int newn=(n/r)-1; int newk=r-(n%r); // cout<<newn<<" "<<newk<<endl; printf("%d\n", solve(newn+newk+1, newn+1)); } }
[ "singhsarvshakti127@gmail.com" ]
singhsarvshakti127@gmail.com
cbdc2070c854abd5f757b2c7985c310575435144
883128f43c1aa8e2d4e556d688a5a18fcae3bbe5
/Firmware/IotaWatt/GetFeedData.ino
9b467a23a1695c5d9372159c26d4d54a775dd22d
[]
no_license
BitKnitting/IoTaWatt
e1b070d65987da622f3fdbd5cff6abb797988da0
664917156262d2845446099a9fc7b3fbba237d2d
refs/heads/master
2021-01-15T18:40:55.622116
2017-08-07T23:15:40
2017-08-07T23:15:40
99,798,265
0
0
null
2017-08-09T10:54:50
2017-08-09T10:54:50
null
UTF-8
C++
false
false
7,998
ino
/*************************************************************************************************** * GetFeedData SERVICE. * * The web server does a pretty good job of handling file downloads and uploads asynchronously, * but assumes that any callbacks to new handlers get the job completely done befor returning. * The GET /feed/data/ request takes a long time and generates a lot of data so it needs to * run as a SERVICE so that sampling can continue while it works on providing the data. * To accomplish that without modifying ESP8266WebServer, we schedule this SERVICE and * block subsequent calls to server.handleClient() until the request is satisfied, at which time * this SERVICE returns with code 0 to cause it's serviceBlock to be deleted. When a new /feed/data * request comes in, the web server handler will reshedule this SERVICE with NewService. * **************************************************************************************************/ uint32_t handleGetFeedData(struct serviceBlock* _serviceBlock){ // trace T_GFD enum states {Initialize, Setup, process}; static states state = Initialize; static IotaLogRecord* logRecord = new IotaLogRecord; static IotaLogRecord* lastRecord = new IotaLogRecord; static IotaLogRecord* swapRecord; static char* bufr = nullptr; static uint32_t bufrSize = 0; static uint32_t bufrPos = 0; static double accum1Then = 0; static double logHoursThen = 0; static double elapsedHours = 0; static uint32_t startUnixTime; static uint32_t endUnixTime; static uint32_t intervalSeconds; static uint32_t UnixTime; static int voltageChannel = 0; static boolean Kwh = false; static String replyData = ""; struct req { req* next; int channel; int queryType; IotaOutputChannel* output; req(){next=nullptr; channel=0; queryType=0; output=nullptr;}; ~req(){delete next;}; } static reqRoot; switch (state) { case Initialize: { state = Setup; return 1; } case Setup: { trace(T_GFD,0); // Parse the ID parm into a list. String idParm = server.arg("id"); reqRoot.next = nullptr; req* reqPtr = &reqRoot; int i = 0; if(idParm.startsWith("[")){ idParm[idParm.length()-1] = ','; i = 1; } else { idParm += ","; } while(i < idParm.length()){ reqPtr->next = new req; reqPtr = reqPtr->next; int id = idParm.substring(i,idParm.indexOf(',',i)).toInt(); i = idParm.indexOf(',',i) + 1; reqPtr->channel = id / 10; reqPtr->queryType = id % 10; if(reqPtr->channel >= 100){ IotaOutputChannel* _output = (IotaOutputChannel*)outputList.findFirst(); while(_output){ if(_output->_channel == reqPtr->channel){ break; } _output = (IotaOutputChannel*)outputList.findNext(_output); } reqPtr->output = _output; } } startUnixTime = server.arg("start").substring(0,10).toInt(); endUnixTime = server.arg("end").substring(0,10).toInt(); intervalSeconds = server.arg("interval").toInt(); accum1Then = 0; logHoursThen = 0; if(startUnixTime >= iotaLog.firstKey()){ lastRecord->UNIXtime = startUnixTime - intervalSeconds; } else { lastRecord->UNIXtime = iotaLog.firstKey(); } // Using String for a large buffer abuses the heap // and takes up a lot of time. We will build // relatively short response elements with String // and copy them to this larger buffer. bufrSize = ESP.getFreeHeap() / 2; if(bufrSize > 4096) bufrSize = 4096; bufr = new char [bufrSize]; // Setup buffer to do it "chunky-style" bufr[3] = '\r'; bufr[4] = '\n'; bufrPos = 5; server.setContentLength(CONTENT_LENGTH_UNKNOWN); server.sendHeader("Accept-Ranges","none"); server.sendHeader("Transfer-Encoding","chunked"); server.send(200,"application/json",""); replyData = "["; UnixTime = startUnixTime; state = process; _serviceBlock->priority = priorityLow; return 1; } case process: { trace(T_GFD,1); uint32_t exitTime = nextCrossMs + 5000 / frequency; // Take an additional half cycle SPI.beginTransaction(SPISettings(SPI_FULL_SPEED, MSBFIRST, SPI_MODE0)); // Loop to generate entries while(UnixTime <= endUnixTime) { logRecord->UNIXtime = UnixTime; int rtc = iotaLog.readKey(logRecord); trace(T_GFD,2); replyData += '['; // + String(UnixTime) + "000,"; elapsedHours = logRecord->logHours - lastRecord->logHours; req* reqPtr = &reqRoot; while((reqPtr = reqPtr->next) != nullptr){ int channel = reqPtr->channel; if(rtc || logRecord->logHours == lastRecord->logHours){ replyData += "null"; } // input channel else if(channel < 100){ trace(T_GFD,3); if(reqPtr->queryType == QUERY_VOLTAGE) { replyData += String((logRecord->channel[channel].accum1 - lastRecord->channel[channel].accum1) / elapsedHours,1); } else if(reqPtr->queryType == QUERY_POWER) { replyData += String((logRecord->channel[channel].accum1 - lastRecord->channel[channel].accum1) / elapsedHours,1); } else if(reqPtr->queryType == QUERY_ENERGY) { replyData += String((logRecord->channel[channel].accum1 / 1000.0),2); } } // output channel else { trace(T_GFD,4); if(reqPtr->output == nullptr){ replyData += "null"; } else if(reqPtr->queryType == QUERY_ENERGY){ replyData += String(reqPtr->output->runScript([](int i)->double { return logRecord->channel[i].accum1 / 1000.0;}), 2); } else { replyData += String(reqPtr->output->runScript([](int i)->double { return (logRecord->channel[i].accum1 - lastRecord->channel[i].accum1) / elapsedHours;}), 1); } } replyData += ','; } replyData.setCharAt(replyData.length()-1,']'); swapRecord = lastRecord; lastRecord = logRecord; logRecord = swapRecord; UnixTime += intervalSeconds; // When buffer is full, send a chunk. trace(T_GFD,5); if((bufrSize - bufrPos - 5) < replyData.length()){ trace(T_GFD,6); sendChunk(bufr, bufrPos); bufrPos = 5; } // Copy this element into the buffer for(int i = 0; i < replyData.length(); i++) { bufr[bufrPos++] = replyData[i]; } replyData = ','; } trace(T_GFD,7); // All entries generated, terminate Json and send. replyData.setCharAt(replyData.length()-1,']'); for(int i = 0; i < replyData.length(); i++) { bufr[bufrPos++] = replyData[i]; } sendChunk(bufr, bufrPos); // Send terminating zero chunk, clean up and exit. sendChunk(bufr, 5); trace(T_GFD,7); delete reqRoot.next; delete[] bufr; state = Setup; serverAvailable = true; return 0; // Done for now, return without scheduling. } } } void sendChunk(char* bufr, const uint32_t bufrPos){ trace(T_GFD,9); const char* hexDigit = "0123456789ABCDEF"; int _len = bufrPos - 5; bufr[0] = hexDigit[_len/256]; bufr[1] = hexDigit[(_len/16) % 16]; bufr[2] = hexDigit[_len % 16]; bufr[bufrPos] = '\r'; bufr[bufrPos+1] = '\n'; bufr[bufrPos+2] = 0; server.sendContent(bufr); }
[ "bob@overeasy.com" ]
bob@overeasy.com
2212c52487c04eaf21283efaf6f8d94e82bc1ee6
e2319cf27b405309f7e73112236f23972f8465bf
/CreateBiTree.cpp
4bd1debeb8bb3c5ec950166b59e15bd18d263856
[]
no_license
YouYaoGuai/DataStructure
c1f10502f28fefa8af07c4ae39f10039625ba5dd
b4b3a6a55cf8df1c4b9df04d0f5186074ed94358
refs/heads/master
2020-05-20T05:30:35.368322
2013-12-01T13:07:38
2013-12-01T13:07:38
null
0
0
null
null
null
null
GB18030
C++
false
false
686
cpp
// huawei.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "string.h" #include "conio.h" #include "stdlib.h" #include "assert.h" #define OK 0 #define ERROR 1 #define MAX 100 typedef char TElemType; typedef struct BiTNode { TElemType data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; BiTree CreateBiTree( ) { BiTree T; TElemType ch = NULL; scanf("%c",&ch); getchar(); if(ch == ' ') T = NULL; else { T = (BiTree)malloc(sizeof(BiTNode)); assert(T != NULL); T->data = ch; T->lchild = CreateBiTree(); T->rchild = CreateBiTree(); } return T; } int main() { BiTree tree = NULL; tree = CreateBiTree( ); system("PAUSE"); }
[ "421997399@qq.com" ]
421997399@qq.com
2700a0c123739c9440f3df5418c71a90167d744b
c47c254ca476c1f9969f8f3e89acb4d0618c14b6
/datasets/github_cpp_10/5/38.cpp
5503ae984bc9a5f85d301762ce3f8a1be9b17629
[ "BSD-2-Clause" ]
permissive
yijunyu/demo
5cf4e83f585254a28b31c4a050630b8f661a90c8
11c0c84081a3181494b9c469bda42a313c457ad2
refs/heads/master
2023-02-22T09:00:12.023083
2021-01-25T16:51:40
2021-01-25T16:51:40
175,939,000
3
6
BSD-2-Clause
2021-01-09T23:00:12
2019-03-16T07:13:00
C
UTF-8
C++
false
false
1,054
cpp
#include <iostream> using namespace std; void tower_of_hanoi (int num_pieces, int left, int middle, int right); void movedisk (int from, int to); void writedisk(int disk) ; int main() { int pieces; int pos1 = 0, pos2 = 1, pos3 = 2; cout << "=============================================" << endl; cout << "Program Solves the Towers of Hanoi Problem" << endl; cout << "Enter number of pieces:" << endl; cin >> pieces; tower_of_hanoi(pieces, pos1, pos2, pos3); return 0; } void tower_of_hanoi (int num_pieces, int left, int middle, int right) { if (num_pieces >=1) { tower_of_hanoi(num_pieces - 1, left, right, middle); movedisk(left, right); tower_of_hanoi(num_pieces -1, middle, left, right); } } void movedisk (int from, int to) { cout << "Move disk from "; writedisk(from); cout << " to "; writedisk(to); cout << "." << endl; } void writedisk(int disk) { switch (disk) { case 0: cout << "left"; break; case 1: cout << "middle"; break; case 2: cout << "right"; break; } }
[ "y.yu@open.ac.uk" ]
y.yu@open.ac.uk
0fe9865c4bb5a4de1b1e56aea085fa35279ca50f
b967295eb531575eb39ef0b2f0d83c4297808fd8
/src/operators/QLinearMatMul.cpp
89e610cf536424fac3687898ce0daac26c8243d2
[ "Apache-2.0" ]
permissive
ai-techsystems/dnnc-operators
de9dc196db343003b6f3506dc0e502d59df2689f
55e682c0318091c4ee87a8e67134a31042c393e1
refs/heads/master
2020-07-02T16:08:37.965213
2019-08-29T14:38:52
2019-08-29T14:38:52
201,582,638
5
7
Apache-2.0
2019-09-06T18:31:19
2019-08-10T05:06:16
C++
UTF-8
C++
false
false
1,187
cpp
// Copyright 2018 The AITS DNNC Authors.All Rights Reserved. // // Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you 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 permissionsand limitations // under the License. // // This file is part of AITS DNN compiler maintained at // https://github.com/ai-techsystems/dnnCompiler // #include "operators/QLinearMatMul.h" using namespace dnnc; using namespace Eigen; #ifdef DNNC_QLINEARMATMUL_TEST #include <iostream> int main() { // ADD YOUR TEST CODE HERE } #endif
[ "gunjan@localhost.localdomain" ]
gunjan@localhost.localdomain
c348378064ec9cd3440f457c79dde5dcc3761db4
d0601b28a3060105e82c2a839d435c4329fe82a9
/OpenGL_DepthTest/DepthTest/openglwidget.h
97952d65efaa7ecb49f2202732ff87c0f1334a1c
[]
no_license
guoerba/opengl
9458b1b3827e24884bcd0a1b91d122ab6a252f8e
103da63ada1703a3f450cfde19f41b04e922187e
refs/heads/master
2020-07-10T15:40:49.828059
2019-08-25T13:52:58
2019-08-25T13:52:58
204,300,456
0
0
null
null
null
null
UTF-8
C++
false
false
2,763
h
#ifndef OPENGLWIDGET_H #define OPENGLWIDGET_H #include <QOpenGLWidget> #include <QOpenGLFunctions_4_5_Core> #include <QSurfaceFormat> #include <QOpenGLShaderProgram> #include <QOpenGLTexture> #include <QVector3D> #include <QColor> #include <QTimer> #include "vertices.h" #include "shader.h" #include "camera.h" #include "sphere.h" #include "material.h" #include "model.h" #define lightcolor (QVector3D(1.0f,1.0f,1.0f)) #define TextureCount 2 class OpenGLWidget : public QOpenGLWidget,protected QOpenGLFunctions_4_5_Core { public: enum Sampler2DN{ SamplerDiffuse = 0, SamplerSpecular }; OpenGLWidget(QWidget *parent = 0); ~OpenGLWidget(); void SetMaterial(Material material, QOpenGLShaderProgram *pro = NULL); void SetMaterial(TexMaterial texmaterial,QOpenGLShaderProgram *pro = NULL); void SetLight(Light light,QOpenGLShaderProgram *pro = NULL); void SetLight(DirectionalLight light,QOpenGLShaderProgram *pro = NULL); void SetLight(PointLight light,QOpenGLShaderProgram *pro = NULL); void SetLight(SpotLight light,QOpenGLShaderProgram *pro = NULL); void ReceiveData(QVector3D location, QVector4D rotate, QVector3D scale, QString dir, QString path); protected: virtual void initializeGL(); virtual void paintGL(); virtual void resizeGL(int w,int h); private: GLuint VAO,VBO,EBO; GLuint VAO_Sphere,VBO_Sphere,EBO_Sphere; int vnumber; QVector<Model*> vectorModel;//模型信息 QVector<QVector3D> vectorTranslate;//模型在世界空间中的位置 QVector<QVector4D> vectorRotate;//模型在世界空间中的旋转 QVector<QVector3D> vectorScale;//模型在世界空间中的缩放 Model *model; void ShaderProgram(const char *vshader, const char *fshader,QOpenGLShaderProgram *pro); void ShaderProgram(const QString &vshaderfileName, const QString &fshaderfileName, QOpenGLShaderProgram *pro); QOpenGLShaderProgram *program,*programforSphere; Camera *viewcamera;//摄像机 void SetModelMatrix(int index,QOpenGLShaderProgram *pro);//模型矩阵(物体空间——世界空间) void SetViewMatrix(QOpenGLShaderProgram *pro);//观察矩阵(世界空间——观察空间) void SetProjectionMatrix(int width,int height,QOpenGLShaderProgram *pro);//投影矩阵(观察空间——切割空间)(将三维坐标映射到2维坐标) QTimer *timer;//刷新 void SetSphereVertex(); QOpenGLTexture *texture[TextureCount];//纹理 GLuint texID[TextureCount]; void SetTexture(QOpenGLTexture *tex, GLuint Sampler, QOpenGLShaderProgram *pro, const char *name, QImage img); int count;//全局变量 bool refreshFlag;//更新标志 void RefreshModel(); }; #endif // OPENGLWIDGET_H
[ "guoerbamicro@outlook.com" ]
guoerbamicro@outlook.com
941481435f80d5f36c8a71187a49a3f610147aec
b4393b82bcccc59e2b89636f1fde16d82f060736
/include/polarphp/utils/FormattedStream.h
d53331b52392e89621cc55d6488ce6c96be97866
[]
no_license
phpmvc/polarphp
abb63ed491a0175aa43c873b1b39811f4eb070a2
eb0b406e515dd550fd99b9383d4b2952fed0bfa9
refs/heads/master
2020-04-08T06:51:03.842159
2018-11-23T06:32:04
2018-11-23T06:32:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,581
h
// This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2018 polarphp software foundation // Copyright (c) 2017 - 2018 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://polarphp.org/LICENSE.txt for license information // See http://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by softboy on 2018/06/04. #ifndef POLARPHP_UTILS_FORMATTED_STREAM_H #define POLARPHP_UTILS_FORMATTED_STREAM_H #include "polarphp/utils/RawOutStream.h" #include <utility> namespace polar { namespace utils { /// FormattedRawOutStream - A RawOutStream that wraps another one and keeps track /// of line and column position, allowing padding out to specific column /// boundaries and querying the number of lines written to the stream. /// class FormattedRawOutStream : public RawOutStream { /// m_theStream - The real stream we output to. We set it to be /// unbuffered, since we're already doing our own buffering. /// RawOutStream *m_theStream; /// Position - The current output column and line of the data that's /// been flushed and the portion of the buffer that's been /// scanned. The line and column scheme is zero-based. /// std::pair<unsigned, unsigned> m_position; /// Scanned - This points to one past the last character in the /// buffer we've scanned. /// const char *m_scanned; void writeImpl(const char *ptr, size_t size) override; /// current_pos - Return the current position within the stream, /// not counting the bytes currently in the buffer. uint64_t getCurrentPos() const override { // Our current position in the stream is all the contents which have been // written to the underlying stream (*not* the current position of the // underlying stream). return m_theStream->tell(); } /// ComputePosition - Examine the given output buffer and figure out the new /// position after output. /// void computePosition(const char *ptr, size_t size); void setStream(RawOutStream &stream) { releaseStream(); m_theStream = &stream; // This FormattedRawOutStream inherits from RawOutStream, so it'll do its // own buffering, and it doesn't need or want m_theStream to do another // layer of buffering underneath. Resize the buffer to what m_theStream // had been using, and tell m_theStream not to do its own buffering. if (size_t bufferSize = m_theStream->getBufferSize()) { setBufferSize(bufferSize); } else { setUnbuffered(); } m_theStream->setUnbuffered(); m_scanned = nullptr; } public: /// FormattedRawOutStream - Open the specified file for /// writing. If an error occurs, information about the error is /// put into ErrorInfo, and the stream should be immediately /// destroyed; the string will be empty if no error occurred. /// /// As a side effect, the given Stream is set to be Unbuffered. /// This is because FormattedRawOutStream does its own buffering, /// so it doesn't want another layer of buffering to be happening /// underneath it. /// FormattedRawOutStream(RawOutStream &stream) : m_theStream(nullptr), m_position(0, 0) { setStream(stream); } explicit FormattedRawOutStream() : m_theStream(nullptr), m_position(0, 0) { m_scanned = nullptr; } ~FormattedRawOutStream() override { flush(); releaseStream(); } /// PadToColumn - Align the output to some column number. If the current /// column is already equal to or more than NewCol, PadToColumn inserts one /// space. /// /// \param NewCol - The column to move to. FormattedRawOutStream &padToColumn(unsigned newCol); /// getColumn - Return the column number unsigned getColumn() { return m_position.first; } /// getLine - Return the line number unsigned getLine() { return m_position.second; } RawOutStream &resetColor() override { m_theStream->resetColor(); return *this; } RawOutStream &reverseColor() override { m_theStream->reverseColor(); return *this; } RawOutStream &changeColor(enum Colors color, bool bold, bool bg) override { m_theStream->changeColor(color, bold, bg); return *this; } bool isDisplayed() const override { return m_theStream->isDisplayed(); } private: void releaseStream() { // Transfer the buffer settings from this RawOutStream back to the underlying // stream. if (!m_theStream) { return; } if (size_t bufferSize = getBufferSize()) { m_theStream->setBufferSize(bufferSize); } else { m_theStream->setUnbuffered(); } } }; /// formatted_out_stream() - This returns a reference to a FormattedRawOutStream for /// standard output. Use it like: formatted_out_stream() << "foo" << "bar"; FormattedRawOutStream &formatted_out_stream(); /// formatted_error_stream() - This returns a reference to a FormattedRawOutStream for /// standard error. Use it like: formatted_error_stream() << "foo" << "bar"; FormattedRawOutStream &formatted_error_stream(); /// formatted_debug_stream() - This returns a reference to a FormattedRawOutStream for /// debug output. Use it like: formatted_debug_stream() << "foo" << "bar"; FormattedRawOutStream &formatted_debug_stream(); } // utils } // polar #endif // POLARPHP_UTILS_FORMATTED_STREAM_H
[ "zzu_softboy@163.com" ]
zzu_softboy@163.com
dcd9a43d80278846bcc78f0608501457a6b8b2d0
90a052bbf3edf692cfba8510d20fa7fca159c3ff
/src/SignalButton.cpp
5ac6c6cfb976a22fb64110f42abfb703d1828138
[]
no_license
dmitribaskakov/IoT.Switch.Atmel
431165784169d591fae0d0fa002efca539956ea1
7645085d13deae0883949283d08dab6706dbc611
refs/heads/master
2023-03-25T14:42:50.222159
2021-03-25T17:00:49
2021-03-25T17:00:49
333,145,561
0
0
null
null
null
null
UTF-8
C++
false
false
7,262
cpp
#include <Arduino.h> //#include <stdio.h> //#include <string.h> //#include <inttypes.h> #include "SignalButton.h" //using namespace std; SignalButton::SignalButton () { signalType = Signal_None; signal = Signal_None; state = Signal_None; nextState = Signal_None; timeToHigh = 0; timeToLow = 0; }; uint32_t SignalButton::calculateTimeToHigh() { uint32_t result = 0; uint32_t time = 0; time = millis(); if (time<2) { time = 2; }; if (timeToHigh>time) { timeToHigh = time - 1; }; if (timeToHigh>0) { result = time - timeToHigh; }; return result; }; uint32_t SignalButton::calculateTimeToLow() { uint32_t result = 0; uint32_t time = 0; time = millis(); if (time < 2) { time = 2; }; if (timeToLow > time) { timeToLow = time - 1; }; if (timeToLow > 0) { result = time - timeToLow; }; return result; }; bool SignalButton::expectCompletion() { if ( (timeToLow > 0) || (timeToHigh>0) || (nextState != Signal_None) ) { return true; }; return false; } void SignalButton::disable(uint8_t __signalType) { signalType &= ~__signalType; if (signalType == Signal_Type_Button_Disabled) { //signal = Signal_None; state = Signal_None; nextState = Signal_None; timeToHigh = 0; timeToLow = 0; }; }; uint8_t SignalButton::setSignal (uint8_t Signal) { signal = Signal; if (signalType == Signal_Type_Button_Disabled) { return Signal_None; }; uint32_t nowTime = millis(); state = Signal_None; if (Signal == HIGH) { //-------------------------------------------------------------------------------------------------- //Есть сигнал на входе if (((nextState == Signal_None) || (nextState & Signal_Button_DetectToClick)) && (!(nextState & Signal_Button_Pressed))) { //следущее состояние тоже нет сигнала //тогда ожидаем несколько миллисикунд на устранение дребезга и ждем нажатия nextState |= Signal_Button_Pressed; timeToHigh = nowTime; }; if (nextState & Signal_Button_Pressed) { if (calculateTimeToHigh() >= Signal_timeTo_Debounce) { //прождали несколько миллисикунд на устранение дребезга //Сигнал остался. Можно считать что кнопка нажата timeToLow = 0; nextState &= ~Signal_Button_Released; if (signalType & Signal_Type_Button_Pressed) { state |= Signal_Button_Pressed; }; if (calculateTimeToHigh() >= Signal_timeTo_Button_Click) { if ((signalType & Signal_Type_Button_DoubleClick) && (nextState & Signal_Button_DetectToClick)) { state |= Signal_Button_DoubleClick; nextState = Signal_Button_ReleasedDoubleClick; }; if ( ( !((signalType & Signal_Type_Button_LongClick) || (signalType & Signal_Type_Button_DoubleClick)) && (signalType & Signal_Type_Button_Click)) ){ state |= Signal_Button_Click; nextState = Signal_Button_Released; }; if ((signalType & Signal_Type_Button_LongClick) && (calculateTimeToHigh() >= Signal_timeTo_Button_LongClick)) { state |= Signal_Button_LongClick; nextState = Signal_Button_ReleasedLongClick; }; }; }; }; } else if (nextState != Signal_None) { //-------------------------------------------------------------------------------------------------- //Нет сигнала на входе (был но пропал - определяем что это было) if (nextState & Signal_Button_Pressed) { //текущее состояние - кнопка нажата и сигнал пропадает //планируем что следущее состояние будет - кнопка отжата nextState |= Signal_Button_Released; }; if (((nextState & Signal_Button_Released) || (nextState & Signal_Button_ReleasedDoubleClick) || (nextState & Signal_Button_ReleasedLongClick)) && (timeToLow==0)) { //как только кнопка была реально отажата, сначала устраним дребезг timeToLow = nowTime; }; if (calculateTimeToLow() < Signal_timeTo_Debounce) { //Ждем несколько миллисикунд на устранение дребезга if ((nextState & Signal_Button_Pressed) && (signalType & Signal_Type_Button_Pressed)) { //считаем что кнопка все еще была нажата state |= Signal_Button_Pressed; }; } else if (calculateTimeToLow() >= Signal_timeTo_Debounce) { //прождали несколько миллисикунд на устранение дребезга //Сигнала нет. Можно считать что кнопка была отжата //теперь распознаем в завистимости от типа кнопки nextState &= ~Signal_Button_Pressed; if (signalType & Signal_Type_Button_Pressed) { state &= ~Signal_Button_Pressed; }; if (nextState & Signal_Button_ReleasedDoubleClick) { timeToHigh = 0; timeToLow = 0; nextState = Signal_None; state = Signal_None; } else if ((nextState & Signal_Button_DetectToClick) && (calculateTimeToLow() >= Signal_timeBetween_Button_Clicks)) { //пауза между нажатиями кнопки в DoubleClick была слишком большой считаем что это уже не DoubleClick timeToHigh = 0; timeToLow = 0; nextState = Signal_None; if (signalType & Signal_Type_Button_Click) { state |= Signal_Button_Click; } else { state = Signal_None; }; } else if (nextState & Signal_Button_Released) { if ((signalType & Signal_Type_Button_DoubleClick) && (calculateTimeToLow() < Signal_timeBetween_Button_Clicks)) { //возможен DoubleClick нужно указать что следующий статус это ожидание втрого нажатия //и на этом статусе уже проверять по времени какой сигнал распознается if (calculateTimeToHigh() > Signal_timeTo_Button_Click) { //кнопка была нажата досточно долго чтобы зафиксировать Click //теперь нужно подожать будет ли DoubleClick nextState |= Signal_Button_DetectToClick; }; } else if ((signalType & Signal_Type_Button_LongClick) && (signalType & Signal_Type_Button_Click)) { //возможны LongClick или Click тогда нужно проверить по времени отпускания, что же произошло if ((calculateTimeToHigh() > Signal_timeTo_Button_Click) && (calculateTimeToHigh() < Signal_timeTo_Button_LongClick)) { state |= Signal_Button_Click; }; timeToHigh = 0; timeToLow = 0; nextState = Signal_None; } else if (!((signalType & Signal_Type_Button_DoubleClick) && (calculateTimeToLow() < Signal_timeBetween_Button_Clicks))) { timeToHigh = 0; timeToLow = 0; nextState = Signal_None; state = Signal_None; }; } else if (nextState & Signal_Button_ReleasedLongClick) { timeToHigh = 0; timeToLow = 0; nextState = Signal_None; state = Signal_None; }; }; }; return state; };
[ "dmitri.baskakov.git@gmail.com" ]
dmitri.baskakov.git@gmail.com
8de66eeef0828406432d542e9d34864240c700f4
2a440aea43b5b880fd433f58098ac3bbc66fcfec
/imm/src/model/GetDRMLicenseResult.cc
db3e79c65122cf85b8b666fc2fe467abe848e6b0
[ "Apache-2.0" ]
permissive
longkai1028/aliyun-openapi-cpp-sdk
30d6553e508c6a38d190557487972553a6ae64d5
97286a49ca7ae8754984f6b8abce1a8e6f48117c
refs/heads/master
2023-04-04T00:13:25.713899
2021-04-13T02:28:45
2021-04-13T02:28:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,506
cc
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/imm/model/GetDRMLicenseResult.h> #include <json/json.h> using namespace AlibabaCloud::Imm; using namespace AlibabaCloud::Imm::Model; GetDRMLicenseResult::GetDRMLicenseResult() : ServiceResult() {} GetDRMLicenseResult::GetDRMLicenseResult(const std::string &payload) : ServiceResult() { parse(payload); } GetDRMLicenseResult::~GetDRMLicenseResult() {} void GetDRMLicenseResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["DRMData"].isNull()) dRMData_ = value["DRMData"].asString(); if(!value["DeviceInfo"].isNull()) deviceInfo_ = value["DeviceInfo"].asString(); } std::string GetDRMLicenseResult::getDeviceInfo()const { return deviceInfo_; } std::string GetDRMLicenseResult::getDRMData()const { return dRMData_; }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
ec104081cd0d747287e0151e43a567f9424cdd78
a008823e08d40d8acf9556b8c11e4743a5bfb16c
/207.cpp
34e3eefaf36115ed61ad261439c61e2eef6e0542
[]
no_license
SccsAtmtn/leetcode
28f13cda594a5e83adb8c44f0ceb3621ddc76509
3ced8022b9f58b13d460650c65be1d43cd3e3f63
refs/heads/master
2021-01-10T15:37:19.836145
2017-01-04T07:00:20
2017-01-04T07:00:20
54,364,332
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { int n = prerequisites.size(); if (n==0) return true; vector<int> one(1, 0); vector<vector<int>> degree(numCourses, one); for (int i=0; i<n; ++i) { ++degree[prerequisites[i].second][0]; degree[prerequisites[i].first].push_back(prerequisites[i].second); } one.clear(); for (int i=0; i<numCourses; ++i) if (degree[i][0]==0) one.push_back(i); while (!one.empty()) { vector<int> temp; for (int i=0; i<one.size(); ++i) for (int j=1; j<degree[one[i]].size(); ++j) { --degree[degree[one[i]][j]][0]; if (degree[degree[one[i]][j]][0]==0) temp.push_back(degree[one[i]][j]); } one = temp; } for (int i=0; i<numCourses; ++i) if (degree[i][0]>0) return false; return true; } };
[ "lizt1994@163.com" ]
lizt1994@163.com
c60142c4d3fe6a476809503917e60981d9a0dd87
3440976909bf3a7c26a0193ed9cec8a00937f71d
/project/freetype/include/NUtf.h
eee4c8d94ffcdd6cd7cdde98f71e9984214992f3
[]
no_license
marsteen/mvfonttableau
200e19cfd0a3574b5a61c4d11c42a10df66bfe16
48565aacf32240714a7acc8c9b3499bbd4a4015f
refs/heads/master
2023-08-27T21:36:20.858981
2021-09-17T09:58:40
2021-09-17T09:58:40
307,953,837
0
0
null
null
null
null
UTF-8
C++
false
false
462
h
//*************************************************************************** // // // @PROJECT : Diercke Digital PAD // @VERSION : 1.0 // @FILENAME : NUtf.h // @DATE : 12.1.2015 // // @AUTHOR : Martin Steen // @EMAIL : msteen@imagon.de // // //*************************************************************************** #ifndef NUTF_H #define NUTF_H namespace NUtf { unsigned int Utf8_to_Utf32(const unsigned char* Utf8, int* Size); } #endif
[ "martin.steen@ksti.de" ]
martin.steen@ksti.de
b7efbf8025edbd1b42a5714dcad10b82960fceaf
a3c2b8e59db2761a68cd81431ef0f43b07629e7f
/Source/GameEngine/Graphic/Scene/Element/Particle/ParticleMeshEmitter.h
d292e46870da73530dee397e6900e7af884a8933
[]
no_license
enriquegr84/GameEngineTutorial
13eeae4b8c65cf94254c4cb7f879f52614fed185
dd6507839a34746dc9b25d28c879f180c62eaab8
refs/heads/master
2021-08-23T09:35:28.257239
2021-08-06T16:52:38
2021-08-06T16:52:38
83,200,106
6
0
null
null
null
null
UTF-8
C++
false
false
6,295
h
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef PARTICLEMESHEMITTER_H #define PARTICLEMESHEMITTER_H #include "ParticleEmitter.h" #include "Graphic/Scene/Element/Mesh/Mesh.h" //! A particle emitter which emits from vertices of a mesh class ParticleMeshEmitter : public BaseParticleEmitter { public: //! constructor ParticleMeshEmitter( const eastl::shared_ptr<BaseMesh>& mesh, bool useNormalDirection = true, const Vector3<float>& direction = Vector3<float>{ 0.f, 0.f, 0.f }, float normalDirectionModifier = 100.0f, int mbNumber = -1, bool everyMeshVertex = false, unsigned int minParticlesPerSecond = 20, unsigned int maxParticlesPerSecond = 40, const eastl::array<float, 4>& minStartColor = eastl::array<float, 4>{255.f, 0.f, 0.f, 0.f}, const eastl::array<float, 4>& maxStartColor = eastl::array<float, 4>{255.f, 255.f, 255.f, 255.f}, unsigned int lifeTimeMin = 2000, unsigned int lifeTimeMax = 4000, int maxAngleDegrees = 0, const Vector2<float>& minStartSize = Vector2<float>{ 5.f, 5.f }, const Vector2<float>& maxStartSize = Vector2<float>{ 5.f, 5.f } ); //! Prepares an array with new particles to emitt into the system //! and returns how much new particles there are. virtual int Emitt(unsigned int now, unsigned int timeSinceLastCall, Particle*& outArray); //! Set Mesh to emit particles from virtual void SetMesh( const eastl::shared_ptr<BaseMesh>& mesh ); //! Set whether to use vertex normal for direction, or direction specified virtual void SetUseNormalDirection( bool useNormalDirection ) { mUseNormalDirection = useNormalDirection; } //! Set direction the emitter emits particles virtual void SetDirection( const Vector3<float>& newDirection ) { mDirection = newDirection; } //! Set the amount that the normal is divided by for getting a particles direction virtual void SetNormalDirectionModifier( float normalDirectionModifier ) { mNormalDirectionModifier = normalDirectionModifier; } //! Sets whether to emit min<->max particles for every vertex per second, or to pick //! min<->max vertices every second virtual void SetEveryMeshVertex( bool everyMeshVertex ) { mEveryMeshVertex = everyMeshVertex; } //! Set minimum number of particles the emitter emits per second virtual void SetMinParticlesPerSecond( unsigned int minPPS ) { mMinParticlesPerSecond = minPPS; } //! Set maximum number of particles the emitter emits per second virtual void SetMaxParticlesPerSecond( unsigned int maxPPS ) { mMaxParticlesPerSecond = maxPPS; } //! Set minimum starting color for particles virtual void SetMinStartColor( const eastl::array<float, 4>& color ) { mMinStartColor = color; } //! Set maximum starting color for particles virtual void SetMaxStartColor( const eastl::array<float, 4>& color ) { mMaxStartColor = color; } //! Set the maximum starting size for particles virtual void SetMaxStartSize( const Vector2<float>& size ) { mMaxStartSize = size; } //! Set the minimum starting size for particles virtual void SetMinStartSize( const Vector2<float>& size ) { mMinStartSize = size; } //! Set the minimum particle life-time in milliseconds virtual void SetMinLifeTime( unsigned int lifeTimeMin ) { mMinLifeTime = lifeTimeMin; } //! Set the maximum particle life-time in milliseconds virtual void SetMaxLifeTime( unsigned int lifeTimeMax ) { mMaxLifeTime = lifeTimeMax; } //! Set maximal random derivation from the direction virtual void SetMaxAngleDegrees( int maxAngleDegrees ) { mMaxAngleDegrees = maxAngleDegrees; } //! Get Mesh we're emitting particles from virtual const eastl::shared_ptr<BaseMesh>& GetMesh() const { return mParticleMesh; } //! Get whether to use vertex normal for direciton, or direction specified virtual bool IsUsingNormalDirection() const { return mUseNormalDirection; } //! Get direction the emitter emits particles virtual const Vector3<float>& GetDirection() const { return mDirection; } //! Get the amount that the normal is divided by for getting a particles direction virtual float GetNormalDirectionModifier() const { return mNormalDirectionModifier; } //! Gets whether to emit min<->max particles for every vertex per second, or to pick //! min<->max vertices every second virtual bool GetEveryMeshVertex() const { return mEveryMeshVertex; } //! Get the minimum number of particles the emitter emits per second virtual unsigned int GetMinParticlesPerSecond() const { return mMinParticlesPerSecond; } //! Get the maximum number of particles the emitter emits per second virtual unsigned int GetMaxParticlesPerSecond() const { return mMaxParticlesPerSecond; } //! Get the minimum starting color for particles virtual const eastl::array<float, 4>& GetMinStartColor() const { return mMinStartColor; } //! Get the maximum starting color for particles virtual const eastl::array<float, 4>& GetMaxStartColor() const { return mMaxStartColor; } //! Gets the maximum starting size for particles virtual const Vector2<float>& GetMaxStartSize() const { return mMaxStartSize; } //! Gets the minimum starting size for particles virtual const Vector2<float>& GetMinStartSize() const { return mMinStartSize; } //! Get the minimum particle life-time in milliseconds virtual unsigned int GetMinLifeTime() const { return mMinLifeTime; } //! Get the maximum particle life-time in milliseconds virtual unsigned int GetMaxLifeTime() const { return mMaxLifeTime; } //! Get maximal random derivation from the direction virtual int GetMaxAngleDegrees() const { return mMaxAngleDegrees; } private: eastl::shared_ptr<BaseMesh> mParticleMesh; eastl::vector<int> mVertexPerMeshBufferList; int mTotalVertices; unsigned int mMBCount; int mMBNumber; float mNormalDirectionModifier; eastl::vector<Particle> mParticles; Vector3<float> mDirection; Vector2<float> mMaxStartSize, mMinStartSize; unsigned int mMinParticlesPerSecond, mMaxParticlesPerSecond; eastl::array<float, 4> mMinStartColor, mMaxStartColor; unsigned int mMinLifeTime, mMaxLifeTime; unsigned int mTime; unsigned int mEmitted; int mMaxAngleDegrees; bool mEveryMeshVertex; bool mUseNormalDirection; }; #endif // _PARTICLE_MESH_EMITTER_H_INCLUDED_
[ "enriquegr84@hotmail.es" ]
enriquegr84@hotmail.es
3ffbc1dbb50ce91b341b1ca6529e8dd87a3d54fe
88fca89dd8fa7072c85ec57c62fb53efb90e1819
/깃헙 연동 시험/깃헙 연동 시험/03 가장 간단한 정렬 알고리즘.cpp
a57f00b78e63e926eb6c9fd271ceda515a377838
[]
no_license
CultureAddiction/200824
e24912f459593e66adff0b5db0a27933668b6d4a
9ea5410e54324eb01650272ddebf4158f30a839b
refs/heads/master
2023-01-08T08:23:46.956892
2020-08-27T06:07:13
2020-08-27T06:07:13
289,879,907
0
0
null
null
null
null
UTF-8
C++
false
false
303
cpp
#include <stdio.h> void swap(int *a, int* b); int main() { int a[] = { 5,6,2,4,2,1,9,10,7 }; } void sort(int a[], int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (a[j] > a[j + 1]) { } } } } void swap(int* a, int* b) { int tmp = *a; *a = *b; *b = tmp; }
[ "didqhtmd@gmail.com" ]
didqhtmd@gmail.com
d81bf7ae9b672d1a42fea50288b7ce82b7b43491
9e1fb87d6aa5084c850d3165ea749da67d0add59
/codeforces/520_D_DIV2_CODEFORCES.cpp
ca3364fec787d14b98b8e6a4308063744517fa78
[]
no_license
Yang-33/competitive-programming
673d57bc95efb559f8e2905bad758cd576505761
f85ef9f1a5763334e4d26f9206154e4f7c0a85ac
refs/heads/master
2021-01-12T03:19:17.961860
2019-10-06T15:35:48
2019-10-06T15:35:48
78,174,818
3
0
null
null
null
null
UTF-8
C++
false
false
1,898
cpp
#include <bits/stdc++.h> using namespace std; using VS = vector<string>; using LL = long long; using VI = vector<int>; using VVI = vector<VI>; using PII = pair<int, int>; using PLL = pair<LL, LL>; using VL = vector<LL>; using VVL = vector<VL>; #define ALL(a) begin((a)),end((a)) #define RALL(a) (a).rbegin(), (a).rend() #define SZ(a) int((a).size()) #define SORT(c) sort(ALL((c))) #define RSORT(c) sort(RALL((c))) #define UNIQ(c) (c).erase(unique(ALL((c))), end((c))) #define FOR(i, s, e) for (int(i) = (s); (i) < (e); (i)++) #define FORR(i, s, e) for (int(i) = (s); (i) > (e); (i)--) //#pragma GCC optimize ("-O3") #ifdef YANG33 #include "mydebug.hpp" #else #define DD(x) #endif const int INF = 1e9; const LL LINF = 1e16; const LL MOD = 1000000007; const double PI = acos(-1.0); int DX[8] = { 0, 0, 1, -1, 1, 1, -1, -1 }; int DY[8] = { 1, -1, 0, 0, 1, -1, 1, -1 }; /* ----- 2018/11/15 Problem: CodeForces520 D div2 / Link: http://codeforces.com/contest/1062/problem/D ----- */ /* ------問題------ -----問題ここまで----- */ /* -----解説等----- 順番にi,-iを足していくと、偶数本しか追加されないので、全部到達可能。 よって1,i以外の約数には到達可能であるから、約数列挙して4倍が答え。 ----解説ここまで---- */ vector<LL> getdivisor(int n) { vector<LL> res; for (LL i = 1; i*i <= n; i++) { if (n%i == 0) { res.push_back(i); if (n / i != i)res.push_back(n / i); } } sort(res.begin(), res.end()); return res; } LL ans = 0LL; int main() { cin.tie(0); ios_base::sync_with_stdio(false); LL N; cin >> N; FOR(i, 4, N + 1) { VL res = getdivisor(i); LL val = 0; for (auto it : res) { if (it == 1 || it == i)continue; val += it; } val *= 4; //DD(de(i, val)); ans += val; } cout << ans << "\n"; return 0; }
[ "kasai.yuta0810@gmail.com" ]
kasai.yuta0810@gmail.com
813d0c28e0b71afd9489b440b9746f7e94ec0674
69fb7f59b9309c95f04f69abfd6dba1a9cb40f09
/Chapter_05/c_04_http_to_hookbin/src/iot_monitor.h
2fb1665a0045621583134a008e721ffd18093d3a
[]
no_license
att-iotstarterkits/sk2-Users-Guide
0c798aa0eaa6e77a9d1a68fbb3277a83dc0a6be0
38d8e851f0bb68bc562b6ca3b688416a101b205e
refs/heads/master
2021-07-21T08:00:45.035713
2020-05-11T03:12:42
2020-05-11T03:12:42
161,242,166
2
1
null
null
null
null
UTF-8
C++
false
false
5,886
h
/* ===================================================================== Copyright © 2016, Avnet (R) www.avnet.com 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. @file iot_monitor.h @version 1.0 @date Sept 2017 ======================================================================== */ #ifndef __IOT_MONITOR_H__ #define __IOT_MONITOR_H__ #ifdef __cplusplus #include <cctype> #include <cstddef> #include <cstring> #include <cstdio> #include <cstdlib> #include <algorithm> #include <functional> #include <string> #endif #define VER 1.03 #define VER_DATE __DATE__ " @ " __TIME__ #define my_getc() getc() #define my_puts(s) puts(s) #define my_putc(c) putchar(c) #define my_printf(fmt,...) printf(fmt, ##__VA_ARGS__) #define MAX(a,b) (((a)>(b))?(a):(b)) #define MIN(a,b) (((a)<(b))?(a):(b)) #define DBG_CURL 0x0001 #define DBG_FLOW 0x0002 #define DBG_M2X 0x0004 #define DBG_MYTIMER 0x0010 #define DBG_LIS2DW12 0x0020 #define DBG_HTS221 0x0040 #define DBG_BINIO 0x0100 #define DBG_MAL 0x0200 #define DBG_DEMO 0x0400 #define DBG_I2C 0x0800 #define DBG_SPI 0x1000 #define DBG_EMISSIN 0x2000 #define MONITOR_PROMPT ((char*)"MON> ") #define FACTORY_PROMPT ((char*)"WNC> ") #define DEFAULT_DEVICE_ID (char*)"e83cdd8645ab1a7c0c480156efbf78f6" #define DEFAULT_TEMP_API_STREAM (char*)"temp" #define DEFAULT_ADC_API_STREAM (char*)"light_sens" #define my_debug(x,...) (__VA_ARGS__); #ifdef __cplusplus typedef struct { std::string firmVer; std::string appsVer; std::string malwarVer; std::string ip; std::string model; std::string imei; std::string imsi; std::string iccid; std::string msisdn; std::string opMode; } sysinfo; extern sysinfo mySystem; #endif // struct of string for the command and pointer to function typedef struct { int max_elements; const char *commandp; const char *help_str; int (*func_p)(int, const char * const *); } cmd_entry; extern const cmd_entry mon_command_table[]; #ifndef _DATADEF_ extern char device_id[]; extern char api_key[]; extern char *temp_stream_name; extern char *adc_stream_name; extern char* strupr(char* s); extern const cmd_entry iot_command_table[]; extern int headless; extern int doM2X; extern int headless_timed; extern unsigned int dbg_flag; extern int ft_time; extern int ft_mode, extendedIO; extern unsigned int dbg_flag; extern void *htsdev; #endif extern int command_help(int argc, const char * const * argv ); extern int command_gpio(int argc, const char * const * argv ); extern int command_blink(int argc, const char * const * argv ); extern int command_sndat(int argc, const char * const * argv ); extern int command_baud(int argc, const char * const * argv ); extern int command_hts221(int argc, const char * const * argv ); extern int command_lis2dw12(int argc, const char * const * argv ); extern int command_spi(int argc, const char * const * argv ); extern int command_i2cpeek(int argc, const char * const * argv ); extern int command_i2cpoke(int argc, const char * const * argv ); extern int command_peek(int argc, const char * const * argv ); extern int command_poke(int argc, const char * const * argv ); extern int command_comscmd(int argc, const char * const * argv); extern int command_http_put(int argc, const char * const * argv); extern int command_http_get(int argc, const char * const * argv); extern int command_iotmon(int argc, const char * const * argv ); extern int command_wnctest(int argc, const char * const * argv ); extern int command_iothelp(int argc, const char * const * argv ); extern int command_WWANStatus(int, char const* const*); extern int command_WWANLED(int, char const* const*); extern int command_WNCInfo(int argc, const char * const * argv ); extern int command_tx2m2x(int argc, const char * const * argv ); extern int command_exit(int argc, const char * const * argv ); extern int command_gps(int argc, const char * const * argv ); extern int command_adc(int argc, const char * const * argv ); extern int command_headless(int argc, const char * const * argv ); extern int command_facttest(int argc, const char * const * argv ); extern int command_dbg(int argc, const char * const * argv ); //extern int command_VL53L0X(int argc, const char * const * argv ); #ifdef __cplusplus extern "C" { #endif extern int command_demo_mode(int, const char * const * argv); extern unsigned int ascii_to_epoch(char *epoch_ascii); extern void doNewLine(void); void *check_gps(void *); void monitor_wwan( void ); void kill_monitor_wwan( void ); #ifdef __cplusplus } #endif extern void sigint_cb (void); extern cmd_entry *current_table; extern int max_moncommands, max_iotcommands; extern char * completion_array []; void set_cmdhandler( void (*of)(const char*), //function to call to output text char *prompt, //prompt to use int plen, //length of prompt void (*siginit_cb)(void), //call back of interrupt signal (^C) int (*exec_cb)(int, char const * const*), //call back to call when a input line is complete char ** (*complete_cb)(int, const char* const*), //call back for command line completion const cmd_entry tabp[]); //what command table to use #endif // __IOT_MONITOR_H__
[ "scott@sgspecker.com" ]
scott@sgspecker.com
ee870fbc0bf62fbe34087c0cf14c939e85a68d3b
1dbed0f84a670c787d2217d97ae3984401c7edb3
/uva/10954.cpp
61af9187f877dadaf1d10760b6e4053f9a5bd414
[]
no_license
prprprpony/oj
311d12a25f06e6c54b88bc2bcd38003f7b6696a9
84988be500c06cb62130585333fddd1a278f0aaa
refs/heads/master
2021-07-13T16:03:54.398841
2021-03-27T14:19:52
2021-03-27T14:19:52
46,796,050
9
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
#include <cstdio> #include <queue> #include <vector> #include <functional> using namespace std; typedef long long ll; int main() { int n; ll i; ll ans; while (scanf("%d", &n) == 1 && n > 0) { priority_queue<ll, vector<ll>, greater<ll> > pq; ans = 0; while (n--) { scanf("%lld", &i); pq.push(i); } while (pq.size() != 1) { i = pq.top(); pq.pop(); i += pq.top(); pq.pop(); ans += i; pq.push(i); } printf("%lld\n", ans); } return 0; }
[ "3254tg89@gmail.com" ]
3254tg89@gmail.com
ab884cbf1b9a540a40e59d2514d8f8946e1d9943
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/leetcode/biweekly/041-080/043/1719.cpp
c26cd31aa3571a84febbeb60dee4f96bfdef1806
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
1,830
cpp
typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- unordered_set<int> E[505]; int N; class Solution { public: int dfs(int root, unordered_set<int>& V) { int N=V.size(); int ret=1; vector<pair<int,int>> cand; FORR(p,E[root]) { if(V.count(p)==0) return 0; if(E[p].size()==N) ret=2; E[p].erase(root); cand.push_back({-(int)E[p].size(),p}); } sort(ALL(cand)); FORR(c,cand) { int num=-c.first; int v=c.second; if(num>=1&&num==E[v].size()) { unordered_set<int> NS; if(E[v].size()<=V.size()) { NS=E[v]; auto it=NS.begin(); while(it!=NS.end()) { if(V.count(*it)) { it++; } else { it=NS.erase(it); } } //FORR(e,E[v]) if(V.count(e)) NS.insert(e); } else { NS=V; auto it=NS.begin(); while(it!=NS.end()) { if(E[v].count(*it)) { it++; } else { it=NS.erase(it); } } //FORR(e,V) if(E[v].count(e)) NS.insert(e); } int d=dfs(v,NS); if(d==0) return 0; if(d==2) ret=2; } } return ret; } int checkWays(vector<vector<int>>& pairs) { unordered_set<int> V; int i; FOR(i,501) E[i].clear(); FORR(p,pairs) { V.insert(p[0]); V.insert(p[1]); E[p[0]].insert(p[1]); E[p[1]].insert(p[0]); } FOR(i,501) if(E[i].size()==V.size()-1) return dfs(i,E[i]); return 0; } };
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
0196b3bef6e9c4ece6b80b1cc77ea9b14aa75efe
5dd036cd8c14208194efa80a20278cf39ac773fa
/SpikeUI/TextArea.h
f2d910c268c28df6a2a8e2e0cc6a2b3c80b234d3
[ "MIT" ]
permissive
theclaw37/SpikeEngine
2a3d0651189e42eae0af9916970b344b1811d304
24c0bc98e9406c95b672a9946ce8d382cb4a52dc
refs/heads/master
2021-04-09T10:23:01.267554
2018-05-07T22:27:28
2018-05-07T22:27:28
125,339,980
2
0
null
null
null
null
UTF-8
C++
false
false
1,571
h
#pragma once #include <functional> #include "Rectangle.h" #include "Font.h" #include "Drawable.h" #include "Colour.h" #include "Key.h" #ifdef DLL_SPIKEUI #define SPIKEUI_EXPORT __declspec(dllexport) #else #define SPIKEUI_EXPORT __declspec(dllimport) #endif namespace SpikeUI { namespace Controls { struct SPIKEUI_EXPORT TextArea : SpikeUI::UI::Drawable { SpikeUI::Containers::Rectangle Place; std::shared_ptr<SpikeUI::Containers::Font> Font; std::shared_ptr<SpikeUI::Colour> TextColour; std::shared_ptr<SpikeUI::Colour> BackgroundColour; std::wstring Text; std::function<void(TextArea &)> hoverIn, hoverOut, lButtonDown, lButtonUp, rButtonDown, rButtonUp;; std::function<void(TextArea &, SpikeUI::Containers::Key const &)> receiveKey; TextArea(SpikeUI::Containers::Rectangle const &, std::shared_ptr<SpikeUI::Containers::Font>, std::shared_ptr<SpikeUI::Colour>, std::shared_ptr<SpikeUI::Colour>, std::string const &); virtual void PointerUpdate(bool, bool, bool, bool); virtual void KeyInput(SpikeUI::Containers::Key const &); virtual void Update(); virtual bool Contains(SpikeUI::Containers::Point const &); virtual void MoveByPixels(SpikeUI::Containers::Point const &); virtual SpikeUI::Containers::Point MoveToPixels(SpikeUI::Containers::Point const &); virtual SpikeUI::Containers::Point RelativePixelDelta(SpikeUI::Containers::Point const &); virtual void HoverIn(); virtual void HoverOut(); virtual void Focus(); virtual void Unfocus(); virtual ~TextArea() = default; }; } }
[ "thclaw@gmail.com" ]
thclaw@gmail.com
598fcb5b897e060f57844f23a1a0bd617741fb1d
49dc1ebb4e4ac3f52a0a0e9bab88ab7914bf43db
/search.h
a53a5faf62f4c801a282118ffb649486966d94b3
[]
no_license
scchess/fire
65a146d22a746c01bc87ef4788520c5d84263e06
f75dd3094e774aaa2bdb3c9a28a062a335dc6950
refs/heads/main
2023-06-28T08:40:00.291938
2021-07-31T11:14:37
2021-07-31T11:14:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,374
h
/* Fire is a freeware UCI chess playing engine authored by Norman Schmidt. Fire utilizes many state-of-the-art chess programming ideas and techniques which have been documented in detail at https://www.chessprogramming.org/ and demonstrated via the very strong open-source chess engine Stockfish... https://github.com/official-stockfish/Stockfish. Fire is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. You should have received a copy of the GNU General Public License with this program: copying.txt. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <atomic> #include <vector> #include "chrono.h" #include "fire.h" #include "movepick.h" #include "position.h" typedef movelist<max_pv> principal_variation; struct search_signals { std::atomic_bool stop_analyzing, stop_if_ponder_hit; }; namespace search { inline search_signals signals; inline search_param param; inline bool running; void init(); void reset(); void adjust_time_after_ponder_hit(); extern uint8_t lm_reductions[2][2][64 * static_cast<int>(plies)][64]; enum nodetype { PV, nonPV }; inline int counter_move_bonus[max_ply]; inline int counter_move_value(const int d) { return counter_move_bonus[static_cast<uint32_t>(d) / plies]; } inline int history_bonus(const int d) { return counter_move_bonus[static_cast<uint32_t>(d) / plies]; } struct easy_move_manager { void clear() { key_after_two_moves = 0; third_move_stable = 0; pv[0] = pv[1] = pv[2] = no_move; } [[nodiscard]] uint32_t expected_move(const uint64_t key) const { return key_after_two_moves == key ? pv[2] : no_move; } void refresh_pv(position& pos, const principal_variation& pv_new) { assert(pv_new.size() >= 3); third_move_stable = pv_new[2] == pv[2] ? third_move_stable + 1 : 0; if (pv_new[0] != pv[0] || pv_new[1] != pv[1] || pv_new[2] != pv[2]) { pv[0] = pv_new[0]; pv[1] = pv_new[1]; pv[2] = pv_new[2]; pos.play_move(pv_new[0]); pos.play_move(pv_new[1]); key_after_two_moves = pos.key(); pos.take_move_back(pv_new[1]); pos.take_move_back(pv_new[0]); } } int third_move_stable; uint64_t key_after_two_moves; uint32_t pv[3]; }; inline easy_move_manager easy_move; inline int draw[num_sides]; inline uint64_t previous_info_time; template <nodetype nt> int alpha_beta(position& pos, int alpha, int beta, int depth, bool cut_node); template <nodetype nt, bool state_check> int q_search(position& pos, int alpha, int beta, int depth); int value_to_hash(int val, int ply); int value_from_hash(int val, int ply); void copy_pv(uint32_t* pv, uint32_t move, uint32_t* pv_lower); void update_stats(const position& pos, bool state_check, uint32_t move, int depth, uint32_t* quiet_moves, int quiet_number); void update_stats_quiet(const position& pos, bool state_check, int depth, uint32_t* quiet_moves, int quiet_number); void update_stats_minus(const position& pos, bool state_check, uint32_t move, int depth); void send_time_info(); inline uint8_t lm_reductions[2][2][64 * static_cast<int>(plies)][64]; // alphabeta inline int max_gain_value = 500; inline int razor_margin = 384; inline int razoring_min_depth = 4; inline int razoring_qs_min_depth = 2; inline int futility_min_depth = 7; inline auto futility_value_0 = 0; inline auto futility_value_1 = 112; inline auto futility_value_2 = 243; inline auto futility_value_3 = 376; inline auto futility_value_4 = 510; inline auto futility_value_5 = 646; inline auto futility_value_6 = 784; inline auto futility_margin_ext_mult = 160; inline auto futility_margin_ext_base = 204; inline int null_move_min_depth = 2; inline int null_move_tempo_mult = 2; inline int null_move_strong_threat_mult = 8; inline int null_move_pos_val_less_than_beta_mult = 12; inline int null_move_max_depth = 8; inline int null_move_tm_base = 540; inline int null_move_tm_mult = 66; inline int null_move_depth_greater_than_mult = 310; inline int null_move_depth_greater_than_div = 204; inline int null_move_depth_greater_than_sub = 20; inline int null_move_depth_greater_than_cut_node_mult = 15; inline int value_less_than_beta_margin = 100; inline int value_greater_than_beta_max_depth = 12; inline int dummy_null_move_threat_min_depth_mult = 6; inline int no_early_pruning_min_depth = 5; inline int no_early_pruning_strong_threat_min_depth = 8; inline int pc_beta_margin = 160; inline int pc_beta_depth_margin = 4; inline int limit_depth_min = 8; inline int no_early_pruning_pv_node_depth_min = 5; inline int no_early_pruning_non_pv_node_depth_min = 8; inline int no_early_pruning_position_value_margin = 102; inline int only_quiet_check_moves_max_depth = 8; inline int excluded_move_min_depth = 8; inline int excluded_move_hash_depth_reduction = 3; inline int excluded_move_r_beta_hash_value_margin_mult = 8; inline int excluded_move_r_beta_hash_value_margin_div = 5; inline int late_move_count_max_depth = 16; inline int quiet_moves_max_depth = 6; inline int quiet_moves_max_gain_base = -44; inline int quiet_moves_max_gain_mult = 12; inline int sort_cmp_sort_value = -200; inline int predicted_depth_max_depth = 7; inline int predicted_depth_see_test_base = 300; inline int predicted_depth_see_test_mult = 20; inline int non_root_node_max_depth = 7; inline int non_root_node_see_test_base = 150; inline int non_root_node_see_test_mult = 20; inline int lmr_min_depth = 3; inline int stats_value_sort_value_add = 2000; inline int r_stats_value_div = 2048; inline int r_stats_value_mult_div = 8; inline int lmr_reduction_min = 5; inline int fail_low_counter_move_bonus_min_depth_mult = 3; inline int fail_low_counter_move_bonus_min_depth_margin = 30; inline int fail_low_counter_move_bonus_min_depth = 3; inline int counter_move_bonus_min_depth = 18; const int futility_values[7] = { futility_value_0, futility_value_1, futility_value_2, futility_value_3, futility_value_4, futility_value_5, futility_value_6 }; inline int futility_margin(const int d) { return futility_values[static_cast<uint32_t>(d) / plies]; } inline int futility_margin_ext(const int d) { return futility_margin_ext_base + futility_margin_ext_mult * static_cast<int>(static_cast<uint32_t>(d) / plies); } constexpr int late_move_number_values[2][32] = { {0, 0, 3, 3, 4, 5, 6, 7, 8, 10, 12, 15, 17, 20, 23, 26, 30, 33, 37, 40, 44, 49, 53, 58, 63, 68, 73, 78, 83, 88, 94, 100}, {0, 0, 5, 5, 6, 7, 9, 11, 14, 17, 20, 23, 27, 31, 35, 40, 45, 50, 55, 60, 65, 71, 77, 84, 91, 98, 105, 112, 119, 127, 135, 143} }; inline int late_move_number(const int d, const bool progress) { return late_move_number_values[progress][static_cast<uint32_t>(d) / (plies / 2)]; } inline int lmr_reduction(const bool pv, const bool vg, const int d, const int n) { return lm_reductions[pv][vg][std::min(d, 64 * static_cast<int>(plies) - 1)][std::min(n, 63)]; } // qsearch inline int qs_futility_value_0 = 102; inline int qs_futility_value_1 = 0; inline int qs_futility_value_2 = 308; inline int qs_futility_value_3 = 818; inline int qs_futility_value_4 = 827; inline int qs_futility_value_5 = 1186; inline int qs_futility_value_6 = 2228; inline int qs_futility_value_7 = 0; const int q_search_futility_value[num_pieces] = { qs_futility_value_0, qs_futility_value_1, qs_futility_value_2, qs_futility_value_3, qs_futility_value_4, qs_futility_value_5, qs_futility_value_6, qs_futility_value_7, qs_futility_value_0, qs_futility_value_1, qs_futility_value_2, qs_futility_value_3, qs_futility_value_4, qs_futility_value_4, qs_futility_value_6, qs_futility_value_7 }; inline int lazy_margin = 480; // sf uses 1400 (* 100 / 256 = 547), but 480 seems optimal here inline int qs_futility_basis_margin = 102; inline int qs_futility_value_capture_history_add_div = 32; inline int qs_stats_value_sortvalue = -12000; inline int qs_skip_see_test_value_greater_than_alpha_sort_value = 1000; inline int qs_skip_see_test_value_less_than_equal_to_alpha_sort_value = 2000; struct rootmove_mc { explicit rootmove_mc(const uint32_t m) : pv(1, m) {} bool operator==(const uint32_t& m) const { return pv[0] == m; } bool operator<(const rootmove_mc& m) const { return m.score != score ? m.score < score : m.previous_score < previous_score; } int score = -max_score; int previous_score = -max_score; int sel_depth = 0; int tb_rank = 0; int best_move_count = 0; int tb_score{}; std::vector<uint32_t> pv; }; typedef std::vector<rootmove_mc> rootmoves_mc; struct stack_mc { uint32_t* pv; piece_to_history* continuation_history; int ply; uint32_t current_move; uint32_t excluded_move; uint32_t killers[2]; int static_eval; int stat_score; int move_count; }; } // mainthread::begin_search inline int default_draw_value = 24; // thread::begin_search inline int v_singular_margin = 102; inline int delta_alpha_margin = 14; inline int delta_beta_margin = 14; inline int value_pawn_mult = 20; inline int improvement_factor_min_base = 1304; inline int improvement_factor_max_base = 652; inline int improvement_factor_max_mult = 160; inline int improvement_factor_bv_mult = 12; inline int best_value_vp_mult = 8; inline int delta_alphabeta_value_add = 4; inline int root_depth_mate_value_bv_add = 10; inline int time_control_optimum_mult_1 = 124; inline int time_control_optimum_mult_2 = 420; inline int info_depth_interval = 1000; template <int max_plus, int max_min> struct piece_square_stats; typedef piece_square_stats<24576, 24576> counter_move_values; const int egtb_helpful = 0 * plies; const int egtb_not_helpful = 10 * plies; inline int tb_number; inline bool tb_root_in_tb; inline int tb_probe_depth; inline int tb_score; typedef int (*egtb_probe)(position& pos); void filter_root_moves(position& pos); std::string score_cp(int score); struct rootmove { rootmove() = default; explicit rootmove(const uint32_t move) { pv.move_number = 1; pv.moves[0] = move; } bool operator<(const rootmove& root_move) const { return root_move.score < score; } bool operator==(const uint32_t& move) const { return pv[0] == move; } bool ponder_move_from_hash(position& pos); void pv_from_hash(position& pos); int depth = depth_0; int score = -max_score; int previous_score = -max_score; int start_value = score_0; principal_variation pv; }; struct rootmoves { rootmoves() = default; int move_number = 0, dummy = 0; rootmove moves[max_moves]; void add(const rootmove root_move) { moves[move_number++] = root_move; } rootmove& operator[](const int index) { return moves[index]; } const rootmove& operator[](const int index) const { return moves[index]; } void clear() { move_number = 0; } int find(const uint32_t move) { for (auto i = 0; i < move_number; i++) if (moves[i].pv[0] == move) return i; return -1; } }; namespace egtb { extern int max_pieces_wdl, max_pieces_dtz, max_pieces_dtm; extern egtb_probe egtb_probe_wdl; extern egtb_probe egtb_probe_dtz; extern egtb_probe egtb_probe_dtm; extern bool use_rule50; extern void syzygy_init(const std::string& path); }
[ "firefather@telenet.be" ]
firefather@telenet.be
6a264d1417ad608cf4aecebd114a52954f04d092
67f3aeaa1d004f214826e1232381797c47dc68c4
/Thi.cpp
5bc66ff9d83841b992c944d46f8e8d1666522c5a
[]
no_license
tranngoctam/Algorithm
28093600706167cd201873de71cd172838ed64e3
e269a2e70ee3990195cfafa701c12ed480aa5538
refs/heads/master
2021-01-20T17:26:20.623937
2016-08-03T03:59:00
2016-08-03T03:59:00
64,813,565
1
0
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
#include<iostream> #include<conio.h> #include<stdio.h> #include<string.h> using namespace std; struct node { char tensp[20]; int gia; int giamgia; node *next; }; struct node* initialize() { node *head=NULL; node*tam; node*p; for(int i=0;i<10;i++) { tam=new node; fflush(stdin); gets(tam->tensp); scanf("%d",&tam->gia); scanf("%d",&tam->giamgia); tam->next=NULL; if(head==NULL) { head=tam; p=head; } else { p->next=tam; p=p->next; } } return head; } //struct node* tinhgia(node *head) //{ // //} struct node*sort(node *head) { node *tam1=head; while(tam1->next!=NULL) { node*m=tam1; node*tam2=tam1->next; while(tam2!=NULL) { if(m->gia>tam2->gia) { m=tam2; } tam2=tam2->next; } int t=tam1->gia; tam1->gia=tam2->gia; tam2->gia=t; char a[20]; strcpy(a,tam1->tensp); strcpy(tam1->tensp,m->tensp); strcpy(m->tensp,a); } tam1=tam1->next; } void inketqua(node *head) { while(head!=NULL) { printf("%d ",head->gia); head=head->next; } } int main() { node *head=initialize(); }
[ "tranngoctam@student.ptithcm.edu.vn" ]
tranngoctam@student.ptithcm.edu.vn
8986b642889f6874f1ba2b7874ec43e820e3390a
b84489c4cbeb54fd28aed86d6aa020c7ffa36057
/src/lmo/pi_lmo_parallel3.cpp
57548be14a644d45fb958712529d159d678b13e8
[ "BSD-2-Clause" ]
permissive
uxn/primecount
4d9890a408f84fa7947b43d905c666bb26bdf757
d43d0e5319b27c299e20a7ec90f29efa3c494396
refs/heads/master
2020-12-28T20:19:48.467746
2015-10-14T19:52:50
2015-10-14T19:52:50
44,270,369
0
0
null
2015-10-14T19:11:12
2015-10-14T19:11:12
null
UTF-8
C++
false
false
8,529
cpp
/// /// @file pi_lmo_parallel3.cpp /// @brief Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. This implementation /// uses improved load balancing and counts the number of /// unsieved elements using POPCNT without using any special /// counting tree data structure. /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <min_max.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <S1.hpp> #include <S2LoadBalancer.hpp> #include <S2Status.hpp> #include <Wheel.hpp> #include <stdint.h> #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array. /// @return Count of crossed-off multiples. /// int64_t cross_off(BitSieve& sieve, int64_t low, int64_t high, int64_t prime, WheelItem& w) { int64_t unset = 0; int64_t m = w.next_multiple; int64_t wheel_index = w.wheel_index; for (; m < high; m += prime * Wheel::next_multiple_factor(&wheel_index)) { // +1 if m is unset the first time unset += sieve[m - low]; sieve.unset(m - low); } w.set(m, wheel_index); return unset; } /// Compute the S2 contribution for the interval /// [low_process, low_process + segments * segment_size[. /// The missing special leaf contributions for the interval /// [1, low_process[ are later reconstructed and added in /// the calling (parent) S2 function. /// int64_t S2_thread(int64_t x, int64_t y, int64_t c, int64_t segment_size, int64_t segments_per_thread, int64_t thread_num, int64_t low, int64_t limit, vector<int32_t>& pi, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, vector<int64_t>& mu_sum, vector<int64_t>& phi) { low += segment_size * segments_per_thread * thread_num; limit = min(low + segment_size * segments_per_thread, limit); int64_t size = pi[min(isqrt(x / low), y)] + 1; int64_t pi_sqrty = pi[isqrt(y)]; int64_t pi_y = pi[y]; int64_t S2_thread = 0; if (c >= size - 1) return 0; BitSieve sieve(segment_size); Wheel wheel(primes, size, low); phi.resize(size, 0); mu_sum.resize(size, 0); // Process the segments assigned to the current thread for (; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = c + 1; // pre-sieve the multiples of the first c primes sieve.pre_sieve(c, low); int64_t count_low_high = sieve.count((high - 1) - low); // For c + 1 <= b < pi_sqrty // Find all special leaves: n = primes[b] * m // which satisfy: mu[m] != 0 && primes[b] < lpf[m], low <= (x / n) < high for (; b < min(pi_sqrty, size); b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); int64_t count = 0; int64_t i = 0; if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t xn = x / (prime * m); int64_t stop = xn - low; count += sieve.count(i, stop); i = stop + 1; int64_t phi_xn = phi[b] + count; S2_thread -= mu[m] * phi_xn; mu_sum[b] -= mu[m]; } } phi[b] += count_low_high; count_low_high -= cross_off(sieve, low, high, prime, wheel[b]); } // For pi_sqrty <= b < pi_y // Find all special leaves: n = primes[b] * prime2 // which satisfy: low <= (x / n) < high for (; b < min(pi_y, size); b++) { int64_t prime = primes[b]; int64_t l = pi[min(x / (prime * low), y)]; int64_t min_m = max3(x / (prime * high), y / prime, prime); int64_t count = 0; int64_t i = 0; if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_m; l--) { int64_t xn = x / (prime * primes[l]); int64_t stop = xn - low; count += sieve.count(i, stop); i = stop + 1; int64_t phi_xn = phi[b] + count; S2_thread += phi_xn; mu_sum[b]++; } phi[b] += count_low_high; count_low_high -= cross_off(sieve, low, high, prime, wheel[b]); } next_segment:; } return S2_thread; } /// Calculate the contribution of the special leaves. /// This is a parallel implementation with advanced load balancing. /// As most special leaves tend to be in the first segments we /// start off with a small segment size and few segments /// per thread, after each iteration we dynamically increase /// the segment size and the segments per thread. /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t c, int64_t s2_approx, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, int threads) { print(""); print("=== S2(x, y) ==="); print("Computation of the special leaves"); int64_t S2_total = 0; int64_t low = 1; int64_t limit = x / y + 1; threads = validate_threads(threads, limit); S2Status status(x); S2LoadBalancer loadBalancer(x, y, limit, threads); int64_t segment_size = loadBalancer.get_min_segment_size(); int64_t segments_per_thread = 1; double time = get_wtime(); vector<int32_t> pi = generate_pi(y); vector<int64_t> phi_total(primes.size(), 0); while (low < limit) { int64_t segments = ceil_div(limit - low, segment_size); threads = in_between(1, threads, segments); segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads)); aligned_vector<vector<int64_t> > phi(threads); aligned_vector<vector<int64_t> > mu_sum(threads); aligned_vector<double> timings(threads); #pragma omp parallel for num_threads(threads) reduction(+: S2_total) for (int i = 0; i < threads; i++) { timings[i] = get_wtime(); S2_total += S2_thread(x, y, c, segment_size, segments_per_thread, i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]); timings[i] = get_wtime() - timings[i]; } // Once all threads have finished reconstruct and add the // missing contribution of all special leaves. This must // be done in order as each thread (i) requires the sum of // the phi values from the previous threads. // for (int i = 0; i < threads; i++) { for (size_t j = 1; j < phi[i].size(); j++) { S2_total += phi_total[j] * mu_sum[i][j]; phi_total[j] += phi[i][j]; } } low += segments_per_thread * threads * segment_size; loadBalancer.update(low, threads, &segment_size, &segments_per_thread, timings); if (print_status()) status.print(S2_total, s2_approx, loadBalancer.get_rsd()); } print("S2", S2_total, time); return S2_total; } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo_parallel3(int64_t x, int threads) { if (x < 2) return 0; double alpha = get_alpha_lmo(x); int64_t x13 = iroot<3>(x); int64_t y = (int64_t) (x13 * alpha); int64_t z = x / y; int64_t c = PhiTiny::get_c(y); print(""); print("=== pi_lmo_parallel3(x) ==="); print("pi(x) = S1 + S2 + pi(y) - 1 - P2"); print(x, y, z, c, alpha, threads); int64_t p2 = P2(x, y, threads); vector<int32_t> mu = generate_moebius(y); vector<int32_t> lpf = generate_least_prime_factors(y); vector<int32_t> primes = generate_primes(y); int64_t pi_y = primes.size() - 1; int64_t s1 = S1(x, y, c, threads); int64_t s2_approx = S2_approx(x, pi_y, p2, s1); int64_t s2 = S2(x, y, c, s2_approx, primes, lpf, mu, threads); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount
[ "kim.walisch@gmail.com" ]
kim.walisch@gmail.com
2e815bd8dfead9613c74a002e84acceb67456eab
d6df418a03c3971b8a509efdf749e12840414043
/285.cpp
a6216d075490909d45643fa1f2ec98566b90c278
[]
no_license
frblazquez/Acepta-el-reto
d64e6ba06bee5b212635ac5d9a23c8a2f73cf54b
c95cb838a52301fd0a91eac2c28924ebe2747d7e
refs/heads/master
2020-03-30T08:23:47.002203
2019-10-27T08:34:28
2019-10-27T08:34:28
151,011,842
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
cpp
/* * Copyright © 2019 * * Francisco Javier Blázquez Martínez ~ frblazqu@ucm.es * * Doble grado Ingeniería informática - Matemáticas * Universidad Complutense de Madrid */ #include <iostream> #include <vector> using namespace std; int main() { int numBuckets, aux; cin >> numBuckets; while(numBuckets) { // Lectura de los datos de la entrada vector<int> buckets; for(int i = 0; i < numBuckets; i++) {cin >> aux; buckets.push_back(aux);} // Tabla de programación dinámica int board[numBuckets][numBuckets]; for(int i = 0; i < numBuckets; i++) board[i][i] = buckets[i]; for(int i = 0; i < numBuckets-1; i++) board[i][i+1] = max(buckets[i],buckets[i+1]); int delta = 1 - numBuckets%2; int op1, op2; for(int i = 2 + delta; i < numBuckets; i += 2) for(int j = 0; j + i < numBuckets; j++) { // Op1: We take the bucket j+i if(buckets[j] > buckets[j+i-1]) op1 = buckets[j+i] + board[j+1][j+i-1]; else op1 = buckets[j+i] + board[j][j+i-2]; // Op2: We take the bucket j if(buckets[j+1] > buckets[j+i]) op2 = buckets[j] + board[j+2][j+i]; else op2 = buckets[j] + board[j+1][j+i-1]; board[j][j+i] = max(op1, op2); } cout << board[0][numBuckets-1] << '\n'; cin >> numBuckets; } return 0; }
[ "fcojavibm1@gmail.com" ]
fcojavibm1@gmail.com
4aa142b8fde2a2b363f1acf881a874e5a7ef979e
68845e7cc9434dd6329e8bcb83140d91de8d8a71
/nana/source/gui/detail/bedrock_windows.cpp
2915ec1cb2db94e9094e81bd3c9760958a5a0545
[]
no_license
atgchan/BasicChattingClient
9e6485bfadcca8d55b456340aaa58bef6917f1e9
1ae4c597d7bca9310aa0965d03a0ffdccbb66eed
refs/heads/master
2021-01-20T18:33:10.544077
2016-07-13T09:08:17
2016-07-13T09:08:17
62,871,066
2
1
null
2016-07-12T16:53:25
2016-07-08T08:16:21
C++
UTF-8
C++
false
false
59,892
cpp
/* * A Bedrock Implementation * Nana C++ Library(http://www.nanapro.org) * Copyright(C) 2003-2016 Jinhao(cnjinhao@hotmail.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) * * @file: nana/gui/detail/win32/bedrock.cpp * @contributors: Ariel Vina-Rodriguez */ #include <nana/detail/platform_spec_selector.hpp> #if defined(NANA_WINDOWS) #include <nana/gui/detail/bedrock.hpp> #include <nana/gui/detail/bedrock_pi_data.hpp> #include <nana/gui/detail/event_code.hpp> #include <nana/system/platform.hpp> #include <sstream> #include <nana/system/timepiece.hpp> #include <nana/gui.hpp> #include <nana/gui/detail/inner_fwd_implement.hpp> #include <nana/gui/detail/native_window_interface.hpp> #include <nana/gui/layout_utility.hpp> #include <nana/gui/detail/element_store.hpp> #include <nana/gui/detail/color_schemes.hpp> #ifndef WM_MOUSEWHEEL #define WM_MOUSEWHEEL 0x020A #endif #ifndef WM_MOUSEHWHEEL #define WM_MOUSEHWHEEL 0x020E #endif typedef void (CALLBACK *win_event_proc_t)(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime); namespace nana { void notifications_window_proc(HWND wd, WPARAM wparam, LPARAM lparam); //Defined in notifier.cpp namespace detail { namespace restrict { typedef struct tagTRACKMOUSEEVENT{ unsigned long cbSize; unsigned long dwFlags; void* hwndTrack; unsigned long dwHoverTime; } TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT; typedef int (__stdcall* track_mouse_event_type)(LPTRACKMOUSEEVENT); int __stdcall dummy_track_mouse_event(LPTRACKMOUSEEVENT) { return 1; } track_mouse_event_type track_mouse_event; typedef HIMC (__stdcall * imm_get_context_type)(HWND); imm_get_context_type imm_get_context; typedef BOOL (__stdcall* imm_release_context_type)(HWND, HIMC); imm_release_context_type imm_release_context; typedef BOOL (__stdcall* imm_set_composition_font_type)(HIMC, LOGFONTW*); imm_set_composition_font_type imm_set_composition_font; typedef BOOL (__stdcall* imm_set_composition_window_type)(HIMC, LPCOMPOSITIONFORM); imm_set_composition_window_type imm_set_composition_window; } #pragma pack(1) //Decoder of WPARAM and LPARAM struct wparam_button { bool left:1; bool right:1; bool shift:1; bool ctrl:1; bool middle:1; bool place_holder:3; char place_holder_c[1]; short wheel_delta; }; template<int Bytes> struct param_mouse { wparam_button button; short x; short y; }; template<> struct param_mouse<8> { wparam_button button; char _x64_placeholder[4]; short x; short y; }; template<int Bytes> struct param_size { unsigned long state; short width; short height; }; template<> struct param_size<8> { unsigned long state; char _x64_placeholder[4]; short width; short height; }; union parameter_decoder { struct { WPARAM wparam; LPARAM lparam; }raw_param; param_mouse<sizeof(LPARAM)> mouse; param_size<sizeof(LPARAM)> size; }; #pragma pack() struct bedrock::thread_context { unsigned event_pump_ref_count{0}; int window_count{0}; //The number of windows core_window_t* event_window{nullptr}; struct platform_detail_tag { wchar_t keychar; }platform; struct cursor_tag { core_window_t * window; native_window_type native_handle; nana::cursor predef_cursor; HCURSOR handle; }cursor; thread_context() { cursor.window = nullptr; cursor.native_handle = nullptr; cursor.predef_cursor = nana::cursor::arrow; cursor.handle = nullptr; } }; struct bedrock::private_impl { typedef std::map<unsigned, thread_context> thr_context_container; std::recursive_mutex mutex; thr_context_container thr_contexts; color_schemes schemes; element_store estore; struct cache_type { struct thread_context_cache { unsigned tid{ 0 }; thread_context *object{ nullptr }; }tcontext; }cache; struct menu_tag { core_window_t* taken_window{ nullptr }; bool delay_restore{ false }; native_window_type window{ nullptr }; native_window_type owner{ nullptr }; bool has_keyboard{false}; }menu; struct keyboard_tracking_state_tag { keyboard_tracking_state_tag() :alt(0) {} bool has_shortkey_occured = false; bool has_keyup = true; unsigned long alt : 2; }keyboard_tracking_state; }; //class bedrock defines a static object itself to implement a static singleton //here is the definition of this object bedrock bedrock::bedrock_object; static LRESULT WINAPI Bedrock_WIN32_WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); bedrock::bedrock() : pi_data_(new pi_data), impl_(new private_impl) { nana::detail::platform_spec::instance(); //to guaranty the platform_spec object is initialized before using. WNDCLASSEX wincl; wincl.hInstance = ::GetModuleHandle(0); wincl.lpszClassName = L"NanaWindowInternal"; wincl.lpfnWndProc = &Bedrock_WIN32_WindowProc; wincl.style = CS_DBLCLKS | CS_OWNDC; wincl.cbSize = sizeof(wincl); wincl.hIcon = ::LoadIcon (0, IDI_APPLICATION); wincl.hIconSm = wincl.hIcon; wincl.hCursor = ::LoadCursor (0, IDC_ARROW); wincl.lpszMenuName = 0; wincl.cbClsExtra = 0; wincl.cbWndExtra = 0; wincl.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); ::RegisterClassEx(&wincl); restrict::track_mouse_event = (restrict::track_mouse_event_type)::GetProcAddress(::GetModuleHandleA("User32.DLL"), "TrackMouseEvent"); if(!restrict::track_mouse_event) restrict::track_mouse_event = restrict::dummy_track_mouse_event; HMODULE imm32 = ::GetModuleHandleA("Imm32.DLL"); restrict::imm_get_context = reinterpret_cast<restrict::imm_get_context_type>( ::GetProcAddress(imm32, "ImmGetContext")); restrict::imm_release_context = reinterpret_cast<restrict::imm_release_context_type>( ::GetProcAddress(imm32, "ImmReleaseContext")); restrict::imm_set_composition_font = reinterpret_cast<restrict::imm_set_composition_font_type>( ::GetProcAddress(imm32, "ImmSetCompositionFontW")); restrict::imm_set_composition_window = reinterpret_cast<restrict::imm_set_composition_window_type>( ::GetProcAddress(imm32, "ImmSetCompositionWindow")); } bedrock::~bedrock() { if(wd_manager().number_of_core_window()) { std::stringstream ss; ss<<"Nana.GUI detects a memory leaks in window_manager, "<<static_cast<unsigned>(wd_manager().number_of_core_window())<<" window(s) are not uninstalled."; ::MessageBoxA(0, ss.str().c_str(), ("Nana C++ Library"), MB_OK); } delete impl_; delete pi_data_; } //inc_window //@brief: increament the number of windows int bedrock::inc_window(unsigned tid) { //impl refers to the object of private_impl, the object is created when bedrock is creating. private_impl * impl = instance().impl_; std::lock_guard<decltype(impl->mutex)> lock(impl->mutex); int & cnt = (impl->thr_contexts[tid ? tid : nana::system::this_thread_id()].window_count); return (cnt < 0 ? cnt = 1 : ++cnt); } auto bedrock::open_thread_context(unsigned tid) -> thread_context* { if(0 == tid) tid = nana::system::this_thread_id(); std::lock_guard<decltype(impl_->mutex)> lock(impl_->mutex); if(impl_->cache.tcontext.tid == tid) return impl_->cache.tcontext.object; impl_->cache.tcontext.tid = tid; auto i = impl_->thr_contexts.find(tid); thread_context * context = (i == impl_->thr_contexts.end() ? &(impl_->thr_contexts[tid]) : &(i->second)); impl_->cache.tcontext.object = context; return context; } auto bedrock::get_thread_context(unsigned tid) -> thread_context * { if(0 == tid) tid = nana::system::this_thread_id(); std::lock_guard<decltype(impl_->mutex)> lock(impl_->mutex); auto & cachectx = impl_->cache.tcontext; if(cachectx.tid == tid) return cachectx.object; auto i = impl_->thr_contexts.find(tid); if(i != impl_->thr_contexts.end()) { cachectx.tid = tid; return (cachectx.object = &(i->second)); } cachectx.tid = 0; return nullptr; } void bedrock::remove_thread_context(unsigned tid) { if(0 == tid) tid = nana::system::this_thread_id(); std::lock_guard<decltype(impl_->mutex)> lock(impl_->mutex); if(impl_->cache.tcontext.tid == tid) { impl_->cache.tcontext.tid = 0; impl_->cache.tcontext.object = nullptr; } impl_->thr_contexts.erase(tid); } bedrock& bedrock::instance() { return bedrock_object; } void bedrock::map_thread_root_buffer(core_window_t* wd, bool forced, const rectangle* update_area) { auto stru = reinterpret_cast<detail::messages::map_thread*>(::HeapAlloc(::GetProcessHeap(), 0, sizeof(detail::messages::map_thread))); if (stru) { if (FALSE == ::PostMessage(reinterpret_cast<HWND>(wd->root), nana::detail::messages::map_thread_root_buffer, reinterpret_cast<WPARAM>(wd), reinterpret_cast<LPARAM>(stru))) ::HeapFree(::GetProcessHeap(), 0, stru); } } void interior_helper_for_menu(MSG& msg, native_window_type menu_window) { switch(msg.message) { case WM_KEYDOWN: case WM_CHAR: case WM_KEYUP: msg.hwnd = reinterpret_cast<HWND>(menu_window); break; } } void bedrock::pump_event(window modal_window, bool is_modal) { const unsigned tid = ::GetCurrentThreadId(); auto context = this->open_thread_context(tid); if(0 == context->window_count) { //test if there is not a window //GetMessage may block if there is not a window remove_thread_context(); return; } ++(context->event_pump_ref_count); auto & intr_locker = wd_manager().internal_lock(); intr_locker.revert(); try { MSG msg; if(modal_window) { HWND native_handle = reinterpret_cast<HWND>(reinterpret_cast<core_window_t*>(modal_window)->root); if (is_modal) { HWND owner = ::GetWindow(native_handle, GW_OWNER); if (owner && owner != ::GetDesktopWindow()) ::EnableWindow(owner, false); while (::IsWindow(native_handle)) { ::WaitMessage(); while (::PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) break; if ((WM_KEYFIRST <= msg.message && msg.message <= WM_KEYLAST) || !::IsDialogMessage(native_handle, &msg)) { auto menu_wd = get_menu(reinterpret_cast<native_window_type>(msg.hwnd), true); if (menu_wd) interior_helper_for_menu(msg, menu_wd); ::TranslateMessage(&msg); ::DispatchMessage(&msg); wd_manager().remove_trash_handle(tid); } } } } else { while (::IsWindow(native_handle)) { if (-1 != ::GetMessage(&msg, 0, 0, 0)) { auto menu_wd = get_menu(reinterpret_cast<native_window_type>(msg.hwnd), true); if (menu_wd) interior_helper_for_menu(msg, menu_wd); ::TranslateMessage(&msg); ::DispatchMessage(&msg); } wd_manager().call_safe_place(tid); wd_manager().remove_trash_handle(tid); if (msg.message == WM_DESTROY && msg.hwnd == native_handle) break; }//end while } } else { while(context->window_count) { if(-1 != ::GetMessage(&msg, 0, 0, 0)) { auto menu_wd = get_menu(reinterpret_cast<native_window_type>(msg.hwnd), true); if(menu_wd) interior_helper_for_menu(msg, menu_wd); ::TranslateMessage(&msg); ::DispatchMessage(&msg); } wd_manager().call_safe_place(tid); wd_manager().remove_trash_handle(tid); }//end while //Empty these rest messages, there is not a window to process these messages. while(::PeekMessage(&msg, 0, 0, 0, PM_REMOVE)); } } catch(std::exception& e) { (msgbox(modal_window, "An uncaptured std::exception during message pumping: ").icon(msgbox::icon_information) <<"\n in form: "<< API::window_caption(modal_window) <<"\n exception : "<< e.what() ).show(); internal_scope_guard lock; _m_except_handler(); intr_locker.forward(); if (0 == --(context->event_pump_ref_count)) { if ((nullptr == modal_window) || (0 == context->window_count)) remove_thread_context(); } throw; } catch(...) { (msgbox(modal_window, "An exception during message pumping!").icon(msgbox::icon_information) <<"An uncaptured non-std exception during message pumping!" ).show(); internal_scope_guard lock; _m_except_handler(); intr_locker.forward(); if(0 == --(context->event_pump_ref_count)) { if((nullptr == modal_window) || (0 == context->window_count)) remove_thread_context(); } throw; } intr_locker.forward(); if(0 == --(context->event_pump_ref_count)) { if((nullptr == modal_window) || (0 == context->window_count)) remove_thread_context(); } }//end pump_event void assign_arg(nana::arg_mouse& arg, basic_window* wd, unsigned msg, const parameter_decoder& pmdec) { arg.window_handle = reinterpret_cast<window>(wd); bool set_key_state = true; switch (msg) { case WM_LBUTTONDOWN: arg.button = ::nana::mouse::left_button; arg.evt_code = event_code::mouse_down; break; case WM_RBUTTONDOWN: arg.button = ::nana::mouse::right_button; arg.evt_code = event_code::mouse_down; break; case WM_MBUTTONDOWN: arg.button = ::nana::mouse::middle_button; arg.evt_code = event_code::mouse_down; break; case WM_LBUTTONUP: arg.button = ::nana::mouse::left_button; arg.evt_code = event_code::mouse_up; break; case WM_RBUTTONUP: arg.button = ::nana::mouse::right_button; arg.evt_code = event_code::mouse_up; break; case WM_MBUTTONUP: arg.button = ::nana::mouse::middle_button; arg.evt_code = event_code::mouse_up; break; case WM_LBUTTONDBLCLK: arg.button = ::nana::mouse::left_button; arg.evt_code = (wd->flags.dbl_click ? event_code::dbl_click : event_code::mouse_down); break; case WM_MBUTTONDBLCLK: arg.button = ::nana::mouse::middle_button; arg.evt_code = (wd->flags.dbl_click ? event_code::dbl_click : event_code::mouse_down); break; case WM_RBUTTONDBLCLK: arg.button = ::nana::mouse::right_button; arg.evt_code = (wd->flags.dbl_click ? event_code::dbl_click : event_code::mouse_down); break; case WM_MOUSEMOVE: arg.button = ::nana::mouse::any_button; arg.evt_code = event_code::mouse_move; break; default: set_key_state = false; } if (set_key_state) { arg.pos.x = pmdec.mouse.x - wd->pos_root.x; arg.pos.y = pmdec.mouse.y - wd->pos_root.y; arg.alt = (::GetKeyState(VK_MENU) < 0); arg.shift = pmdec.mouse.button.shift; arg.ctrl = pmdec.mouse.button.ctrl; arg.left_button = pmdec.mouse.button.left; arg.mid_button = pmdec.mouse.button.middle; arg.right_button = pmdec.mouse.button.right; } } void assign_arg(arg_focus& arg, basic_window* wd, native_window_type recv, bool getting) { arg.window_handle = reinterpret_cast<window>(wd); arg.receiver = recv; arg.getting = getting; } void assign_arg(arg_wheel& arg, basic_window* wd, const parameter_decoder& pmdec) { arg.window_handle = reinterpret_cast<window>(wd); arg.evt_code = event_code::mouse_wheel; POINT point = { pmdec.mouse.x, pmdec.mouse.y }; ::ScreenToClient(reinterpret_cast<HWND>(wd->root), &point); arg.upwards = (pmdec.mouse.button.wheel_delta >= 0); arg.distance = static_cast<unsigned>(arg.upwards ? pmdec.mouse.button.wheel_delta : -pmdec.mouse.button.wheel_delta); arg.pos.x = static_cast<int>(point.x) - wd->pos_root.x; arg.pos.y = static_cast<int>(point.y) - wd->pos_root.y; arg.left_button = pmdec.mouse.button.left; arg.mid_button = pmdec.mouse.button.middle; arg.right_button = pmdec.mouse.button.right; arg.ctrl = pmdec.mouse.button.ctrl; arg.shift = pmdec.mouse.button.shift; } //trivial_message // The Windows messaging always sends a message to the window thread queue when the calling is in other thread. //If messages can be finished without expecting Nana's window manager, the trivail_message function would //handle those messages. This is a method to avoid a deadlock, that calling waits for the handling and they require //Nana's window manager. bool trivial_message(HWND wd, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT & ret) { bedrock & bedrock = bedrock::instance(); switch(msg) { case nana::detail::messages::async_activate: ::EnableWindow(wd, true); ::SetActiveWindow(wd); return true; case nana::detail::messages::async_set_focus: ::SetFocus(wd); return true; case nana::detail::messages::operate_caret: //Refer to basis.hpp for this specification. switch(wParam) { case 1: //Delete ::DestroyCaret(); break; case 2: //SetPos ::SetCaretPos(reinterpret_cast<nana::detail::messages::caret*>(lParam)->x, reinterpret_cast<nana::detail::messages::caret*>(lParam)->y); delete reinterpret_cast<nana::detail::messages::caret*>(lParam); break; } return true; case nana::detail::messages::map_thread_root_buffer: { auto stru = reinterpret_cast<detail::messages::map_thread*>(lParam); bedrock.wd_manager().map(reinterpret_cast<bedrock::core_window_t*>(wParam), stru->forced, (stru->ignore_update_area ? nullptr : &stru->update_area)); ::UpdateWindow(wd); ::HeapFree(::GetProcessHeap(), 0, stru); } return true; case nana::detail::messages::remote_thread_move_window: { auto * mw = reinterpret_cast<nana::detail::messages::move_window*>(wParam); ::RECT r; ::GetWindowRect(wd, &r); if(mw->ignore & mw->Pos) { mw->x = r.left; mw->y = r.top; } else { HWND owner = ::GetWindow(wd, GW_OWNER); if(owner) { ::RECT owr; ::GetWindowRect(owner, &owr); ::POINT pos = {owr.left, owr.top}; ::ScreenToClient(owner, &pos); mw->x += (owr.left - pos.x); mw->y += (owr.top - pos.y); } } if(mw->ignore & mw->Size) { mw->width = r.right - r.left; mw->height = r.bottom - r.top; } ::MoveWindow(wd, mw->x, mw->y, mw->width, mw->height, true); delete mw; } return true; case nana::detail::messages::remote_thread_set_window_pos: ::SetWindowPos(wd, reinterpret_cast<HWND>(wParam), 0, 0, 0, 0, static_cast<UINT>(lParam)); return true; case nana::detail::messages::remote_thread_set_window_text: ::SetWindowTextW(wd, reinterpret_cast<wchar_t*>(wParam)); delete [] reinterpret_cast<wchar_t*>(wParam); return true; case nana::detail::messages::remote_thread_destroy_window: detail::native_interface::close_window(reinterpret_cast<native_window_type>(wd)); //The owner would be actived before the message has posted in current thread. { internal_scope_guard sg; auto * thrd = bedrock.get_thread_context(); if(thrd && (thrd->window_count == 0)) ::PostQuitMessage(0); } ret = ::DefWindowProc(wd, msg, wParam, lParam); return true; case nana::detail::messages::tray: notifications_window_proc(wd, wParam, lParam); return true; default: break; } switch(msg) { case WM_DESTROY: case WM_SHOWWINDOW: case WM_SIZING: case WM_MOVE: case WM_SIZE: case WM_SETFOCUS: case WM_KILLFOCUS: case WM_PAINT: case WM_CLOSE: case WM_MOUSEACTIVATE: case WM_GETMINMAXINFO: case WM_WINDOWPOSCHANGED: case WM_NCDESTROY: case WM_NCLBUTTONDOWN: case WM_NCRBUTTONDOWN: case WM_NCMBUTTONDOWN: case WM_IME_STARTCOMPOSITION: case WM_DROPFILES: case WM_MOUSELEAVE: case WM_MOUSEWHEEL: //The WM_MOUSELAST may not include the WM_MOUSEWHEEL/WM_MOUSEHWHEEL when the version of SDK is low. case WM_MOUSEHWHEEL: return false; default: if((WM_MOUSEFIRST <= msg && msg <= WM_MOUSELAST) || (WM_KEYFIRST <= msg && msg <= WM_KEYLAST)) return false; } ret = ::DefWindowProc(wd, msg, wParam, lParam); return true; } void adjust_sizing(bedrock::core_window_t* wd, ::RECT * const r, int edge, unsigned req_width, unsigned req_height) { unsigned width = static_cast<unsigned>(r->right - r->left) - wd->extra_width; unsigned height = static_cast<unsigned>(r->bottom - r->top) - wd->extra_height; if(wd->max_track_size.width && (wd->max_track_size.width < req_width)) req_width = wd->max_track_size.width; else if(wd->min_track_size.width && (wd->min_track_size.width > req_width)) req_width = wd->min_track_size.width; if(wd->max_track_size.height && (wd->max_track_size.height < req_height)) req_height = wd->max_track_size.height; else if(wd->min_track_size.height && (wd->min_track_size.height > req_height)) req_height = wd->min_track_size.height; if(req_width != width) { switch(edge) { case WMSZ_LEFT: case WMSZ_BOTTOMLEFT: case WMSZ_TOPLEFT: r->left = r->right - static_cast<int>(req_width) - wd->extra_width; break; case WMSZ_RIGHT: case WMSZ_BOTTOMRIGHT: case WMSZ_TOPRIGHT: case WMSZ_TOP: case WMSZ_BOTTOM: r->right = r->left + static_cast<int>(req_width) + wd->extra_width; break; } } if(req_height != height) { switch(edge) { case WMSZ_TOP: case WMSZ_TOPLEFT: case WMSZ_TOPRIGHT: r->top = r->bottom - static_cast<int>(req_height) - wd->extra_height; break; case WMSZ_BOTTOM: case WMSZ_BOTTOMLEFT: case WMSZ_BOTTOMRIGHT: case WMSZ_LEFT: case WMSZ_RIGHT: r->bottom = r->top + static_cast<int>(req_height) + wd->extra_height; break; } } } template<typename Arg> void emit_drawer(void (::nana::detail::drawer::*event_ptr)(const Arg&), basic_window* wd, const Arg& arg, bedrock::thread_context* thrd) { if (bedrock::instance().wd_manager().available(wd) == false) return; basic_window* prev_event_wd; if (thrd) { prev_event_wd = thrd->event_window; thrd->event_window = wd; } if (wd->other.upd_state == basic_window::update_state::none) wd->other.upd_state = basic_window::update_state::lazy; (wd->drawer.*event_ptr)(arg); if (thrd) thrd->event_window = prev_event_wd; } LRESULT CALLBACK Bedrock_WIN32_WindowProc(HWND root_window, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT window_proc_value = 0; if(trivial_message(root_window, message, wParam, lParam, window_proc_value)) return window_proc_value; static auto& brock = bedrock::instance(); static restrict::TRACKMOUSEEVENT track = {sizeof track, 0x00000002}; auto native_window = reinterpret_cast<native_window_type>(root_window); auto* root_runtime = brock.wd_manager().root_runtime(native_window); if(root_runtime) { bool def_window_proc = false; auto& context = *brock.get_thread_context(); auto pressed_wd = root_runtime->condition.pressed; auto pressed_wd_space = root_runtime->condition.pressed_by_space; auto hovered_wd = root_runtime->condition.hovered; parameter_decoder pmdec; pmdec.raw_param.lparam = lParam; pmdec.raw_param.wparam = wParam; internal_scope_guard lock; auto msgwnd = root_runtime->window; switch(message) { case WM_IME_STARTCOMPOSITION: if(msgwnd->other.attribute.root->ime_enabled) { auto native_font = msgwnd->drawer.graphics.typeface().handle(); LOGFONTW logfont; ::GetObjectW(reinterpret_cast<HFONT>(native_font), sizeof logfont, &logfont); HIMC imc = restrict::imm_get_context(root_window); restrict::imm_set_composition_font(imc, &logfont); POINT pos; ::GetCaretPos(&pos); COMPOSITIONFORM cf = {CFS_POINT}; cf.ptCurrentPos = pos; restrict::imm_set_composition_window(imc, &cf); restrict::imm_release_context(root_window, imc); } def_window_proc = true; break; case WM_GETMINMAXINFO: { bool take_over = false; auto mmi = reinterpret_cast<MINMAXINFO*>(lParam); if(msgwnd->min_track_size.width && msgwnd->min_track_size.height) { mmi->ptMinTrackSize.x = static_cast<LONG>(msgwnd->min_track_size.width + msgwnd->extra_width); mmi->ptMinTrackSize.y = static_cast<LONG>(msgwnd->min_track_size.height + msgwnd->extra_height); take_over = true; } if(false == msgwnd->flags.fullscreen) { if(msgwnd->max_track_size.width && msgwnd->max_track_size.height) { mmi->ptMaxTrackSize.x = static_cast<LONG>(msgwnd->max_track_size.width + msgwnd->extra_width); mmi->ptMaxTrackSize.y = static_cast<LONG>(msgwnd->max_track_size.height + msgwnd->extra_height); if(mmi->ptMaxSize.x > mmi->ptMaxTrackSize.x) mmi->ptMaxSize.x = mmi->ptMaxTrackSize.x; if(mmi->ptMaxSize.y > mmi->ptMaxTrackSize.y) mmi->ptMaxSize.y = mmi->ptMaxTrackSize.y; take_over = true; } } if (take_over) return 0; } break; case WM_SHOWWINDOW: if (msgwnd->visible && (wParam == FALSE)) brock.event_expose(msgwnd, false); else if ((!msgwnd->visible) && (wParam != FALSE)) brock.event_expose(msgwnd, true); def_window_proc = true; break; case WM_WINDOWPOSCHANGED: if ((reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW) && (!msgwnd->visible)) brock.event_expose(msgwnd, true); else if ((reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_HIDEWINDOW) && msgwnd->visible) brock.event_expose(msgwnd, false); def_window_proc = true; break; case WM_SETFOCUS: if(msgwnd->flags.enabled && msgwnd->flags.take_active) { auto focus = msgwnd->other.attribute.root->focus; if(focus && focus->together.caret) focus->together.caret->set_active(true); arg_focus arg; assign_arg(arg, focus, native_window, true); if (!brock.emit(event_code::focus, focus, arg, true, &context)) brock.wd_manager().set_focus(msgwnd, true); } def_window_proc = true; break; case WM_KILLFOCUS: if(msgwnd->other.attribute.root->focus) { auto focus = msgwnd->other.attribute.root->focus; arg_focus arg; assign_arg(arg, focus, reinterpret_cast<native_window_type>(wParam), false); if(brock.emit(event_code::focus, focus, arg, true, &context)) { if(focus->together.caret) focus->together.caret->set_active(false); } //wParam indicates a handle of window that receives the focus. brock.close_menu_if_focus_other_window(reinterpret_cast<native_window_type>(wParam)); } def_window_proc = true; break; case WM_MOUSEACTIVATE: if(msgwnd->flags.take_active == false) return MA_NOACTIVATE; def_window_proc = true; break; case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: //Ignore mouse events when a window has been pressed by pressing spacebar if (pressed_wd_space) break; pressed_wd = nullptr; msgwnd = brock.wd_manager().find_window(native_window, pmdec.mouse.x, pmdec.mouse.y); if(msgwnd && msgwnd->flags.enabled) { if (msgwnd->flags.take_active && !msgwnd->flags.ignore_mouse_focus) { auto killed = brock.wd_manager().set_focus(msgwnd, false); if (killed != msgwnd) brock.wd_manager().do_lazy_refresh(killed, false); } arg_mouse arg; assign_arg(arg, msgwnd, message, pmdec); if (brock.emit(arg.evt_code, msgwnd, arg, true, &context)) { if (brock.wd_manager().available(msgwnd)) pressed_wd = msgwnd; } } break; case WM_NCLBUTTONDOWN: case WM_NCMBUTTONDOWN: case WM_NCRBUTTONDOWN: brock.close_menu_if_focus_other_window(native_window); def_window_proc = true; break; case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: //Ignore mouse events when a window has been pressed by pressing spacebar if (pressed_wd_space) break; msgwnd = brock.wd_manager().find_window(native_window, pmdec.mouse.x, pmdec.mouse.y); if ((nullptr == msgwnd) || (pressed_wd && (msgwnd != pressed_wd))) break; //if event on the menubar, just remove the menu if it is not associating with the menubar if ((msgwnd == msgwnd->root_widget->other.attribute.root->menubar) && brock.get_menu(msgwnd->root, true)) brock.erase_menu(true); else brock.close_menu_if_focus_other_window(msgwnd->root); if(msgwnd->flags.enabled) { pressed_wd = msgwnd; if (WM_LBUTTONDOWN == message) //Sets focus only if left button is pressed { auto new_focus = (msgwnd->flags.take_active ? msgwnd : msgwnd->other.active_window); if (new_focus && (!new_focus->flags.ignore_mouse_focus)) { auto kill_focus = brock.wd_manager().set_focus(new_focus, false); if (kill_focus != new_focus) brock.wd_manager().do_lazy_refresh(kill_focus, false); } } arg_mouse arg; assign_arg(arg, msgwnd, message, pmdec); msgwnd->flags.action = mouse_action::pressed; auto retain = msgwnd->together.events_ptr; if (brock.emit(event_code::mouse_down, msgwnd, arg, true, &context)) { //If a root_window is created during the mouse_down event, Nana.GUI will ignore the mouse_up event. if (msgwnd->root != native_interface::get_focus_window()) { auto pos = native_interface::cursor_position(); auto rootwd = native_interface::find_window(pos.x, pos.y); native_interface::calc_window_point(rootwd, pos); if(msgwnd != brock.wd_manager().find_window(rootwd, pos.x, pos.y)) { //call the drawer mouse up event for restoring the surface graphics msgwnd->flags.action = mouse_action::normal; arg.evt_code = event_code::mouse_up; emit_drawer(&drawer::mouse_up, msgwnd, arg, &context); brock.wd_manager().do_lazy_refresh(msgwnd, false); } } } else pressed_wd = nullptr; } break; //mouse_click, mouse_up case WM_LBUTTONUP: case WM_MBUTTONUP: case WM_RBUTTONUP: //Ignore mouse events when a window has been pressed by pressing spacebar if (pressed_wd_space) break; msgwnd = brock.wd_manager().find_window(native_window, pmdec.mouse.x, pmdec.mouse.y); if(nullptr == msgwnd) break; msgwnd->flags.action = mouse_action::normal; if(msgwnd->flags.enabled) { auto retain = msgwnd->together.events_ptr; ::nana::arg_mouse arg; assign_arg(arg, msgwnd, message, pmdec); ::nana::arg_click click_arg; //the window_handle of click_arg is used as a flag to determinate whether to emit click event click_arg.window_handle = nullptr; click_arg.mouse_args = &arg; if (msgwnd->dimension.is_hit(arg.pos)) { msgwnd->flags.action = mouse_action::over; if ((::nana::mouse::left_button == arg.button) && (pressed_wd == msgwnd)) { click_arg.window_handle = reinterpret_cast<window>(msgwnd); emit_drawer(&drawer::click, msgwnd, click_arg, &context); } } //Do mouse_up, this handle may be closed by click handler. if(brock.wd_manager().available(msgwnd) && msgwnd->flags.enabled) { arg.evt_code = event_code::mouse_up; emit_drawer(&drawer::mouse_up, msgwnd, arg, &context); if (click_arg.window_handle) retain->click.emit(click_arg); if (brock.wd_manager().available(msgwnd)) { arg.evt_code = event_code::mouse_up; retain->mouse_up.emit(arg); } } else if (click_arg.window_handle) retain->click.emit(click_arg); brock.wd_manager().do_lazy_refresh(msgwnd, false); } pressed_wd = nullptr; break; case WM_MOUSEMOVE: //Ignore mouse events when a window has been pressed by pressing spacebar if (pressed_wd_space) break; msgwnd = brock.wd_manager().find_window(native_window, pmdec.mouse.x, pmdec.mouse.y); if (brock.wd_manager().available(hovered_wd) && (msgwnd != hovered_wd)) { brock.event_msleave(hovered_wd); hovered_wd->flags.action = mouse_action::normal; hovered_wd = nullptr; //if msgwnd is neither captured window nor the child of captured window, //redirect the msgwnd to the captured window. auto wd = brock.wd_manager().capture_redirect(msgwnd); if(wd) msgwnd = wd; } else if(msgwnd) { bool prev_captured_inside; if(brock.wd_manager().capture_window_entered(pmdec.mouse.x, pmdec.mouse.y, prev_captured_inside)) { event_code evt_code; if(prev_captured_inside) { evt_code = event_code::mouse_leave; msgwnd->flags.action = mouse_action::normal; } else { evt_code = event_code::mouse_enter; if (pressed_wd == msgwnd) msgwnd->flags.action = mouse_action::pressed; else if (mouse_action::pressed != msgwnd->flags.action) msgwnd->flags.action = mouse_action::over; } arg_mouse arg; assign_arg(arg, msgwnd, message, pmdec); arg.evt_code = evt_code; brock.emit(evt_code, msgwnd, arg, true, &context); } } if(msgwnd) { arg_mouse arg; assign_arg(arg, msgwnd, message, pmdec); if (hovered_wd != msgwnd) { if (pressed_wd == msgwnd) msgwnd->flags.action = mouse_action::pressed; else if (mouse_action::pressed != msgwnd->flags.action) msgwnd->flags.action = mouse_action::over; hovered_wd = msgwnd; arg.evt_code = event_code::mouse_enter; brock.emit(event_code::mouse_enter, msgwnd, arg, true, &context); } arg.evt_code = event_code::mouse_move; brock.emit(event_code::mouse_move, msgwnd, arg, true, &context); track.hwndTrack = native_window; restrict::track_mouse_event(&track); } if (!brock.wd_manager().available(hovered_wd)) hovered_wd = nullptr; break; case WM_MOUSELEAVE: brock.event_msleave(hovered_wd); hovered_wd = nullptr; break; case WM_MOUSEWHEEL: case WM_MOUSEHWHEEL: { //The focus window receives the message in Windows system, it should be redirected to the hovered window ::POINT scr_pos{ pmdec.mouse.x, pmdec.mouse.y}; //Screen position auto pointer_wd = ::WindowFromPoint(scr_pos); if (pointer_wd == root_window) { ::ScreenToClient(pointer_wd, &scr_pos); auto scrolled_wd = brock.wd_manager().find_window(reinterpret_cast<native_window_type>(pointer_wd), scr_pos.x, scr_pos.y); def_window_proc = true; auto evt_wd = scrolled_wd; while (evt_wd) { if (evt_wd->together.events_ptr->mouse_wheel.length() != 0) { def_window_proc = false; nana::point mspos{ scr_pos.x, scr_pos.y }; brock.wd_manager().calc_window_point(evt_wd, mspos); arg_wheel arg; arg.which = (WM_MOUSEHWHEEL == message ? arg_wheel::wheel::horizontal : arg_wheel::wheel::vertical); assign_arg(arg, evt_wd, pmdec); brock.emit(event_code::mouse_wheel, evt_wd, arg, true, &context); break; } evt_wd = evt_wd->parent; } if (scrolled_wd && (nullptr == evt_wd)) { nana::point mspos{ scr_pos.x, scr_pos.y }; brock.wd_manager().calc_window_point(scrolled_wd, mspos); arg_wheel arg; arg.which = (WM_MOUSEHWHEEL == message ? arg_wheel::wheel::horizontal : arg_wheel::wheel::vertical); assign_arg(arg, scrolled_wd, pmdec); brock.emit_drawer(event_code::mouse_wheel, scrolled_wd, arg, &context); brock.wd_manager().do_lazy_refresh(scrolled_wd, false); } } else { DWORD pid = 0; ::GetWindowThreadProcessId(pointer_wd, &pid); if (pid == ::GetCurrentProcessId()) ::PostMessage(pointer_wd, message, wParam, lParam); } } break; case WM_DROPFILES: { HDROP drop = reinterpret_cast<HDROP>(wParam); POINT pos; ::DragQueryPoint(drop, &pos); msgwnd = brock.wd_manager().find_window(native_window, pos.x, pos.y); if(msgwnd) { arg_dropfiles dropfiles; std::unique_ptr<wchar_t[]> varbuf; std::size_t bufsize = 0; unsigned size = ::DragQueryFile(drop, 0xFFFFFFFF, 0, 0); for(unsigned i = 0; i < size; ++i) { unsigned reqlen = ::DragQueryFile(drop, i, 0, 0) + 1; if(bufsize < reqlen) { varbuf.reset(new wchar_t[reqlen]); bufsize = reqlen; } ::DragQueryFile(drop, i, varbuf.get(), reqlen); dropfiles.files.emplace_back(to_utf8(varbuf.get())); } while(msgwnd && (msgwnd->flags.dropable == false)) msgwnd = msgwnd->parent; if(msgwnd) { dropfiles.pos.x = pos.x; dropfiles.pos.y = pos.y; brock.wd_manager().calc_window_point(msgwnd, dropfiles.pos); dropfiles.window_handle = reinterpret_cast<window>(msgwnd); msgwnd->together.events_ptr->mouse_dropfiles.emit(dropfiles); brock.wd_manager().do_lazy_refresh(msgwnd, false); } } ::DragFinish(drop); } break; case WM_SIZING: { ::RECT* const r = reinterpret_cast<RECT*>(lParam); unsigned width = static_cast<unsigned>(r->right - r->left) - msgwnd->extra_width; unsigned height = static_cast<unsigned>(r->bottom - r->top) - msgwnd->extra_height; if(msgwnd->max_track_size.width || msgwnd->min_track_size.width) { if(wParam == WMSZ_LEFT || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT) { if(msgwnd->max_track_size.width && (width > msgwnd->max_track_size.width)) r->left = r->right - static_cast<int>(msgwnd->max_track_size.width) - msgwnd->extra_width; if(msgwnd->min_track_size.width && (width < msgwnd->min_track_size.width)) r->left = r->right - static_cast<int>(msgwnd->min_track_size.width) - msgwnd->extra_width; } else if(wParam == WMSZ_RIGHT || wParam == WMSZ_BOTTOMRIGHT || wParam == WMSZ_TOPRIGHT) { if(msgwnd->max_track_size.width && (width > msgwnd->max_track_size.width)) r->right = r->left + static_cast<int>(msgwnd->max_track_size.width) + msgwnd->extra_width; if(msgwnd->min_track_size.width && (width < msgwnd->min_track_size.width)) r->right = r->left + static_cast<int>(msgwnd->min_track_size.width) + msgwnd->extra_width; } } if(msgwnd->max_track_size.height || msgwnd->min_track_size.height) { if(wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT) { if(msgwnd->max_track_size.height && (height > msgwnd->max_track_size.height)) r->top = r->bottom - static_cast<int>(msgwnd->max_track_size.height) - msgwnd->extra_height; if(msgwnd->min_track_size.height && (height < msgwnd->min_track_size.height)) r->top = r->bottom - static_cast<int>(msgwnd->min_track_size.height) - msgwnd->extra_height; } else if(wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT) { if(msgwnd->max_track_size.height && (height > msgwnd->max_track_size.height)) r->bottom = r->top + static_cast<int>(msgwnd->max_track_size.height) + msgwnd->extra_height; if(msgwnd->min_track_size.height && (height < msgwnd->min_track_size.height)) r->bottom = r->top + static_cast<int>(msgwnd->min_track_size.height) + msgwnd->extra_height; } } nana::size size_before( static_cast<unsigned>(r->right - r->left - msgwnd->extra_width), static_cast<unsigned>(r->bottom - r->top - msgwnd->extra_height)); arg_resizing arg; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.width = size_before.width; arg.height = size_before.height; switch (wParam) { case WMSZ_LEFT: arg.border = window_border::left; break; case WMSZ_RIGHT: arg.border = window_border::right; break; case WMSZ_BOTTOM: arg.border = window_border::bottom; break; case WMSZ_BOTTOMLEFT: arg.border = window_border::bottom_left; break; case WMSZ_BOTTOMRIGHT: arg.border = window_border::bottom_right; break; case WMSZ_TOP: arg.border = window_border::top; break; case WMSZ_TOPLEFT: arg.border = window_border::top_left; break; case WMSZ_TOPRIGHT: arg.border = window_border::top_right; break; } brock.emit(event_code::resizing, msgwnd, arg, false, &context); if (arg.width != width || arg.height != height) { adjust_sizing(msgwnd, r, static_cast<int>(wParam), arg.width, arg.height); return TRUE; } } break; case WM_SIZE: if(wParam != SIZE_MINIMIZED) brock.wd_manager().size(msgwnd, size(pmdec.size.width, pmdec.size.height), true, true); break; case WM_MOVE: brock.event_move(msgwnd, (int)(short) LOWORD(lParam), (int)(short) HIWORD(lParam)); break; case WM_PAINT: { ::PAINTSTRUCT ps; ::BeginPaint(root_window, &ps); if (msgwnd->is_draw_through()) { msgwnd->other.attribute.root->draw_through(); } else { //Don't copy root_graph to the window directly, otherwise the edge nimbus effect will be missed. ::nana::rectangle update_area(ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right - ps.rcPaint.left, ps.rcPaint.bottom - ps.rcPaint.top); if (!update_area.empty()) msgwnd->drawer.map(reinterpret_cast<window>(msgwnd), true, &update_area); } ::EndPaint(root_window, &ps); } break; case WM_SYSCHAR: def_window_proc = true; brock.set_keyboard_shortkey(true); msgwnd = brock.wd_manager().find_shortkey(native_window, static_cast<unsigned long>(wParam)); if(msgwnd) { arg_keyboard arg; arg.evt_code = event_code::shortkey; arg.key = static_cast<wchar_t>(wParam < 0x61 ? wParam + 0x61 - 0x41 : wParam); arg.ctrl = arg.shift = false; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.ignore = false; brock.emit(event_code::shortkey, msgwnd, arg, true, &context); def_window_proc = false; } break; case WM_SYSKEYDOWN: def_window_proc = true; if (brock.whether_keyboard_shortkey() == false) { msgwnd = msgwnd->root_widget->other.attribute.root->menubar; if (msgwnd) { bool focused = (brock.focus() == msgwnd); arg_keyboard arg; arg.evt_code = event_code::key_press; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.ignore = false; arg.key = static_cast<wchar_t>(wParam); brock.get_key_state(arg); brock.emit(event_code::key_press, msgwnd, arg, true, &context); msgwnd->root_widget->flags.ignore_menubar_focus = (focused && (brock.focus() != msgwnd)); } else brock.erase_menu(true); } break; case WM_SYSKEYUP: def_window_proc = true; if(brock.set_keyboard_shortkey(false) == false) { msgwnd = msgwnd->root_widget->other.attribute.root->menubar; if(msgwnd) { //Don't call default window proc to avoid popuping system menu. def_window_proc = false; bool set_focus = (brock.focus() != msgwnd) && (!msgwnd->root_widget->flags.ignore_menubar_focus); if (set_focus) brock.wd_manager().set_focus(msgwnd, false); arg_keyboard arg; arg.evt_code = event_code::key_release; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.ignore = false; arg.key = static_cast<wchar_t>(wParam); brock.get_key_state(arg); brock.emit(event_code::key_release, msgwnd, arg, true, &context); if (!set_focus) { brock.set_menubar_taken(nullptr); msgwnd->root_widget->flags.ignore_menubar_focus = false; } } } break; case WM_KEYDOWN: if(msgwnd->flags.enabled) { auto menu_wd = brock.get_menu(); if (menu_wd) brock.delay_restore(0); //Enable delay restore if (msgwnd->root != menu_wd) msgwnd = brock.focus(); if(msgwnd) { auto & wd_manager = brock.wd_manager(); if((VK_TAB == wParam) && (!msgwnd->visible || (false == (msgwnd->flags.tab & tab_type::eating)))) //Tab { bool is_forward = (::GetKeyState(VK_SHIFT) >= 0); auto tstop_wd = wd_manager.tabstop(msgwnd, is_forward); if (tstop_wd) { wd_manager.set_focus(tstop_wd, false); wd_manager.do_lazy_refresh(msgwnd, false); wd_manager.do_lazy_refresh(tstop_wd, true); } } else if ((VK_SPACE == wParam) && msgwnd->flags.space_click_enabled) { //Clicked by spacebar if (nullptr == pressed_wd && nullptr == pressed_wd_space) { arg_mouse arg; arg.alt = false; arg.button = ::nana::mouse::left_button; arg.ctrl = false; arg.evt_code = event_code::mouse_down; arg.left_button = true; arg.mid_button = false; arg.pos.x = 0; arg.pos.y = 0; arg.window_handle = reinterpret_cast<window>(msgwnd); msgwnd->flags.action = mouse_action::pressed; pressed_wd_space = msgwnd; auto retain = msgwnd->together.events_ptr; emit_drawer(&drawer::mouse_down, msgwnd, arg, &context); wd_manager.do_lazy_refresh(msgwnd, false); } } else { arg_keyboard arg; arg.evt_code = event_code::key_press; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.ignore = false; arg.key = static_cast<wchar_t>(wParam); brock.get_key_state(arg); brock.emit(event_code::key_press, msgwnd, arg, true, &context); if (msgwnd->root_widget->other.attribute.root->menubar == msgwnd) { //In order to keep the focus on the menubar, cancel the delay_restore //when pressing ESC to close the menu which is popuped by the menubar. //If no menu popuped by the menubar, it should enable delay restore to //restore the focus for taken window. int cmd = (menu_wd && (keyboard::escape == static_cast<wchar_t>(wParam)) ? 1 : 0); brock.delay_restore(cmd); } } } } break; case WM_CHAR: msgwnd = brock.focus(); if (msgwnd && msgwnd->flags.enabled) { // When tab is pressed, only tab-eating mode is allowed if ((9 != wParam) || (msgwnd->flags.tab & tab_type::eating)) { arg_keyboard arg; arg.evt_code = event_code::key_char; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.key = static_cast<wchar_t>(wParam); brock.get_key_state(arg); arg.ignore = false; msgwnd->together.events_ptr->key_char.emit(arg); if ((false == arg.ignore) && brock.wd_manager().available(msgwnd)) brock.emit_drawer(event_code::key_char, msgwnd, arg, &context); brock.wd_manager().do_lazy_refresh(msgwnd, false); } } return 0; case WM_KEYUP: if(wParam != VK_MENU) //MUST NOT BE AN ALT { msgwnd = brock.focus(); if(msgwnd) { if (msgwnd == pressed_wd_space) { msgwnd->flags.action = mouse_action::normal; arg_click click_arg; click_arg.mouse_args = nullptr; click_arg.window_handle = reinterpret_cast<window>(msgwnd); auto retain = msgwnd->together.events_ptr; if (brock.emit(event_code::click, msgwnd, click_arg, true, &context)) { arg_mouse arg; arg.alt = false; arg.button = ::nana::mouse::left_button; arg.ctrl = false; arg.evt_code = event_code::mouse_up; arg.left_button = true; arg.mid_button = false; arg.pos.x = 0; arg.pos.y = 0; arg.window_handle = reinterpret_cast<window>(msgwnd); emit_drawer(&drawer::mouse_up, msgwnd, arg, &context); brock.wd_manager().do_lazy_refresh(msgwnd, false); } pressed_wd_space = nullptr; } else { arg_keyboard arg; arg.evt_code = event_code::key_release; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.key = static_cast<wchar_t>(wParam); brock.get_key_state(arg); arg.ignore = false; brock.emit(event_code::key_release, msgwnd, arg, true, &context); } } } else brock.set_keyboard_shortkey(false); //Do delay restore if key is not arrow_left/right/up/down, otherwise //A menubar will be restored if the item is empty(not have a menu item) if (wParam < 37 || 40 < wParam) brock.delay_restore(2); //Restores while key release break; case WM_CLOSE: { arg_unload arg; arg.window_handle = reinterpret_cast<window>(msgwnd); arg.cancel = false; brock.emit(event_code::unload, msgwnd, arg, true, &context); if (!arg.cancel) { def_window_proc = true; //Activate is owner, refer to the window_manager::close for the explaination if (msgwnd->flags.modal || (msgwnd->owner == 0) || msgwnd->owner->flags.take_active) native_interface::activate_owner(msgwnd->root); } break; } case WM_DESTROY: if (msgwnd->root == brock.get_menu()) { brock.erase_menu(false); brock.delay_restore(3); //Restores if delay_restore not decleared } brock.wd_manager().destroy(msgwnd); nana::detail::platform_spec::instance().release_window_icon(msgwnd->root); break; case WM_NCDESTROY: brock.manage_form_loader(msgwnd, false); brock.wd_manager().destroy_handle(msgwnd); if(--context.window_count <= 0) { ::PostQuitMessage(0); def_window_proc = true; } break; default: def_window_proc = true; } root_runtime = brock.wd_manager().root_runtime(native_window); if(root_runtime) { root_runtime->condition.pressed = pressed_wd; root_runtime->condition.hovered = hovered_wd; root_runtime->condition.pressed_by_space = pressed_wd_space; } if (!def_window_proc) return 0; } return ::DefWindowProc(root_window, message, wParam, lParam); } ::nana::category::flags bedrock::category(core_window_t* wd) { internal_scope_guard lock; return (wd_manager().available(wd) ? wd->other.category : ::nana::category::flags::super); } auto bedrock::focus() ->core_window_t* { core_window_t* wd = wd_manager().root(native_interface::get_focus_window()); return (wd ? wd->other.attribute.root->focus : nullptr); } void bedrock::set_menubar_taken(core_window_t* wd) { auto pre = impl_->menu.taken_window; impl_->menu.taken_window = wd; //assigning of a nullptr taken window is to restore the focus of pre taken //don't restore the focus if pre is a menu. if ((!wd) && pre && (pre->root != get_menu())) { internal_scope_guard lock; wd_manager().set_focus(pre, false); wd_manager().update(pre, true, false); } } //0:Enable delay, 1:Cancel, 2:Restores, 3: Restores when menu is destroying void bedrock::delay_restore(int state) { switch (state) { case 0: //Enable break; case 1: //Cancel break; case 2: //Restore if key released //restores the focus when menu is closed by pressing keyboard if ((!impl_->menu.window) && impl_->menu.delay_restore) set_menubar_taken(nullptr); break; case 3: //Restores if destroying //when the menu is destroying, restores the focus if delay restore is not declared if (!impl_->menu.delay_restore) set_menubar_taken(nullptr); } impl_->menu.delay_restore = (0 == state); } bool bedrock::close_menu_if_focus_other_window(native_window_type wd) { if(impl_->menu.window && (impl_->menu.window != wd)) { wd = native_interface::get_owner_window(wd); while(wd) { if(wd != impl_->menu.window) wd = native_interface::get_owner_window(wd); else return false; } erase_menu(true); return true; } return false; } void bedrock::set_menu(native_window_type menu_wd, bool has_keyboard) { if(menu_wd && impl_->menu.window != menu_wd) { erase_menu(true); impl_->menu.window = menu_wd; impl_->menu.owner = native_interface::get_owner_window(menu_wd); impl_->menu.has_keyboard = has_keyboard; } } native_window_type bedrock::get_menu(native_window_type owner, bool is_keyboard_condition) { if( (impl_->menu.owner == nullptr) || (owner && (impl_->menu.owner == owner)) ) { return ((!is_keyboard_condition) || impl_->menu.has_keyboard ? impl_->menu.window : nullptr); } return nullptr; } native_window_type bedrock::get_menu() { return impl_->menu.window; } void bedrock::erase_menu(bool try_destroy) { if (impl_->menu.window) { if (try_destroy) native_interface::close_window(impl_->menu.window); impl_->menu.window = impl_->menu.owner = nullptr; impl_->menu.has_keyboard = false; } } void bedrock::get_key_state(arg_keyboard& kb) { kb.ctrl = (0 != (::GetKeyState(VK_CONTROL) & 0x80)); kb.shift = (0 != (::GetKeyState(VK_SHIFT) & 0x80)); } bool bedrock::set_keyboard_shortkey(bool yes) { bool ret = impl_->keyboard_tracking_state.has_shortkey_occured; impl_->keyboard_tracking_state.has_shortkey_occured = yes; return ret; } bool bedrock::whether_keyboard_shortkey() const { return impl_->keyboard_tracking_state.has_shortkey_occured; } element_store& bedrock::get_element_store() const { return impl_->estore; } void bedrock::map_through_widgets(core_window_t* wd, native_drawable_type drawable) { #if defined(NANA_WINDOWS) auto graph_context = reinterpret_cast<HDC>(wd->root_graph->handle()->context); for (auto child : wd->children) { if (!child->visible) continue; if (::nana::category::flags::widget == child->other.category) { ::BitBlt(reinterpret_cast<HDC>(drawable), child->pos_root.x, child->pos_root.y, static_cast<int>(child->dimension.width), static_cast<int>(child->dimension.height), graph_context, child->pos_root.x, child->pos_root.y, SRCCOPY); } else if (::nana::category::flags::lite_widget == child->other.category) map_through_widgets(child, drawable); } #endif } bool bedrock::emit(event_code evt_code, core_window_t* wd, const ::nana::event_arg& arg, bool ask_update, thread_context* thrd) { if (wd_manager().available(wd) == false) return false; basic_window* prev_event_wd; if (thrd) { prev_event_wd = thrd->event_window; thrd->event_window = wd; _m_event_filter(evt_code, wd, thrd); } if (wd->other.upd_state == core_window_t::update_state::none) wd->other.upd_state = core_window_t::update_state::lazy; _m_emit_core(evt_code, wd, false, arg); if (ask_update) wd_manager().do_lazy_refresh(wd, false); else if (wd_manager().available(wd)) wd->other.upd_state = basic_window::update_state::none; if (thrd) thrd->event_window = prev_event_wd; return true; } bool bedrock::emit_drawer(event_code evt_code, core_window_t* wd, const ::nana::event_arg& arg, thread_context* thrd) { if (bedrock_object.wd_manager().available(wd) == false) return false; core_window_t* prev_event_wd; if (thrd) { prev_event_wd = thrd->event_window; thrd->event_window = wd; } if (wd->other.upd_state == core_window_t::update_state::none) wd->other.upd_state = core_window_t::update_state::lazy; _m_emit_core(evt_code, wd, true, arg); if (thrd) thrd->event_window = prev_event_wd; return true; } const wchar_t* translate(cursor id) { const wchar_t* name = IDC_ARROW; switch(id) { case cursor::arrow: name = IDC_ARROW; break; case cursor::wait: name = IDC_WAIT; break; case cursor::hand: name = IDC_HAND; break; case cursor::size_we: name = IDC_SIZEWE; break; case cursor::size_ns: name = IDC_SIZENS; break; case cursor::size_bottom_left: case cursor::size_top_right: name = IDC_SIZENESW; break; case cursor::size_top_left: case cursor::size_bottom_right: name = IDC_SIZENWSE; break; case cursor::iterm: name = IDC_IBEAM; break; } return name; } void bedrock::thread_context_destroy(core_window_t * wd) { auto * thr = get_thread_context(0); if (thr && thr->event_window == wd) thr->event_window = nullptr; } void bedrock::thread_context_lazy_refresh() { auto* thrd = get_thread_context(0); if (thrd && thrd->event_window) { //the state none should be tested, becuase in an event, there would be draw after an update, //if the none is not tested, the draw after update will not be refreshed. switch (thrd->event_window->other.upd_state) { case core_window_t::update_state::none: case core_window_t::update_state::lazy: thrd->event_window->other.upd_state = core_window_t::update_state::refresh; default: break; } } } //Dynamically set a cursor for a window void bedrock::set_cursor(core_window_t* wd, nana::cursor cur, thread_context* thrd) { if (nullptr == thrd) thrd = get_thread_context(wd->thread_id); if ((cursor::arrow == cur) && !thrd->cursor.native_handle) return; thrd->cursor.window = wd; if ((thrd->cursor.native_handle == wd->root) && (cur == thrd->cursor.predef_cursor)) return; thrd->cursor.native_handle = wd->root; if (thrd->cursor.predef_cursor != cur) { thrd->cursor.predef_cursor = cur; thrd->cursor.handle = ::LoadCursor(nullptr, translate(cur)); } if (wd->root_widget->other.attribute.root->running_cursor != cur) { wd->root_widget->other.attribute.root->running_cursor = cur; #ifdef _WIN64 ::SetClassLongPtr(reinterpret_cast<HWND>(wd->root), GCLP_HCURSOR, reinterpret_cast<LONG_PTR>(thrd->cursor.handle)); #else ::SetClassLong(reinterpret_cast<HWND>(wd->root), GCL_HCURSOR, static_cast<unsigned long>(reinterpret_cast<size_t>(thrd->cursor.handle))); #endif } if (cursor::arrow == thrd->cursor.predef_cursor) { thrd->cursor.window = nullptr; thrd->cursor.native_handle = nullptr; } } void bedrock::define_state_cursor(core_window_t* wd, nana::cursor cur, thread_context* thrd) { wd->root_widget->other.attribute.root->state_cursor = cur; wd->root_widget->other.attribute.root->state_cursor_window = wd; set_cursor(wd, cur, thrd); auto cur_handle = ::LoadCursor(nullptr, translate(cur)); ::SetCursor(cur_handle); ::ShowCursor(TRUE); } void bedrock::undefine_state_cursor(core_window_t * wd, thread_context* thrd) { if (nullptr == thrd) thrd = get_thread_context(wd->thread_id); HCURSOR rev_handle = ::LoadCursor(nullptr, IDC_ARROW); if (!wd_manager().available(wd)) { ::ShowCursor(FALSE); ::SetCursor(rev_handle); return; } wd->root_widget->other.attribute.root->state_cursor = nana::cursor::arrow; wd->root_widget->other.attribute.root->state_cursor_window = nullptr; auto pos = native_interface::cursor_position(); auto native_handle = native_interface::find_window(pos.x, pos.y); if (!native_handle) { ::ShowCursor(FALSE); ::SetCursor(rev_handle); return; } native_interface::calc_window_point(native_handle, pos); auto rev_wd = wd_manager().find_window(native_handle, pos.x, pos.y); if (rev_wd) { set_cursor(rev_wd, rev_wd->predef_cursor, thrd); rev_handle = thrd->cursor.handle; } ::ShowCursor(FALSE); ::SetCursor(rev_handle); } void bedrock::_m_event_filter(event_code event_id, core_window_t * wd, thread_context * thrd) { auto not_state_cur = (wd->root_widget->other.attribute.root->state_cursor == nana::cursor::arrow); switch(event_id) { case event_code::mouse_enter: if (not_state_cur) set_cursor(wd, wd->predef_cursor, thrd); break; case event_code::mouse_leave: if (not_state_cur && (wd->predef_cursor != cursor::arrow)) set_cursor(wd, cursor::arrow, thrd); break; case event_code::destroy: if (wd->root_widget->other.attribute.root->state_cursor_window == wd) undefine_state_cursor(wd, thrd); if(wd == thrd->cursor.window) { set_cursor(wd, cursor::arrow, thrd); wd->root_widget->other.attribute.root->running_cursor = cursor::arrow; } break; default: break; } } }//end namespace detail }//end namespace nana #endif //NANA_WINDOWS
[ "kmc5500@naver.com" ]
kmc5500@naver.com
9b40cbbd0921d0e34aab20194738a6cb0f92ef0b
6c3a03b9f1316b60c0ea9dd70e8b521c92ea197d
/include/glm/detail/func_integer.inl
c71a49cc4a7b265394db0432afe57df2b6564a9d
[]
no_license
DarkTong/OpenGL
2e52effc42c4deea20454c109607ac31f1604cf0
bc28e9be4f03633667992d24f82af3d03e21b078
refs/heads/master
2021-01-19T23:06:48.482773
2017-05-08T06:37:33
2017-05-08T06:37:33
88,926,003
0
0
null
null
null
null
UTF-8
C++
false
false
16,742
inl
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// /// @ref core /// @file glm/core/func_integer.inl /// @date 2010-03-17 / 2011-06-15 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// #include "type_vec2.hpp" #include "type_vec3.hpp" #include "type_vec4.hpp" #include "type_int.hpp" #include "_vectorize.hpp" #if(GLM_ARCH != GLM_ARCH_PURE) #if(GLM_COMPILER & GLM_COMPILER_VC) # include <intrin.h> # pragma intrinsic(_BitScanReverse) #endif//(GLM_COMPILER & GLM_COMPILER_VC) #endif//(GLM_ARCH != GLM_ARCH_PURE) #include <limits> namespace glm { // uaddCarry template <> GLM_FUNC_QUALIFIER uint uaddCarry ( uint const & x, uint const & y, uint & Carry ) { uint64 Value64 = static_cast<uint64>(x) + static_cast<uint64>(y); uint32 Result = static_cast<uint32>(Value64 % (static_cast<uint64>(1) << static_cast<uint64>(32))); Carry = (Value64 % (static_cast<uint64>(1) << static_cast<uint64>(32))) > 1 ? static_cast<uint32>(1) : static_cast<uint32>(0); return Result; } template <> GLM_FUNC_QUALIFIER uvec2 uaddCarry ( uvec2 const & x, uvec2 const & y, uvec2 & Carry ) { return uvec2( uaddCarry(x[0], y[0], Carry[0]), uaddCarry(x[1], y[1], Carry[1])); } template <> GLM_FUNC_QUALIFIER uvec3 uaddCarry ( uvec3 const & x, uvec3 const & y, uvec3 & Carry ) { return uvec3( uaddCarry(x[0], y[0], Carry[0]), uaddCarry(x[1], y[1], Carry[1]), uaddCarry(x[2], y[2], Carry[2])); } template <> GLM_FUNC_QUALIFIER uvec4 uaddCarry ( uvec4 const & x, uvec4 const & y, uvec4 & Carry ) { return uvec4( uaddCarry(x[0], y[0], Carry[0]), uaddCarry(x[1], y[1], Carry[1]), uaddCarry(x[2], y[2], Carry[2]), uaddCarry(x[3], y[3], Carry[3])); } // usubBorrow template <> GLM_FUNC_QUALIFIER uint usubBorrow ( uint const & x, uint const & y, uint & Borrow ) { GLM_STATIC_ASSERT(sizeof(uint) == sizeof(uint32), "uint and uint32 size mismatch"); Borrow = x >= y ? static_cast<uint32>(0) : static_cast<uint32>(1); if(y >= x) return y - x; else return static_cast<uint32>((static_cast<int64>(1) << static_cast<int64>(32)) + (static_cast<int64>(y) - static_cast<int64>(x))); } template <> GLM_FUNC_QUALIFIER uvec2 usubBorrow ( uvec2 const & x, uvec2 const & y, uvec2 & Borrow ) { return uvec2( usubBorrow(x[0], y[0], Borrow[0]), usubBorrow(x[1], y[1], Borrow[1])); } template <> GLM_FUNC_QUALIFIER uvec3 usubBorrow ( uvec3 const & x, uvec3 const & y, uvec3 & Borrow ) { return uvec3( usubBorrow(x[0], y[0], Borrow[0]), usubBorrow(x[1], y[1], Borrow[1]), usubBorrow(x[2], y[2], Borrow[2])); } template <> GLM_FUNC_QUALIFIER uvec4 usubBorrow ( uvec4 const & x, uvec4 const & y, uvec4 & Borrow ) { return uvec4( usubBorrow(x[0], y[0], Borrow[0]), usubBorrow(x[1], y[1], Borrow[1]), usubBorrow(x[2], y[2], Borrow[2]), usubBorrow(x[3], y[3], Borrow[3])); } // umulExtended template <> GLM_FUNC_QUALIFIER void umulExtended ( uint const & x, uint const & y, uint & msb, uint & lsb ) { GLM_STATIC_ASSERT(sizeof(uint) == sizeof(uint32), "uint and uint32 size mismatch"); uint64 Value64 = static_cast<uint64>(x) * static_cast<uint64>(y); uint32* PointerMSB = (reinterpret_cast<uint32*>(&Value64) + 1); msb = *PointerMSB; uint32* PointerLSB = (reinterpret_cast<uint32*>(&Value64) + 0); lsb = *PointerLSB; } template <> GLM_FUNC_QUALIFIER void umulExtended ( uvec2 const & x, uvec2 const & y, uvec2 & msb, uvec2 & lsb ) { umulExtended(x[0], y[0], msb[0], lsb[0]); umulExtended(x[1], y[1], msb[1], lsb[1]); } template <> GLM_FUNC_QUALIFIER void umulExtended ( uvec3 const & x, uvec3 const & y, uvec3 & msb, uvec3 & lsb ) { umulExtended(x[0], y[0], msb[0], lsb[0]); umulExtended(x[1], y[1], msb[1], lsb[1]); umulExtended(x[2], y[2], msb[2], lsb[2]); } template <> GLM_FUNC_QUALIFIER void umulExtended ( uvec4 const & x, uvec4 const & y, uvec4 & msb, uvec4 & lsb ) { umulExtended(x[0], y[0], msb[0], lsb[0]); umulExtended(x[1], y[1], msb[1], lsb[1]); umulExtended(x[2], y[2], msb[2], lsb[2]); umulExtended(x[3], y[3], msb[3], lsb[3]); } // imulExtended template <> GLM_FUNC_QUALIFIER void imulExtended ( int const & x, int const & y, int & msb, int & lsb ) { GLM_STATIC_ASSERT(sizeof(int) == sizeof(int32), "int and int32 size mismatch"); int64 Value64 = static_cast<int64>(x) * static_cast<int64>(y); int32* PointerMSB = (reinterpret_cast<int32*>(&Value64) + 1); msb = *PointerMSB; int32* PointerLSB = (reinterpret_cast<int32*>(&Value64)); lsb = *PointerLSB; } template <> GLM_FUNC_QUALIFIER void imulExtended ( ivec2 const & x, ivec2 const & y, ivec2 & msb, ivec2 & lsb ) { imulExtended(x[0], y[0], msb[0], lsb[0]), imulExtended(x[1], y[1], msb[1], lsb[1]); } template <> GLM_FUNC_QUALIFIER void imulExtended ( ivec3 const & x, ivec3 const & y, ivec3 & msb, ivec3 & lsb ) { imulExtended(x[0], y[0], msb[0], lsb[0]), imulExtended(x[1], y[1], msb[1], lsb[1]); imulExtended(x[2], y[2], msb[2], lsb[2]); } template <> GLM_FUNC_QUALIFIER void imulExtended ( ivec4 const & x, ivec4 const & y, ivec4 & msb, ivec4 & lsb ) { imulExtended(x[0], y[0], msb[0], lsb[0]), imulExtended(x[1], y[1], msb[1], lsb[1]); imulExtended(x[2], y[2], msb[2], lsb[2]); imulExtended(x[3], y[3], msb[3], lsb[3]); } // bitfieldExtract template <typename genIUType> GLM_FUNC_QUALIFIER genIUType bitfieldExtract ( genIUType const & Value, int const & Offset, int const & Bits ) { int GenSize = int(sizeof(genIUType)) << int(3); assert(Offset + Bits <= GenSize); genIUType ShiftLeft = Bits ? Value << (GenSize - (Bits + Offset)) : genIUType(0); genIUType ShiftBack = ShiftLeft >> genIUType(GenSize - Bits); return ShiftBack; } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec2<T, P> bitfieldExtract ( detail::tvec2<T, P> const & Value, int const & Offset, int const & Bits ) { return detail::tvec2<T, P>( bitfieldExtract(Value[0], Offset, Bits), bitfieldExtract(Value[1], Offset, Bits)); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec3<T, P> bitfieldExtract ( detail::tvec3<T, P> const & Value, int const & Offset, int const & Bits ) { return detail::tvec3<T, P>( bitfieldExtract(Value[0], Offset, Bits), bitfieldExtract(Value[1], Offset, Bits), bitfieldExtract(Value[2], Offset, Bits)); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec4<T, P> bitfieldExtract ( detail::tvec4<T, P> const & Value, int const & Offset, int const & Bits ) { return detail::tvec4<T, P>( bitfieldExtract(Value[0], Offset, Bits), bitfieldExtract(Value[1], Offset, Bits), bitfieldExtract(Value[2], Offset, Bits), bitfieldExtract(Value[3], Offset, Bits)); } // bitfieldInsert template <typename genIUType> GLM_FUNC_QUALIFIER genIUType bitfieldInsert ( genIUType const & Base, genIUType const & Insert, int const & Offset, int const & Bits ) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'bitfieldInsert' only accept integer values"); assert(Offset + Bits <= sizeof(genIUType)); if(Bits == 0) return Base; genIUType Mask = 0; for(int Bit = Offset; Bit < Offset + Bits; ++Bit) Mask |= (1 << Bit); return (Base & ~Mask) | (Insert & Mask); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec2<T, P> bitfieldInsert ( detail::tvec2<T, P> const & Base, detail::tvec2<T, P> const & Insert, int const & Offset, int const & Bits ) { return detail::tvec2<T, P>( bitfieldInsert(Base[0], Insert[0], Offset, Bits), bitfieldInsert(Base[1], Insert[1], Offset, Bits)); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec3<T, P> bitfieldInsert ( detail::tvec3<T, P> const & Base, detail::tvec3<T, P> const & Insert, int const & Offset, int const & Bits ) { return detail::tvec3<T, P>( bitfieldInsert(Base[0], Insert[0], Offset, Bits), bitfieldInsert(Base[1], Insert[1], Offset, Bits), bitfieldInsert(Base[2], Insert[2], Offset, Bits)); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec4<T, P> bitfieldInsert ( detail::tvec4<T, P> const & Base, detail::tvec4<T, P> const & Insert, int const & Offset, int const & Bits ) { return detail::tvec4<T, P>( bitfieldInsert(Base[0], Insert[0], Offset, Bits), bitfieldInsert(Base[1], Insert[1], Offset, Bits), bitfieldInsert(Base[2], Insert[2], Offset, Bits), bitfieldInsert(Base[3], Insert[3], Offset, Bits)); } // bitfieldReverse template <typename genIUType> GLM_FUNC_QUALIFIER genIUType bitfieldReverse(genIUType const & Value) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'bitfieldReverse' only accept integer values"); genIUType Out = 0; std::size_t BitSize = sizeof(genIUType) * 8; for(std::size_t i = 0; i < BitSize; ++i) if(Value & (genIUType(1) << i)) Out |= genIUType(1) << (BitSize - 1 - i); return Out; } VECTORIZE_VEC(bitfieldReverse) // bitCount template <typename genIUType> GLM_FUNC_QUALIFIER int bitCount(genIUType const & Value) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'bitCount' only accept integer values"); int Count = 0; for(std::size_t i = 0; i < sizeof(genIUType) * std::size_t(8); ++i) { if(Value & (1 << i)) ++Count; } return Count; } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec2<int, P> bitCount ( detail::tvec2<T, P> const & value ) { return detail::tvec2<int, P>( bitCount(value[0]), bitCount(value[1])); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec3<int, P> bitCount ( detail::tvec3<T, P> const & value ) { return detail::tvec3<int, P>( bitCount(value[0]), bitCount(value[1]), bitCount(value[2])); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec4<int, P> bitCount ( detail::tvec4<T, P> const & value ) { return detail::tvec4<int, P>( bitCount(value[0]), bitCount(value[1]), bitCount(value[2]), bitCount(value[3])); } // findLSB template <typename genIUType> GLM_FUNC_QUALIFIER int findLSB ( genIUType const & Value ) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'findLSB' only accept integer values"); if(Value == 0) return -1; genIUType Bit; for(Bit = genIUType(0); !(Value & (1 << Bit)); ++Bit) {} return Bit; } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec2<int, P> findLSB ( detail::tvec2<T, P> const & value ) { return detail::tvec2<int, P>( findLSB(value[0]), findLSB(value[1])); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec3<int, P> findLSB ( detail::tvec3<T, P> const & value ) { return detail::tvec3<int, P>( findLSB(value[0]), findLSB(value[1]), findLSB(value[2])); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec4<int, P> findLSB ( detail::tvec4<T, P> const & value ) { return detail::tvec4<int, P>( findLSB(value[0]), findLSB(value[1]), findLSB(value[2]), findLSB(value[3])); } // findMSB #if((GLM_ARCH != GLM_ARCH_PURE) && (GLM_COMPILER & GLM_COMPILER_VC)) template <typename genIUType> GLM_FUNC_QUALIFIER int findMSB ( genIUType const & Value ) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'findMSB' only accept integer values"); if(Value == 0) return -1; unsigned long Result(0); _BitScanReverse(&Result, Value); return int(Result); } /* // __builtin_clz seems to be buggy as it crasks for some values, from 0x00200000 to 80000000 #elif((GLM_ARCH != GLM_ARCH_PURE) && (GLM_COMPILER & GLM_COMPILER_GCC) && (GLM_COMPILER >= GLM_COMPILER_GCC40)) template <typename genIUType> GLM_FUNC_QUALIFIER int findMSB ( genIUType const & Value ) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'findMSB' only accept integer values"); if(Value == 0) return -1; // clz returns the number or trailing 0-bits; see // http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Other-Builtins.html // // NoteBecause __builtin_clz only works for unsigned ints, this // implementation will not work for 64-bit integers. // return 31 - __builtin_clzl(Value); } */ #else /* SSE implementation idea __m128i const Zero = _mm_set_epi32( 0, 0, 0, 0); __m128i const One = _mm_set_epi32( 1, 1, 1, 1); __m128i Bit = _mm_set_epi32(-1, -1, -1, -1); __m128i Tmp = _mm_set_epi32(Value, Value, Value, Value); __m128i Mmi = Zero; for(int i = 0; i < 32; ++i) { __m128i Shilt = _mm_and_si128(_mm_cmpgt_epi32(Tmp, One), One); Tmp = _mm_srai_epi32(Tmp, One); Bit = _mm_add_epi32(Bit, _mm_and_si128(Shilt, i)); Mmi = _mm_and_si128(Mmi, One); } return Bit; */ template <typename genIUType> GLM_FUNC_QUALIFIER int findMSB ( genIUType const & Value ) { GLM_STATIC_ASSERT(std::numeric_limits<genIUType>::is_integer, "'findMSB' only accept integer values"); if(Value == genIUType(0) || Value == genIUType(-1)) return -1; else if(Value > 0) { genIUType Bit = genIUType(-1); for(genIUType tmp = Value; tmp > 0; tmp >>= 1, ++Bit) {} return Bit; } else //if(Value < 0) { int const BitCount(sizeof(genIUType) * 8); int MostSignificantBit(-1); for(int BitIndex(0); BitIndex < BitCount; ++BitIndex) MostSignificantBit = (Value & (1 << BitIndex)) ? MostSignificantBit : BitIndex; assert(MostSignificantBit >= 0); return MostSignificantBit; } } #endif//(GLM_COMPILER) template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec2<int, P> findMSB ( detail::tvec2<T, P> const & value ) { return detail::tvec2<int, P>( findMSB(value[0]), findMSB(value[1])); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec3<int, P> findMSB ( detail::tvec3<T, P> const & value ) { return detail::tvec3<int, P>( findMSB(value[0]), findMSB(value[1]), findMSB(value[2])); } template <typename T, precision P> GLM_FUNC_QUALIFIER detail::tvec4<int, P> findMSB ( detail::tvec4<T, P> const & value ) { return detail::tvec4<int, P>( findMSB(value[0]), findMSB(value[1]), findMSB(value[2]), findMSB(value[3])); } }//namespace glm
[ "13427508433@163.com" ]
13427508433@163.com
0cd5934f11bc977dcfa05ed3c944fcc9f8d450da
d2beaa00e5f5dd514b862d6bad385596746bebdc
/MPalabrados2/src/main.cpp
6787cb6dad630f134fa5fceaf6a529b75746f17b
[]
no_license
Agumeri/MP-2020
4960c217febec2fbb2d9921046feebac1ad0880f
344eedd69e078332cfaf32f8d67b76dac3e43dd1
refs/heads/master
2022-04-27T09:50:12.581905
2020-04-27T19:05:28
2020-04-27T19:05:28
258,991,157
0
0
null
null
null
null
UTF-8
C++
false
false
3,212
cpp
/** * @file main.cpp * @author DECSAI * @note To be implemented by students either completely or by giving them * key functions prototipes to guide the implementation */ #include <string> #include <iostream> #include "mi_random.h" #include "language.h" #include "bag.h" #include "player.h" ///@warning complete missing #includes using namespace std; /** * @brief Shows final data * @param l Language * @param random Random seed * @param b Final bag * @param p Final player * @param nwords Number of words found * @param score Number of letters found * @param result Aggregation of all valid words found */ void HallOfFame(const Language &l, int random, const Bag &b, const Player &p, int nwords, int score, const string &result); /** * @brief Main function. * @return */ int main() { int Id; /// To be used in bag.setRandom()) Bag bag; /// Bag of letters Player player; /// Player set of letters string lang; /// Language to be loaded from disk string result, palabra; /// String that contains all the words found int nletters, /// Number of letters found nwords; /// Number of words found bool extraer = false, rendirse = false; cout << "TYPE LANGUAGE: "; cin >> lang; Language language(lang); cout << "ALLOWED LETTERS: " << toUTF(language.getLetterSet()) <<endl; cout << "TYPE SEED (<0 RANDOM): "; cin >> Id; bag.setRandom(Id); bag.define(language); player.add(bag.extract(7)); cout << "BAG ("<<bag.size()<<") : "<<toUTF(bag.to_string())<< endl; cout << "-----COMIENZA EL JUEGO-----(Escribe rendirse para terminar)" << endl; while(bag.size()>0 && !rendirse){ cout << "\nPLAYER: "<< toUTF(player.to_string()) << " BAG(" <<bag.size() << ")" << endl; cout << "\nEscribe una palabra posible: " ; cin >> palabra; if(palabra != "rendirse"){ if(player.isValid(palabra)){ if(language.query(palabra)){ cout << palabra << " es una palabra valida, y se ha extraido,continua con el juego" << endl; nwords++; result += palabra+"-"; extraer = true; } if(extraer){ player.extract(palabra); player.add(bag.extract(7-player.size())); extraer = false; } } }else{ rendirse = true; } } cout << "\n-----FIN DEL JUEGO-----" << endl; cout << "R E S U L T A D O S" << endl; HallOfFame(language,Id,bag,player, nwords, nletters, result); return 0; } void HallOfFame(const Language &l, int random, const Bag &b, const Player &p, int nwords, int score, const string &result) { cout << endl << "LANGUAGE: "<<l.getLanguage()<< " ID: " << random << endl; cout << "BAG ("<<b.size()<<"): " << toUTF(b.to_string()) << endl; cout << "PLAYER (" <<p.size() << "): " << toUTF(p.to_string())<<endl; cout << nwords << " words and " << score << " letters "<<endl << toUTF(result) << endl; }
[ "agumeri003@outlook.com" ]
agumeri003@outlook.com
5db25d958f20b8d598bc30fbd3363b064ac79afb
6fb27f2b8d5dcec339f661f037fe9a58b359c696
/Program3/LoanShark.cpp
130012e516d2a0a37c47a646e64887ba6bae79bd
[]
no_license
JoshAnderson4201/ObjectOrientedExamples
1c0cb83c21473b116b7eefc4a326206015070905
896980ff848643cff8db9230c62f6ef222f6446f
refs/heads/master
2021-04-15T10:41:21.559480
2018-03-26T17:43:51
2018-03-26T17:43:51
126,866,374
0
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
/* Josh Anderson LoanShark.cpp */ #include "PlayerClass.h" #include "Agent.h" #include "LoanShark.h" #include "rank.h" #include<vector> #include<map> #include <fstream> #include <iostream> #include <cstddef> const string LoanShark::TYPE = "LOANSHARK"; int LoanShark::DICE[GameSpace::NUM_ROLL_TYPE][3] = { //Rage {2,6,0}, //Max Speed {1,6,3}, //Willpower {1,6,6}, //physDam {1,3,0}, //Defense {2,4,2}}; LoanShark::LoanShark(): Criminal("LoanShark", LoanShark::DICE) { cout << "DEF_LoanShark" << endl; } LoanShark::LoanShark(string initName): Criminal(initName, LoanShark::DICE) { cout << "PARAM_LoanShark" << endl; } string LoanShark::Type_Str() { return TYPE; } void LoanShark::Write(ostream& out) const { out << TYPE << "#"; Criminal::Write(out); }
[ "joshanderson4201@gmail.com" ]
joshanderson4201@gmail.com
c7bbb6d3b348716969eb91de9a63cde5bc61d890
5a90b7b9cccda65b7e2c8e443ea4d2f2910853e3
/HW1_Final/Party.h
b45c6cd1c48da5347371e57a20b2f359cbc2ea51
[]
no_license
Idokah/CPP-HW1
6c55ebc89b0a9de48d3a007a9e4f9f78ca472ef7
dde60724b64d4184e65fe805674af9ce1f7c53ff
refs/heads/master
2023-02-06T06:49:04.432235
2020-12-19T15:54:26
2020-12-19T15:54:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
h
#pragma once #include "Citizen.h" #include "List/CitizenList.h" #include <iostream> using namespace std; class Party { public: Party(); Party(char* name, Citizen* head); Party(const Party& other); ~Party(); int getID() const; void addRepresentive(const int districtId, Citizen* newRepresentive); void operator=(const Party& other); Citizen* getPartyHead(); char* getName(); char* getName() const; char* getPartyHeadName() const; void printNRepresantive(const int districtID,const int n); ////prints the first n represantives of the party in district - districtID int getNumberOfVotes(); void increaseNumberOfVotes(); void increaseNumberOfWinningRepresentives(const int n); int getNumberOfWinningRepresantives(); friend ostream& operator<<(ostream&, const Party&); private: char* name; Citizen* partyHead; int id; CitizenList* representivesArr; int sizeRepresentivesArr; int generateID(); void increaseArrSize(const int newSize); int numberOfVotes; int numberOfWinningRepresantives; };
[ "idokh@mta.ac.il" ]
idokh@mta.ac.il
e40dc5ae90dd4a876cb90b38afe90e04cd6041ab
89f251b2a2552dfacfa3decdd37ad594e289b467
/engine/source/2d/sceneobject/SceneObject.h
8d9273b04db9a3c638c001a3a7fd395f50683c6c
[]
no_license
NovaVirtus/Torque2D-NV1
d324e5120d8f841cb9c7d184e9968f09968ccea6
294983771a97a70b72088b6115c104fdf4e78545
refs/heads/master
2021-01-24T02:39:17.037578
2016-04-25T03:02:42
2016-04-25T03:02:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
48,740
h
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #ifndef _SCENE_OBJECT_H_ #define _SCENE_OBJECT_H_ #ifndef _SCENE_H_ #include "2d/scene/Scene.h" #endif #ifndef _DEBUG_STATS_H_ #include "2d/scene/DebugStats.h" #endif #ifndef _SIMBASE_H_ #include "sim/simBase.h" #endif #ifndef _MMATH_H_ #include "math/mMath.h" #endif #ifndef _SCENE_WINDOW_H_ #include "2d/gui/SceneWindow.h" #endif #ifndef _BATCH_RENDER_H_ #include "2d/core/BatchRender.h" #endif #ifndef _UTILITY_H_ #include "2d/core/Utility.h" #endif #ifndef _PHYSICS_PROXY_H_ #include "2d/scene/PhysicsProxy.h" #endif #ifndef _SCENE_RENDER_OBJECT_H_ #include "2d/scene/SceneRenderObject.h" #endif #ifndef _BEHAVIOR_COMPONENT_H_ #include "component/behaviors/behaviorComponent.h" #endif #ifndef _BEHAVIORINSTANCE_H_ #include "component/behaviors/behaviorInstance.h" #endif //----------------------------------------------------------------------------- struct tDestroyNotification { SceneObject* mpSceneObject; U32 mRefCount; }; //----------------------------------------------------------------------------- typedef VectorPtr<b2FixtureDef*> typeCollisionFixtureDefVector; typedef VectorPtr<b2Fixture*> typeCollisionFixtureVector; typedef Vector<tDestroyNotification> typeDestroyNotificationVector; //----------------------------------------------------------------------------- const S32 GL_INVALID_BLEND_FACTOR = -1; const S32 INVALID_COLLISION_SHAPE_INDEX = -1; //----------------------------------------------------------------------------- extern EnumTable bodyTypeTable; extern EnumTable srcBlendFactorTable; extern EnumTable dstBlendFactorTable; //----------------------------------------------------------------------------- class SceneObject : public BehaviorComponent, public SceneRenderObject, public PhysicsProxy { private: typedef BehaviorComponent Parent; public: friend class Scene; friend class SceneWindow; friend class ContactFilter; friend class WorldQuery; friend class DebugDraw; friend class SceneObjectMoveToEvent; friend class SceneObjectRotateToEvent; protected: /// Scene. SimObjectPtr<Scene> mpScene; /// Target Scene. /// NOTE: Unfortunately this is required as the scene can be set via a field which /// occurs before the object is registered with the simulation therefore /// any simulation related functionality cannot be used such as TorqueScript /// callbacks. SimObjectPtr<Scene> mpTargetScene; /// Lifetime. F32 mLifetime; bool mLifetimeActive; /// Scene layers. U32 mSceneLayer; U32 mSceneLayerMask; F32 mSceneLayerDepth; /// Scene groups. U32 mSceneGroup; U32 mSceneGroupMask; /// Area. Vector2 mSize; bool mAutoSizing; b2AABB mPreTickAABB; b2AABB mCurrentAABB; Vector2 mLocalSizeOOBB[4]; Vector2 mRenderOOBB[4]; S32 mWorldProxyId; /// Position / Angle. Vector2 mPreTickPosition; F32 mPreTickAngle; Vector2 mRenderPosition; F32 mRenderAngle; bool mSpatialDirty; /// Body. b2Body* mpBody; b2BodyDef mBodyDefinition; U32 mWorldQueryKey; /// Collision control. U32 mCollisionLayerMask; U32 mCollisionGroupMask; bool mCollisionSuppress; b2FixtureDef mDefaultFixture; bool mGatherContacts; Scene::typeContactVector* mpCurrentContacts; /// General collision shape access. typeCollisionFixtureDefVector mCollisionFixtureDefs; typeCollisionFixtureVector mCollisionFixtures; /// Render visibility. bool mVisible; /// Render blending. bool mBlendMode; S32 mSrcBlendFactor; S32 mDstBlendFactor; ColorF mBlendColor; F32 mAlphaTest; /// Render sorting. Vector2 mSortPoint; /// Input events. bool mUseInputEvents; /// Script callbacks. bool mUpdateCallback; bool mCollisionCallback; bool mSleepingCallback; bool mLastAwakeState; /// Debug mode. U32 mDebugMask; /// Camera mounting. SceneWindow* mpAttachedCamera; /// GUI attachment. bool mAttachedGuiSizeControl; GuiControl* mpAttachedGui; SceneWindow* mpAttachedGuiSceneWindow; /// Safe deletion. bool mBeingSafeDeleted; bool mSafeDeleteReady; /// Destroy notifications. typeDestroyNotificationVector mDestroyNotifyList; /// Miscellaneous. bool mBatchIsolated; U32 mSerialiseKey; bool mEditorTickAllowed; bool mPickingAllowed; bool mAlwaysInScope; U32 mMoveToEventId; U32 mRotateToEventId; U32 mSerialId; StringTableEntry mRenderGroup; protected: static S32 QSORT_CALLBACK sceneObjectLayerDepthSort(const void* a, const void* b); /// Scene (un)registering. virtual void OnRegisterScene( Scene* pScene ); virtual void OnUnregisterScene( Scene* pScene ); /// Ticking. void resetTickSpatials( const bool resize = false ); inline bool getSpatialDirty( void ) const { return mSpatialDirty; } /// Contact processing. void initializeContactGathering( void ); /// Taml callbacks. virtual void onTamlCustomWrite( TamlCustomNodes& customNodes ); virtual void onTamlCustomRead( const TamlCustomNodes& customNodes ); public: SceneObject(); virtual ~SceneObject(); /// Engine. virtual bool onAdd(); virtual void onRemove(); virtual void onDestroyNotify( SceneObject* pSceneObject ); static void initPersistFields(); /// Integration. virtual void preIntegrate( const F32 totalTime, const F32 elapsedTime, DebugStats* pDebugStats ); virtual void integrateObject( const F32 totalTime, const F32 elapsedTime, DebugStats* pDebugStats ); virtual void postIntegrate(const F32 totalTime, const F32 elapsedTime, DebugStats *pDebugStats); virtual void interpolateObject( const F32 timeDelta ); inline bool getIsEditorTickAllowed( void ) const { return mEditorTickAllowed; } /// Render batching. inline void setBatchIsolated( const bool batchIsolated ) { mBatchIsolated = batchIsolated; } virtual bool getBatchIsolated( void ) { return mBatchIsolated; } virtual bool isBatchRendered( void ) { return true; } virtual bool validRender( void ) const { return true; } virtual bool shouldRender( void ) const { return false; } /// Render Output. virtual bool canPrepareRender( void ) const { return false; } virtual void scenePrepareRender( const SceneRenderState* pSceneRenderState, SceneRenderQueue* pSceneRenderQueue ) {} virtual void sceneRender( const SceneRenderState* pSceneRenderState, const SceneRenderRequest* pSceneRenderRequest, BatchRender* pBatchRenderer ) {} virtual void sceneRenderFallback( const SceneRenderState* pSceneRenderState, const SceneRenderRequest* pSceneRenderRequest, BatchRender* pBatchRenderer ); virtual void sceneRenderOverlay( const SceneRenderState* pSceneRenderState ); /// Networking. virtual U32 packUpdate(NetConnection * conn, U32 mask, BitStream *stream); virtual void unpackUpdate(NetConnection * conn, BitStream *stream); /// Scene. inline Scene* const getScene( void ) const { return mpScene; } inline F32 getSceneTime( void ) const { if ( mpScene ) return mpScene->getSceneTime(); else return 0.0f; } /// Enabled. virtual void setEnabled( const bool enabled ); /// Lifetime. void setLifetime( const F32 lifetime ); inline F32 getLifetime( void ) const { return mLifetime; } void updateLifetime( const F32 elapsedTime ); /// Scene layers. void setSceneLayer( const U32 sceneLayer ); inline U32 getSceneLayer(void) const { return mSceneLayer; } inline U32 getSceneLayerMask( void ) const { return mSceneLayerMask; } /// Scene Layer depth. inline void setSceneLayerDepth( const F32 order ) { mSceneLayerDepth = order; }; inline F32 getSceneLayerDepth( void ) const { return mSceneLayerDepth; } bool setSceneLayerDepthFront( void ); bool setSceneLayerDepthBack( void ); bool setSceneLayerDepthForward( void ); bool setSceneLayerDepthBackward( void ); /// Scene groups. void setSceneGroup( const U32 sceneGroup ); inline U32 getSceneGroup(void ) const { return mSceneGroup; } inline U32 getSceneGroupMask( void ) const { return mSceneGroupMask; } /// Area. virtual void setArea( const Vector2& corner1, const Vector2& corner2 ); inline bool getAutoSizing( void ) const { return mAutoSizing; } virtual void setSize( const Vector2& size ); inline void setSize( const F32 width, const F32 height ){ setSize( Vector2(width, height) ); } inline Vector2 getSize( void ) const { return mSize; } inline Vector2 getHalfSize( void ) const { return mSize * 0.5f; } inline b2AABB getAABB( void ) const { return mCurrentAABB; } inline RectF getAABBRectangle( void ) const { const b2Vec2 size = mCurrentAABB.upperBound-mCurrentAABB.lowerBound; return RectF( mCurrentAABB.lowerBound.x, mCurrentAABB.lowerBound.y, size.x, size.y ); } inline S32 getWorldProxy( void ) const { return mWorldProxyId; } /// Position / Angle. virtual void setPosition( const Vector2& position ); inline Vector2 getPosition(void) const { if ( mpScene ) return mpBody->GetPosition(); else return mBodyDefinition.position; } inline Vector2 getRenderPosition(void) const { return mRenderPosition; } inline F32 getRenderAngle(void) const { return mRenderAngle; } inline const b2Vec2* getRenderOOBB(void) const { return mRenderOOBB; } inline const b2Vec2* getLocalSizedOOBB( void ) const { return mLocalSizeOOBB; } virtual void setAngle( const F32 radians ); inline F32 getAngle(void) const { if ( mpScene ) return mpBody->GetAngle(); else return mBodyDefinition.angle; } virtual void setFixedAngle( const bool fixed ) { if ( mpScene ) mpBody->SetFixedRotation( fixed ); else mBodyDefinition.fixedRotation = fixed; } inline bool getFixedAngle(void) const { if ( mpScene ) return mpBody->IsFixedRotation(); else return mBodyDefinition.fixedRotation; } b2Transform getTransform( void ) const { if ( mpScene ) return mpBody->GetTransform(); else return b2Transform( mBodyDefinition.position, b2Rot(mBodyDefinition.angle) ); } b2Transform getRenderTransform( void ) const { return b2Transform( getRenderPosition(), b2Rot( getRenderAngle()) ); } inline Vector2 getLocalCenter(void) const { if ( mpScene ) return mpBody->GetLocalCenter(); else return b2Vec2_zero; } inline Vector2 getWorldCenter(void) const { if ( mpScene ) return mpBody->GetWorldCenter(); else return mBodyDefinition.position; } Vector2 getLocalPoint( const Vector2& worldPoint ); Vector2 getWorldPoint( const Vector2& localPoint ); Vector2 getLocalVector( const Vector2& worldVector ); Vector2 getWorldVector( const Vector2& localVector ); bool getIsPointInOOBB( const Vector2& worldPoint ); bool getIsPointInCollisionShape( const U32 shapeIndex, const Vector2& worldPoint ); /// Body. virtual ePhysicsProxyType getPhysicsProxyType( void ) const { return PhysicsProxy::PHYSIC_PROXY_SCENEOBJECT; } inline b2Body* getBody( void ) const { return mpBody; } void setBodyType( const b2BodyType type ); inline b2BodyType getBodyType(void) const { if ( mpScene ) return mpBody->GetType(); else return mBodyDefinition.type; } inline void setActive( const bool active ) { if ( mpScene ) mpBody->SetActive( active ); else mBodyDefinition.active = active; } inline bool getActive(void) const { if ( mpScene ) return mpBody->IsActive(); else return mBodyDefinition.active; } inline void setAwake( const bool awake ) { if ( mpScene ) mpBody->SetAwake( awake ); else mBodyDefinition.awake = awake; } inline bool getAwake(void) const { if ( mpScene ) return mpBody->IsAwake(); else return mBodyDefinition.awake; } inline void setBullet( const bool bullet ) { if ( mpScene ) mpBody->SetBullet( bullet ); else mBodyDefinition.bullet = bullet; } inline bool getBullet(void) const { if ( mpScene ) return mpBody->IsBullet(); else return mBodyDefinition.bullet; } inline void setSleepingAllowed( const bool allowed ) { if ( mpScene ) mpBody->SetSleepingAllowed( allowed ); else mBodyDefinition.allowSleep = allowed; } inline bool getSleepingAllowed(void) const { if ( mpScene ) return mpBody->IsSleepingAllowed(); else return mBodyDefinition.allowSleep; } inline F32 getMass( void ) const { if ( mpScene ) return mpBody->GetMass(); else return 0.0f; } inline F32 getInertia( void ) const { if ( mpScene ) return mpBody->GetInertia(); else return 0.0f; } /// Collision control. void setCollisionAgainst( const SceneObject* pSceneObject, const bool clearMasks ); inline void setCollisionGroupMask( const U32 groupMask ) { mCollisionGroupMask = groupMask; } inline U32 getCollisionGroupMask(void) const { return mCollisionGroupMask; } inline void setCollisionLayerMask( const U32 layerMask ) { mCollisionLayerMask = layerMask; } inline U32 getCollisionLayerMask(void) const { return mCollisionLayerMask; } void setDefaultDensity( const F32 density, const bool updateShapes = true ); inline F32 getDefaultDensity( void ) const { return mDefaultFixture.density; } void setDefaultFriction( const F32 friction, const bool updateShapes = true ); inline F32 getDefaultFriction( void ) const { return mDefaultFixture.friction; } void setDefaultRestitution( const F32 restitution, const bool updateShapes = true ); inline F32 getDefaultRestitution( void ) const { return mDefaultFixture.restitution; } inline void setCollisionSuppress( const bool status ) { mCollisionSuppress = status; } inline bool getCollisionSuppress(void) const { return mCollisionSuppress; } inline const Scene::typeContactVector* getCurrentContacts( void ) const { return mpCurrentContacts; } inline U32 getCurrentContactCount( void ) const { if ( mpCurrentContacts != NULL ) return mpCurrentContacts->size(); else return 0; } virtual void setGatherContacts( const bool gatherContacts ) { mGatherContacts = gatherContacts; initializeContactGathering(); } inline bool getGatherContacts( void ) const { return mGatherContacts; } virtual void onBeginCollision( const TickContact& tickContact ); virtual void onEndCollision( const TickContact& tickContact ); /// Velocities. inline void setLinearVelocity( const Vector2& velocity ) { if ( mpScene ) mpBody->SetLinearVelocity( velocity ); else mBodyDefinition.linearVelocity = velocity; } inline Vector2 getLinearVelocity(void) const { if ( mpScene ) return mpBody->GetLinearVelocity(); else return mBodyDefinition.linearVelocity; } inline Vector2 getLinearVelocityFromWorldPoint( const Vector2& worldPoint ) { if ( mpScene ) return mpBody->GetLinearVelocityFromWorldPoint( worldPoint ); else return mBodyDefinition.linearVelocity; } inline Vector2 getLinearVelocityFromLocalPoint( const Vector2& localPoint ) { if ( mpScene ) return mpBody->GetLinearVelocityFromLocalPoint( localPoint ); else return mBodyDefinition.linearVelocity; } inline void setAngularVelocity( const F32 velocity ) { if ( mpScene ) mpBody->SetAngularVelocity( velocity ); else mBodyDefinition.angularVelocity = velocity; } inline F32 getAngularVelocity(void) const { if ( mpScene ) return mpBody->GetAngularVelocity(); else return mBodyDefinition.angularVelocity; } inline void setLinearDamping( const F32 damping ) { if ( mpScene ) mpBody->SetLinearDamping( damping ); else mBodyDefinition.linearDamping = damping; } inline F32 getLinearDamping(void) const { if ( mpScene ) return mpBody->GetLinearDamping(); else return mBodyDefinition.linearDamping; } inline void setAngularDamping( const F32 damping ) { if ( mpScene ) mpBody->SetAngularDamping( damping ); else mBodyDefinition.angularDamping = damping; } inline F32 getAngularDamping(void) const { if ( mpScene ) return mpBody->GetAngularDamping(); else return mBodyDefinition.angularDamping; } /// Move/Rotate to. bool moveTo( const Vector2& targetWorldPoint, const F32 speed, const bool autoStop = true, const bool warpToTarget = true, const F32 yScaling = 1 ); bool moveTo( U32 & arrivalTime, const Vector2& targetWorldPoint, const F32 speed, const bool autoStop = true, const bool warpToTarget = true, const F32 yScaling = 1 ); bool rotateTo( const F32 targetAngle, const F32 speed, const bool autoStop = true, const bool warpToTarget = true ); void cancelMoveTo( const bool autoStop = true ); void cancelRotateTo( const bool autoStop = true ); inline bool isMoveToComplete( void ) const { return mMoveToEventId == 0; } inline bool isRotateToComplete( void ) const { return mRotateToEventId == 0; } /// Force and impulse. void applyForce( const Vector2& worldForce, const bool wake = true ); void applyForce( const Vector2& worldForce, const Vector2& worldPoint, const bool wake = true); void applyTorque( const F32 torque, const bool wake = true ); void applyLinearImpulse( const Vector2& worldImpulse, const bool wake = true ); void applyLinearImpulse( const Vector2& worldImpulse, const Vector2& worldPoint, const bool wake = true ); void applyAngularImpulse( const F32 impulse, const bool wake = true ); /// Gravity scaling. inline void setGravityScale( const F32 scale ) { if ( mpScene ) mpBody->SetGravityScale( scale ); else mBodyDefinition.gravityScale = scale; } inline F32 getGravityScale(void) const { if ( mpScene ) return mpBody->GetGravityScale(); else return mBodyDefinition.gravityScale; } /// General collision shape access. void deleteCollisionShape( const U32 shapeIndex ); void clearCollisionShapes( void ); inline U32 getCollisionShapeCount( void ) const { if ( mpScene ) return mCollisionFixtures.size(); else return mCollisionFixtureDefs.size(); } b2Shape::Type getCollisionShapeType( const U32 shapeIndex ) const; S32 getCollisionShapeIndex( const b2Fixture* pFixture ) const; void setCollisionShapeDefinition( const U32 shapeIndex, const b2FixtureDef& fixtureDef ); b2FixtureDef getCollisionShapeDefinition( const U32 shapeIndex ) const; const b2CircleShape* getCollisionCircleShape( const U32 shapeIndex ) const; const b2PolygonShape* getCollisionPolygonShape( const U32 shapeIndex ) const; const b2ChainShape* getCollisionChainShape( const U32 shapeIndex ) const; const b2EdgeShape* getCollisionEdgeShape( const U32 shapeIndex ) const; void setCollisionShapeDensity( const U32 shapeIndex, const F32 density ); F32 getCollisionShapeDensity( const U32 shapeIndex ) const; void setCollisionShapeFriction( const U32 shapeIndex, const F32 friction ); F32 getCollisionShapeFriction( const U32 shapeIndex ) const; void setCollisionShapeRestitution( const U32 shapeIndex, const F32 restitution ); F32 getCollisionShapeRestitution( const U32 shapeIndex ) const; void setCollisionShapeIsSensor( const U32 shapeIndex, const bool isSensor ); bool getCollisionShapeIsSensor( const U32 shapeIndex ) const; /// Circle collision shape creation. S32 createCircleCollisionShape( const F32 radius ); S32 createCircleCollisionShape( const F32 radius, const b2Vec2& localPosition ); /// Circle collision shape access. F32 getCircleCollisionShapeRadius( const U32 shapeIndex ) const; Vector2 getCircleCollisionShapeLocalPosition( const U32 shapeIndex ) const; /// Polygon collision shape creation. S32 createPolygonCollisionShape( const U32 pointCount, const b2Vec2* localPoints ); S32 createPolygonBoxCollisionShape( const F32 width, const F32 height ); S32 createPolygonBoxCollisionShape( const F32 width, const F32 height, const b2Vec2& localCentroid ); S32 createPolygonBoxCollisionShape( const F32 width, const F32 height, const b2Vec2& localCentroid, const F32 rotation ); /// Polygon collision shape access. U32 getPolygonCollisionShapePointCount( const U32 shapeIndex ) const; Vector2 getPolygonCollisionShapeLocalPoint( const U32 shapeIndex, const U32 pointIndex ) const; /// Chain collision shape creation. S32 createChainCollisionShape( const U32 pointCount, const b2Vec2* localPoints ); S32 createChainCollisionShape( const U32 pointCount, const b2Vec2* localPoints, const bool hasAdjacentLocalPositionStart, const bool hasAdjacentLocalPositionEnd, const b2Vec2& adjacentLocalPositionStart, const b2Vec2& adjacentLocalPositionEnd ); /// Chain collision shape access. U32 getChainCollisionShapePointCount( const U32 shapeIndex ) const; Vector2 getChainCollisionShapeLocalPoint( const U32 shapeIndex, const U32 pointIndex ) const; bool getChainCollisionShapeHasAdjacentStart( const U32 shapeIndex ) const; bool getChainCollisionShapeHasAdjacentEnd( const U32 shapeIndex ) const; Vector2 getChainCollisionShapeAdjacentStart( const U32 shapeIndex ) const; Vector2 getChainCollisionShapeAdjacentEnd( const U32 shapeIndex ) const; /// Edge collision shape creation. S32 createEdgeCollisionShape( const b2Vec2& localPositionStart, const b2Vec2& localPositionEnd ); S32 createEdgeCollisionShape( const b2Vec2& localPositionStart, const b2Vec2& localPositionEnd, const bool hasAdjacentLocalPositionStart, const bool hasAdjacentLocalPositionEnd, const b2Vec2& adjacentLocalPositionStart, const b2Vec2& adjacentLocalPositionEnd ); /// Edge collision shape access. Vector2 getEdgeCollisionShapeLocalPositionStart( const U32 shapeIndex ) const; Vector2 getEdgeCollisionShapeLocalPositionEnd( const U32 shapeIndex ) const; bool getEdgeCollisionShapeHasAdjacentStart( const U32 shapeIndex ) const; bool getEdgeCollisionShapeHasAdjacentEnd( const U32 shapeIndex ) const; Vector2 getEdgeCollisionShapeAdjacentStart( const U32 shapeIndex ) const; Vector2 getEdgeCollisionShapeAdjacentEnd( const U32 shapeIndex ) const; /// Render visibility. inline void setVisible( const bool status ) { mVisible = status; } inline bool getVisible(void) const { return mVisible; } /// Render blending. inline void setBlendMode( const bool blendMode ) { mBlendMode = blendMode; } inline bool getBlendMode( void ) const { return mBlendMode; } inline void setSrcBlendFactor( const S32 blendFactor ) { mSrcBlendFactor = blendFactor; } inline S32 getSrcBlendFactor( void ) const { return mSrcBlendFactor; } inline void setDstBlendFactor( const S32 blendFactor ) { mDstBlendFactor = blendFactor; } inline S32 getDstBlendFactor( void ) const { return mDstBlendFactor; } inline void setBlendColor( const ColorF& blendColor ) { mBlendColor = blendColor; } inline const ColorF& getBlendColor( void ) const { return mBlendColor; } inline void setBlendAlpha( const F32 alpha ) { mBlendColor.alpha = alpha; } inline F32 getBlendAlpha( void ) const { return mBlendColor.alpha; } inline void setAlphaTest( const F32 alpha ) { mAlphaTest = alpha; } inline F32 getAlphaTest( void ) const { return mAlphaTest; } void setBlendOptions( void ); static void resetBlendOptions( void ); /// Render sorting. inline void setSortPoint( const Vector2& pt ) { mSortPoint = pt; } inline const Vector2& getSortPoint(void) const { return mSortPoint; } inline void setRenderGroup( const char* pRenderGroup ) { mRenderGroup = StringTable->insert(pRenderGroup); } inline StringTableEntry getRenderGroup( void ) const { return mRenderGroup; } /// Input events. inline void setUseInputEvents( bool mouseStatus ) { mUseInputEvents = mouseStatus; } inline bool getUseInputEvents( void ) const { return mUseInputEvents; } virtual void onInputEvent( StringTableEntry name, const GuiEvent& event, const Vector2& worldMousePoint ); // Script callbacks. inline void setUpdateCallback( bool status ) { mUpdateCallback = status; } inline bool getUpdateCallback( void ) const { return mUpdateCallback; } inline void setCollisionCallback( const bool status ) { mCollisionCallback = status; } inline bool getCollisionCallback(void) const { return mCollisionCallback; } inline void setSleepingCallback( bool status ) { mSleepingCallback = status; } inline bool getSleepingCallback( void ) const { return mSleepingCallback; } /// Debug mode. inline void setDebugOn( const U32 debugMask ) { mDebugMask |= debugMask; } inline void setDebugOff( const U32 debugMask ) { mDebugMask &= ~debugMask; } inline U32 getDebugMask( void ) const { return mDebugMask; } /// Camera mounting. inline void addCameraMountReference( SceneWindow* pAttachedCamera ) { mpAttachedCamera = pAttachedCamera; } inline void removeCameraMountReference( void ) { mpAttachedCamera = NULL; } inline void dismountCamera( void ) { if ( mpAttachedCamera ) mpAttachedCamera->dismountMe( this ); } // GUI attachment. void attachGui( GuiControl* pGuiControl, SceneWindow* pSceneWindow, const bool sizeControl ); void detachGui( void ); inline void updateAttachedGui( void ); // Picking. inline void setPickingAllowed( const bool pickingAllowed ) { mPickingAllowed = pickingAllowed; } inline bool getPickingAllowed(void) const { return mPickingAllowed; } /// Cloning. virtual void copyFrom( SceneObject* pSceneObject, const bool copyDynamicFields ); virtual void copyTo( SimObject* object ); S32 copyCollisionShapes( SceneObject* pSceneObject, const bool clearTargetShapes = true, const S32 shapeIndex = -1 ); /// Safe deletion. inline void setSafeDelete( const bool status ) { mSafeDeleteReady = status; } inline bool getSafeDelete( void ) const { return mSafeDeleteReady; } inline bool isBeingDeleted( void ) const { return mBeingSafeDeleted; } virtual void safeDelete( void ); /// Destroy notifications. void addDestroyNotification( SceneObject* pSceneObject ); void removeDestroyNotification( SceneObject* pSceneObject ); void processDestroyNotifications( void ); /// Component notifications. void notifyComponentsAddToScene( void ); void notifyComponentsRemoveFromScene( void ); void notifyComponentsUpdate( void ); /// Miscellaneous. inline const char* scriptThis(void) const { return Con::getIntArg(getId()); } inline bool getIsAlwaysInScope(void) const { return mAlwaysInScope; } inline void setWorldQueryKey( const U32 key ) { mWorldQueryKey = key; } inline U32 getWorldQueryKey( void ) const { return mWorldQueryKey; } static U32 getGlobalSceneObjectCount( void ); inline U32 getSerialId( void ) const { return mSerialId; } // Read / Write fields. virtual bool writeField(StringTableEntry fieldname, const char* value); static b2BodyType getBodyTypeEnum(const char* label); static const char* getBodyTypeDescription(const b2BodyType bodyType); static b2Shape::Type getCollisionShapeTypeEnum(const char* label); static const char* getCollisionShapeTypeDescription(const b2Shape::Type collisionShapeType); static S32 getSrcBlendFactorEnum(const char* label); static S32 getDstBlendFactorEnum(const char* label); static const char* getSrcBlendFactorDescription(const GLenum factor); static const char* getDstBlendFactorDescription(const GLenum factor); /// Declare Console Object. DECLARE_CONOBJECT( SceneObject ); protected: S32 copyCircleCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const; S32 copyPolygonCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const; S32 copyChainCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const; S32 copyEdgeCollisionShapeTo( SceneObject* pSceneObject, const b2FixtureDef& fixtureDef ) const; protected: /// Lifetime. static bool setLifetime(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setLifetime(dAtof(data)); return false; } static bool writeLifetime( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getLifetime() > 0.0f ; } /// Scene layers. static bool setSceneLayer(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setSceneLayer(dAtoi(data)); return false; } static bool writeSceneLayer( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getSceneLayer() > 0 ; } static bool setSceneLayerDepth(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setSceneLayerDepth(dAtof(data)); return false; } static bool writeSceneLayerDepth( void* obj, StringTableEntry pFieldName ) { return mNotZero(static_cast<SceneObject*>(obj)->getSceneLayerDepth()); } /// Scene groups. static bool setSceneGroup(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setSceneGroup(dAtoi(data)); return false; } static bool writeSceneGroup( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getSceneGroup() > 0 ; } /// Area. static bool setSize(void* obj, const char* data) { SceneObject* pSceneObject = static_cast<SceneObject*>(obj); if ( pSceneObject->getAutoSizing() ) { Con::warnf( "Cannot set the size of a type '%s' as it automatically sizes itself.", pSceneObject->getClassName() ); return false; } pSceneObject->setSize(Vector2(data)); return false; } static bool writeSize( void* obj, StringTableEntry pFieldName ) { SceneObject* pSceneObject = static_cast<SceneObject*>(obj); return !pSceneObject->getAutoSizing() && pSceneObject->getSize().notEqual(Vector2::getOne()); } /// Position / Angle. static bool setPosition(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setPosition(Vector2(data)); return false; } static const char* getPosition(void* obj, const char* data) { return static_cast<SceneObject*>(obj)->getPosition().scriptThis(); } static bool writePosition( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getPosition().notZero(); } static bool setAngle(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setAngle(mDegToRad(dAtof(data))); return false; } static const char* getAngle(void* obj, const char* data) { return Con::getFloatArg( mRadToDeg(static_cast<SceneObject*>(obj)->getAngle() ) ); } static bool writeAngle( void* obj, StringTableEntry pFieldName ) { return mNotZero(static_cast<SceneObject*>(obj)->getAngle()); } static bool setFixedAngle(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setFixedAngle(dAtob(data)); return false; } static const char* getFixedAngle(void* obj, const char* data) { return Con::getBoolArg( static_cast<SceneObject*>(obj)->getFixedAngle() ); } static bool writeFixedAngle( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getFixedAngle() == true; } /// Body. static bool setBodyType(void* obj, const char* data) { // Fetch body type. const b2BodyType type = getBodyTypeEnum( data ); // Check for error. if ( type != b2_staticBody && type != b2_kinematicBody && type != b2_dynamicBody ) return false; static_cast<SceneObject*>(obj)->setBodyType(type); return false; } static const char* getBodyType(void* obj, const char* data) { return getBodyTypeDescription( static_cast<SceneObject*>(obj)->getBodyType() ); } static bool writeBodyType( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getBodyType() != b2_dynamicBody; } static bool setActive(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setActive(dAtob(data)); return false; } static const char* getActive(void* obj, const char* data) { return Con::getBoolArg( static_cast<SceneObject*>(obj)->getActive() ); } static bool writeActive( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getActive() == false; } static bool setAwake(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setAwake(dAtob(data)); return false; } static const char* getAwake(void* obj, const char* data) { return Con::getBoolArg( static_cast<SceneObject*>(obj)->getAwake() ); } static bool writeAwake( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getAwake() == false; } static bool setBullet(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setBullet(dAtob(data)); return false; } static const char* getBullet(void* obj, const char* data) { return Con::getBoolArg( static_cast<SceneObject*>(obj)->getBullet() ); } static bool writeBullet( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getBullet() == true; } static bool setSleepingAllowed(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setSleepingAllowed(dAtob(data)); return false; } static const char* getSleepingAllowed(void* obj, const char* data) { return Con::getBoolArg( static_cast<SceneObject*>(obj)->getSleepingAllowed() ); } static bool writeSleepingAllowed( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getSleepingAllowed() == false; } /// Collision control. static bool setDefaultDensity(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setDefaultDensity(dAtof(data)); return false; } static bool writeDefaultDensity( void* obj, StringTableEntry pFieldName ) { return mNotEqual(static_cast<SceneObject*>(obj)->getDefaultDensity(), 1.0f); } static bool setDefaultFriction(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setDefaultFriction(dAtof(data)); return false; } static bool writeDefaultFriction( void* obj, StringTableEntry pFieldName ) {return mNotEqual(static_cast<SceneObject*>(obj)->getDefaultFriction(), 0.2f); } static bool setDefaultRestitution(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setDefaultRestitution(dAtof(data)); return false; } static bool writeDefaultRestitution( void* obj, StringTableEntry pFieldName ) { return mNotEqual(static_cast<SceneObject*>(obj)->getDefaultRestitution(), 0.0f); } static bool setCollisionGroups(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setCollisionGroupMask(dAtoi(data)); return false; } static bool writeCollisionGroups( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getCollisionGroupMask() != MASK_ALL; } static bool setCollisionLayers(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setCollisionLayerMask(dAtoi(data)); return false; } static bool writeCollisionLayers( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getCollisionLayerMask() != MASK_ALL; } static bool writeCollisionSuppress( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getCollisionSuppress() == true; } static bool setGatherContacts(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setGatherContacts(dAtoi(data)); return false; } static bool writeGatherContacts( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getGatherContacts() == true; } /// Velocities. static bool setLinearVelocity(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setLinearVelocity(Vector2(data)); return false; } static const char* getLinearVelocity(void* obj, const char* data) { return static_cast<SceneObject*>(obj)->getLinearVelocity().scriptThis(); } static bool writeLinearVelocity( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getLinearVelocity().notZero(); } static bool setAngularVelocity(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setAngularVelocity(mDegToRad(dAtof(data))); return false; } static const char* getAngularVelocity(void* obj, const char* data) { return Con::getFloatArg( mRadToDeg(static_cast<SceneObject*>(obj)->getAngularVelocity() ) ); } static bool writeAngularVelocity( void* obj, StringTableEntry pFieldName ) { return mNotZero(static_cast<SceneObject*>(obj)->getAngularVelocity()); } static bool setLinearDamping(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setLinearDamping(dAtof(data)); return false; } static const char* getLinearDamping(void* obj, const char* data) { return Con::getFloatArg( static_cast<SceneObject*>(obj)->getLinearDamping() ); } static bool writeLinearDamping( void* obj, StringTableEntry pFieldName ) { return mNotZero(static_cast<SceneObject*>(obj)->getLinearDamping()); } static bool setAngularDamping(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setAngularDamping(dAtof(data)); return false; } static const char* getAngularDamping(void* obj, const char* data) { return Con::getFloatArg( static_cast<SceneObject*>(obj)->getAngularDamping() ); } static bool writeAngularDamping( void* obj, StringTableEntry pFieldName ) { return mNotZero(static_cast<SceneObject*>(obj)->getAngularDamping()); } /// Gravity scaling. static bool setGravityScale(void* obj, const char* data) { static_cast<SceneObject*>(obj)->setGravityScale(dAtof(data)); return false; } static const char* getGravityScale(void* obj, const char* data) { return Con::getFloatArg( static_cast<SceneObject*>(obj)->getGravityScale() ); } static bool writeGravityScale( void* obj, StringTableEntry pFieldName ) { return mNotEqual(static_cast<SceneObject*>(obj)->getGravityScale(), 1.0f); } /// Render visibility. static bool writeVisible( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getVisible() == false; } /// Render blending. static bool writeBlendMode( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getBlendMode() == false; } static bool writeSrcBlendFactor( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getSrcBlendFactor() != GL_SRC_ALPHA; } static bool writeDstBlendFactor( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getDstBlendFactor() != GL_ONE_MINUS_SRC_ALPHA; } static bool writeBlendColor( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getBlendColor() != ColorF(1.0f, 1.0f, 1.0f, 1.0f); } static bool writeAlphaTest( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getAlphaTest() >= 0.0f; } /// Render sorting. static bool writeSortPoint( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getSortPoint().notZero(); } static bool writeRenderGroup( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getRenderGroup() != StringTable->EmptyString; } /// Input events. static bool writeUseInputEvents( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getUseInputEvents() == true; } /// Picking. static bool writePickingAllowed( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getPickingAllowed() == false; } /// Script callbacks. static bool writeUpdateCallback( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getUpdateCallback() == true; } static bool writeCollisionCallback( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getCollisionCallback() == true; } static bool writeSleepingCallback( void* obj, StringTableEntry pFieldName ) { return static_cast<SceneObject*>(obj)->getSleepingCallback() == true; } /// Scene. static bool setScene(void* obj, const char* data) { Scene* pScene = dynamic_cast<Scene*>(Sim::findObject(data)); SceneObject* object = static_cast<SceneObject*>(obj); if (pScene) { if (object->getScene()) object->getScene()->removeFromScene(object); // is the scene object registered? if ( object->isProperlyAdded() ) { // Yes, so we can add to the scene now. pScene->addToScene(object); } else { // No, so just set the target scene directly and it will be added to that scene when registered. object->mpTargetScene = pScene; } } return false; } static bool writeScene( void* obj, StringTableEntry pFieldName ) { return false; } }; #endif // _SCENE_OBJECT_H_
[ "ncpeterson2@gmail.com" ]
ncpeterson2@gmail.com
f25e04d6ba8b540825d28fa1edca12f41abbdeca
590d6779cb3d480ec320369649b987e0da2c9f1a
/Space Shooter/ComponentTypes.hpp
6b80f7e936af62ac47a80f6a88b1753ccf0d94af
[]
no_license
joekarl/Space-Shooter
24ace76fea4140807f86a262864aeb9c678d67ba
5cfb7165c735f29d8a0bf6c17ae282928870db1b
refs/heads/master
2021-01-10T20:35:27.783303
2015-09-14T04:21:47
2015-09-14T04:21:47
41,829,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,411
hpp
// // ComponentTypes.hpp // Space Shooter // // Created by Karl Kirch on 8/27/15. // Copyright © 2015 Karl Kirch. All rights reserved. // #ifndef ComponentTypes_hpp #define ComponentTypes_hpp #include "Entity.hpp" #include "SpriteRenderComponent.hpp" #include "TransformComponent.hpp" #include "PlayerDetailsComponent.hpp" #include "DiesWhenOffscreenComponent.hpp" #include "AABBComponent.hpp" #include "AutoMovementComponent.hpp" #include "CollisionComponent.hpp" #include "LaserUpgradeComponent.hpp" #include "LaserDetailsComponent.hpp" #include "DiesAfterTimePeriodComponent.hpp" #include "EnemyAIComponent.hpp" template<> int getTypeId<TransformComponent>() { return 0; } template <> int getTypeId<SpriteRenderComponent>() { return 1; } template <> int getTypeId<PlayerDetailsComponent>() { return 2; } template <> int getTypeId<CollisionComponent>() { return 3; } template <> int getTypeId<DiesWhenOffscreenComponent>() { return 4; } template<> int getTypeId<AABBComponent>() { return 5; } template<> int getTypeId<AutoMovementComponent>() { return 6; } template<> int getTypeId<LaserUpgradeComponent>() { return 7; } template<> int getTypeId<LaserDetailsComponent>() { return 8; } template<> int getTypeId<DiesAfterTimePeriodComponent>() { return 9; } template<> int getTypeId<EnemyAIComponent>() { return 10; } #endif /* ComponentTypes_h */
[ "karl@simple.com" ]
karl@simple.com
3c3d68d84e69c691cde9106faae365dd226ad1cf
83d0a08dec952a0729526e1db52e0eb71af24d06
/examples/2020/lec_8_class/square.h
070b1fb9b14d639b738e384897f08f114460ee13
[]
no_license
VetrovSV/OOP
e732eccfffc4e76cb3e7a4126ffd80217863342b
39182900aa5ed4dd3dc5d1f3624a7436fd53d3d6
refs/heads/master
2023-06-10T18:07:42.488280
2023-06-03T01:25:06
2023-06-03T01:25:06
107,647,790
15
10
null
null
null
null
UTF-8
C++
false
false
765
h
#ifndef SQUARE_H #define SQUARE_H enum SquareExceptions { InvalidArgument }; class Square{ private: // закрытый раздел float a; // поле - перем. внутри класса public: // открытый раздел // Конструкторы -- функции инициализирующие объект Square(); // конструктор без параметров Square(float a1); // конструктор с параметром // методы - функции внутри класса void set_a(float a1); float get_a() const; // const значит, что метод не меняет полей класса float perimeter() const; float area() const; }; #endif // SQUARE_H
[ "s" ]
s
212edb5347de123a8273ea20254fc381ace4ca57
4b05a0e9b5f1d6b8d9222fcbd3b4f9f5a25a8484
/level.h
f5224d62f78f6a8094a00f7684e1792eaef07484
[]
no_license
kokorhekkus/the-ship-cpp
06506c6b60ca395aac2672f725325e7550f5d7d4
98ec21ab96ddc437e107569c4ddc52adea7ebf80
refs/heads/master
2021-01-18T22:20:29.481830
2016-12-09T16:53:26
2016-12-09T16:53:26
7,685,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,708
h
#ifndef SHIP_LEVEL #define SHIP_LEVEL 1 #include "map.h" #include "object.h" #include "enums.h" #include "monster.h" #include <list> // A class basically used to store a level map and the objects found on // that level. The Thing vector wasn't added to the LevelMap object due // to class/header dependency hell that I am currently to lazy/stupid // to fix class Level { private: // needs to be pointers to the base class due to object slicing std::list<Thing*> objects; std::list<Monster> monsters; LevelMap* levelMap; inventoryType getInventoryType(int i); public: Level(LevelMap* a_levelMap); ~Level(); // add a load of random items to the floor of the level, percent chance // to generate an item is chanceToGen void addFloorItems(int chanceToGen); // generate monsters for the level void addLevelMonsters(); // add a monster to the level void addMonster(Monster m); // return the location of an empty map location Location findEmptyLocation() const; // return 0 if no object at location, otherwise return object ID unsigned int objectAt(int x, int y); // return a ref to an object with a certain ID, // use with objectAt() above or you may not get anything back Thing& getObject(unsigned int id); // add an object to the level void addObject(Thing& t); // remove an object from the level, using its ID void delObject(unsigned int id); // print all objects on the level to the terminal void printObjects() const; // print all monsters on the level to the terminal void printMonsters() const; // prints everything on the level void print() const; }; #endif
[ "karimrashad@gmail.com" ]
karimrashad@gmail.com
7b4e7ab41bb418384e7c5237577e605d7ac0ab2f
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/3d/d52f16ee6fff28/main.cpp
e9bb3466204e6674ae8cb88584498551ff165fed
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
1,532
cpp
#include <iostream> #include <string> #include <vector> #include <functional> class ContainsObj { public: ContainsObj() { } ~ContainsObj() { } std::string lhs; std::string rhs; operator bool() const { return lhs.find(rhs) != std::string::npos; } } containsobj; ContainsObj& operator+(const std::string& lhs, ContainsObj& rhs) { rhs.lhs = lhs; return rhs; } ContainsObj& operator+(ContainsObj& lhs, const std::string& rhs) { lhs.rhs = rhs; return lhs; } #define contains + containsobj + class InObj { public: InObj() { } ~InObj() { } int lhs; std::vector<int> rhs; } inobj; #define in + inobj + InObj& operator+(const int& lhs, InObj& rhs) { rhs.lhs = lhs; return rhs; } InObj& operator+(InObj& lhs, const std::vector<int>& rhs) { lhs.rhs = rhs; return lhs; } class PerformObj { int counter; public: PerformObj() : counter(0) { } ~PerformObj() { } InObj lhs; std::function<int(int)> rhs; operator int() const { return rhs(lhs.rhs[counter]); } } performobj; #define perform + performobj + PerformObj& operator+(const InObj& lhs, PerformObj& rhs) { rhs.lhs = lhs; return rhs; } PerformObj& operator+(PerformObj& lhs, const std::function<int(int)>& rhs) { lhs.rhs = rhs; return lhs; } int main() { std::vector<int> nums = {1,2,3}; int x = 0; auto cube = [] (int n) { return n * n * n; }; std::cout << x in nums perform cube << std::endl; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
c760da12ea37726b1e0a257523c071b5a0f14ced
19421bab23618a00e6abbc200ea9ca774b8c6361
/example7.cpp
ff6437e084c9f750f78b9547f1ab6cbf691dbd8f
[]
no_license
jinwook-aero/hello-world-SFINAE
b949bb7887651cc016820bb2a12ad47389752f70
167201dec089842bc39d2e51bd56ad42c4acbd9e
refs/heads/master
2022-04-18T14:20:19.981799
2020-04-15T07:52:14
2020-04-15T07:52:14
255,820,697
0
0
null
null
null
null
UTF-8
C++
false
false
864
cpp
// main.cpp // Main file for testing SFINAE // // Author : Jinwook Lee // Reviewer: Sungwook Lee // First version: April 14, 2020 // Last update : April 14, 2020 // #include <iostream> #include <type_traits> // Example7: Approaching a hint template<typename U = T> template <typename T> class OddClass { public: template<typename U = T> typename std::enable_if_t<std::is_integral_v<U>, bool> is_odd(U i) { std::cout << "Modular can be computed" << std::endl; return bool(i % 2); } template<typename U = T> typename std::enable_if_t<!std::is_integral_v<U>, bool> is_odd(U i) { std::cout << "Modular cannot be computed" << std::endl; return false; } }; typename std::enable_if_t<std::is_integral_v<U>, bool> is_odd(U i) int main() { int x = 1; double y = 1; OddClass<int> theClass; theClass.is_odd(x); theClass.is_odd(y); return 0; }
[ "jinwook.aero@gmail.com" ]
jinwook.aero@gmail.com
6c9cfbd30dd67a9c6548872601d513b698c7fcf6
aeccd87d431ae3877e7820206c737895f6aaa068
/honours_project/components/cmp_basic_movement.h
7d47b18f14d1c26cff090548657df37b371740ca
[ "MIT" ]
permissive
alexbarker/soc10101_honours_project
421c2a29cebc1ef149acd0bf43c09c8454bc4981
c29c10f0e5d7bed50819c948f841dd97e7d68809
refs/heads/master
2020-04-05T17:24:00.193199
2019-03-28T22:37:41
2019-03-28T22:37:41
157,058,553
0
0
null
null
null
null
UTF-8
C++
false
false
681
h
#pragma once #include <ecm.h> // A component to allow basic movement behaviour class BasicMovementComponent : public Component { protected: // Speed we can travel float _speed; // Checks if the move is valid bool validMove(const sf::Vector2f&); public: // Will check the keyboard and move the component's parent void update(double) override; // Moves the component's parent void move(const sf::Vector2f&); // Moves the component's parent void move(float x, float y); // Component does not need to be rendered void render() override {} // Used to create the component for an entity explicit BasicMovementComponent(Entity* p); BasicMovementComponent() = delete; };
[ "40333139@live.napier.ac.uk" ]
40333139@live.napier.ac.uk
e9de737cc61f9247bc0927e0de4c3bd8686a0701
f26b9a0907c4e3f81d69f6d269efcd1a719090f6
/RayTracing1/float3.h
1e282a68a402369203f469b5fa4edd69d6e79a78
[]
no_license
wdkenn/graphics-eggs-of-all-shapes-and-sizes
64e3cd4a160e48039f567f4ff698b3a3d27db8cf
6a17f9b0bd7dd38bd5e864be5e9b23b51dacd388
refs/heads/master
2021-01-19T03:16:49.051976
2015-03-02T20:15:11
2015-03-02T20:15:11
31,560,806
0
0
null
null
null
null
UTF-8
C++
false
false
2,171
h
// // float3.h // RayTracing // // Created by Walker Kennedy on 3/20/14. // Copyright (c) 2014 ait.hu.bud.kennedy. All rights reserved. // #pragma once #include <math.h> #include <stdlib.h> class float3 { public: float x; float y; float z; float3() { x = ((float)rand() / RAND_MAX) * 2 - 1; y = ((float)rand() / RAND_MAX) * 2 - 1; z = ((float)rand() / RAND_MAX) * 2 - 1; } float3(float x, float y, float z):x(x),y(y),z(z){} float3 operator-() const { return float3(-x, -y, -z); } float3 operator+(const float3& addOperand) const { return float3(x + addOperand.x, y + addOperand.y, z + addOperand.z); } float3 operator-(const float3& operand) const { return float3(x - operand.x, y - operand.y, z - operand.z); } float3 operator*(const float3& operand) const { return float3(x * operand.x, y * operand.y, z * operand.z); } float3 operator*(float operand) const { return float3(x * operand, y * operand, z * operand); } float3 operator/(const float3& operand) const { return float3(x / operand.x, y / operand.y, z / operand.z); } float3 operator/(float operand) const { return float3(x / operand, y / operand, z / operand); } void operator-=(const float3& a) { x -= a.x; y -= a.y; z -= a.z; } void operator+=(const float3& a) { x += a.x; y += a.y; z += a.z; } void operator*=(const float3& a) { x *= a.x; y *= a.y; z *= a.z; } void operator*=(float a) { x *= a; y *= a; z *= a; } float norm() const { return sqrtf(x*x+y*y+z*z); } float norm2() const { return x*x+y*y+z*z; } float3 normalize() { float oneOverLength = 1.0f / norm(); x *= oneOverLength; y *= oneOverLength; z *= oneOverLength; return *this; } float3 cross(const float3& operand) const { return float3( y * operand.z - z * operand.y, z * operand.x - x * operand.z, x * operand.y - y * operand.x); } float dot(const float3& operand) const { return x * operand.x + y * operand.y + z * operand.z; } };
[ "wdkenn42@gmail.com" ]
wdkenn42@gmail.com
1891726ee031e35bfa86f939ffa5658587d8a693
bea79b1534463f3db4c8e5149a83094830e60e01
/Cell Centre Crypt Simulation/Cell Centre Crypt Simulation/CellCycle.cpp
493752d7f81413e24189f6c80deb6e61713670e3
[]
no_license
TimInghamDempster/Cell-Centre-Crypt-Cpp
b22f80812d5a0b93e3e7032287a8d8b9adf96c52
791c2317a078f0bee982939a88a8eab400fba5dc
refs/heads/master
2021-04-09T16:13:57.011923
2017-06-19T09:37:50
2017-06-19T09:37:50
47,827,695
1
1
null
null
null
null
UTF-8
C++
false
false
181
cpp
namespace CellCycleStages { enum Stages { Child, // This cell is not yet independant and forms part of a growing cell before it divides. G0, G1, M }; }
[ "tim_ingham_dempster@hotmail.co.uk" ]
tim_ingham_dempster@hotmail.co.uk
7b5e0e759c2780fb71b89088ba205666519aeee8
6d7f2381b8f1c5c0e0d96156ae36cac12be3017b
/codeforces/e90/D/main.cpp
2cf23c373c7fcfc692ef3d64116f4393002ac6d8
[ "Unlicense" ]
permissive
Johniel/contests
708ccf944d6aeb0ef0404eec47e8ff7819ea00f0
15d465b08cac56e394509bcf8f24764e3dc6ca7d
refs/heads/master
2023-09-04T07:32:49.822786
2023-09-02T13:44:28
2023-09-02T13:44:50
48,701,889
0
0
null
2019-10-25T09:21:20
2015-12-28T16:38:38
C++
UTF-8
C++
false
false
2,907
cpp
// codeforces/e90/D/main.cpp // author: @___Johniel // github: https://github.com/johniel/ #include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; for (auto& i: v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { for (auto& i: v) is >> i; return is; } template<typename T> ostream& operator << (ostream& os, set<T> s) { os << "#{"; for (auto& i: s) os << i << ","; os << "}"; return os; } template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; for (auto& i: m) os << i << ","; os << "}"; return os; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } using lli = long long int; using ull = unsigned long long; using point = complex<double>; using str = string; template<typename T> using vec = vector<T>; constexpr array<int, 8> di({0, 1, -1, 0, 1, -1, 1, -1}); constexpr array<int, 8> dj({1, 0, 0, -1, 1, -1, -1, 1}); constexpr lli mod = 1e9 + 7; int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); cout.setf(ios_base::fixed); cout.precision(15); int _; cin >> _; int n; while (cin >> n) { vec<lli> a(n); cin >> a; // cout << "a: " << a << endl; lli mx = 0; for (int i = 0; i < a.size(); i+=2) { mx += a[i]; } vec<lli> o = a; vec<lli> e = a; for (int i = 0; i < a.size(); ++i) { if (i % 2) e[i] = 0; else o[i] = 0; } // cout << e << endl; // cout << o << endl; vec<lli> x({0}); vec<lli> y({0}); for (int i = 0; i < a.size(); ++i) { x.push_back(x.back() + e[i]); y.push_back(y.back() + o[i]); } // cout << x << endl; // cout << y << endl; priority_queue<vec<lli>> O; priority_queue<vec<lli>> E; for (int i = 0; i <= a.size(); ++i) { if (1 < i) { int j = i; int k = i; auto v = (i % 2 ? O.top() : E.top()); // cout << v << endl; lli s = (x.back() - x[j]) + v[1]; lli t = y[k] - v[2]; setmax(mx, s + t); // cout << "(("<<x.back() <<"-"<<x[j]<< ")+" << v[1] << ")+(" << y[k] <<"-"<< v[2] << ")=" << s+t << endl; } // if (i) q.push({x[i-1] - y[i-1], x[i-1], y[i-1]}); if (i%2) O.push({x[i] - y[i], x[i], y[i]}); else E.push({x[i] - y[i], x[i], y[i]}); } cout << mx << endl; // cout << endl; } return 0; }
[ "johniel.s.m@gmail.com" ]
johniel.s.m@gmail.com
43f3e2f2257f2ea051bcca24b8c6b624adee4dba
e64d1ce916c42dcf0f860071ffc2297a9b6d175a
/cppPoc/橱窗布置.cpp
5ea96dd0c9173de3c0b086b629ed927a0a062dd3
[]
no_license
sc-0571/cppPoc
6af608df8ecc758c0178f5c1c9f04cd4808fdbe3
4a92886d502e152a76a12101f5a446dab8895d9b
refs/heads/master
2020-03-20T21:56:55.920233
2019-11-09T04:28:15
2019-11-09T04:28:15
137,770,158
0
0
null
null
null
null
GB18030
C++
false
false
1,131
cpp
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> using namespace std; int a[101][101],b[101][101],c[101][101],d[101]; int main() { int f,v,k; scanf("%d%d",&f,&v); memset(b,128,sizeof(b)); for(int i=1;i<=f;i++) for(int j=1;j<=v;j++) { scanf("%d",&a[i][j]); } for(int i=1;i<=v-f+1;i++) b[1][i]=a[1][i]; for(int i=2;i<=f;i++) { for(int j=i;j<=v-f+i;j++) { for(k=i-1;k<=j-1;k++) { if(b[i][j]<b[i-1][k]+a[i][j]) { b[i][j]=b[i-1][k]+a[i][j]; c[i][j]=k; } } } } int maxx=-210000000,sig;for(int i=f;i<=v;i++) { if(b[f][i]>maxx) { maxx=b[f][i]; sig=i; //标记最后一束花的位置; } } printf("%d\n",maxx); for(int i=1;i<=f;i++) { d[i]=sig; sig=c[f-i+1][sig];//下一束花的位置 } for(int i=f;i>=2;i--) cout<<d[i]<<" "; cout<<d[1]<<endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
127d391c178d4f7c0867050698775d7f58ca5700
1629476aaa8c7fe790534a382a5de239c53efbbc
/Problem_4.cpp
5d30c80fd86815d434b6fe072799e2a39ee8ca4b
[]
no_license
solitoraynerussel/Experiment-2
f20c33e637457e9a8cfc1460d52afe5f32d50be0
da949909a7c49f2193caa51fa30afb5c91b387d3
refs/heads/master
2020-05-19T12:52:51.216669
2019-05-05T11:55:31
2019-05-05T11:55:31
184,865,678
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include <iostream> #include <conio.h> using namespace std; int main() { int counter; cout << "Counting to 30... START\n"; for(counter=1;counter<=9;counter++) { cout << counter << "," ; } for(counter=10;counter<=30;counter+=2) { cout << counter << ","; } getch(); return 0; }
[ "raynerussel.solito.eng@ust.edu.ph" ]
raynerussel.solito.eng@ust.edu.ph
f73f064e8e497e4c955d20bb1ee18c75b99f6d67
4a132a0c3d56276853b080008c36c379d49c473c
/Statistics/2012/bin/ra7StatConverter.h
ec772ceae3c3e55b7973f1c0cc7840b93723b287
[]
no_license
fratnikov/SusyAnalysisRA7
e0770eeb482441a6b36537a23cb021cb3834984e
35979b05bdd7265e046a07be2d67dd506ed6780f
refs/heads/master
2016-09-06T20:01:32.295348
2014-04-24T01:12:27
2014-04-24T01:12:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,854
h
// // F. Ratnikov, KIT, Sep. 2012 (fedor.ratnikov@cern.ch) // // EWKino CLs model. The stand-alone code implementing complete // description of RA7 without simplifications to reduce total number // of nuisances. // - ra7StatConverter.h/C // - CONLSP_RUTCOMB_KFactor_V02.txt, CUDAVISscanfileGGMkfactor.txt - GGM scans // // To run from the ROOT prompt: // root [1] .L ra7StatConverter.C+ // root [2] cout << "CLs 95%C.L. UL: " << ra7StatConverter::runCLs() << endl; // #include <vector> #include <string> using namespace std; namespace ra7StatConverter { struct Signature { int id; std::string name; int observed; double background; double yield; double sigmaBackgroundUncorrelated; double sigmaBackgroundDD; double sigmaBackgroundJes; double sigmaBackgroundWZ; double sigmaBackgroundZZ; double sigmaBackgroundZGamma; double sigmaBackgroundRare; double sigmaLumi; double sigmaYieldUncorrelated; double sigmaYieldElectron; double sigmaYieldMuon; double sigmaYieldTau; double sigmaYieldJes; double sigmaYieldTrigger; double sigmaYieldTheory; double quickLimit; double getQuickLimit () const; double getExpectedLimit () const; double sigmaBackground () const; double sigmaYield () const; }; typedef std::vector<Signature> Signatures; struct StatModelChannel { int id; std::string name; int observed; double background; double yield; double sigmaBackgroundUncorrelated; double sigmaBackgroundWZ; double sigmaBackgroundDD; double sigmaBackgroundZGamma; double sigmaBackgroundZZ; double sigmaBackgroundRare; double sigmaBackgroundJes; double sigmaLumi; double sigmaYieldUncorrelated; double sigmaYieldMuon; double sigmaYieldElectron; double sigmaYieldTau; double sigmaYieldTrigger; double sigmaYieldJes; double sigmaYieldTheory; }; typedef std::vector<StatModelChannel> StatModelChannels; double sumYield (const Signatures& fSignatures, int fLimit = 0); int sumObserved (const Signatures& fSignatures); double sumBackgrounds (const Signatures& fSignatures); void dump (const Signature& fSignature); void dump (const Signatures& fSignatures, int fLimit = 10); bool dumpCombined (const Signatures& fSignatures, const std::string& fFile, const std::string& fTitle = "", bool normalizeYield = false, int fChannels = 0); bool lessQuickLimit (const Signature& a, const Signature& b); bool lessExpectedLimit (const Signature& a, const Signature& b); void addDataFiles (const std::string& fMegaName, Signatures* fSignatures); bool readScanFiles (const std::string& fMegaName, int fM1, int fM2, Signatures* fSignatures, double fScale = 1); double totalXSection (const std::string& fMegaName, int fM1, int fM2); } // namespace ra7StatConverter
[ "" ]
41eab3015f1bf9ef227c01a69cde263311059df7
b936a4f32e4ffda53dcb77541a7ba68c41bcbb94
/Source/MainWindow.h
e60ac7ae682b47069b8d8f58ec70dffe3cbf0917
[ "Unlicense" ]
permissive
connerlacy/quneo_demo_lab
070c9a5f3e5249c2acd0c09e4d829b3d6e1104f1
073a81d7fa7fa462e07c7b33de3e982a03a0055c
refs/heads/master
2021-06-28T21:04:54.180420
2017-09-21T18:17:12
2017-09-21T18:17:12
12,309,331
1
0
null
null
null
null
UTF-8
C++
false
false
2,142
h
/* ============================================================================== This file was auto-generated! It contains the basic outline for a simple desktop window. ============================================================================== */ #ifndef __MAINWINDOW_H_B8899AFD__ #define __MAINWINDOW_H_B8899AFD__ #include "../JuceLibraryCode/JuceHeader.h" #include "QuNeoGraph.h" #include "AudioEngine.h" #include "MidiManager.h" #include "PluginMessage.h" #include "AboutQuNeoDemo.h" #include "MouseMask.h" #include "MenuBarObject.h" class AudioEngine; //============================================================================== class MainAppWindow : public DocumentWindow { public: //============================================================================== MainAppWindow(); ~MainAppWindow(); MenuBarObject *menuBarObject; QuNeoGraph* quNeoGraph; MidiManager* midiManager; PluginMessage* pluginMessage; IIRFilterAudioSource* samplerFilter; void closeButtonPressed(); void showAbout(); AboutQuNeoDemo* abq; ApplicationCommandManager commandManager; /* Note: Be careful when overriding DocumentWindow methods - the base class uses a lot of them, so by overriding you might break its functionality. It's best to do all your work in you content component instead, but if you really have to override any DocumentWindow methods, make sure your implementation calls the superclass's method. */ private: AudioDeviceManager deviceManager; MidiKeyboardState keyboardState; AudioSourcePlayer audioSourcePlayer; AudioSourcePlayer looperSourcePlayer; AudioSourcePlayer filterSourcePlayer; ScopedPointer<AudioEngine> audioEngine; Sampler* sampler; MouseMask* mouseMask; //MidiBuffer* masterMidi; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainAppWindow) }; #endif // __MAINWINDOW_H_B8899AFD__
[ "conner@connerlacy.com" ]
conner@connerlacy.com
7c3e2590278037f65131a8f6ff7b1fc6f5d04678
1786f51414ac5919b4a80c7858e11f7eb12cb1a9
/USST/26/B.cpp
f2161de96f51863ba9a2dce4ac0636a5c91a8abb
[]
no_license
SetsunaChyan/OI_source_code
206c4d7a0d2587a4d09beeeb185765bca0948f27
bb484131e02467cdccd6456ea1ecb17a72f6e3f6
refs/heads/master
2020-04-06T21:42:44.429553
2019-12-02T09:18:54
2019-12-02T09:18:54
157,811,588
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <cstdio> typedef long long ll; const ll mod=19260817; ll n,k; int main() { scanf("%lld%lld",&n,&k); ll ans=1,base=k+1; while(n) { if(n&1) ans=ans*base%mod; base=base*base%mod; n>>=1; } printf("%lld",ans); return 0; }
[ "ctzguozi@163.com" ]
ctzguozi@163.com
8a15065b5d15655446b88cfc3b235386eaddd67a
6f0b249aeec54eb1ff70ff366e337dcea71af00f
/aws-cpp-sdk-globalaccelerator/include/aws/globalaccelerator/model/DescribeEndpointGroupRequest.h
10cf445bc2a6f105b88e7e5fdaf4dc590caa40ee
[ "Apache-2.0", "MIT", "JSON" ]
permissive
phrocker/aws-sdk-cpp
04d6e894d59445d514414b6067ae4a6b0586b09c
352852a088161573f320ae9c6b58b27696fcf057
refs/heads/master
2020-05-16T08:32:11.091036
2019-04-23T02:19:19
2019-04-23T02:19:19
182,906,953
0
0
Apache-2.0
2019-04-23T02:18:20
2019-04-23T02:18:19
null
UTF-8
C++
false
false
3,515
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/globalaccelerator/GlobalAccelerator_EXPORTS.h> #include <aws/globalaccelerator/GlobalAcceleratorRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace GlobalAccelerator { namespace Model { /** */ class AWS_GLOBALACCELERATOR_API DescribeEndpointGroupRequest : public GlobalAcceleratorRequest { public: DescribeEndpointGroupRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DescribeEndpointGroup"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline const Aws::String& GetEndpointGroupArn() const{ return m_endpointGroupArn; } /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline bool EndpointGroupArnHasBeenSet() const { return m_endpointGroupArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline void SetEndpointGroupArn(const Aws::String& value) { m_endpointGroupArnHasBeenSet = true; m_endpointGroupArn = value; } /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline void SetEndpointGroupArn(Aws::String&& value) { m_endpointGroupArnHasBeenSet = true; m_endpointGroupArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline void SetEndpointGroupArn(const char* value) { m_endpointGroupArnHasBeenSet = true; m_endpointGroupArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline DescribeEndpointGroupRequest& WithEndpointGroupArn(const Aws::String& value) { SetEndpointGroupArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline DescribeEndpointGroupRequest& WithEndpointGroupArn(Aws::String&& value) { SetEndpointGroupArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the endpoint group to describe.</p> */ inline DescribeEndpointGroupRequest& WithEndpointGroupArn(const char* value) { SetEndpointGroupArn(value); return *this;} private: Aws::String m_endpointGroupArn; bool m_endpointGroupArnHasBeenSet; }; } // namespace Model } // namespace GlobalAccelerator } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
22be1fe0c7bc06fb85444b7ca376af13927492af
65aaba4d24cfbddb05acc0b0ad814632e3b52837
/src/osrm.net/libosrm/osrm-deps/boost/include/boost-1_62/boost/compute/algorithm/detail/copy_to_device.hpp
8054be5ee4f8a1a3a2849c5da9669ea7740dc494
[ "MIT" ]
permissive
tstaa/osrmnet
3599eb01383ee99dc6207ad39eda13a245e7764f
891e66e0d91e76ee571f69ef52536c1153f91b10
refs/heads/master
2021-01-21T07:03:22.508378
2017-02-26T04:59:50
2017-02-26T04:59:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:bc6a6bf2694dcc32f78beb1aa22a0362f032fbf61517d2d08826e1d4e9169522 size 6344
[ "ssuluh@yahoo.com" ]
ssuluh@yahoo.com
1f13c4158aa0303cea10f0e56ab9dfc9b7f23b24
7ad1f86b11739822c9e4b10fb6bace3966b8b950
/src/main.cpp
10f030578a13f174010cb087f9006b312d563f1e
[]
no_license
shadowmedia/delijn-bb10
09bf90a876f51e243fe3f8887f8b1f31e4ba94a5
39b28d6bdd58892797a15e13054f39086e2d5b2b
refs/heads/master
2021-01-13T14:04:36.367094
2013-03-29T22:58:50
2013-03-29T22:58:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,008
cpp
// Default empty project template #include <bb/cascades/Application> #include <QLocale> #include <QTranslator> #include "applicationui.hpp" // include JS Debugger / CS Profiler enabler // this feature is enabled by default in the debug build only #include <Qt/qdeclarativedebug.h> using namespace bb::cascades; Q_DECL_EXPORT int main(int argc, char **argv) { // this is where the server is started etc Application app(argc, argv); // localization support QTranslator translator; QString locale_string = QLocale().name(); QString filename = QString( "DeLijn_%1" ).arg( locale_string ); if (translator.load(filename, "app/native/qm")) { app.installTranslator( &translator ); } new ApplicationUI(&app); // we complete the transaction started in the app constructor and start the client event loop here return Application::exec(); // when loop is exited the Application deletes the scene which deletes all its children (per qt rules for children) }
[ "steven.beeckman@gmail.com" ]
steven.beeckman@gmail.com
2c73cd24ec3b46834f1a031772bc5087b304fef2
d771aaf2171df1d4d2ad1ad8386e87f6b6d29739
/network/src/network.cpp
fbeb154b677ee1331e539036a2fa96051e810e16
[]
no_license
Petterf91/ScrapEscape-Game
1d759557819671fca4d2c56f611a1e79b544a214
6141dc997c87c5a9eee14c90f27a553e3ff2e524
refs/heads/master
2020-05-20T07:22:57.560322
2019-05-07T20:54:36
2019-05-07T20:54:36
185,450,036
0
1
null
null
null
null
UTF-8
C++
false
false
625
cpp
#include "network.hpp" #include <iostream> namespace network { int Messenger::id() const { return player_id; } bool Messenger::connected() const { return /*player_host.connected();*/ true; } void Messenger::update(GameState& state, const char* ip_address) { if (ip_address) player_host = Host{ip_address}; if (player_host.client()) { GameInput send_data; send_data.data = state.inputs[player_id]; send_data.id = player_id; player_host.send(send_data); player_host.receive(state); } else { player_host.send(state); player_host.receive(state.inputs); } player_id = state.player_id; } }
[ "petter.flood91@gmail.com" ]
petter.flood91@gmail.com
c6efc4369d3358459a495b5f7758fe8c094b6401
08ed38b70ccde334ddf6abbf6d740df559731e2b
/TRC2PMBUSTool/USBI2CRS232Panel.h
1cbaa3955bbf635381f7f6b0435e5f8064b10c85
[]
no_license
bingshiue/wxPSU
32ac806cdbada9c934b18ddd00c152d0eb433c3b
33d0bf9e3c324b69e2c9f22db8c5c9d9fb6ebd13
refs/heads/master
2021-01-23T21:37:41.981082
2018-02-05T03:42:46
2018-02-05T03:42:46
57,594,833
1
0
null
null
null
null
UTF-8
C++
false
false
2,158
h
/** * @file USBI2CRS232Panel.h */ #ifndef _USBI2CRS232PANEL_H_ #define _USBI2CRS232PANEL_H_ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/aboutdlg.h> #include <wx/artprov.h> #include <wx/colordlg.h> #include <wx/wfstream.h> #include <wx/animate.h> #include <wx/statline.h> #include "Task.h" #include "PMBUSHelper.h" #include "USBAdaptorSetting.h" class USBI2CRS232Panel : public wxPanel { public: enum { CID_SMBUS_CHKBOX = 5050, }; enum { CID_UART_BUADRATE_CHKBOX = 5080, CID_UART_DATABITS_CHKBOX, CID_UART_STOPBITS_CHKBOX, CID_UART_PARITYCHK_CHKBOX }; /** * @brief Constructor. */ USBI2CRS232Panel(wxWindow* parent, IOACCESS* ioaccess, unsigned int* currentUseIO); /** * @brief Deconstructor. */ ~USBI2CRS232Panel(); wxBoxSizer *m_topLevelSizer; wxFlexGridSizer* m_fgSizer1; wxFlexGridSizer* m_fgSizer2; wxStaticBoxSizer *m_i2cportSB; wxStaticBoxSizer *m_rs232portSB; wxTextValidator m_decimalValidator; /* I2C Port */ wxStaticText *m_i2cBitRateST; wxComboBox *m_i2cBitRateCB; wxCheckBox *m_smbusCheckBox; wxStaticText *m_commBusTimeoutST; wxTextCtrl *m_commTC; wxTextCtrl *m_BusTimeoutTC; wxStaticText *m_i2cRecvBuffSizeST; wxTextCtrl *m_i2cRecvBuffSizeTC; /* RS232 Port */ wxStaticText *m_rs232PortNumberST; wxComboBox *m_rs232PortNumberCB; wxStaticText *m_rs232BuadRateST; wxComboBox *m_rs232BuadRateCB; wxStaticText *m_rs232DataBitsST; wxComboBox *m_rs232DataBitsCB; wxStaticText *m_rs232StopBitsST; wxComboBox *m_rs232StopBitsCB; wxStaticText *m_rs232ParityCheckST; wxComboBox *m_rs232ParityCheckCB; wxStaticText *m_rs232RecvBuffSizeST; wxTextCtrl *m_rs232RecvBuffSizeTC; unsigned long i2cBitRateSpeedItemArray[I2C_BIT_RATE_SPEED_ITEM_SIZE]; private: IOACCESS *m_ioaccess; unsigned int *m_currentUseIO; void SendUARTSettingAgent(void); void OnSMBUSCheckBox(wxCommandEvent& event); void OnUARTBuadRateCheckBox(wxCommandEvent& event); void OnUARTDataBitsCheckBox(wxCommandEvent& event); void OnUARTStopBitsCheckBox(wxCommandEvent& event); void OnUARTParityCheckCheckBox(wxCommandEvent& event); wxDECLARE_EVENT_TABLE(); }; #endif
[ "Ben_Hsieh@APITECT.com.tw" ]
Ben_Hsieh@APITECT.com.tw
e01e8e5e2f53cb0135ae419f5a3a3712a4baf5ae
d3273fc5d137364fb9619a6edefa9e8363572576
/src/lexer/unknowntoken.cpp
6cd9e4f2289c9ea6bb21c3802c40efd4f69fa24c
[ "MIT" ]
permissive
masyagin1998/CSC
245f054cbfe6ba9996a07a1ad41a2962eb4cd60d
d1e93697f80b071a69f776e70ea15b3280a53837
refs/heads/master
2020-05-09T20:37:25.227647
2019-07-28T06:37:07
2019-07-28T06:37:07
181,414,110
12
3
null
null
null
null
UTF-8
C++
false
false
710
cpp
#include "unknowntoken.hpp" UNKNOWN_TOKEN*UNKNOWN_TOKEN::read(POSITION pos) { POSITION starting = pos; std::string unknown = ""; while (pos.is_unknown() && !pos.is_EOF()) { unknown += pos.get_code(); pos = pos.next(); } return new UNKNOWN_TOKEN(DOMAIN_TAG::UNKNOWN, unknown, starting, pos); } UNKNOWN_TOKEN::UNKNOWN_TOKEN(DOMAIN_TAG tag, std::string unknown, POSITION starting, POSITION following) : TOKEN(tag, starting, following), unknown(unknown) {} std::string UNKNOWN_TOKEN::get_unknown() const { return unknown; } std::ostream& operator<<(std::ostream &strm, const UNKNOWN_TOKEN &tok) { return strm << "UNKNOWN " << ((TOKEN) tok) << ": " << tok.unknown; }
[ "masyagin1998@yandex.ru" ]
masyagin1998@yandex.ru
cf8a181aa0147a6c2d4de59b19586d080fbe84d7
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/codeforce/701-750/703/d2.cpp
d89777ddfb46b3830241f88de7b0f844a82656a5
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
1,231
cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define FORR2(x,y,arr) for(auto& [x,y]:arr) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) template<class T> bool chmax(T &a, const T &b) { if(a<b){a=b;return 1;}return 0;} template<class T> bool chmin(T &a, const T &b) { if(a>b){a=b;return 1;}return 0;} //------------------------------------------------------- int N,K; int A[202020]; int S[202020]; int ok(int v) { int i; int mi=1<<20; FOR(i,N) { if(A[i]>=v) S[i+1]=S[i]+1; else S[i+1]=S[i]-1; if(i+1>=K) mi=min(mi,S[i+1-K]); if(S[i+1]-mi>0) return 1; } return 0; } void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>K; FOR(i,N) cin>>A[i]; int ma=0; for(i=20;i>=0;i--) if(ok(ma+(1<<i))) ma+=1<<i; cout<<ma<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
6ddbe37d106b6400f90fbc69d271826b1088e9df
71713e3ea8979e5da20e4dc0ce473acfbec39d41
/sortproject-cpp/stackSort.cpp
014f58fee9c052e334ae1e6783ecd1c12bc03263
[]
no_license
FuzuoZhang/practice
7b6cce93361bb47eb95d7bef012f115a7f96b90c
1d33eff10a62039a3bd21dc73c03be5687c57ac8
refs/heads/master
2020-04-17T17:04:25.952091
2019-04-19T13:26:28
2019-04-19T13:26:28
166,768,820
0
0
null
null
null
null
GB18030
C++
false
false
2,111
cpp
#include<iostream> #include<vector> using namespace std; void creatstack(vector<int> *arr) { int n = arr->size(); int tail = n / 2 - 1; //最后一个非叶节点的索引; int i; for (i = tail; i >= 0; i--) { int j = i; while (j <= tail) { int maxchi; if (2 * j + 2 < n) { maxchi = (*arr)[2 * j + 1] > (*arr)[2 * j + 2] ? (*arr)[2 * j + 1] : (*arr)[2 * j + 2]; } else maxchi = (*arr)[2 * j + 1]; if ((*arr)[j] < maxchi) { int temp = (*arr)[j]; if (2 * j + 2 < n && (*arr)[2 * j + 1] < (*arr)[2 * j + 2]) { (*arr)[j] = (*arr)[2 * j + 2]; (*arr)[2 * j + 2] = temp; j = 2 * j + 2; } else { (*arr)[j] = (*arr)[2 * j + 1]; (*arr)[2 * j + 1] = temp; j = 2 * j + 1; } } else break; } } } //堆排序 大顶堆 vector<int> stacksort(vector<int> arr){ int n = arr.size(); if (n <= 1) return arr; creatstack(&arr); //建堆 int i,j,len; for (i = 0; i < n - 1 ; i++) { //swap head and tail int temp = arr[0]; arr[0] = arr[n - 1 - i]; arr[n - 1 - i] = temp; len = n - 1 - i; //下滤 for (j = 0; j <= len / 2 - 1;) { int maxchi; if (2 * j + 2 < len) { maxchi = arr[2 * j + 1] > arr[2 * j + 2] ? arr[2 * j + 1] : arr[2 * j + 2]; } else maxchi = arr[2 * j + 1]; if (arr[j] < maxchi) { int temp = arr[j]; if (2 * j + 2 < len && arr[2 * j + 1] < arr[2 * j + 2]) { arr[j] = arr[2 * j + 2]; arr[2 * j + 2] = temp; j = 2 * j + 2; } else { arr[j] = arr[2 * j + 1]; arr[2 * j + 1] = temp; j = 2 * j + 1; } } else break; } } return arr; } void showarr(vector<int> arr) { vector<int>::iterator i; for (i = arr.begin(); i != arr.end(); i++) { cout << *i<<" "; } cout << endl; } int main() { int n; //length of arr cin >> n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } cout << "Ending input."; cout << "The arr before is:" << endl; showarr(arr); vector<int> sort_arr = stacksort(arr); cout << "The arr sorted is:" << endl; showarr(sort_arr); system("pause"); return 0; }
[ "zfz_ll@163.com" ]
zfz_ll@163.com
0fef90d2e44435c849e64e2d70316976172d9261
a9a4f3701dca2023ec8c6c0b5b600b6d13274bab
/AnomolyDetection/include/armadillo_bits/SpRow_bones.hpp
dab47a400e074bf5669b2ccdbad7932e1b29d14b
[]
no_license
tjflexmaster/CS650
54d9a56224925768188791da2e05d6442328daf1
be12ab2a2365b1c591eb97e082868030c0c1c1e7
refs/heads/master
2021-03-19T07:13:50.025532
2012-12-12T17:10:41
2012-12-12T17:10:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,236
hpp
// Copyright (C) 2011-2012 Ryan Curtin // Copyright (C) 2011 Matthew Amidon // // This file is part of the Armadillo C++ library. // It is provided without any warranty of fitness // for any purpose. You can redistribute this file // and/or modify it under the terms of the GNU // Lesser General Public License (LGPL) as published // by the Free Software Foundation, either version 3 // of the License or (at your option) any later version. // (see http://www.opensource.org/licenses for more info) //! \addtogroup SpRow //! @{ //! Class for sparse row vectors (sparse matrices with only one row) template<typename eT> class SpRow : public SpMat<eT> { public: typedef eT elem_type; typedef typename get_pod_type<eT>::result pod_type; static const bool is_row = true; static const bool is_col = false; inline SpRow(); inline explicit SpRow(const uword N); inline SpRow(const uword in_rows, const uword in_cols); inline SpRow(const char* text); inline const SpRow& operator=(const char* text); inline SpRow(const std::string& text); inline const SpRow& operator=(const std::string& text); inline const SpRow& operator=(const eT val); template<typename T1> inline SpRow(const Base<eT,T1>& X); template<typename T1> inline const SpRow& operator=(const Base<eT,T1>& X); template<typename T1> inline SpRow(const SpBase<eT,T1>& X); template<typename T1> inline const SpRow& operator=(const SpBase<eT,T1>& X); template<typename T1, typename T2> inline explicit SpRow(const SpBase<pod_type,T1>& A, const SpBase<pod_type,T2>& B); inline SpValProxy<SpMat<eT> > col(const uword col_num); inline eT col(const uword col_num) const; // arma_inline subview_row<eT> cols(const uword in_col1, const uword in_col2); // arma_inline const subview_row<eT> cols(const uword in_col1, const uword in_col2) const; // arma_inline subview_row<eT> subvec(const uword in_col1, const uword in_col2); // arma_inline const subview_row<eT> subvec(const uword in_col1, const uword in_col2) const; // arma_inline subview_row<eT> subvec(const span& col_span); // arma_inline const subview_row<eT> subvec(const span& col_span) const; // arma_inline subview_row<eT> operator()(const span& col_span); // arma_inline const subview_row<eT> operator()(const span& col_span) const; inline void shed_col (const uword col_num); inline void shed_cols(const uword in_col1, const uword in_col2); // inline void insert_cols(const uword col_num, const uword N, const bool set_to_zero = true); // template<typename T1> inline void insert_cols(const uword col_num, const Base<eT,T1>& X); typedef typename SpMat<eT>::iterator row_iterator; typedef typename SpMat<eT>::const_iterator const_row_iterator; inline row_iterator begin_row(); inline const_row_iterator begin_row() const; inline row_iterator end_row(); inline const_row_iterator end_row() const; #ifdef ARMA_EXTRA_SPROW_PROTO #include ARMA_INCFILE_WRAP(ARMA_EXTRA_SPROW_PROTO) #endif }; //! @}
[ "tjflexmaster@gmail.com" ]
tjflexmaster@gmail.com
71cf410c9c66aaa91445529a377d75b3605d9d8c
de196b61e4dd7964f83b52d6756af99a0218a051
/Warp Syndrome/Motor2D/j1Audio.h
ea11aa415f61b76dd9dfba87758ba802fcfbbce7
[ "Zlib" ]
permissive
oscarpm5/Warp-Syndrome
77228575fdcef03ed1b377079565b6d6b169f4fe
87bff81c57a593fd163558ca4e60b31f2c2d227f
refs/heads/master
2020-09-22T03:46:38.329323
2019-11-20T08:41:46
2019-11-20T08:41:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
h
#ifndef __j1AUDIO_H__ #define __j1AUDIO_H__ #include "j1Module.h" #include "SDL_mixer\include\SDL_mixer.h" #include "p2List.h" #define DEFAULT_MUSIC_FADE_TIME 2.0f struct _Mix_Music; struct Mix_Chunk; enum Audio_Flags { MUSIC_AND_FX=-1, MUSIC, FX }; class j1Audio : public j1Module { public: //--------INTERNAL CONTROL---------// //Constructor j1Audio(); // Destructor virtual ~j1Audio(); // Called before render is available bool Awake(pugi::xml_node&); // Called before quitting bool CleanUp(); // Play a music file bool PlayMusic(const char* path, float fade_time = DEFAULT_MUSIC_FADE_TIME); //Set the volume of the audio. //For the flags use -1 for both channels, 0 for just music and 1 for just FX, or use the "Audio_Flags" enum as a value. void SetVolume(int volume,int flag=-1); //Adds a volume to the current volume value. //For the flags use -1 for both channels, 0 for just music and 1 for just FX, or use the "Audio_Flags" enum as a value. void AddVolume(int volume, int flag = -1); //--------AUDIO---------// // Load a WAV in memory unsigned int LoadFx(const char* path); // Play a previously loaded WAV bool PlayFx(unsigned int fx, int repeat = 0); bool Load(pugi::xml_node&); bool Save(pugi::xml_node&) const; private: //--------AUDIO---------// //Pointer to the level's track _Mix_Music* music; //List to all sound effects p2List<Mix_Chunk*> fx; uint music_volume=0; uint fx_volume=0; }; #endif // __j1AUDIO_H__
[ "47557468+oscarpm5@users.noreply.github.com" ]
47557468+oscarpm5@users.noreply.github.com
122e19b743e29f528d07bd7d6045f20cd3d604de
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/spirit/home/karma/numeric/int.hpp
234652700402538467ec14c721af366a5da25343
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,427
hpp
// Copyright (c) 2001-2012 Hartmut Kaiser // // 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) #if !defined(BOOST_SPIRIT_KARMA_INT_FEB_23_2007_0840PM) #define BOOST_SPIRIT_KARMA_INT_FEB_23_2007_0840PM #if defined(_MSC_VER) #pragma once #endif #include <sstd/boost/limits.hpp> #include <sstd/boost/config.hpp> #include <sstd/boost/mpl/bool.hpp> #include <sstd/boost/utility/enable_if.hpp> #include <sstd/boost/spirit/home/support/common_terminals.hpp> #include <sstd/boost/spirit/home/support/string_traits.hpp> #include <sstd/boost/spirit/home/support/numeric_traits.hpp> #include <sstd/boost/spirit/home/support/info.hpp> #include <sstd/boost/spirit/home/support/char_class.hpp> #include <sstd/boost/spirit/home/support/container.hpp> #include <sstd/boost/spirit/home/support/detail/get_encoding.hpp> #include <sstd/boost/spirit/home/support/detail/is_spirit_tag.hpp> #include <sstd/boost/spirit/home/karma/meta_compiler.hpp> #include <sstd/boost/spirit/home/karma/delimit_out.hpp> #include <sstd/boost/spirit/home/karma/auxiliary/lazy.hpp> #include <sstd/boost/spirit/home/karma/detail/get_casetag.hpp> #include <sstd/boost/spirit/home/karma/detail/extract_from.hpp> #include <sstd/boost/spirit/home/karma/detail/enable_lit.hpp> #include <sstd/boost/spirit/home/karma/domain.hpp> #include <sstd/boost/spirit/home/karma/numeric/detail/numeric_utils.hpp> #include <sstd/boost/fusion/include/at.hpp> #include <sstd/boost/fusion/include/value_at.hpp> #include <sstd/boost/fusion/include/vector.hpp> /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { namespace tag { template <typename T, unsigned Radix, bool force_sign> struct int_generator { BOOST_SPIRIT_IS_TAG() }; } namespace karma { /////////////////////////////////////////////////////////////////////// // This one is the class that the user can instantiate directly in // order to create a customized int generator template <typename T = int, unsigned Radix = 10, bool force_sign = false> struct int_generator : spirit::terminal<tag::int_generator<T, Radix, force_sign> > {}; } /////////////////////////////////////////////////////////////////////////// // Enablers /////////////////////////////////////////////////////////////////////////// template <> struct use_terminal<karma::domain, tag::short_> // enables short_ : mpl::true_ {}; template <> struct use_terminal<karma::domain, tag::int_> // enables int_ : mpl::true_ {}; template <> struct use_terminal<karma::domain, tag::long_> // enables long_ : mpl::true_ {}; #ifdef BOOST_HAS_LONG_LONG template <> struct use_terminal<karma::domain, tag::long_long> // enables long_long : mpl::true_ {}; #endif /////////////////////////////////////////////////////////////////////////// template <> struct use_terminal<karma::domain, short> // enables lit(short(0)) : mpl::true_ {}; template <> struct use_terminal<karma::domain, int> // enables lit(0) : mpl::true_ {}; template <> struct use_terminal<karma::domain, long> // enables lit(0L) : mpl::true_ {}; #ifdef BOOST_HAS_LONG_LONG template <> struct use_terminal<karma::domain, boost::long_long_type> // enables lit(0LL) : mpl::true_ {}; #endif /////////////////////////////////////////////////////////////////////////// template <typename A0> struct use_terminal<karma::domain // enables short_(...) , terminal_ex<tag::short_, fusion::vector1<A0> > > : mpl::true_ {}; template <typename A0> struct use_terminal<karma::domain // enables int_(...) , terminal_ex<tag::int_, fusion::vector1<A0> > > : mpl::true_ {}; template <typename A0> struct use_terminal<karma::domain // enables long_(...) , terminal_ex<tag::long_, fusion::vector1<A0> > > : mpl::true_ {}; #ifdef BOOST_HAS_LONG_LONG template <typename A0> struct use_terminal<karma::domain // enables long_long(...) , terminal_ex<tag::long_long, fusion::vector1<A0> > > : mpl::true_ {}; #endif /////////////////////////////////////////////////////////////////////////// template <> // enables *lazy* short_(...) struct use_lazy_terminal<karma::domain, tag::short_, 1> : mpl::true_ {}; template <> // enables *lazy* int_(...) struct use_lazy_terminal<karma::domain, tag::int_, 1> : mpl::true_ {}; template <> // enables *lazy* long_(...) struct use_lazy_terminal<karma::domain, tag::long_, 1> : mpl::true_ {}; #ifdef BOOST_HAS_LONG_LONG template <> // enables *lazy* long_long(...) struct use_lazy_terminal<karma::domain, tag::long_long, 1> : mpl::true_ {}; #endif /////////////////////////////////////////////////////////////////////////// // enables any custom int_generator template <typename T, unsigned Radix, bool force_sign> struct use_terminal<karma::domain, tag::int_generator<T, Radix, force_sign> > : mpl::true_ {}; // enables any custom int_generator(...) template <typename T, unsigned Radix, bool force_sign, typename A0> struct use_terminal<karma::domain , terminal_ex<tag::int_generator<T, Radix, force_sign> , fusion::vector1<A0> > > : mpl::true_ {}; // enables *lazy* custom int_generator template <typename T, unsigned Radix, bool force_sign> struct use_lazy_terminal< karma::domain , tag::int_generator<T, Radix, force_sign> , 1 // arity > : mpl::true_ {}; // enables lit(int) template <typename A0> struct use_terminal<karma::domain , terminal_ex<tag::lit, fusion::vector1<A0> > , typename enable_if<traits::is_int<A0> >::type> : mpl::true_ {}; }} /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { namespace karma { #ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS using spirit::short_; using spirit::int_; using spirit::long_; #ifdef BOOST_HAS_LONG_LONG using spirit::long_long; #endif using spirit::lit; // lit(1) is equivalent to 1 #endif using spirit::short_type; using spirit::int_type; using spirit::long_type; #ifdef BOOST_HAS_LONG_LONG using spirit::long_long_type; #endif using spirit::lit_type; /////////////////////////////////////////////////////////////////////////// // This specialization is used for int generators not having a direct // initializer: int_, long_ etc. These generators must be used in // conjunction with an Attribute. /////////////////////////////////////////////////////////////////////////// template < typename T, typename CharEncoding, typename Tag, unsigned Radix , bool force_sign> struct any_int_generator : primitive_generator<any_int_generator<T, CharEncoding, Tag, Radix , force_sign> > { private: template <typename OutputIterator, typename Attribute> static bool insert_int(OutputIterator& sink, Attribute const& attr) { return sign_inserter::call(sink, traits::test_zero(attr) , traits::test_negative(attr), force_sign) && int_inserter<Radix, CharEncoding, Tag>::call(sink , traits::get_absolute_value(attr)); } public: template <typename Context, typename Unused> struct attribute { typedef T type; }; // check template Attribute 'Radix' for validity BOOST_SPIRIT_ASSERT_MSG( Radix == 2 || Radix == 8 || Radix == 10 || Radix == 16, not_supported_radix, ()); BOOST_SPIRIT_ASSERT_MSG(std::numeric_limits<T>::is_signed, signed_unsigned_mismatch, ()); // int has a Attribute attached template <typename OutputIterator, typename Context, typename Delimiter , typename Attribute> static bool generate(OutputIterator& sink, Context& context, Delimiter const& d , Attribute const& attr) { if (!traits::has_optional_value(attr)) return false; // fail if it's an uninitialized optional return insert_int(sink, traits::extract_from<T>(attr, context)) && delimit_out(sink, d); // always do post-delimiting } // this int has no Attribute attached, it needs to have been // initialized from a direct literal template <typename OutputIterator, typename Context, typename Delimiter> static bool generate(OutputIterator&, Context&, Delimiter const&, unused_type) { // It is not possible (doesn't make sense) to use numeric generators // without providing any attribute, as the generator doesn't 'know' // what to output. The following assertion fires if this situation // is detected in your code. BOOST_SPIRIT_ASSERT_FAIL(OutputIterator, int_not_usable_without_attribute, ()); return false; } template <typename Context> static info what(Context const& /*context*/) { return info("integer"); } }; /////////////////////////////////////////////////////////////////////////// // This specialization is used for int generators having a direct // initializer: int_(10), long_(20) etc. /////////////////////////////////////////////////////////////////////////// template < typename T, typename CharEncoding, typename Tag, unsigned Radix , bool force_sign, bool no_attribute> struct literal_int_generator : primitive_generator<literal_int_generator<T, CharEncoding, Tag, Radix , force_sign, no_attribute> > { private: template <typename OutputIterator, typename Attribute> static bool insert_int(OutputIterator& sink, Attribute const& attr) { return sign_inserter::call(sink, traits::test_zero(attr) , traits::test_negative(attr), force_sign) && int_inserter<Radix, CharEncoding, Tag>::call(sink , traits::get_absolute_value(attr)); } public: template <typename Context, typename Unused = unused_type> struct attribute : mpl::if_c<no_attribute, unused_type, T> {}; literal_int_generator(typename add_const<T>::type n) : n_(n) {} // check template Attribute 'Radix' for validity BOOST_SPIRIT_ASSERT_MSG( Radix == 2 || Radix == 8 || Radix == 10 || Radix == 16, not_supported_radix, ()); BOOST_SPIRIT_ASSERT_MSG(std::numeric_limits<T>::is_signed, signed_unsigned_mismatch, ()); // A int_(1) which additionally has an associated attribute emits // its immediate literal only if it matches the attribute, otherwise // it fails. template <typename OutputIterator, typename Context, typename Delimiter , typename Attribute> bool generate(OutputIterator& sink, Context& context , Delimiter const& d, Attribute const& attr) const { typedef typename attribute<Context>::type attribute_type; if (!traits::has_optional_value(attr) || n_ != traits::extract_from<attribute_type>(attr, context)) { return false; } return insert_int(sink, n_) && delimit_out(sink, d); } // A int_(1) without any associated attribute just emits its // immediate literal template <typename OutputIterator, typename Context, typename Delimiter> bool generate(OutputIterator& sink, Context&, Delimiter const& d , unused_type) const { return insert_int(sink, n_) && delimit_out(sink, d); } template <typename Context> static info what(Context const& /*context*/) { return info("integer"); } T n_; }; /////////////////////////////////////////////////////////////////////////// // Generator generators: make_xxx function (objects) /////////////////////////////////////////////////////////////////////////// namespace detail { template <typename T, typename Modifiers, unsigned Radix = 10 , bool force_sign = false> struct make_int { static bool const lower = has_modifier<Modifiers, tag::char_code_base<tag::lower> >::value; static bool const upper = has_modifier<Modifiers, tag::char_code_base<tag::upper> >::value; typedef any_int_generator< T , typename spirit::detail::get_encoding_with_case< Modifiers, unused_type, lower || upper>::type , typename detail::get_casetag<Modifiers, lower || upper>::type , Radix , force_sign > result_type; result_type operator()(unused_type, unused_type) const { return result_type(); } }; } /////////////////////////////////////////////////////////////////////////// template <typename Modifiers> struct make_primitive<tag::short_, Modifiers> : detail::make_int<short, Modifiers> {}; template <typename Modifiers> struct make_primitive<tag::int_, Modifiers> : detail::make_int<int, Modifiers> {}; template <typename Modifiers> struct make_primitive<tag::long_, Modifiers> : detail::make_int<long, Modifiers> {}; #ifdef BOOST_HAS_LONG_LONG template <typename Modifiers> struct make_primitive<tag::long_long, Modifiers> : detail::make_int<boost::long_long_type, Modifiers> {}; #endif template <typename T, unsigned Radix, bool force_sign, typename Modifiers> struct make_primitive<tag::int_generator<T, Radix, force_sign>, Modifiers> : detail::make_int<typename remove_const<T>::type , Modifiers, Radix, force_sign> {}; /////////////////////////////////////////////////////////////////////////// namespace detail { template <typename T, typename Modifiers, unsigned Radix = 10 , bool force_sign = false> struct make_int_direct { static bool const lower = has_modifier<Modifiers, tag::char_code_base<tag::lower> >::value; static bool const upper = has_modifier<Modifiers, tag::char_code_base<tag::upper> >::value; typedef literal_int_generator< T , typename spirit::detail::get_encoding_with_case< Modifiers, unused_type, lower || upper>::type , typename detail::get_casetag<Modifiers, lower || upper>::type , Radix, force_sign, false > result_type; template <typename Terminal> result_type operator()(Terminal const& term, unused_type) const { return result_type(fusion::at_c<0>(term.args)); } }; } /////////////////////////////////////////////////////////////////////////// template <typename Modifiers, typename A0> struct make_primitive< terminal_ex<tag::short_, fusion::vector1<A0> >, Modifiers> : detail::make_int_direct<short, Modifiers> {}; template <typename Modifiers, typename A0> struct make_primitive< terminal_ex<tag::int_, fusion::vector1<A0> >, Modifiers> : detail::make_int_direct<int, Modifiers> {}; template <typename Modifiers, typename A0> struct make_primitive< terminal_ex<tag::long_, fusion::vector1<A0> >, Modifiers> : detail::make_int_direct<long, Modifiers> {}; #ifdef BOOST_HAS_LONG_LONG template <typename Modifiers, typename A0> struct make_primitive< terminal_ex<tag::long_long, fusion::vector1<A0> >, Modifiers> : detail::make_int_direct<boost::long_long_type, Modifiers> {}; #endif template <typename T, unsigned Radix, bool force_sign, typename A0 , typename Modifiers> struct make_primitive< terminal_ex<tag::int_generator<T, Radix, force_sign> , fusion::vector1<A0> >, Modifiers> : detail::make_int_direct<typename remove_const<T>::type , Modifiers, Radix, force_sign> {}; /////////////////////////////////////////////////////////////////////////// namespace detail { template <typename T, typename Modifiers> struct basic_int_literal { static bool const lower = has_modifier<Modifiers, tag::char_code_base<tag::lower> >::value; static bool const upper = has_modifier<Modifiers, tag::char_code_base<tag::upper> >::value; typedef literal_int_generator< T , typename spirit::detail::get_encoding_with_case< Modifiers, unused_type, lower || upper>::type , typename detail::get_casetag<Modifiers, lower || upper>::type , 10, false, true > result_type; template <typename T_> result_type operator()(T_ i, unused_type) const { return result_type(i); } }; } template <typename Modifiers> struct make_primitive<short, Modifiers> : detail::basic_int_literal<short, Modifiers> {}; template <typename Modifiers> struct make_primitive<int, Modifiers> : detail::basic_int_literal<int, Modifiers> {}; template <typename Modifiers> struct make_primitive<long, Modifiers> : detail::basic_int_literal<long, Modifiers> {}; #ifdef BOOST_HAS_LONG_LONG template <typename Modifiers> struct make_primitive<boost::long_long_type, Modifiers> : detail::basic_int_literal<boost::long_long_type, Modifiers> {}; #endif // lit(int) template <typename Modifiers, typename A0> struct make_primitive< terminal_ex<tag::lit, fusion::vector1<A0> > , Modifiers , typename enable_if<traits::is_int<A0> >::type> { static bool const lower = has_modifier<Modifiers, tag::char_code_base<tag::lower> >::value; static bool const upper = has_modifier<Modifiers, tag::char_code_base<tag::upper> >::value; typedef literal_int_generator< typename remove_const<A0>::type , typename spirit::detail::get_encoding_with_case< Modifiers, unused_type, lower || upper>::type , typename detail::get_casetag<Modifiers, lower || upper>::type , 10, false, true > result_type; template <typename Terminal> result_type operator()(Terminal const& term, unused_type) const { return result_type(fusion::at_c<0>(term.args)); } }; }}} #endif
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
fd3f224eb6f67fda986c466d459f3d05c5e4d5ba
641768eb03144e6e66bcc5991e6b151885952c12
/src/ANM/ModesCalculator/Internals/InternalModesCalculator.cpp
f2fc6c241fe9591dfcf8eb44feb66784b0663d3d
[ "MIT" ]
permissive
victor-gil-sepulveda/PhD-ANMInternalCoordinates
47f42b0b07e5df947c163ddda2d7d6567d008445
c49b8627f08f614cef764692dee8627c182d9b6c
refs/heads/master
2021-01-21T12:49:56.260755
2015-04-08T13:26:30
2015-04-08T13:26:30
31,322,617
2
0
null
null
null
null
UTF-8
C++
false
false
12,515
cpp
///////////////////////////////////////////////////////////////////////////// /// InternalModesCalculator.cpp /// /// Implementation of InternalModesCalculator class /// /// /// \copyright Copyright 2010-2014 BARCELONA SUPERCOMPUTING CENTER. See the COPYRIGHT file at the top-level directory of this distribution. /// /// \author mrivero /// \date 05/09/2012 ///////////////////////////////////////////////////////////////////////////// #include "InternalModesCalculator.h" #include "MatrixCalculationFunctions/HessianFunctions.h" #include "MatrixCalculationFunctions/KineticMatrixFunctions.h" #include "../../Parameters/AnmParameters.h" #include "../../ModesCalculator/AnmEigen.h" #include "../../AnmNodeList.h" #include "../../AnmUnitNodeList.h" #include "CoarseGrainModel/Unit.h" #include <vector> #include "../../../Tools/Utils.h" #include "../../../Tools/Math/Point.h" #include "MatrixCalculationFunctions/ANMICMath.h" #include <string> #include "../../../Tools/TestTools.h" #include "ElasticConstantCalculator.h" #include <iostream> #include "../../Tools/Inout/ModesWriter.h" #include "InverseExponentialElasticConstant.h" #include "CoarseGrainModel/UnitTools.h" #include <map> using namespace std; //------------------------------------- // C definition of the needed functions from LAPACK. This definitions must be moved to the Math package upon // final merge. //------------------------------------- extern "C" { void dspgvx_(int* itype, char* jobz, char* range, char* uplo, int* N, double* A, double* B, double* vl, double* vu, int* il, int* iu, double* abstol, int* M, double*W, double* Z, int* ldz, double* work, int* iwork, int* ifail, int* info); double dlamch_(char* cmach); } //-------------------------------- InternalModesCalculator::InternalModesCalculator() : ModesCalculator() { } InternalModesCalculator::~InternalModesCalculator(){ } /////////////////////////////////////////////////////////////// /// \remarks /// Calculation of the eigenvalues and vectors of a given structure defined by its coarse grained model. /// /// \param anmParameters [In ] Parameters of this ANM calculation /// \param node_list [In ] Stores the coarse grain representation of the structure in Unit objects. /// \param eigen [In / Out] The object that will hold the eigenvectors and values once calculated. /// /// \author vgil /// \date 07/01/2015 /////////////////////////////////////////////////////////////// void InternalModesCalculator::calculateEigenValuesAndVectors(AnmParameters * anmParameters, const AnmNodeList & node_list, AnmEigen * eigen) { // We need to first update the model AnmUnitNodeList &unitNodeList = dynamic_cast<AnmUnitNodeList &>(const_cast<AnmNodeList &>(node_list)); // Recenter unitNodeList.centerAtCOM(); // Update nodes unitNodeList.updateUnitList(); // Build coarse grain model std::vector<Unit*> units = unitNodeList.getNodeList(); // TODO: RELLENAR modelo cout<<"DBG: Calculating Eig. for "<< units.size() <<" units."<<endl; // Calculate K and H double cutoff = anmParameters->getCutoff(); double k = anmParameters->getConstantForHessian(); cout<<"DBG: InternalModesCalculator::calculateEigenValuesAndVectors - k: "<<k<<", cutoff: "<<cutoff<<endl; InverseExponentialElasticConstant ecc(k, 3.8, 6); std::vector< std::vector<double> > U = ANMICHessianCalculator::calculateU(cutoff*cutoff, &ecc, units, false); // Skip OXT TriangularMatrix* H = ANMICHessianCalculator::calculateH(units, U); if(anmParameters->getTipEffectLowering()){ cout<<"DBG: Trying to lower tip effect."<<endl; ANMICHessianCalculator::modifyHessianWithExtraTorsion(H); } TriangularMatrix* K = ANMICKineticMatrixCalculator::calculateK(units, INMA); // And then the modes calculate_modes(anmParameters, H, K, eigen); delete H; delete K; } /////////////////////////////////////////////////////////////// /// \remarks /// Does the actual eigencalculation using K and H matrices. /// /// \param anmParameters [In ] Parameters of this ANM calculation /// \param H [In / Out] H matrix (hessian matrix). May be modified by LAPACK. /// \param K [In / Out] K matrix (kinetic matrix). May be modified by LAPACK. /// \param eigen [In / Out] The object that will hold the calculated eigenvectors and values. /// /// \author vgil /// \date 07/01/2015 /////////////////////////////////////////////////////////////// void InternalModesCalculator::calculate_modes(AnmParameters * anmParameters, TriangularMatrix* H, TriangularMatrix* K, AnmEigen* eigen){ // TestTools::save_vector( H->data().begin(), "H.txt", 0, H->data().size()-1, 4); // TestTools::save_vector( K->data().begin(), "K.txt", 0, K->data().size()-1, 4); int number_of_eigen = anmParameters->getNumberOfModes(); int itype = 1; char jobz = 'V'; char range = 'I'; char uplo = 'U'; int N = K->size1(); int il = 1; int iu = number_of_eigen; char cmach = 'S'; double abstol = 2*dlamch_(&cmach); //override abstol = 0.0001; int M; double* W = new double[number_of_eigen]; double* Z = new double[N*number_of_eigen]; double * WORK = new double[N*8]; int * IWORK = new int[N*5]; int * IFAIL = new int[N]; int info; dspgvx_(&itype, // ITYPE A*x = (lambda)*B*x &jobz, // JOBZ Compute eigenvalues and eigenvectors. &range, // RANGE &uplo, &N, H->data().begin(), K->data().begin(), NULL, // vl vu NULL, &il, // il iu &iu, &abstol,// ABSTOL &M, // M The total number of eigenvalues found W, // W (vector) eigenvalues in ascending order Z, // Z (Matrix) eigenvectors &N, // LDZ leading dimension de Z WORK, IWORK, IFAIL, // IFAIL contains the indices of the eigenvectors that failed to converge &info); delete [] WORK; delete [] IWORK; delete [] IFAIL; for (unsigned int i = 0; i < number_of_eigen; i++){ cout<<"DBG: eigen val: "<<W[i]<<endl; } eigen->initialize(W, Z, number_of_eigen, H->size1(), false); delete [] W; delete [] Z; } /////////////////////////////////////////////////////////////// /// \remarks /// Converts the modes expressed in internal coordinates to modes expressed in /// cartesian coordinates (all atom). See code for details on calculations. /// /// \param units [In ] Coarse grain representation of the structure in Unit objects. /// \param in [In / Out] AnmEigen object containing modes in internal coordinates. /// /// \return The AnmEigen object holding the converted modes. /// /// \author vgil /// \date 07/01/2015 /////////////////////////////////////////////////////////////// AnmEigen* InternalModesCalculator::internalToCartesian(vector<Unit*>& units, AnmEigen* in, bool onlyHeavy) { AnmEigen* out = new AnmEigen; unsigned int number_of_modes = in->getNumberOfModes(); unsigned int number_of_dihedrals = units.size() - 1; vector<double> eigenvalues_cc; vector< vector<double> > eigenvectors_cc; vector<Atom*> unit_atoms; UnitTools::getAllAtomsFromUnits(units, unit_atoms, onlyHeavy); cout<<"DBG: Conversion from IC to CC. N.Units: "<<units.size()<<" N.Atoms "<<(onlyHeavy? "(Heavy): ": "(All): ")<<unit_atoms.size()<<endl; // Create a dictionary to index them using the pointer map<Atom*,int> atom2index; for (unsigned int i =0; i< unit_atoms.size();++i){ atom2index[unit_atoms[i]] = i; } // Precalculate terms of ecs 4.1.12 and .13 in J.R. Lopez Blanco Thesis (dr/dq) vector<Point> term1, term2, term1b, term2b; double I[3][3], I_inv[3][3]; ANMICKineticMatrixCalculator::calculateI(I, units, pair<int,int>(0, units.size()-1), INMA); // calculate I for all units i in [0,number_of_units-1] ANMICMath::invertIMatrix(I,I_inv); for(unsigned int dihedral = 0; dihedral < number_of_dihedrals; ++dihedral){ ANMICKineticMatrixCalculator::dr1dq( units, dihedral, I_inv, term1, term2); ANMICKineticMatrixCalculator::dr2dq( units, dihedral, I_inv, term1b, term2b); } // Calculate per-atom contributions of each dihedral turn for (unsigned int k = 0; k < number_of_modes; k++){ // Add eigenvalue (no need to convert this one) eigenvalues_cc.push_back( in->getEigenValueOfMode(k)); //Calc eigenvector for mode vector<double> eigenvector_ic = in->getEigenVectorOfMode(k); // Mode k , eigenvector in internal coords Point p_eigenvector_cc[unit_atoms.size()]; vector<Atom*> all_atoms; UnitTools::getAllAtomsFromUnitRange(units, all_atoms, 0, units.size()-1, onlyHeavy); for(unsigned int dihedral = 0; dihedral < number_of_dihedrals; ++dihedral){ vector<Atom*> left_atoms, right_atoms; UnitTools::getAllAtomsFromUnitRange(units, left_atoms, 0, dihedral, onlyHeavy); UnitTools::getAllAtomsFromUnitRange(units, right_atoms, dihedral+1, units.size()-1, onlyHeavy); // Contributions of dihedral i to left atoms // term1 - term2 x r1 for(unsigned int i = 0; i < left_atoms.size(); ++i){ Point r_i = left_atoms[i]->toPoint(); Point dr_dqa = Point::subtract(term1[dihedral], ANMICMath::crossProduct(term2[dihedral], r_i)); dr_dqa.multiplyByScalar(eigenvector_ic[dihedral]); p_eigenvector_cc[atom2index[left_atoms[i]]].add(dr_dqa); } // Contributions of dihedral i to right atoms // -term1 + term2 x r1 for(unsigned int i = 0; i < right_atoms.size(); ++i){ Point r_i = right_atoms[i]->toPoint(); Point dr_dqb = Point::subtract(ANMICMath::crossProduct(term2b[dihedral], r_i), term1b[dihedral]); dr_dqb.multiplyByScalar(eigenvector_ic[dihedral]); p_eigenvector_cc[atom2index[right_atoms[i]]].add(dr_dqb); } } // Convert from point cc to flat vector vector<double> mode_cc; for (unsigned int i = 0; i < unit_atoms.size(); ++i){ mode_cc.push_back(p_eigenvector_cc[i].getX()); mode_cc.push_back(p_eigenvector_cc[i].getY()); mode_cc.push_back(p_eigenvector_cc[i].getZ()); } eigenvectors_cc.push_back(mode_cc); } out->initialize(eigenvalues_cc, eigenvectors_cc, false); return out; } /////////////////////////////////////////////////////////////// /// \remarks /// Converts a collection of modes expressed in cartesian coordinates in torsional rotations (can be /// seen as their conversion to IC. /// /// \param units [In] Coarse grain representation of the structure in Unit objects. /// \param in [In / Out] AnmEigen object containing modes (or forces or whatever) in cartesian coordinates. /// /// \return The AnmEigen object holding the converted modes. /// /// \author vgil /// \date 01/03/2015 /////////////////////////////////////////////////////////////// AnmEigen* InternalModesCalculator::cartesianToInternal(vector<Unit*>& units, AnmEigen* in){ AnmEigen* out = new AnmEigen; unsigned int number_of_modes = in->getNumberOfModes(); // Calculate Jacobi cout<<"Jacobi calculation..."<<endl; vector<vector<double> > Ki, J, Jt; ANMICKineticMatrixCalculator::Jacobi2(units, J); ANMICMath::transpose(J,Jt); // Calculate K cout<<"K calculation..."<<endl; TriangularMatrix* K = ANMICKineticMatrixCalculator::calculateK(units, INMA); cout<<"K inversion..."<<endl; ANMICMath::invertMatrix(K); TriangularMatrixTools::triangularMatrixToVectorMatrix(K, Ki); // M matrix bool onlyHeavyAtoms = true; vector<Atom*> all_atoms; UnitTools::getAllAtomsFromUnits(units, all_atoms, onlyHeavyAtoms); vector<vector<double> > M(all_atoms.size()*3, vector<double>(all_atoms.size()*3,0)); for (unsigned int i = 0; i < all_atoms.size(); ++i){ unsigned int offset = i*3; double mass = all_atoms[i]->getMass(); M[offset][offset] = mass; M[offset+1][offset+1] = mass; M[offset+2][offset+2] = mass; } cout<<"Conversion..."<<endl; // We do this for every of the modes we have in cartesian coordinates vector< vector<double> > new_evectors; for (unsigned int i = 0; i < number_of_modes; ++i){ vector<double>& original_mode = in->vectors[i]; vector<vector<double> > rt, r, Mr, JtMr, KiJtMr, Jr; rt.push_back(original_mode); ANMICMath::transpose(rt,r); ANMICMath::multiplyMatrixByMatrix(M, r, Mr); ANMICMath::multiplyMatrixByMatrix(Jt, Mr , JtMr); ANMICMath::multiplyMatrixByMatrix(Ki, JtMr , KiJtMr); ANMICMath::multiplyMatrixByMatrix(Jt,r,Jr); vector< vector<double> > evec; ANMICMath::transpose(KiJtMr,evec); new_evectors.push_back(evec[0]); } delete K; cout<<"Creating anm eigen object..."<<endl; bool notUsingCartesian = false; out->initialize(in->values, new_evectors, notUsingCartesian); return out; } std::string InternalModesCalculator::generateReport() const { return "Modes calculated using internal coordinates"; }
[ "victor.gil.sepulveda@gmail.com" ]
victor.gil.sepulveda@gmail.com
040a449a26777c58cf70d0dc3bc699cd505cee1a
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/jd2/archive/VarianceStatisticsArchive.cc
b904733867ae049156dbf6e69c649a41284c4daf
[]
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
2,182
cc
// -*- 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 IterativeAbrelax /// @brief iterative protocol starting with abinitio and getting progressively more concerned with full-atom relaxed structures /// @details /// @author Oliver Lange // Unit Headers #include <protocols/jd2/archive/VarianceStatisticsArchive.hh> // Package Headers #include <core/io/silent/SilentStruct.hh> // Utility Headers #include <basic/Tracer.hh> #include <basic/MemTracer.hh> #include <numeric/random/random.hh> static basic::Tracer tr( "protocols.iterative.VarianceStatistics" ); static basic::MemTracer mem_tr; using core::Real; namespace protocols { namespace jd2 { namespace archive { VarianceStatisticsArchive::VarianceStatisticsArchive( std::string name ) : insertion_prob_( 0.1 ) { set_name( name ); } bool VarianceStatisticsArchive::add_evaluated_structure( core::io::silent::SilentStructOP evaluated_decoy, core::io::silent::SilentStructOP /*alternative_decoy*/, Batch const& ) { if ( decoys().size() < nstruct() ) { tr.Debug << "added " << evaluated_decoy->decoy_tag() << " to " << name() << std::endl; decoys().insert( decoys().begin(), evaluated_decoy ); invalidate_score_variations(); return true; } if ( numeric::random::rg().uniform() < insertion_prob_ ) { //keep or not ? //replace with random element Size rg_pos( static_cast< int >( numeric::random::rg().uniform() * decoys().size() ) ); runtime_assert( rg_pos < decoys().size() ); auto it=decoys().begin(); while ( rg_pos-- > 0 ) { ++it; } runtime_assert( it != decoys().end() ); *it=evaluated_decoy; invalidate_score_variations(); return true; } return false; } } } //abinitio } //protocols
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
5ddfe7190518797105881d0daf2cbfc73180702e
4a7be38e24d8bfb0eacd380d5c0cf3995c40c761
/src/relay_module.h
102c7ef824e5cb054b0fe68ab2dff5a438e56304
[]
no_license
adrianbica/BLE_thpsensor_RX23W
b03356bce81edb0cce19133a5e1a9518bb933003
22b60fa1c6cdf2c15188b19ebbda15a9b51da2a5
refs/heads/master
2021-02-14T07:40:15.529166
2020-03-05T03:44:19
2020-03-05T03:44:19
244,785,400
3
0
null
null
null
null
UTF-8
C++
false
false
587
h
/* * relay_module.h * * Created on: Mar 1, 2020 * Author: adrian.bica */ #ifndef RELAY_MODULE_H_ #define RELAY_MODULE_H_ #include <stdint.h> /* * A relay module has 4 relays connected to four digital outputs from the microcontroller * A logic 0 to the output will activate the relay, while a */ class relayModule { #define NB_RELAYS (4) private: relayModule(void); void Deactivate(int relay); void Activate(int relay); public: ~relayModule(void); static relayModule& GetInstance(void); void Init(int relay); void task(void); }; #endif /* RELAY_MODULE_H_ */
[ "adrianbica@yahoo.com" ]
adrianbica@yahoo.com
bc42215609fb03ede453938c5fe9501668677a47
1f85142263a08d2e20080f18756059f581d524df
/lib/tags/lib-1.12.4.0/src/pagespeed/image_compression/jpeg_optimizer.h
df1cedf5b9dd9f42e444ce1a325b4e34a635c875
[ "Apache-2.0" ]
permissive
songlibo/page-speed
60edce572136a4b35f4d939fd11cc4d3cfd04567
8776e0441abd3f061da969644a9db6655fe01855
refs/heads/master
2021-01-22T08:27:40.145133
2016-02-03T15:34:40
2016-02-03T15:34:40
43,261,473
0
0
null
2015-09-27T19:32:17
2015-09-27T19:32:17
null
UTF-8
C++
false
false
3,634
h
/** * Copyright 2009 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: Bryan McQuade, Matthew Steele, Satyanarayana Manyam #ifndef JPEG_OPTIMIZER_H_ #define JPEG_OPTIMIZER_H_ #include <string> #include <setjmp.h> extern "C" { #ifdef USE_SYSTEM_LIBJPEG #include "jpeglib.h" #else #include "third_party/libjpeg/jpeglib.h" #endif } #include "pagespeed/image_compression/scanline_interface.h" namespace pagespeed { namespace image_compression { struct JpegCompressionOptions { JpegCompressionOptions() : lossy(false), quality(85), progressive(false) {} // Whether or not to perform lossy compression. If true, then the quality // parameter is used to determine how much quality to retain. bool lossy; // jpeg_quality - Can take values in the range [1,100]. // For web images, the preferred value for quality is 85. // For smaller images like thumbnails, the preferred value for quality is 75. // Setting it to values below 50 is generally not preferable. int quality; // Whether or not to produce a progressive JPEG. bool progressive; }; // Performs lossless optimization, that is, the output image will be // pixel-for-pixel identical to the input image. bool OptimizeJpeg(const std::string &original, std::string *compressed); // Performs JPEG optimizations with the provided options. bool OptimizeJpegWithOptions(const std::string &original, std::string *compressed, const JpegCompressionOptions *options); // User of this class must call this functions in the following sequence // func () { // JpegScanlineWriter jpeg_writer; // jmp_buf env; // if (setjmp(env)) { // jpeg_writer.AbortWrite(); // return; // } // jpeg_writer.SetJmpBufEnv(&env); // if (jpeg_writer.Init(width, height, format)) { // jpeg_writer.SetJpegCompressParams(quality); // jpeg_writer.InitializeWrite(out); // while(has_lines_to_write) { // writer.WriteNextScanline(next_scan_line); // } // writer.FinalizeWrite() // } // } class JpegScanlineWriter : public ScanlineWriterInterface { public: JpegScanlineWriter(); virtual ~JpegScanlineWriter(); // Set the environment for longjmp calls. void SetJmpBufEnv(jmp_buf* env); // This function is only called when jpeg library call longjmp for // cleaning up the jpeg structs. void AbortWrite(); // Since writer only supports lossy encoding, it is an error to pass // in a compression options that has lossy field set to false. void SetJpegCompressParams(const JpegCompressionOptions& options); bool InitializeWrite(std::string *compressed); virtual bool Init(const size_t width, const size_t height, PixelFormat pixel_format); virtual bool WriteNextScanline(void *scanline_bytes); virtual bool FinalizeWrite(); private: // Structures for jpeg compression. jpeg_compress_struct jpeg_compress_; jpeg_error_mgr compress_error_; DISALLOW_COPY_AND_ASSIGN(JpegScanlineWriter); }; } // namespace image_compression } // namespace pagespeed #endif // JPEG_OPTIMIZER_H_
[ "bmcquade@google.com" ]
bmcquade@google.com