hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
63c959aec1a10a74b83fe080855b263420d5e6b1
2,074
cpp
C++
Data Structures/Graphs/graph4.cpp
sirkp/Data-Structures-and-Algorithms
38d2786f93cad3f3f156f48867d9eaff7a391d40
[ "Apache-2.0" ]
1
2020-01-21T20:00:16.000Z
2020-01-21T20:00:16.000Z
Data Structures/Graphs/graph4.cpp
sirkp/Data-Structures-and-Algorithms
38d2786f93cad3f3f156f48867d9eaff7a391d40
[ "Apache-2.0" ]
null
null
null
Data Structures/Graphs/graph4.cpp
sirkp/Data-Structures-and-Algorithms
38d2786f93cad3f3f156f48867d9eaff7a391d40
[ "Apache-2.0" ]
null
null
null
// Detect Cycle in a Directed Graph // https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ #include <bits/stdc++.h> using namespace std; class Graph { private: int V; list<int> *adj; bool isCyclicUtil(int s, bool visited[], bool recStack[]); public: Graph(int V) { this->V = V; adj = new list<int>[V]; } ~Graph(){delete []adj;} void addEdgeDirected(int u, int v); void addEdgeUndirected(int u, int v); void print(); bool isCyclic(); }; void Graph::addEdgeDirected(int u,int v) { adj[u].push_back(v); } void Graph::addEdgeUndirected(int u,int v) { adj[u].push_back(v); adj[v].push_back(u); } void Graph::print() { for(int i=0;i<V;i++) { cout<<i<<"-->"; for(auto x:adj[i]) cout<<x<<"->"; cout<<endl; } } bool Graph::isCyclicUtil(int s,bool visited[],bool recStack[]) { visited[s] = true; recStack[s] = true; for(auto x:adj[s]) { if(!visited[x] && isCyclicUtil(x,visited,recStack)) return true; else if(recStack[x]) return true; } recStack[s] = false; return false; } bool Graph::isCyclic()// O(V+E) { bool *visited = new bool[V]; bool *recStack = new bool[V]; for(int i=0;i<V;i++) { recStack[i]=false; visited[i]=false; } for(int i=0;i<V;i++) { if(!visited[i]) if(isCyclicUtil(i,visited,recStack)) { delete []visited; delete []recStack; return true; } } delete []visited; delete []recStack; return false; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif Graph g(4); g.addEdgeDirected(0, 1); g.addEdgeDirected(0, 2); g.addEdgeDirected(1, 2); g.addEdgeDirected(2, 3); if(g.isCyclic()) cout<<"contains cycle"<<endl; else cout<<"doesn't contains cycle"<<endl; Graph G(4); G.addEdgeDirected(0, 1); G.addEdgeDirected(0, 2); G.addEdgeDirected(1, 2); G.addEdgeDirected(2, 0); G.addEdgeDirected(2, 3); G.addEdgeDirected(3, 3); if(G.isCyclic()) cout<<"contains cycle"<<endl; else cout<<"doesn't contains cycle"<<endl; }
17
62
0.610415
sirkp
63ca894c603dba0988865d3e5c7111faa95a5008
2,287
cpp
C++
edbee-lib/edbee/commands/cutcommand.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
445
2015-01-04T16:30:56.000Z
2022-03-30T02:27:05.000Z
edbee-lib/edbee/commands/cutcommand.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
305
2015-01-04T09:20:03.000Z
2020-10-01T08:45:45.000Z
edbee-lib/edbee/commands/cutcommand.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
49
2015-02-14T01:43:38.000Z
2022-02-15T17:03:55.000Z
/** * Copyright 2011-2012 - Reliable Bits Software by Blommers IT. All Rights Reserved. * Author Rick Blommers */ #include "cutcommand.h" #include <QApplication> #include <QClipboard> #include <QMimeData> #include "edbee/commands/copycommand.h" #include "edbee/models/textdocument.h" #include "edbee/models/change.h" #include "edbee/models/textrange.h" #include "edbee/models/textundostack.h" #include "edbee/texteditorcontroller.h" #include "edbee/views/textselection.h" #include "edbee/debug.h" namespace edbee { /// Performs the cut command /// @param controller the controller context void CutCommand::execute(TextEditorController* controller) { QClipboard *clipboard = QApplication::clipboard(); TextRangeSet* sel = controller->textSelection(); // get the selected text QString str = sel->getSelectedText(); if( !str.isEmpty() ) { clipboard->setText( str ); controller->replaceSelection( "", 0); return; // perform a full-lines cut } else { // fetch the selected lines TextRangeSet newSel( *sel ); newSel.expandToFullLines(1); str = newSel.getSelectedText(); // we only coalesce if 1 range is available int coalesceId = ( sel->rangeCount() != 1) ? 0 : CoalesceId_CutLine; // when the previous command was a cut // and there's a line on the stack, we need to expand the line if( controller->textDocument()->textUndoStack()->lastCoalesceIdAtCurrentLevel() == CoalesceId_CutLine ) { QClipboard* clipboard = QApplication::clipboard(); const QMimeData* mimeData = clipboard->mimeData(); if( mimeData->hasFormat( CopyCommand::EDBEE_TEXT_TYPE ) ) { str = mimeData->text() + str; } } // set the new clipboard data QMimeData* mimeData = new QMimeData(); mimeData->setText( str ); mimeData->setData( CopyCommand::EDBEE_TEXT_TYPE, "line" ); clipboard->setMimeData( mimeData ); //delete mimeData; // remove the selection controller->replaceRangeSet( newSel, "", coalesceId ); return; } } /// Converts this command to a string QString CutCommand::toString() { return "CutCommand"; } } // edbee
27.890244
113
0.647136
UniSwarm
63cd6875187a29c598dc189f355139ae75080873
1,002
cpp
C++
includes/fog.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
2
2019-05-20T11:12:07.000Z
2021-03-25T04:24:57.000Z
includes/fog.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
null
null
null
includes/fog.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
null
null
null
#include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #include <math.h> #include <fog.hpp> #include <string> #include <common.h> using namespace std; void initializeFog(){ glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_START, 0.0); glFogf(GL_FOG_END, 9.0); float color[] = {0.6, 0.6, 0.6, 1.0}; glFogfv(GL_FOG_COLOR, color); glEnable(GL_FOG); } void resetFog(){ glDisable(GL_FOG); } void displayFog(){ glClearColor( 0.6, 0.6, 0.6, 1.0 ); // Clear Color and Depth Buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode( GL_PROJECTION ); // Reset transformations glLoadIdentity(); gluPerspective(45.0f, SCR_WIDTH/SCR_HEIGHT, 0.1f, 1000.0f); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); if(!show_text){ glTranslatef(0,0,-7-sin(glutGet(GLUT_ELAPSED_TIME)*0.0004)*3); glRotatef(glutGet(GLUT_ELAPSED_TIME)*0.02,0,1,0); glColor3f(0.6, 0.3, 0.0); glutSolidTeapot(1); } fps_counter(); render_ImGui(); glutSwapBuffers(); }
22.266667
66
0.684631
MuUusta
63d4bf25b8dbfe622bacf739a7c35a3a016ade45
147
cpp
C++
Source/ClimbingSystem/ClimbingSystem.cpp
LaudateCorpus1/Climbing-Movement-Component
2311c0468bab8e59bf1c042d855e95dd0d891ec4
[ "MIT" ]
237
2016-06-16T09:01:19.000Z
2022-03-30T03:11:27.000Z
Source/ClimbingSystem/ClimbingSystem.cpp
LaudateCorpus1/Climbing-Movement-Component
2311c0468bab8e59bf1c042d855e95dd0d891ec4
[ "MIT" ]
2
2017-12-14T22:54:02.000Z
2020-11-18T08:08:03.000Z
Source/ClimbingSystem/ClimbingSystem.cpp
LaudateCorpus1/Climbing-Movement-Component
2311c0468bab8e59bf1c042d855e95dd0d891ec4
[ "MIT" ]
68
2016-06-16T11:49:56.000Z
2022-03-11T14:34:01.000Z
// Copyright 2016 Dmitriy #include "ClimbingSystem.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, ClimbingSystem, "ClimbingSystem" );
24.5
90
0.823129
LaudateCorpus1
63d73091144362d28c1bf1262c8e1adfd2ceb627
1,218
cpp
C++
HackerRank/Interview Preparation Kit/WarmUp Problems/repeated-strings.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
7
2018-11-08T11:39:27.000Z
2020-09-10T17:50:57.000Z
HackerRank/Interview Preparation Kit/WarmUp Problems/repeated-strings.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
null
null
null
HackerRank/Interview Preparation Kit/WarmUp Problems/repeated-strings.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
2
2019-09-16T14:34:03.000Z
2019-10-12T19:24:00.000Z
#include <bits/stdc++.h> using namespace std; /*int main() { long long int n, maxl=0; string s, p=""; cin >> s; cin >> n; for(long long int i=0; i<n; i++) { if( s.length() >= n ) { break; } p = p + s; } for(int i=0; i<n; i++) { if(s[i] == 'a') { maxl++; } } cout<<maxl<<"\n"; return 0; }*/ int main() { long long int n, sum=0, i = 0; string s, p = "" ; map<char, int> m; cin >> s; scanf("%lld", &n); while( !(p.length() >= n) ) { p.append(s); } //cout<< "String Before Sorting : " << p << endl; //sort(p.begin(), p.end()); //cout<< "String After Sorting : " << p << endl; string::iterator it = p.begin(); for(it; it != p.begin()+n; it++){ cout<<*it<<" "; m[*it]++; } /*for(char x : p) { if( i == n ) { break; } if( x == 'a' ) { sum++ ; } else { break ; } i ++ ; } cout << sum << " \n" ;*/ cout<<m['a']<<endl; return 0; }
15.417722
53
0.328407
annukamat
63db174ad70c33b8f55efa7e5b56a7ac50241cfd
5,923
hpp
C++
AStar.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
AStar.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
AStar.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <unordered_map> #include <functional> #include <algorithm> #include <vector> #include "sign.hpp" #include "Point.hpp" #include "Direction.hpp" #include "runTests.hpp" namespace putils { /* * Pathfinding algorithm implementing the AStar algorithm described on Wikipedia */ class AStar { // Get the next move towards goal public: template<typename Precision> static std::vector<putils::Point<Precision>> getNextDirection(const Point<Precision> & start, const Point<Precision> & goal, bool diagonals, Precision step, Precision desiredDistance, const std::function<bool(const Point<Precision> & from, const Point<Precision> & to)> & canMoveTo) noexcept; }; /* * Implementation details */ namespace { template<typename Precision> double heuristic_cost_estimate(const putils::Point<Precision> & start, const putils::Point<Precision> & goal) noexcept { return std::sqrt( std::pow(goal.x - start.x, 2) + std::pow(goal.y - start.y, 2) ); } template<typename Precision> std::vector<putils::Point<Precision>> reconstruct_path(const std::unordered_map<Point<Precision>, Point<Precision>> & cameFrom, putils::Point<Precision> & current, const putils::Point<Precision> & pos) noexcept { std::vector<putils::Point<Precision>> res; if (!cameFrom.size()) return res; while (cameFrom.at(current) != pos) { res.emplace(res.begin(), current); current = cameFrom.at(current); } res.emplace(res.begin(), current); return res; } } template<typename Precision> std::vector<putils::Point<Precision>> AStar::getNextDirection( const Point<Precision> & start, const Point<Precision> & goal, bool diagonals, Precision step, Precision desiredDistance, const std::function<bool(const Point<Precision> & from, const Point<Precision> & to)> & canMoveTo) noexcept { bool first = true; Point<Precision> closest; // The set of nodes already evaluated. std::vector<Point<Precision>> closedSet; // The set of currently discovered nodes still to be evaluated. // Initially, only the start node is known. std::vector<Point<Precision>> openSet({ start }); // For each node, which node it can most efficiently be reached from. // If a node can be reached from many nodes, cameFrom will eventually contain the // most efficient previous step. std::unordered_map<Point<Precision>, Point<Precision>> cameFrom; // For each node, the cost of getting from the start node to that node. std::unordered_map<Point<Precision>, double> gScore; // The cost of going from start to start is zero. gScore.emplace(start, 0); // For each node, the total cost of getting from the start node to the goal // by passing by that node. That value is partly known, partly heuristic. std::unordered_map<Point<Precision>, double> fScore; // For the first node, that value is completely heuristic. fScore.emplace(start, heuristic_cost_estimate(start, goal)); const auto findClosest = [&fScore](const auto & l, const auto & r) { return fScore.at(l) < fScore.at(r); }; while (openSet.size()) { const auto it = std::min_element(openSet.cbegin(), openSet.cend(), findClosest); auto current = *it; if (first || closest.distanceTo(goal) > current.distanceTo(goal)) { closest = current; first = false; } if (goal.distanceTo(current) < desiredDistance) return reconstruct_path(cameFrom, current, start); openSet.erase(it); closedSet.push_back(current); Point<Precision> neighbor; for (Precision x = current.x - step; x <= current.x + step; x += step) for (Precision y = current.y - step; y <= current.y + step; y += step) { if (!diagonals && ((x == current.x && y == current.y) || (x != current.x && y != current.y))) continue; else if (diagonals && x == current.x && y == current.y) continue; neighbor = { x, y }; if (std::find(closedSet.cbegin(), closedSet.cend(), neighbor) != closedSet.cend()) continue; // Ignore the neighbor which is already evaluated. if (goal.distanceTo(neighbor) >= desiredDistance && !canMoveTo(current, neighbor)) continue; // The distance from start to a neighbor auto tentative_gScore = gScore.at(current) + step; if (std::find(openSet.begin(), openSet.end(), neighbor) == openSet.end()) openSet.push_back(neighbor); else if (tentative_gScore >= gScore[neighbor]) continue; // This is not a better path // This path is the best until now. Record it! cameFrom[neighbor] = current; gScore[neighbor] = tentative_gScore; fScore[neighbor] = tentative_gScore + heuristic_cost_estimate(neighbor, goal); } } return reconstruct_path(cameFrom, closest, start); } }
42.307143
221
0.554955
ValtoLibraries
63dcb72c79c52b3efb6fe505ac43ed8c8f318902
935
cpp
C++
Greet-core/src/ecs/ECSManager.cpp
Thraix/Greet-Engine
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
Greet-core/src/ecs/ECSManager.cpp
Thraix/Greet-Engine
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
1
2018-03-30T18:10:37.000Z
2018-03-30T18:10:37.000Z
Greet-core/src/ecs/ECSManager.cpp
Thraix/Greet-Engine-Port
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
#include "ECSManager.h" namespace Greet { ECSManager::~ECSManager() { for(auto&& components : componentPool) { delete components.second; } componentPool.clear(); } EntityID ECSManager::CreateEntity() { ASSERT(currentEntityId != (uint32_t)-1, "No more entities available"); entities.emplace(currentEntityId); currentEntityId++; return currentEntityId-1; } void ECSManager::DestroyEntity(EntityID entity) { auto it = entities.find(entity); ASSERT(it != entities.end(), "Entity does not exist in ECSManager (entity=", entity, ")"); entities.erase(it); for(auto&& pool : componentPool) { pool.second->Erase(entity); } } bool ECSManager::ValidEntity(EntityID entity) { return entities.find(entity) != entities.end(); } void ECSManager::Each(std::function<void(EntityID)> function) { for(auto e : entities) function(e); } }
21.25
94
0.648128
Thraix
63ddaea5b49669b7f4d9baf765ca8de3b922c7f0
781
cpp
C++
src/util/Animation.cpp
ds84182/WiMu
91988bef1b82fda31bfee75e920b384831584e9b
[ "MIT" ]
1
2015-12-17T16:17:50.000Z
2015-12-17T16:17:50.000Z
src/util/Animation.cpp
ds84182/WiMu
91988bef1b82fda31bfee75e920b384831584e9b
[ "MIT" ]
null
null
null
src/util/Animation.cpp
ds84182/WiMu
91988bef1b82fda31bfee75e920b384831584e9b
[ "MIT" ]
null
null
null
#include "Animation.h" #include <math.h> AnimatableFloat::~AnimatableFloat() { } AnimatableColor::~AnimatableColor() { } namespace EasingFunction { f32 linear(f32 t, f32 d) { return t/d; } f32 inQuad(f32 t, f32 d) { return pow(t/d, 2.0f); } f32 outQuad(f32 t, f32 d) { t /= d; return -t * (t-2.0f); } f32 inOutQuad(f32 t, f32 d) { t = t/d*2; if (t < 1.0f) { return pow(t, 2.0f)/2.0f; } else { return -((t - 1.0f) * (t - 3.0f) - 1.0f)/2.0f; } } f32 outInQuad(f32 t, f32 d) { if (t < d/2) return outQuad(t*2.0f, d)/2.0f; return inQuad((t*2.0f)-d, d)/2.0f+0.5f; } EasingFunc LINEAR = &linear; EasingFunc IN_QUAD = &inQuad; EasingFunc OUT_QUAD = &outQuad; EasingFunc IN_OUT_QUAD = &inOutQuad; EasingFunc OUT_IN_QUAD = &outInQuad; }
16.270833
49
0.600512
ds84182
63e07fe85ae2bca967155a2353b79040277e03cc
1,116
hpp
C++
src/io/byte_buffer.hpp
Yanick-Salzmann/grower-controller-rpi
30f279e960a3cc8125f112c76ee943b1fa766191
[ "MIT" ]
null
null
null
src/io/byte_buffer.hpp
Yanick-Salzmann/grower-controller-rpi
30f279e960a3cc8125f112c76ee943b1fa766191
[ "MIT" ]
null
null
null
src/io/byte_buffer.hpp
Yanick-Salzmann/grower-controller-rpi
30f279e960a3cc8125f112c76ee943b1fa766191
[ "MIT" ]
null
null
null
#ifndef GROWER_CONTROLLER_RPI_BYTE_BUFFER_HPP #define GROWER_CONTROLLER_RPI_BYTE_BUFFER_HPP #include <vector> #include <cstdint> namespace grower::io { class little_endian_trait { public: static void add_to_buffer(const void *value, std::size_t num_bytes, std::vector<uint8_t> &buffer); }; class big_endian_trait { public: static void add_to_buffer(const void *value, std::size_t num_bytes, std::vector<uint8_t> &buffer); }; class byte_buffer { std::vector<uint8_t> _buffer{}; public: template<typename type, typename endian_trait = little_endian_trait> byte_buffer &append(const type &value) { endian_trait::add_to_buffer(&value, sizeof(type), _buffer); return *this; } byte_buffer &append(const std::vector<uint8_t> &value) { _buffer.insert(_buffer.end(), value.begin(), value.end()); return *this; } [[nodiscard]] const std::vector<uint8_t> &buffer() const { return _buffer; } }; } #endif //GROWER_CONTROLLER_RPI_BYTE_BUFFER_HPP
27.9
106
0.647849
Yanick-Salzmann
63e28140659e53d2c9d358a422e71faafa9ea3f4
1,675
hxx
C++
planners/lapkt-public/include/aptk/planrec.hxx
miquelramirez/aamas18-planning-for-transparency
dff3e635102bf351906807c5181113fbf4b67083
[ "MIT" ]
null
null
null
planners/lapkt-public/include/aptk/planrec.hxx
miquelramirez/aamas18-planning-for-transparency
dff3e635102bf351906807c5181113fbf4b67083
[ "MIT" ]
null
null
null
planners/lapkt-public/include/aptk/planrec.hxx
miquelramirez/aamas18-planning-for-transparency
dff3e635102bf351906807c5181113fbf4b67083
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <map> #include <ff_to_aptk.hxx> #include <strips_prob.hxx> #include <fluent.hxx> #include <action.hxx> #include <cond_eff.hxx> #include <strips_state.hxx> #include <fwd_search_prob.hxx> #include <h_1.hxx> #include <aptk/open_list.hxx> #include <aptk/string_conversions.hxx> #include <aptk/at_bfs.hxx> #include <fstream> #include <boost/program_options.hpp> using aptk::agnostic::Fwd_Search_Problem; std::vector<double> plan_recognition(const aptk::STRIPS_Problem& prob, std::vector<aptk::Fluent_Vec>& goal_set, std::vector<double> priors, std::vector<unsigned>& observations, aptk::Fluent_Vec& init, float beta, bool optimal); std::vector<double> plan_recognition_approx(const aptk::STRIPS_Problem& prob, std::vector<aptk::Fluent_Vec>& goal_set, std::vector<double> priors, std::vector<unsigned>& observations, aptk::Fluent_Vec& init, float beta, unsigned approx_type); std::vector<double> simulate_plan_for_recog(std::vector<aptk::Action_Idx>& plan, aptk::STRIPS_Problem& prob, std::vector<aptk::Fluent_Vec>& goal_set, std::vector<double>& priors, float beta); #ifndef __PLANREC_H__ #define __PLANREC_H__ template<class T> void print_vector(std::vector<T> v){ for (unsigned int i = 0; i < v.size(); i++){ std::cout << i << ": " << std::to_string(v[i]) << std::endl; } } template< typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type > std::vector<double> normalize_vector(std::vector<T> v){ std::vector<double> n_v; double sum = (double) std::accumulate(v.begin(), v.end(), (T) 0); for(T e : v){ n_v.push_back( ((double) e) / sum); } return n_v; } #endif
28.87931
242
0.72
miquelramirez
63e324abce25101720b78772c2aa12e260d2e0a7
255
hpp
C++
addons/niarms/caliber/blackout/ar15.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/niarms/caliber/blackout/ar15.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/niarms/caliber/blackout/ar15.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
// AR-15 Rifles // AR15 - Medium Barrel class hlc_rifle_Bushmaster300: hlc_ar15_base { recoil = QCLASS(300B_MediumBarrel); }; // Black Jack - Medium Barrel class hlc_rifle_bcmblackjack: hlc_rifle_bcmjack { recoil = QCLASS(300B_MediumBarrel); };
21.25
49
0.745098
Theseus-Aegis
63e4027da577945329734e57710b230e5c7871f0
34,965
cpp
C++
src/classic/SxEAM.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
src/classic/SxEAM.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
src/classic/SxEAM.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The ab-initio based multiscale library // // S / P H I / n X // // Copyright: Max-Planck-Institute for Iron Research // 40237 Duesseldorf, Germany // // Contact: https://sxlib.mpie.de // Authors: see sphinx/AUTHORS // License: see sphinx/LICENSE // // --------------------------------------------------------------------------- #include <SxTimer.h> #include <SxEAM.h> #include <fstream> SxEAM::SxEAM (const SxAtomicStructure &str, const SxSymbolTable *table) { sxprintf ("This is SxEAM::SxEAM\n"); speciesData = SxSpeciesData (&*table); nAtoms = str.getNAtoms (); species.resize (nAtoms); nSpecies = str.getNSpecies (); cout << nSpecies << endl; //--- up to 2 different species implemented yet if (nSpecies > 2) { cout << "Only up to 2 different species implemented in SxEAM" << endl; SX_QUIT; } else { if (nSpecies == 1) { V.resize (1); F.resize (1); rho.resize (1); dV.resize (1); dF.resize (1); drho.resize (1); } if (nSpecies == 2) { V.resize (3); F.resize (3); rho.resize (3); dV.resize (3); dF.resize (3); drho.resize (3); } } int counter = 0; for (int is = 0; is < str.getNSpecies (); is++) { SxString elem = speciesData.chemName(is); for (int ia = 0; ia < str.getNAtoms(is); ia++) { species(counter) = elem; counter++; } } setupSplines ((table -> getGroup("eamPot") -> getGroup("params"))); if (table -> getGroup("eamPot") -> contains("noLinkCell")) noLinkCell = table -> getGroup("eamPot") -> get ("noLinkCell") -> toBool (); else noLinkCell = false; neigh.resize (nAtoms); dist.resize (nAtoms); pw.resize (nAtoms); cell.resize (nAtoms); if (!noLinkCell) { length = 6; setLinkCellMethodParams (str); } update (str); sxprintf("TOTAL ENERGY (Hartree): %.11f\n", getTotalEnergy ()); /* SxAtomicStructure test; test.copy (tau); SxMatrix3<Double> mat; mat.set(0.); for (double aLat = 3.45; aLat < 8.0; aLat += 0.01) { double a0 = tau.cell(0)(0); double a = 2.*A2B*aLat; double scale = a/a0; mat (0, 0) = mat(1, 1) = mat(2, 2) = a; test.cell.set(mat); test.set (scale*test.coordRef ()); update (test); cout << "MURN: " << aLat << " " << getTotalEnergy () << endl; } */ /* SxAtomicStructure test; test.copy (tau); for (int i = 0; i < nAtoms; i++) { for (int j = 0; j < 3; j++) { test.ref(i)(j) += 0.05*rand()/(double) 0x7fffffff; } } SxAtomicStructure f1 = getForces (test, table); SxAtomicStructure f2 = getNumericalForces (test, 0.01); SxAtomicStructure f3 = getNumericalForces (test, 0.0001); SxAtomicStructure f = f1 - f2; cout << "LARS3" << endl; fflush(stdout); cout << f1 << endl; cout << f2 << endl; cout << f3 << endl; cout << f << endl; QUIT; */ /* for (int i = 0; i < 100; i++) { cout << "UPDATE" << i << endl; SxAtomicStructure f = getForces (test, table); } for (int i = 0; i < neigh.getSize (); i++) cout << neigh(i).getSize () << endl; */ } SxEAM::~SxEAM () { // empty } void SxEAM::setLinkCellMethodParams (const SxAtomicStructure &tau) { int i, j; double min = 1e20; double max = -1e20; for ( i = 0; i < nAtoms; i++ ) { for (j = 0; j < 3; j++) { if ( tau(i)(j) < min ) min = tau(i)(j); if ( tau(i)(j) > max ) max = tau(i)(j); } } cout << "min " << min << endl; cout << "max " << max << endl; meshOrigin.set(min-(cutoff+2*length)); double meshLength = max + 2*cutoff + 4*length - meshOrigin(0); n = int(meshLength/length); length = meshLength/n; cout << "n: " << n << endl; cout << "length: " << length << endl; cout << "meshOrigin: " << meshOrigin << endl; int nHalf = (int) n/2; SxVector3<Double> RmeshHalf; RmeshHalf.set(length*(nHalf-1)); RmeshHalf += meshOrigin; SxArray<SxVector3<Int> > a1, a2; a1.resize(64); a2.resize(64); for (i = 0; i < 64; i++) { a1(i)(0) = (int) i/32; a1(i)(1) = (int) (i - a1(i)(0)*32)/16; a1(i)(2) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16)/8; a2(i)(0) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16 - a1(i)(2)*8)/4; a2(i)(1) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16 - a1(i)(2)*8 - a2(i)(0)*4)/2; a2(i)(2) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16 - a1(i)(2)*8 - a2(i)(0)*4 - a2(i)(1)*2); } SxList<SxVector3<Int> > neighborsReference; neighborsReference.resize(0); SxVector3<Double> Rmesh, v; int x, y, z; double norm; double minNorm; for (z = 0; z < n; z++) { for (y = 0; y < n; y++) { for (x = 0; x < n; x++) { minNorm = 1e20; Rmesh(0) = length*x + meshOrigin(0); Rmesh(1) = length*y + meshOrigin(1); Rmesh(2) = length*z + meshOrigin(2); for (i = 0; i < 64; i++) { v = Rmesh + length*a1(i) - (RmeshHalf + length*a2(i)); if ((norm = v.norm()) < minNorm) minNorm = norm; } if ((minNorm < cutoff) && ((nHalf-1)!=x || (nHalf-1)!=y || (nHalf-1)!=z)) neighborsReference.append(SxVector3<Int> (x,y,z)); } } } cout << "size of neighborsReference " << neighborsReference.getSize() << endl; SxList<SxVector3<Int> > origMeshTmp; SxList<SxArray<SxVector3<Int> > > neighborsTmp; SxArray<SxVector3<Int> > shiftedReference = neighborsReference; SxVector3<Double> midVec; origMeshTmp.resize(0); neighborsTmp.resize(0); for (z = 0; z < n; z++) { for (y = 0; y < n; y++) { for (x = 0; x < n; x++) { Rmesh = length * (SxVector3<Int> (x,y,z)) + meshOrigin; for (i = 0; i < 64; i=i+8) { v = Rmesh + length*a1(i); v = tau.cell.inverse()^v; if ((v(0) >= 0. && v(0) < 1.) && (v(1) >= 0. && v(1) < 1.) && v(2) >= 0. && v(2) < 1.) { origMeshTmp.append(SxVector3<Int> (x,y,z)); for (j = 0; j < shiftedReference.getSize(); j++) shiftedReference(j) = neighborsReference(j) + (SxVector3<Double> (x-nHalf+1,y-nHalf+1,z-nHalf+1)); neighborsTmp.append(shiftedReference); break; } } } } } origMesh = origMeshTmp; neighbors = neighborsTmp; } bool SxEAM::isRegistered (const SxSymbolTable *cmd) const { SX_CHECK (cmd); SxString str = cmd->getName (); return ( str=="forces" || str=="HesseMatrix" || str=="TTensor" ); } int SxEAM::getInteractionType (int i, int j) { if (speciesData.chemName.getSize () == 1) { return 0; } else { if (i == j) { if (species(i) == speciesData.chemName(0)) return 0; if (species(i) == speciesData.chemName(1)) return 1; SX_EXIT; } else { if ( (species(i) == speciesData.chemName(0)) && (species(j) == speciesData.chemName(0)) ) return 0; if ( (species(i) == speciesData.chemName(1)) && (species(j) == speciesData.chemName(1)) ) return 1; return 2; } } } double SxEAM::getDist (int i, int j, const SxVector3<Double> &R) { SxVector3<Double> v = tau.ref(i) - tau.ref(j) - R; if (fabs(v(0)) > cutoff) return fabs (v(0)); if (fabs(v(1)) > cutoff) return fabs (v(1)); if (fabs(v(2)) > cutoff) return fabs (v(2)); return v.norm (); } void SxEAM::updateNeighsLinkCellMethod () { int cX, cY, cZ, i, j; // int sCut = (int) (cutoff/tau.cell(0, 0)) + 1; int sCut = 1; for (i = 0; i < 3; i++) { int a = (int) (cutoff/tau.cell(i, i)) + 1; if (a > sCut) sCut = a; } SxVector3<Double> v, v1, vMesh, R, vCheck, vReduced; SxArray<SxList<int> > neighList; SxArray<SxList<int> > pwList; SxArray<SxList<double> > distList; SxArray<SxList<SxVector3<Double> > > cellList; neighList.resize(nAtoms); distList.resize(nAtoms); pwList.resize(nAtoms); cellList.resize(nAtoms); SxArray<SxArray<SxArray<SxList<int> > > > meshAtomNr, meshAtomNrPeriodic; SxArray<SxArray<SxArray<SxList<SxVector3<Double> > > > > meshAtomCoord, meshAtomCoordPeriodic; SxArray<SxArray<SxArray<SxList<SxVector3<Double> > > > > meshAtomCell, meshAtomCellPeriodic; meshAtomNr.resize(n); meshAtomNrPeriodic.resize(n); meshAtomCoord.resize(n); meshAtomCoordPeriodic.resize(n); meshAtomCell.resize(n); meshAtomCellPeriodic.resize(n); for (i = 0; i < n; i++) { meshAtomNr(i).resize(n); meshAtomNrPeriodic(i).resize(n); meshAtomCoord(i).resize(n); meshAtomCoordPeriodic(i).resize(n); meshAtomCell(i).resize(n); meshAtomCellPeriodic(i).resize(n); for (j = 0; j < n; j++) { meshAtomNr(i)(j).resize(n); meshAtomNrPeriodic(i)(j).resize(n); meshAtomCoord(i)(j).resize(n); meshAtomCoordPeriodic(i)(j).resize(n); meshAtomCell(i)(j).resize(n); meshAtomCellPeriodic(i)(j).resize(n); } } SxCell inv = tau.cell.inverse(); for (cZ = -sCut; cZ <= sCut; cZ++) { for (cY = -sCut; cY <= sCut; cY++) { for (cX = -sCut; cX <= sCut; cX++) { R = cX*tau.cell(0) + cY*tau.cell(1) + cZ*tau.cell(2); for (i = 0; i < nAtoms; i++) { v = R + tau(i); vMesh = (v - meshOrigin)/length; vReduced = inv^v; // cout << vReduced << " " << n << endl; if (0 <= vMesh(0) && vMesh(0) < n && 0 <= vMesh(1) && vMesh(1) < n && 0 <= vMesh(2) && vMesh(2) < n) { if ((vReduced(0) >= -0.00001 && vReduced(0) < 0.99999999) && (vReduced(1) >= -0.00001 && vReduced(1) < 0.99999999) && (vReduced(2) >= -0.00001 && vReduced(2) < 0.99999999)) { // <-------- meshAtomNr((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(i); meshAtomCoord((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(v); meshAtomCell((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(R); // <-------- } else { // <-------------- meshAtomNrPeriodic((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(i); meshAtomCoordPeriodic((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(v); meshAtomCellPeriodic((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(R); // <-------------- } } } } } } for (i = 0; i < nAtoms; i++) { distList(i). resize (0); pwList(i). resize (0); neighList(i).resize (0); cellList(i). resize (0); } int a1, a2, k, l; double distance; SxArray<int> currentAtomNrs, neighborsAtomNrs; SxArray<int> currentAtomNrsPeriodic, neighborsAtomNrsPeriodic; SxArray<SxVector3<Double> > currentAtomCoords, neighborsAtomCoords; SxArray<SxVector3<Double> > currentAtomCoordsPeriodic, neighborsAtomCoordsPeriodic; SxArray<SxVector3<Double> > currentAtomCells, neighborsAtomCells; SxArray<SxVector3<Double> > currentAtomCellsPeriodic, neighborsAtomCellsPeriodic; for (i = 0; i < origMesh.getSize(); i++) { int a = origMesh(i)(0); int b = origMesh(i)(1); int c = origMesh(i)(2); currentAtomNrs = meshAtomNr(a)(b)(c); currentAtomCoords = meshAtomCoord(a)(b)(c); currentAtomCells = meshAtomCell(a)(b)(c); currentAtomNrsPeriodic = meshAtomNrPeriodic(a)(b)(c); currentAtomCoordsPeriodic = meshAtomCoordPeriodic(a)(b)(c); currentAtomCellsPeriodic = meshAtomCellPeriodic(a)(b)(c); for (j = 0; j < currentAtomNrs.getSize(); j++) { a1 = currentAtomNrs(j); v1 = currentAtomCoords(j); for (k = 0; k < currentAtomNrs.getSize(); k++) { if ( k != j ) { a2 = currentAtomNrs(k); v = currentAtomCoords(k); R = currentAtomCells(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } } for (k = 0; k < currentAtomNrsPeriodic.getSize(); k++) { a2 = currentAtomNrsPeriodic(k); v = currentAtomCoordsPeriodic(k); R = currentAtomCellsPeriodic(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } for (l = 0; l < neighbors(i).getSize(); l++) { int a = neighbors(i)(l)(0); int b = neighbors(i)(l)(1); int c = neighbors(i)(l)(2); // <-------- neighborsAtomNrs = meshAtomNr(a)(b)(c); neighborsAtomCoords = meshAtomCoord(a)(b)(c); neighborsAtomCells = meshAtomCell(a)(b)(c); neighborsAtomNrsPeriodic = meshAtomNrPeriodic(a)(b)(c); neighborsAtomCoordsPeriodic = meshAtomCoordPeriodic(a)(b)(c); neighborsAtomCellsPeriodic = meshAtomCellPeriodic(a)(b)(c); // <-------- for (k = 0; k < neighborsAtomNrs.getSize(); k++) { a2 = neighborsAtomNrs(k); v = neighborsAtomCoords(k); R = neighborsAtomCells(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } for (k = 0; k < neighborsAtomNrsPeriodic.getSize(); k++) { a2 = neighborsAtomNrsPeriodic(k); v = neighborsAtomCoordsPeriodic(k); R = neighborsAtomCellsPeriodic(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } } } } for (i = 0; i < nAtoms; i++) { neigh(i) = neighList(i); dist(i) = distList(i); pw(i) = pwList(i); cell(i) = cellList(i); } } void SxEAM::updateNeighs () { double distance; SxVector3<Double> R; SxArray<SxList<int> > neighList; SxArray<SxList<double> > distList; SxArray<SxList<SxVector3<Double> > > cellList; neighList.resize(nAtoms); distList.resize(nAtoms); cellList.resize(nAtoms); int i, j; int sCut = (int) (cutoff/tau.cell(0, 0)) + 1; for (i = 0; i < nAtoms; i++) { distList(i). resize (0); neighList(i).resize (0); cellList(i). resize (0); } for (i = 0; i < nAtoms; i++) { for (int cX = -sCut; cX <= sCut; cX++) { for (int cY = -sCut; cY <= sCut; cY++) { for (int cZ = -sCut; cZ <= sCut; cZ++) { R = cX*tau.cell(0) + cY*tau.cell(1) + cZ*tau.cell(2); for (j = 0; j < nAtoms; j++) { if ( ((i != j)) && ((distance = getDist(i, j, R)) < cutoff )) { neighList(i).append (j); distList(i).append (distance); cellList(i).append ( tau.ref(i) - tau.ref(j) - R ); } } } } } } for (i = 0; i < nAtoms; i++) { neigh(i) = neighList(i); dist(i) = distList(i); cell(i) = cellList(i); } } void SxEAM::update (const SxAtomicStructure &newTau) { double R; tau = SxAtomicStructure (newTau, SxAtomicStructure::Copy); if (noLinkCell) updateNeighs(); else updateNeighsLinkCellMethod(); //--- updating charge densities on atom positions rhoSum.resize (0); rhoSum.resize (nAtoms); int iType; for (int i = 0; i < nAtoms; i++) { rhoSum(i) = 0.; for (int j = 0; j < neigh(i).getSize (); j++) { R = dist(i)(j); iType = getInteractionType (neigh(i)(j), neigh(i)(j)); rhoSum(i) += getRho(R, iType); } } } SxList<double> SxEAM::readData(const SxString &fileName) { SxList<double> list; ifstream filestr; double d1, d2; filestr.open(fileName.ascii()); filestr >> d1; filestr >> d2; list.append(d1); list.append(d2); while (filestr) { filestr >> d1; if (filestr) { filestr >> d2; list.append(d1); list.append(d2); } } filestr.close(); return list; } void SxEAM::setupSplines (const SxSymbolTable *cmd) { cout << "Setting up splines ..." << endl; SxList<double> readList; SxArray<double> Vx, Vy, y2; double dx, dy, xMax, xMin, x; int noI = (int)V.getSize (); int nSP; //--- number of points for tabulating potentials //nPoints = 1000000; nPoints = 100000; //---read in V(r) in eV(Angstroem) if (cmd->contains("V")) readList = cmd -> get ("V") -> toList (); else readList = readData(cmd->get("VFile")->toString()); nSP = (int)readList.getSize () / 2 / noI; for (int nI = 0; nI < noI; nI++) { Vx.resize (readList.getSize () / 2 / noI); Vy.resize (readList.getSize () / 2 / noI); y2.resize (readList.getSize () / 2 / noI); for (int i = 0; i < Vx.getSize (); i++) { Vx(i) = readList(2*(nSP*nI + i) ); Vy(i) = readList(2*(nSP*nI + i) + 1); } dy = Vy(1) - Vy(0); dx = Vx(1) - Vx(0); spline (Vx, Vy, (int)Vx.getSize (), dy/dx, 0., &y2); V(nI).resize (2); V(nI)(0).resize (nPoints+1); V(nI)(1).resize (nPoints+1); xMax = Vx(Vx.getSize () - 1); cutoff = xMax * A2B; //cutoff = xMax; xMin = Vx(0); dx = (xMax - xMin)/(double)nPoints; for (int i = 0; i <= nPoints; i++) { x = xMin + dx*(double)i; V(nI)(0)(i) = x; V(nI)(1)(i) = splint (Vx, Vy, y2, (int)Vx.getSize (), x); } } //---read in Rho(r) in eV(Angstroem) if (cmd->contains("RHO")) readList = cmd -> get ("RHO") -> toList (); else readList = readData(cmd->get("RHOFile")->toString()); nSP = (int)readList.getSize () / 2 / noI; for (int nI = 0; nI < noI; nI++) { Vx.resize (readList.getSize () / 2 / noI); Vy.resize (readList.getSize () / 2 / noI); y2.resize (readList.getSize () / 2 / noI); for (int i = 0; i < Vx.getSize (); i++) { Vx(i) = readList(2*(nSP*nI + i) ); Vy(i) = readList(2*(nSP*nI + i) + 1); } dy = Vy(1) - Vy(0); dx = Vx(1) - Vx(0); spline (Vx, Vy, (int)Vx.getSize (), dy/dx, 0., &y2); rho(nI).resize (2); rho(nI)(0).resize (nPoints+1); rho(nI)(1).resize (nPoints+1); xMax = Vx(Vx.getSize () - 1); if ( xMax*A2B > cutoff ) cutoff = xMax*A2B; xMin = Vx(0); dx = (xMax - xMin)/(double)nPoints; for (int i = 0; i <= nPoints; i++) { x = xMin + dx*(double)i; rho(nI)(0)(i) = x; rho(nI)(1)(i) = splint (Vx, Vy, y2, (int)Vx.getSize (), x); // cout << "RHO: " << rho(0)(i) << " " << rho(1)(i) << endl; } } //---read in F(r) in eV(Angstroem) if (cmd->contains("F")) readList = cmd -> get ("F") -> toList (); else readList = readData(cmd->get("FFile")->toString()); nSP = (int)readList.getSize () / 2 / noI; for (int nI = 0; nI < noI; nI++) { Vx.resize (readList.getSize () / 2 / noI); Vy.resize (readList.getSize () / 2 / noI); y2.resize (readList.getSize () / 2 / noI); for (int i = 0; i < Vx.getSize (); i++) { Vx(i) = readList(2*(nSP*nI + i) ); Vy(i) = readList(2*(nSP*nI + i) + 1); } dy = Vy(1) - Vy(0); dx = Vx(1) - Vx(0); spline (Vx, Vy, (int)Vx.getSize (), dy/dx, 0., &y2); F(nI).resize (2); F(nI)(0).resize (nPoints+1); F(nI)(1).resize (nPoints+1); xMax = Vx(Vx.getSize () - 1); xMin = Vx(0); dx = (xMax - xMin)/(double)nPoints; for (int i = 0; i <= nPoints; i++) { x = xMin + dx*(double)i; F(nI)(0)(i) = x; F(nI)(1)(i) = splint (Vx, Vy, y2, (int)Vx.getSize (), x); // cout << "FF: " << F(0)(i) << " " << F(1)(i) << endl; } } //--- tabulating derivatives for (int nI = 0; nI < noI; nI++) { dV(nI).resize (2); dV(nI)(0).resize (V(nI)(0).getSize ()); dV(nI)(1).resize (V(nI)(1).getSize ()); drho(nI).resize (2); drho(nI)(0).resize (rho(nI)(0).getSize ()); drho(nI)(1).resize (rho(nI)(1).getSize ()); dF(nI).resize (2); dF(nI)(0).resize (F(nI)(0).getSize ()); dF(nI)(1).resize (F(nI)(1).getSize ()); for (int i = 1; i < (dV(nI)(0).getSize () - 1); i++) { dV(nI)(0)(i) = V(nI)(0)(i); dy = V(nI)(1)(i + 1) - V(nI)(1)(i - 1); dx = V(nI)(0)(i + 1) - V(nI)(0)(i - 1); dV(nI)(1)(i) = dy/dx; } dV(nI)(0)(0) = V(nI)(0)(0); dV(nI)(0)(dV(nI).getSize() - 1) = V(nI)(0)(dV(nI).getSize () - 1); dV(nI)(1)(0) = dV(nI)(1)(1); dV(nI)(1)(dV(nI).getSize() - 1) = dV(nI)(1)(dV(nI).getSize () - 2); for (int i = 1; i < (dF(nI)(0).getSize () - 1); i++) { dF(nI)(0)(i) = F(nI)(0)(i); dy = F(nI)(1)(i + 1) - F(nI)(1)(i - 1); dx = F(nI)(0)(i + 1) - F(nI)(0)(i - 1); dF(nI)(1)(i) = dy/dx; } dF(nI)(0)(0) = F(nI)(0)(0); dF(nI)(0)(dF(nI).getSize() - 1) = F(nI)(0)(dF(nI).getSize () - 1); dF(nI)(1)(0) = dF(nI)(1)(1); dF(nI)(1)(dF(nI).getSize() - 1) = dF(nI)(1)(dF(nI).getSize () - 2); for (int i = 1; i < (drho(nI)(0).getSize () - 1); i++) { drho(nI)(0)(i) = rho(nI)(0)(i); dy = rho(nI)(1)(i + 1) - rho(nI)(1)(i - 1); dx = rho(nI)(0)(i + 1) - rho(nI)(0)(i - 1); drho(nI)(1)(i) = dy/dx; } drho(nI)(0)(0) = rho(nI)(0)(0); drho(nI)(0)(drho(nI).getSize() - 1) = rho(nI)(0)(drho(nI).getSize () - 1); drho(nI)(1)(0) = drho(nI)(1)(1); drho(nI)(1)(drho(nI).getSize() - 1) = drho(nI)(1)(drho(nI).getSize () - 2); } // for (int i = 0; i < F(0)(0).getSize (); i++) // if ((i < 100) || (i > (drho(0)(0).getSize () - 100))) // cout << F(1)(0)(i) << " " << F(1)(1)(i) << " " << dF(1)(1)(i) << endl; // QUIT; } double SxEAM::getEnergy () const { return totalEnergy; } double SxEAM::getPotentialEnergy () const { return totalEnergy; } SxSpeciesData SxEAM::getSpeciesData () const { return speciesData; } SxAtomicStructure SxEAM::getNumericalForces (const SxAtomicStructure &tauIn, const double &dx) { SxAtomicStructure Forces (tauIn, SxAtomicStructure::Copy); SxAtomicStructure undevCoord (tauIn, SxAtomicStructure::Copy); SxAtomicStructure devCoord (tauIn, SxAtomicStructure::Copy); double undevEnergy; update(tauIn); undevEnergy = getTotalEnergy (); for (int i = 0; i < nAtoms; i++) { for (int j = 0; j < 3; j++) { Forces.ref(i)(j) = 0.; devCoord.ref(i)(j) += dx; update(devCoord); Forces.ref(i)(j) -= (getTotalEnergy () - undevEnergy)/dx/2.; devCoord.ref(i)(j) -= 2.*dx; update(devCoord); Forces.ref(i)(j) += (getTotalEnergy() - undevEnergy)/dx/2.; devCoord.ref(i)(j) += dx; } } return Forces; } SxArray<SxAtomicStructure> SxEAM::getNumericalHesseMatrix (const SxAtomicStructure &tauIn, const double &dx) { SxArray<SxAtomicStructure> Hesse; Hesse.resize (3*nAtoms); SxAtomicStructure A, B; SxAtomicStructure devCoord (tauIn, SxAtomicStructure::Copy); SxSymbolTable *table = NULL; // CF 2016-07-07: where should table come from ??? for (int i = 0; i < nAtoms; i++) { for (int j = 0; j < 3; j++) { devCoord.ref(i)(j) += dx; A = getForces (devCoord, table); devCoord.ref(i)(j) -= 2.*dx; B = getForces (devCoord, table); Hesse(3*i+j).copy ((1./dx/2.)*(A-B)); //Hesse(3*i+j) = (1./dx/2.)*(A-B); devCoord.ref(i)(j) += dx; } } return Hesse; } SxArray<SxArray<SxAtomicStructure> > SxEAM::getNumericalTTensor (const SxAtomicStructure &tauIn, const double &dx) { double threshold = 1e-9; SxArray<SxArray<SxAtomicStructure> > TTensor; TTensor.resize(3*nAtoms); SxArray<SxAtomicStructure> A, B, Delta; SxAtomicStructure devCoord (tauIn, SxAtomicStructure::Copy); int i,j,k,l,m; sxprintf("nAtoms=%d",nAtoms); fflush(stdout); for (i = 0; i < nAtoms; i++) { sxprintf(" %d",i+1); fflush(stdout); for (j = 0; j < 3; j++) { devCoord.ref(i)(j) += dx; A = getNumericalHesseMatrix (devCoord,dx); devCoord.ref(i)(j) -= 2.*dx; B = getNumericalHesseMatrix (devCoord,dx); //Delta = A-B; Delta.resize(3*nAtoms); for (k=0;k<Delta.getSize();k++) { Delta(k) = A(k) - B(k); Delta(k) = (1./dx/2.) * Delta(k); for (l=0; l<nAtoms; l++) { for (m=0; m<3; m++) { if (Delta(k).ref(l)(m) < threshold) Delta(k).ref(l)(m)=0.; } } } // cout << "Delta " << Delta(24)( << endl; TTensor(3*i+j) = Delta; devCoord.ref(i)(j) += dx; } } cout << endl; return TTensor; } void SxEAM::exportForces (const SxAtomicStructure &forces, const SxString &fileName) { int i; ofstream filestr; filestr.open(fileName.ascii(), ifstream::trunc); for (i=0; i<nAtoms; i++) { filestr << forces(i)(0) << " " << forces(i)(1) << " " << forces(i)(2) << endl; } filestr.close(); } void SxEAM::exportHesse (const SxArray<SxAtomicStructure> &hesse, const SxString &fileName) { int i, j; ofstream filestr; filestr.open(fileName.ascii(), ifstream::trunc); for (i=0; i<3*nAtoms; i++) { for (j=0; j<nAtoms; j++) { filestr << -hesse(i)(j)(0) << " " << -hesse(i)(j)(1) << " " << -hesse(i)(j)(2) << " "; } filestr << endl; } filestr.close(); } void SxEAM::exportTTensor (const SxArray<SxArray<SxAtomicStructure> > &TTensor, const SxString &fileName) { int i, j, k; ofstream filestr; filestr.open(fileName.ascii(), ifstream::trunc); for (k=0;k<3*nAtoms;k++) { for (i=0; i<3*nAtoms; i++) { for (j=0; j<nAtoms; j++) { filestr << TTensor(k)(i)(j)(0) << " " << TTensor(k)(i)(j)(1) << " " << TTensor(k)(i)(j)(2) << " "; } } filestr << endl; } filestr.close(); } SxAtomicStructure SxEAM::getForces (const SxAtomicStructure &tauIn, const SxSymbolTable *dummy) { // SVN_HEAD; // this line MUST NOT be removed SxAtomicStructure forces (tauIn, SxAtomicStructure::Copy); update (tauIn); double R = 0.; SxVector3<Double> e; int n = 0; int iType1; int iType2; int iType3; for (int i = 0; i < nAtoms; i++) { forces.ref(i).set(0.); for (int j = 0; j < neigh(i).getSize (); j++) { n = neigh(i)(j); R = dist(i)(j); e = (1./R)*cell(i)(j); iType1 = getInteractionType(i, n); iType2 = getInteractionType(n, n); iType3 = getInteractionType(i, i); forces.ref(i) -= (getdV(R, iType1) + getdF(rhoSum(n), iType2) *getdRho(R, iType3) + getdF(rhoSum(i), iType3) *getdRho(R, iType2))*e; } } totalEnergy = getTotalEnergy (); // cout << tauIn << endl; return ((1./HA2EV)*forces); } double SxEAM::getV (const double &r, int isP) { double rB = r/A2B; double idxD = ((rB - V(isP)(0)(0))/(V(isP)(0)(1)-V(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; return ((1. - interpol)*V(isP)(1)(idx) + interpol*V(isP)(1)(idx + 1)); } double SxEAM::getdV (const double &r, int isP) { double rB = r/A2B; double idxD = ((rB - dV(isP)(0)(0))/(dV(isP)(0)(1)-dV(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; //double interpol = 0.; return (((1. - interpol)*dV(isP)(1)(idx) + interpol*dV(isP)(1)(idx + 1))/A2B); } double SxEAM::getRho (const double &r, int isP) { double rB = r/A2B; //double last = rho(isP)(0)(rho(isP)(0).getSize()-1); double idxD = ((rB - rho(isP)(0)(0))/(rho(isP)(0)(1) -rho(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; return ((1. - interpol)*rho(isP)(1)(idx) + interpol*rho(isP)(1)(idx + 1)); } double SxEAM::getdRho (const double &r, int isP) { double rB = r/A2B; double idxD = ((rB - drho(isP)(0)(0))/(drho(isP)(0)(1) - drho(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; //double interpol = 0.; return (((1. - interpol)*drho(isP)(1)(idx) + interpol*drho(isP)(1)(idx + 1))/A2B); } double SxEAM::getF (const double &rh, int isP) { double rB = rh; double idxD = ((rB - F(isP)(0)(0))/(F(isP)(0)(1)-F(isP)(0)(0))); int idx = (int) idxD; if (idx >= F(isP)(0).getSize ()) return (F(isP)(1)(F(isP)(0).getSize () - 1)); double interpol = idxD - (double)idx; return ((1. - interpol)*F(isP)(1)(idx) + interpol*F(isP)(1)(idx + 1)); } double SxEAM::getdF (const double &rh, int isP) { double rB = rh; double idxD = ((rB - dF(isP)(0)(0))/(dF(isP)(0)(1) - dF(isP)(0)(0))); int idx = (int) idxD; if (idx >= dF(isP)(0).getSize ()) return 0.; double interpol = idxD - (double)idx; //double interpol = 0.; return ((1. - interpol)*dF(isP)(1)(idx) + interpol*dF(isP)(1)(idx + 1)); } double SxEAM::getTotalEnergy () { double energy, R; int i, j; energy = 0.; int iType; for (i = 0; i < nAtoms; i++) { for (j = 0; j < neigh(i).getSize (); j++) { iType = getInteractionType(i, neigh(i)(j)); R = dist(i)(j); energy += 0.5*getV (R, iType); } iType = getInteractionType(i, i); energy += getF (rhoSum(i), iType); } return (energy/HA2EV); } void SxEAM::execute (const SxSymbolTable *cmd, bool calc) { cout << "Executing EAM Potential" << endl << endl; SxString s = cmd->getName(); double disp; update (tau); SxAtomicStructure str=tau; exportForces(tau,"cartesian_coords"); cout << "cartesian_coords in bohr exported." << endl << endl; if (s=="forces") { if (cmd->contains("numerical")) { disp = (cmd->contains("disp")) ? cmd->get("disp")->toReal() : 0.01; cout << "Calculating numerical forces with displacement " << disp << " Angstrom..." << endl; exportForces(getNumericalForces(tau, disp),"Forces"); cout << "Forces in hartree/bohr exported." << endl << endl; } else { cout << "Calculating analytical forces..." << endl; exportForces(getForces(tau),"Forces"); cout << "Forces in hartree/bohr exported." << endl << endl; } } if (s=="HesseMatrix") { disp = (cmd->contains("disp")) ? cmd->get("disp")->toReal() : 0.01; cout << "Calculating numerical Hesse matrix with displacement " << disp << " Angstrom (forces are analytical)..." << endl; exportHesse(getNumericalHesseMatrix(tau, disp),"HesseMatrix"); cout << "HesseMatrix in hartree/(u*bohr^2) exported." << endl << endl; } if (s=="TTensor") { disp = (cmd->contains("disp")) ? cmd->get("disp")->toReal() : 0.01; cout << "Calculating numerical TTensor with displacement " << disp << " Angstrom (forces are analytical)..." << endl; SxArray<SxArray<SxAtomicStructure> > TTensor; TTensor = getNumericalTTensor(tau,disp); exportTTensor(TTensor,"TTensor"); cout << "TTensor in hartree/(u*bohr^3) exported." << endl << endl; } return; } void SxEAM::spline (const SxArray<double> &x, const SxArray<double> &y, int n, double yp1, double ypn, SxArray<double> *y2) { int i, k; double p, qn, sig, un; SxArray<double> u (x.getSize ()); if (yp1 > 0.99e30) (*y2)(0) = u(0) = 0.; else { (*y2)(0) = -0.5; u(0) = (3.0/(x(1) - x(0))) * ((y(1) - y(0))/(x(1) - x(0)) - yp1); } for (i = 1; i <= (n-2); i++) { sig = (x(i) - x(i-1))/(x(i+1) - (x(i-1))); p = sig* (*y2)(i-1) + 2.; (*y2)(i) = (sig - 1.)/p; u(i) = (y(i+1) - y(i))/(x(i+1) - x(i)) - (y(i) - y(i-1))/(x(i) - x(i-1)); u(i) = (6.0*u(i)/(x(i+1) - x(i-1)) -sig*u(i-1))/p; } if (ypn > 0.99e30) qn = un = 0.0; else { qn = 0.5; un = (3.0/(x(n-1) - x(n-2)))*(ypn - (y(n-1) - y(n-2))/(x(n-1) - x(n-2))); } (*y2)(n-1) = (un - qn*u(n-2))/(qn* (*y2)(n-2) + 1.); for (k = (n-2); k>= 0; k--) (*y2)(k) = (*y2)(k)*(*y2)(k + 1) + u(k); } double SxEAM::splint (const SxArray<double> &xa, const SxArray<double> &ya, const SxArray<double> &y2a, int n, double x) { int klo, khi, k; double h,b,a; klo = 0; khi = n-1; while ( (khi-klo) > 1) { k = (khi + klo) >> 1; if (xa(k) > x) khi = k; else klo = k; } h = (xa(khi) - xa(klo)); if (h == 0.) { cout << "Bad xa input to routine splint" << endl; SX_EXIT; } a = (xa(khi) - x)/h; b = (x - xa(klo))/h; double y = a*ya(klo) + b*ya(khi)+((a*a*a - a)*y2a(klo) + (b*b*b - b)*y2a(khi))*(h*h)/6.0; return y; }
29.606266
115
0.498956
ashtonmv
63e5ce142b41ff52370b391a71f1250f4dcdfbf7
8,335
cpp
C++
operators/data_sender_bcast_tcp.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
operators/data_sender_bcast_tcp.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
operators/data_sender_bcast_tcp.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2015, Pythia authors (see AUTHORS file). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "operators.h" #include "operators_priv.h" #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <ifaddrs.h> #include <arpa/inet.h> #include <unistd.h> #include <iostream> #include <cstdlib> #include <iomanip> #include "../rdtsc.h" #include "../util/tcpsocket.h" #include <fstream> #include <string> using std::make_pair; //input attributes for rdma send: // int port: port used for TCP/IP to do sync // int msgsize: send message size, 4096 bytes by default // int buffnum: number of buffers used in send void DataSenderBcastTcpOp::init(libconfig::Config& root, libconfig::Setting& cfg) { //static_assert(sizeof(struct thread_rc_t)%CACHE_LINE_SIZE == 0); //static_assert(sizeof(struct destlink_t)%CACHE_LINE_SIZE == 0); Operator::init(root, cfg); schema = nextOp->getOutSchema(); //todo: the following varaibles should come from config file if (cfg.exists("threadnum")) { threadnum_ = cfg["threadnum"]; } else { threadnum_ = 1; } if (cfg.exists("opid")) { operator_id_ = cfg["opid"]; } else { operator_id_ = 0; } atomic_thread_cnt_ = threadnum_; msgsize_ = cfg["msgsize"]; nodenum_ = cfg["nodenum"]; assert(nodenum_ < MAX_LINKS); node_id_ = cfg["nodeid"]; //node id is to identify each node, frange from 0 to n-1 host_ip_ = (const char*) cfg["hostIP"]; //loop to get all ip adress of remote node libconfig::Setting& ipgrp = cfg["destIP"]; int size = ipgrp.getLength(); assert( size != 0 ); assert( size <= MAX_LINKS ); for (int i=0; i<size; ++i) { std::string ipaddr = (const char*) ipgrp[i]; dest_ip_.push_back(ipaddr); } vector<int> temp_sock_id; for (int i=0; i<size; i++) { temp_sock_id.push_back(-1); } for (int i=0; i<threadnum_; i++) { sock_id_.push_back(temp_sock_id); } //buffer for data to each destination for (int i=0; i<MAX_THREADS; i++) { thread_rc_[i].out_buffer = &EmptyPage; } } void DataSenderBcastTcpOp::threadInit(unsigned short threadid) { assert(threadid < threadnum_); thread_rc_[threadid].buf = numaallocate_local("DSbf", msgsize_, this); thread_rc_[threadid].rdma_buf.set((char*)thread_rc_[threadid].buf); if (threadid == 0) { for (int i=0; i<threadnum_; i++) { TcpServer(LISTEN_PORT+i+operator_id_*MAX_THREADS, host_ip_.c_str(), nodenum_, sock_id_[i]); for (int j=0; j<nodenum_; j++) { assert(sock_id_[i][j] != -1); } //sync to exit for (int j=0; j<nodenum_; j++) { if(sock_id_[i][j] == -1) { continue; } char temp = 'a'; assert(send(sock_id_[i][j], &temp, sizeof(temp), MSG_DONTWAIT) != -1); //cout << "send hand sig from " << node_id_ << " to " << j << endl; } for (int j=0; j<nodenum_; j++) { if(sock_id_[i][j] == -1) { continue; } char temp = 'b'; assert(recv(sock_id_[i][j], &temp, sizeof(temp), MSG_WAITALL) != -1); //cout << "recv hand sig " << temp << " from " << j << " to " << node_id_ << endl; } } } } Operator::ResultCode DataSenderBcastTcpOp::scanStart(unsigned short threadid, Page* indexdatapage, Schema& indexdataschema) { //cout << "before scan start" << endl; ResultCode rescode; thread_rc_[threadid].out_buffer = new Page(thread_rc_[threadid].rdma_buf.msg, msgsize_-12, NULL, schema.getTupleSize()); thread_rc_[threadid].out_buffer->clear(); rescode = nextOp->scanStart(threadid, indexdatapage, indexdataschema); return rescode; } Operator::GetNextResultT DataSenderBcastTcpOp::getNext(unsigned short threadid) { //here we assume a one to one mapping between rdma wr_id and send buff //addr and 0 to buffer0, 1 to buffer1, buffnum_-1 to buffer buffnum_-1 //cout << "before getnext" << endl; Operator::GetNextResultT result; result = nextOp->getNext(threadid); Page* in; Operator::ResultCode rc; in = result.second; rc = result.first; void *tuple; int tupoffset = 0; while (1) { while ((tuple = in->getTupleOffset(tupoffset)) != NULL) { //if data in page in is less than left space in send buffer uint64_t left_data_in = in->getUsedSpace()-tupoffset*in->getTupleSize(); if (thread_rc_[threadid].out_buffer->canStore(left_data_in)) { void * bucketspace = thread_rc_[threadid].out_buffer->allocate(left_data_in); memcpy(bucketspace, tuple, left_data_in); break; } //data in page in is more than left space in send buffer else { uint64_t left_space_in_buffer = thread_rc_[threadid].out_buffer->capacity() - thread_rc_[threadid].out_buffer->getUsedSpace(); void *bucketspace = thread_rc_[threadid].out_buffer->allocate(left_space_in_buffer); memcpy(bucketspace, tuple, left_space_in_buffer); tupoffset += left_space_in_buffer/in->getTupleSize(); int datalen = thread_rc_[threadid].out_buffer->getUsedSpace(); thread_rc_[threadid].rdma_buf.deplete = MoreData; thread_rc_[threadid].rdma_buf.datalen = datalen; thread_rc_[threadid].rdma_buf.nodeid = node_id_; thread_rc_[threadid].rdma_buf.serialize(); for (int i=0; i<nodenum_; i++) { send(sock_id_[threadid][i], thread_rc_[threadid].rdma_buf.buffaddr(), msgsize_, MSG_WAITALL); } //clear buffer after send out thread_rc_[threadid].out_buffer->clear(); } } if (rc == Finished) { int datalen = thread_rc_[threadid].out_buffer->getUsedSpace(); thread_rc_[threadid].rdma_buf.deplete = Depleted; thread_rc_[threadid].rdma_buf.datalen = datalen; thread_rc_[threadid].rdma_buf.nodeid = node_id_; thread_rc_[threadid].rdma_buf.serialize(); for (int i=0; i<nodenum_; i++) { send(sock_id_[threadid][i], thread_rc_[threadid].rdma_buf.buffaddr(), msgsize_, MSG_WAITALL); } //clear buffer after send out thread_rc_[threadid].out_buffer->clear(); return make_pair(Finished, &EmptyPage); } result = nextOp->getNext(threadid); rc = result.first; in = result.second; tupoffset = 0; } } void DataSenderBcastTcpOp::threadClose(unsigned short threadid) { //shake hands to exit //block until all destinations receive all the data //is this necessary? or should we put this in scan stop? //cout << "before t close" << endl; for (int i=0; i<nodenum_; i++) { char temp = 'a'; assert(send(sock_id_[threadid][i], &temp, sizeof(temp), MSG_DONTWAIT) != -1); //cout << "send hand sig from " << node_id_ << " to " << i << endl; } for (int i=0; i<nodenum_; i++) { char temp = 'b'; assert(recv(sock_id_[threadid][i], &temp, sizeof(temp), MSG_WAITALL) != -1); //cout << "recv hand sig " << temp << " from " << i << " to " << node_id_ << endl; } numadeallocate(thread_rc_[threadid].buf); //delete Page in out_buffer_ if (thread_rc_[threadid].out_buffer != &EmptyPage) { delete thread_rc_[threadid].out_buffer; } for (int i=0; i<nodenum_; i++) { close(sock_id_[threadid][i]); } }
32.558594
130
0.695381
damodar123
63e5f158d4fab037a3dd67342b140a8007c9112c
7,764
cpp
C++
src/prod/src/Reliability/Replication/CopyContextReceiver.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Reliability/Replication/CopyContextReceiver.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Reliability/Replication/CopyContextReceiver.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" namespace Reliability { namespace ReplicationComponent { using Common::AcquireExclusiveLock; using Common::Assert; using Common::AsyncCallback; using Common::AsyncOperation; using Common::AsyncOperationSPtr; using Common::ComPointer; using Common::ComponentRoot; using Common::ErrorCode; using Common::make_com; using Common::make_unique; using Common::ReaderQueue; using Common::Threadpool; using std::move; using std::wstring; CopyContextReceiver::CopyContextReceiver( REInternalSettingsSPtr const & config, Common::Guid const & partitionId, std::wstring const & purpose, ReplicationEndpointId const & from, FABRIC_REPLICA_ID to) : Common::ComponentRoot(), config_(config), partitionId_(partitionId), endpointUniqueId_(from), replicaId_(to), purpose_(purpose), queue_( partitionId_, GetDescription(purpose, from, to), config->InitialCopyQueueSize, config->MaxCopyQueueSize, 0, // no max memory size for copy context queue 0, 0, /*hasPersistedState*/ false, /*cleanOnComplete*/ true, /*ignoreCommit*/ true, 1, nullptr), lastCopyContextSequenceNumber_(Constants::NonInitializedLSN), allOperationsReceived_(false), dispatchQueue_(ReaderQueue<ComOperationCPtr>::Create()), ackSender_(config_, partitionId_, endpointUniqueId_), lastAckSent_(Constants::InvalidLSN), copyContextEnumerator_(), errorCodeValue_(0), isActive_(true), lock_() { queue_.SetCommitCallback( [this] (ComOperationCPtr const & operation) { this->DispatchOperation(operation); }); } CopyContextReceiver::~CopyContextReceiver() { } wstring CopyContextReceiver::GetDescription( std::wstring const & purpose, ReplicationEndpointId const & from, FABRIC_REPLICA_ID to) { wstring desc; Common::StringWriter(desc).Write("{0}->{1}:{2}", from, to, purpose); return desc; } void CopyContextReceiver::GetStateAndSetLastAck( __out FABRIC_SEQUENCE_NUMBER & lastCompletedSequenceNumber, __out int & errorCodeValue) { AcquireExclusiveLock lock(lock_); errorCodeValue = errorCodeValue_; if (lastCopyContextSequenceNumber_ != Constants::NonInitializedLSN && (lastCopyContextSequenceNumber_ - 1) == queue_.LastCompletedSequenceNumber) { // last operation (empty) has been seen and queue completed to lastSeenLSN-1 lastCompletedSequenceNumber = lastCopyContextSequenceNumber_; } else { lastCompletedSequenceNumber = queue_.LastCompletedSequenceNumber; } lastAckSent_ = lastCompletedSequenceNumber; } void CopyContextReceiver::Open( SendCallback const & copySendCallback) { ackSender_.Open(*this, copySendCallback); } void CopyContextReceiver::Close(ErrorCode const error) { bool errorsEncountered = !error.IsSuccess(); // First, set up the state and close the copy context enumerator; // then close the dispatch queue (which will finish any pending GetNext // on the enumerator) and, if needed, schedule one last ACK // to let the other part know that we completed with error. { AcquireExclusiveLock lock(lock_); isActive_ = false; errorCodeValue_ = error.ReadValue(); // Close the enumerator, which will break the pointer cycle copyContextEnumerator_->Close(errorsEncountered); } dispatchQueue_->Close(); if (errorsEncountered) { // Send one last message to let the other part know that an error occurred ackSender_.ScheduleOrSendAck(true); } ackSender_.Close(); } void CopyContextReceiver::CreateEnumerator( __out ComPointer<IFabricOperationDataStream> & context) { ComPointer<ComOperationDataAsyncEnumerator> localEnum = make_com<ComOperationDataAsyncEnumerator>( *this, dispatchQueue_); context = ComPointer<IFabricOperationDataStream>(localEnum, IID_IFabricOperationDataStream); { // Keep a copy of the enumerator, // to be able to report any outside errors AcquireExclusiveLock lock(lock_); copyContextEnumerator_ = move(localEnum); } } bool CopyContextReceiver::ProcessCopyContext( ComOperationCPtr && operation, bool isLast) { bool shouldDispatch = false; bool forceSend = false; bool shouldCloseDispatchQueue = false; { AcquireExclusiveLock lock(lock_); // Process the copy context operation, unless // All operations have already been received // or the copy context receiver already encountered an error. // Otherwise, no processing is needed, but the ACK must be sent if (isActive_ && !allOperationsReceived_ && errorCodeValue_ == 0) { if (isLast) { lastCopyContextSequenceNumber_ = operation->SequenceNumber; } else { auto localOperation = move(operation); if (queue_.TryEnqueue(localOperation).IsSuccess()) { if (!queue_.Complete()) { // There are no in-order items, there is no need to send ACK. return false; } } shouldDispatch = true; } if (queue_.LastCompletedSequenceNumber == (lastCopyContextSequenceNumber_ - 1)) { // Since the last completed sequence number is the last copy sequenceNumber, // copy context is done. ReplicatorEventSource::Events->PrimaryAllCCReceived( partitionId_, endpointUniqueId_, replicaId_, purpose_, lastCopyContextSequenceNumber_); allOperationsReceived_ = true; shouldCloseDispatchQueue = true; forceSend = true; } else if (queue_.LastCompletedSequenceNumber > lastAckSent_ + config_->MaxPendingAcknowledgements) { forceSend = true; } } } if (shouldCloseDispatchQueue) { dispatchQueue_->Close(); } if (shouldDispatch) { // Dispatch all items in the dispatch queue // outside the lock and on a different thread. auto root = this->CreateComponentRoot(); Threadpool::Post([this, root]() { this->dispatchQueue_->Dispatch(); }); } // If we got to this point, we need to send ACK back to the secondary ackSender_.ScheduleOrSendAck(forceSend); return true; } void CopyContextReceiver::DispatchOperation(ComOperationCPtr const & operation) { bool success = dispatchQueue_->EnqueueWithoutDispatch(make_unique<ComOperationCPtr>(operation)); ASSERT_IFNOT(success, "{0}->{1}:{2}: EnqueueWithoutDispatch CopyCONTEXT should succeed", endpointUniqueId_, replicaId_, purpose_); ReplicatorEventSource::Events->PrimaryCCEnqueueWithoutDispatch( partitionId_, endpointUniqueId_, replicaId_, purpose_, operation->SequenceNumber); } } // end namespace ReplicationComponent } // end namespace Reliability
32.621849
134
0.632535
gridgentoo
63e7071bdaa4b29f8cf58e81570e3d44530ebdc4
564
cpp
C++
Pyramid Printer/pyramid.cpp
noahkiss/intro-to-cpp
8a4a8836f9e52ddffe6229d8d07e7b34d6a6fbb1
[ "MIT" ]
null
null
null
Pyramid Printer/pyramid.cpp
noahkiss/intro-to-cpp
8a4a8836f9e52ddffe6229d8d07e7b34d6a6fbb1
[ "MIT" ]
null
null
null
Pyramid Printer/pyramid.cpp
noahkiss/intro-to-cpp
8a4a8836f9e52ddffe6229d8d07e7b34d6a6fbb1
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { int row = 8; //cout << "How many rows of numbers? "; //cin >> row; row--; for (int line = 0; line <= row; line++) { cout << setw(36 - 4 * line) << 1; for (int num = 1; num <= line; num++) { cout << setw(4) << pow(2, num); } for (int num = line - 1; num > 0; num--) { cout << setw(4) << pow(2, num); } if (line) cout << setw(4) << 1; cout << endl; } return 0; }
20.142857
50
0.437943
noahkiss
63eea8d4b9f2ea73481028908dcdc2430b86b0f2
437
hh
C++
emu-ex-plus-alpha/imagine/src/io/mmap/generic/IoMmapGeneric.hh
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
1
2018-11-14T23:40:35.000Z
2018-11-14T23:40:35.000Z
emu-ex-plus-alpha/imagine/src/io/mmap/generic/IoMmapGeneric.hh
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
emu-ex-plus-alpha/imagine/src/io/mmap/generic/IoMmapGeneric.hh
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
#pragma once #include <engine-globals.h> #include <io/mmap/IoMmap.hh> #include <mem/interface.h> class IoMmapGeneric : public IoMmap { public: static Io* open(const uchar * buffer, size_t size); ~IoMmapGeneric() { close(); } void close(); // optional function to call on close, <ptr> is the buffer passed during open() typedef void (*FreeFunc)(void *ptr); void memFreeFunc(FreeFunc free); private: FreeFunc free = nullptr; };
20.809524
80
0.71167
damoonvisuals
63f277898b3f89389f3df8d83b2aec541ab3bcf7
240
cc
C++
cpp-tutorial/main/test/hello-greet-test.cc
yuryu/bazel-examples
817f2f84211ca21733a78eefcb0b47aeb2cfddf0
[ "Apache-2.0" ]
null
null
null
cpp-tutorial/main/test/hello-greet-test.cc
yuryu/bazel-examples
817f2f84211ca21733a78eefcb0b47aeb2cfddf0
[ "Apache-2.0" ]
null
null
null
cpp-tutorial/main/test/hello-greet-test.cc
yuryu/bazel-examples
817f2f84211ca21733a78eefcb0b47aeb2cfddf0
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include "../hello-greet.h" TEST(hello_greet_test, empty_string) { EXPECT_EQ(get_greet(""), std::string("Hello ")); } TEST(hello_greet_test, with_name) { EXPECT_EQ(get_greet("abc"), std::string("Hello ")); }
17.142857
53
0.683333
yuryu
63f348161aa46325097f3cbaf745da391ba962a9
1,416
cpp
C++
ring/eran/gurobi900/linux64/examples/c++/lpmethod_c++.cpp
Practical-Formal-Methods/clam-racetrack
75d05ca72dab67b065c8cbab983b1b83a21fede8
[ "Apache-2.0" ]
4
2021-05-19T17:35:30.000Z
2021-08-17T04:03:21.000Z
ring/eran/gurobi900/linux64/examples/c++/lpmethod_c++.cpp
Practical-Formal-Methods/clam-racetrack
75d05ca72dab67b065c8cbab983b1b83a21fede8
[ "Apache-2.0" ]
null
null
null
ring/eran/gurobi900/linux64/examples/c++/lpmethod_c++.cpp
Practical-Formal-Methods/clam-racetrack
75d05ca72dab67b065c8cbab983b1b83a21fede8
[ "Apache-2.0" ]
1
2022-01-15T11:20:30.000Z
2022-01-15T11:20:30.000Z
/* Copyright 2019, Gurobi Optimization, LLC */ /* Solve a model with different values of the Method parameter; show which value gives the shortest solve time. */ #include "gurobi_c++.h" using namespace std; int main(int argc, char *argv[]) { if (argc < 2) { cout << "Usage: lpmethod_c++ filename" << endl; return 1; } try { // Read model GRBEnv env = GRBEnv(); GRBModel m = GRBModel(env, argv[1]); // Solve the model with different values of Method int bestMethod = -1; double bestTime = m.get(GRB_DoubleParam_TimeLimit); for (int i = 0; i <= 2; ++i) { m.reset(); m.set(GRB_IntParam_Method, i); m.optimize(); if (m.get(GRB_IntAttr_Status) == GRB_OPTIMAL) { bestTime = m.get(GRB_DoubleAttr_Runtime); bestMethod = i; // Reduce the TimeLimit parameter to save time // with other methods m.set(GRB_DoubleParam_TimeLimit, bestTime); } } // Report which method was fastest if (bestMethod == -1) { cout << "Unable to solve this model" << endl; } else { cout << "Solved in " << bestTime << " seconds with Method: " << bestMethod << endl; } } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } return 0; }
24.842105
63
0.586864
Practical-Formal-Methods
63f356155a61afd86e38cf2ba0a470edd392ac42
732
hpp
C++
idock/src/summary.hpp
kingdavid72/Calici-Nebular
6bd51f63c7de37605dcbfbd3669462a997638ffb
[ "Apache-2.0" ]
30
2015-02-09T00:53:09.000Z
2022-01-19T13:36:20.000Z
idock/src/summary.hpp
kingdavid72/Calici-Nebular
6bd51f63c7de37605dcbfbd3669462a997638ffb
[ "Apache-2.0" ]
3
2016-06-16T18:07:30.000Z
2019-01-15T23:45:34.000Z
idock/src/summary.hpp
kingdavid72/Calici-Nebular
6bd51f63c7de37605dcbfbd3669462a997638ffb
[ "Apache-2.0" ]
19
2015-04-15T12:48:13.000Z
2021-04-19T11:30:46.000Z
#pragma once #ifndef IDOCK_SUMMARY_HPP #define IDOCK_SUMMARY_HPP #include "conformation.hpp" /// Represents a summary of docking results of a ligand. class summary { public: size_t index; fl energy; fl rfscore; conformation conf; explicit summary(const size_t index, const fl energy, const fl rfscore, const conformation& conf) : index(index), energy(energy), rfscore(rfscore), conf(conf) { } summary(const summary&) = default; summary(summary&&) = default; summary& operator=(const summary&) = default; summary& operator=(summary&&) = default; }; /// For sorting ptr_vector<summary>. inline bool operator<(const summary& a, const summary& b) { return a.energy < b.energy; // return a.rfscore > b.rfscore; } #endif
22.181818
159
0.729508
kingdavid72
63fb9e9bebb977d4a10f0cd7dfce48358a18c8ae
4,657
cpp
C++
src/Socket.cpp
pmelendez/chimire
001482acb05a119674fd04abe327eb7f1698b72d
[ "MIT" ]
null
null
null
src/Socket.cpp
pmelendez/chimire
001482acb05a119674fd04abe327eb7f1698b72d
[ "MIT" ]
null
null
null
src/Socket.cpp
pmelendez/chimire
001482acb05a119674fd04abe327eb7f1698b72d
[ "MIT" ]
null
null
null
/* * File: Socket.cpp * Author: pedro * * Created on July 17, 2014, 8:26 AM based on previous version Oct 17, 2010 11:56 AM */ #include "Socket.h" Socket::Socket() { socketID=NULL_SOCKET; max_connections= DEFAULT_MAXCONNECTIONS; init_variables(); } Socket::Socket(int socket_id, sockaddr_in addr) { max_connections= DEFAULT_MAXCONNECTIONS; socketID=socket_id; serv_addr=addr; init_variables(); } Socket::Socket(const Socket& orig) { Socket& orig_socket=const_cast<Socket&>(orig); max_connections= DEFAULT_MAXCONNECTIONS; setSocketInfo(orig.getSocketInfo()); m_is_open=orig_socket.is_open(); last_error=orig_socket.last_error; m_is_loggedin=orig_socket.is_loggedin(); userId = orig_socket.get_user_id(); } Socket::Socket(SocketInfo info) { serv_addr=info.serv_addr; socketID=info.socketID; init_variables(); } Socket::~Socket() { if(m_is_open) { close(); shutdown(); m_is_open=false; } } void Socket::init_variables() { m_is_open=false; last_error=0; m_is_loggedin=false; } void Socket::login(bool p_result,std::string p_user_id) { m_is_loggedin=p_result; userId = p_user_id; } std::string Socket::get_user_id() { return userId; } const SocketInfo Socket::getSocketInfo() const { struct SocketInfo info; info.serv_addr=serv_addr; info.socketID=socketID; return info; } void Socket::setSocketInfo(const SocketInfo info) { socketID=info.socketID; serv_addr=info.serv_addr; } SocketInfo Socket::accept() { int clilen; struct sockaddr_in cli_addr; struct SocketInfo result; clilen=sizeof(cli_addr); result.socketID=-1; result.socketID=::accept(socketID, (struct sockaddr *) &cli_addr, (socklen_t*)&clilen); result.serv_addr=cli_addr; return result; } void Socket::accepted(clock_t pTime) { m_accepted_time= pTime; } bool Socket::is_open() { return m_is_open; } clock_t Socket::get_accepted_time() { return m_accepted_time; } bool Socket::bind(const int port) { bool result=true; int status; bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port); status=::bind(socketID, (struct sockaddr *) &serv_addr, sizeof(serv_addr)); if(status<0) { result=false; last_error=errno; } else { m_is_open=true; } return result; } void Socket::close() { ::close(socketID); } void Socket::shutdown() { ::shutdown(socketID,SHUT_RDWR); } bool Socket::connect(const std::string host, const int port) { struct hostent *server; int result; bzero((char *) &serv_addr, sizeof(serv_addr)); server= gethostbyname(host.c_str()); if(socketID==NULL_SOCKET) { create(); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); serv_addr.sin_addr.s_addr=*((unsigned long*)server->h_addr); result=false; if(socketID>0) { result=::connect(socketID,(const sockaddr*)&serv_addr,sizeof(serv_addr)); if(result) { m_is_open=true; } } return result; } bool Socket::create() { bool res=false; socketID = socket(AF_INET, SOCK_STREAM, 0); if(socketID>0) { res=true; } else { last_error=errno; return false; } int optval = 1 ; if (setsockopt(socketID,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(int)) == -1) { last_error=errno; return false; } return res; } bool Socket::listen() { int status; bool result=true; status=::listen(socketID,max_connections); if(status<0) result=false; return result; } bool Socket::listen(const int p_max_connections) { max_connections=p_max_connections; return listen(); } int Socket::recv(std::string& msg) const { int n; char buffer[256]; bzero(buffer,256); n = ::recv(socketID,buffer,255,MSG_DONTWAIT); if (n >= 0) { msg=buffer; } return n; } bool Socket::send(const std::string &msg) { bool res=true; int status; status=write(socketID,msg.c_str(),msg.size()); if(status==-1) { res=false; } return res; } void Socket::operator =(int p_socket_id) { socketID=p_socket_id; } bool Socket::is_loggedin() { return m_is_loggedin; } clock_t Socket::get_last_time() { return m_last_time_message; } void Socket::set_last_time(clock_t time) { m_last_time_message = time; }
16.340351
91
0.638394
pmelendez
12079ed9ec0b32ec980ceaa86058f5346b35cf35
471
cpp
C++
books/tech/cpp/std-14/s_meyers-effective_modern_cpp/code/ch_08-tweaks/item_41-consider_pass_by_value/01-copying_and_moving_parameters-01/main.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
books/techno/cpp/__intermediate/effective_modern_cpp_s_meyers/code/ch_8-TWEAKS/item_41-consider_pass_by_value/01-copying_and_moving_parameters-01/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
books/techno/cpp/__intermediate/effective_modern_cpp_s_meyers/code/ch_8-TWEAKS/item_41-consider_pass_by_value/01-copying_and_moving_parameters-01/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
#include <memory> #include <string> #include <vector> class Widget { public: void addName(const std::string& newName) { names.push_back(newName); } void addName(std::string&& newName) { names.push_back(std::move(newName)); } private: std::vector<std::string> names; }; int main() { Widget w; std::string s = "jack"; w.addName(s); w.addName(std::string("jack")); return 0; }
17.444444
50
0.549894
ordinary-developer
120af4df2daf003089cbeda6b5ccb7ca7d99aa22
18,775
cc
C++
modules/adminapi/dba/upgrade_metadata.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
null
null
null
modules/adminapi/dba/upgrade_metadata.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
1
2021-09-12T22:07:06.000Z
2021-09-12T22:07:06.000Z
modules/adminapi/dba/upgrade_metadata.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "modules/adminapi/dba/upgrade_metadata.h" #include <algorithm> #include <string> #include <vector> #include "modules/adminapi/common/accounts.h" #include "modules/adminapi/common/metadata_management_mysql.h" #include "modules/adminapi/common/router.h" #include "mysqlshdk/include/shellcore/shell_options.h" #include "mysqlshdk/include/shellcore/shell_resultset_dumper.h" #include "mysqlshdk/libs/mysql/utils.h" #include "mysqlshdk/libs/utils/array_result.h" #include "mysqlshdk/libs/utils/compiler.h" #include "mysqlshdk/libs/utils/debug.h" #include "mysqlshdk/shellcore/shell_console.h" namespace mysqlsh { namespace dba { using MDState = mysqlsh::dba::metadata::State; Upgrade_metadata::Upgrade_metadata( const std::shared_ptr<MetadataStorage> &metadata, bool interactive, bool dry_run) : m_metadata(metadata), m_target_instance(m_metadata->get_md_server()), m_interactive(interactive), m_dry_run(dry_run), m_abort_rolling_upgrade(false) {} /* * Validates the parameter and performs other validations regarding * the command execution */ void Upgrade_metadata::prepare() { // Acquire required locks on target instance. // No "write" operation allowed to be executed concurrently on the target // instance. m_target_instance->get_lock_exclusive(); std::string current_user, current_host; m_target_instance->get_current_user(&current_user, &current_host); std::string error_info; auto console = mysqlsh::current_console(); if (!validate_cluster_admin_user_privileges(*m_target_instance, current_user, current_host, &error_info)) { console->print_error(error_info); throw shcore::Exception::runtime_error( "The account " + shcore::make_account(current_user, current_host) + " is missing privileges required for this operation."); } mysqlshdk::utils::Version installed, current = mysqlsh::dba::metadata::current_version(); m_metadata->check_version(&installed); auto instance_data = m_target_instance->descr(); // If the installed version is lower than the current one, we first validate // if it is valid before continuing if (installed < current && !metadata::is_valid_version(installed)) { throw shcore::Exception::runtime_error( "Installed metadata at '" + instance_data + "' has an unknown version (" + installed.get_base() + "), upgrading this version of the metadata is not supported."); } switch (m_metadata->get_state()) { case MDState::EQUAL: console->print_note("Installed metadata at '" + instance_data + "' is up to date (version " + installed.get_base() + ")."); break; case MDState::MAJOR_HIGHER: case MDState::MINOR_HIGHER: case MDState::PATCH_HIGHER: throw std::runtime_error( "Installed metadata at '" + instance_data + "' is newer than the version version supported by " "this Shell (installed: " + installed.get_base() + ", shell: " + current.get_base() + ")."); break; case MDState::PATCH_LOWER: case MDState::MINOR_LOWER: case MDState::MAJOR_LOWER: console->print_info(shcore::str_format( "InnoDB Cluster Metadata Upgrade\n\n" "The cluster you are connected to is using an outdated metadata " "schema version %s and needs to be upgraded to %s.\n\n" "Without doing this upgrade, no AdminAPI calls except read only " "operations will be allowed.", installed.get_base().c_str(), current.get_base().c_str())); if (m_metadata->get_state() == MDState::MAJOR_LOWER) { console->print_info(); console->print_note( "After the upgrade, this InnoDB Cluster/ReplicaSet can no longer " "be managed using older versions of MySQL Shell."); } if (m_metadata->get_state() != MDState::PATCH_LOWER) prepare_rolling_upgrade(); break; case MDState::UPGRADING: throw std::runtime_error(shcore::str_subvars( mysqlsh::dba::metadata::kFailedUpgradeError, [](const std::string &var) { return shcore::get_member_name(var, shcore::current_naming_style()); }, "<<<", ">>>")); break; case MDState::FAILED_SETUP: throw std::runtime_error( "Metadata setup is not finished. Incomplete metadata schema must be" " dropped."); case MDState::FAILED_UPGRADE: // Nothing to do, prepare succeeds and lets the logic go right to // execute() break; case MDState::NONEXISTING: // NO OP: Preconditions won't allow this case to be called break; } } shcore::Array_t Upgrade_metadata::get_outdated_routers() { auto routers_dict = mysqlsh::dba::router_list(m_metadata.get(), "", true).as_map(); shcore::Array_t routers; if (!routers_dict->empty()) { routers = shcore::make_array(); auto columns = shcore::make_array(); columns->emplace_back("Instance"); columns->emplace_back("Version"); columns->emplace_back("Last Check-in"); columns->emplace_back("R/O Port"); columns->emplace_back("R/W Port"); routers->emplace_back(std::move(columns)); for (const auto &router_md : *routers_dict) { auto router = shcore::make_array(); router->emplace_back(router_md.first); auto router_data = router_md.second.as_map(); router->push_back((*router_data)["version"]); router->push_back((*router_data)["lastCheckin"]); router->push_back((*router_data)["roPort"]); router->push_back((*router_data)["rwPort"]); routers->emplace_back(std::move(router)); } } return routers; } void Upgrade_metadata::prepare_rolling_upgrade() { // The router accounts need to be upgraded first, no matter if there are // outdated routers or not, i.e. router 8.0.19 could have been used to // bootstrap under MD 1.0.1 in which case the account will be incomplete but // the router will be up to date upgrade_router_users(); auto routers = get_outdated_routers(); if (routers) { auto console = current_console(); // For patch upgrades, rolling upgrade is not considered bool done_router_upgrade = m_metadata->get_state() == MDState::PATCH_LOWER; // Doing the rolling upgrade is mandatory for a MAJOR upgrade, on a minor // upgrade the user can decide whether to do it or not bool do_rolling_upgrade = m_metadata->get_state() == MDState::MAJOR_LOWER; if (!done_router_upgrade) { console->println(shcore::str_format( "An upgrade of all cluster router instances is %s. All router " "installations should be updated first before doing the actual " "metadata upgrade.\n", do_rolling_upgrade ? "required" : "recommended")); print_router_list(routers); if (m_interactive && !m_dry_run) { if (!do_rolling_upgrade) { if (console->confirm( "Do you want to proceed with the upgrade (Yes/No)") == mysqlsh::Prompt_answer::YES) { do_rolling_upgrade = true; } else { // If user was given the option to do rolling upgrade and he chooses // not to do it, it's ok, we should continue done_router_upgrade = true; } } while (do_rolling_upgrade && routers) { size_t count = routers->size() - 1; std::string answer; console->println(shcore::str_format( "There %s %zu Router%s to upgrade. Please " "upgrade %s and select Continue once %s restarted.\n", (count == 1) ? "is" : "are", count, (count == 1) ? "" : "s", (count == 1) ? "it" : "them", (count == 1) ? "it is" : "they are")); std::vector<std::string> options = { "Re-check for outdated Routers and continue with the metadata " "upgrade.", "Unregister the remaining Routers.", "Abort the operation.", "Help"}; if (console->select( "Please select an option: ", &answer, options, 0UL, true, [&options](const std::string &a) -> std::string { if (a.size() == 1) { if (a.find_first_of("?aArCuUhH") == std::string::npos) { return "Invalid option selected"; } } else { if (std::find(options.begin(), options.end(), a) == std::end(options) && !shcore::str_caseeq(a, "abort") && !shcore::str_caseeq(a, "continue") && !shcore::str_caseeq(a, "unregister") && !shcore::str_caseeq(a, "help")) { return "Invalid option selected"; } } return ""; })) { switch (answer[0]) { case 'U': case 'u': if (console->confirm( "Unregistering a Router implies it will not " "be used in the " "Cluster, do you want to continue?") == mysqlsh::Prompt_answer::YES) { // First row is the table headers routers->erase(routers->begin()); unregister_routers(routers); } // NOTE: This fallback is required, after unregistering the // listed routers it will refresh the list if needed (implicit // retry) FALLTHROUGH; case 'R': case 'r': DBUG_EXECUTE_IF("dba_EMULATE_ROUTER_UNREGISTER", { m_target_instance->execute( "DELETE FROM mysql_innodb_cluster_metadata.routers WHERE " "router_id = 2"); }); DBUG_EXECUTE_IF("dba_EMULATE_ROUTER_UPGRADE", { m_target_instance->execute( "UPDATE mysql_innodb_cluster_metadata.routers SET " "attributes=JSON_OBJECT('version','8.0.19') WHERE " "router_id = 2"); }); routers = get_outdated_routers(); if (routers) { print_router_list(routers); } else { done_router_upgrade = true; } break; case 'A': case 'a': do_rolling_upgrade = false; m_abort_rolling_upgrade = true; break; case 'H': case 'h': case '?': console->println(shcore::str_subvars( "To perform a rolling upgrade of the InnoDB " "Cluster/ReplicaSet metadata, execute the following " "steps:\n\n" "1 - Upgrade the Shell to the latest version\n" "2 - Execute dba.<<<upgradeMetadata>>>() (the current " "step)\n" "3 - Upgrade MySQL Router instances to the latest " "version\n" "4 - Continue with the metadata upgrade once all Router " "instances are upgraded or accounted for\n", [](const std::string &var) { return shcore::get_member_name( var, shcore::current_naming_style()); }, "<<<", ">>>")); routers = get_outdated_routers(); if (routers) { console->println( "If the following Router instances no longer exist, " "select Unregister to delete their metadata."); print_router_list(routers); } break; } } else { // Ctrl+C was hit do_rolling_upgrade = false; m_abort_rolling_upgrade = true; } } } if (!done_router_upgrade) { if (m_dry_run) { size_t count = routers->size() - 1; console->println(shcore::str_format( "There %s %zu Router%s to be upgraded in order to perform the " "Metadata schema upgrade.\n", (count == 1) ? "is" : "are", count, (count == 1) ? "" : "s")); } else if (m_abort_rolling_upgrade) { console->println("The metadata upgrade has been aborted."); } else { throw shcore::Exception::runtime_error( "Outdated Routers found. Please upgrade the Routers before " "upgrading the Metadata schema"); } } } } } void Upgrade_metadata::print_router_list(const shcore::Array_t &routers) { // Prints up to 10 rows, if more than 10 routers the last wor will have // ellipsis on each column const shcore::Array_t print_list = shcore::make_array(); size_t index = 0; size_t count = routers->size(); size_t max = count > 11 ? 10 : count; while (index < max) { print_list->push_back((*routers)[index]); index++; } if (count > 11) { auto etc = shcore::make_array(); for (size_t idx = 0; idx < 5; idx++) { etc->push_back(shcore::Value("...")); } print_list->push_back(shcore::Value(etc)); } shcore::Array_as_result result(print_list); mysqlsh::Resultset_dumper dumper( &result, mysqlsh::current_shell_options()->get().wrap_json, "table", false, false); dumper.dump("", true, false); } void Upgrade_metadata::unregister_routers(const shcore::Array_t &routers) { for (const auto &router : *routers) { auto router_def = router.as_array(); m_metadata->remove_router((*router_def)[0].as_string()); } } void Upgrade_metadata::upgrade_router_users() { std::vector<std::pair<std::string, std::string>> users; auto result = m_target_instance->query( "SELECT user, host FROM mysql.user WHERE user LIKE " "'mysql_router%'"); auto row = result->fetch_one(); while (row) { users.push_back({row->get_string(0), row->get_string(1)}); row = result->fetch_one(); } size_t size = users.size(); auto console = current_console(); console->print_info( "\nThe grants for the MySQL Router accounts that were created " "automatically when bootstrapping need to be updated to match the new " "metadata version's requirements."); if (!users.empty()) { console->print_info( m_dry_run ? shcore::str_format("%zi Router account%s need to be updated.", size, (size == 1) ? "" : "s") : "Updating Router accounts..."); if (!m_dry_run) { std::vector<std::string> queries = { "GRANT SELECT, EXECUTE ON mysql_innodb_cluster_metadata.* TO ", "GRANT SELECT ON performance_schema.replication_group_members TO ", "GRANT SELECT ON performance_schema.replication_group_member_stats " "TO ", "GRANT SELECT ON performance_schema.global_variables TO ", "GRANT UPDATE, INSERT, DELETE ON " "mysql_innodb_cluster_metadata.v2_routers TO ", "GRANT UPDATE, INSERT, DELETE ON " "mysql_innodb_cluster_metadata.routers TO "}; // When migrating to version 2.0.0 this dummy view is required to enable // giving the router users the right permissions, it will be updated to // the correct view once the upgrade is done if (mysqlsh::dba::metadata::current_version() == mysqlshdk::utils::Version(2, 0, 0)) { m_target_instance->execute( "CREATE OR REPLACE VIEW mysql_innodb_cluster_metadata.v2_routers " "AS " "SELECT 1"); } log_debug("Metadata upgrade for version %s, upgraded Router accounts:", mysqlsh::dba::metadata::current_version().get_base().c_str()); for (const auto &user : users) { shcore::sqlstring user_host("!@!", 0); user_host << std::get<0>(user); user_host << std::get<1>(user); std::string str_user = user_host.str(); log_debug("- %s", str_user.c_str()); for (const auto &query : queries) { m_target_instance->execute(query + str_user); } } console->print_note(shcore::str_format( "%zi Router account%s %s been updated.", size, (size == 1) ? "" : "s", (size == 1 ? "has" : "have"))); } } else { console->print_note("No automatically created Router accounts were found."); } console->print_warning( "If MySQL Routers have been bootstrapped using custom accounts, their " "grants can not be updated during the metadata upgrade, they have to " "be updated using the <<<setupRouterAccount>>> function. \nFor " "additional information use: \\? <<<setupRouterAccount>>>\n"); } /* * Executes the API command. */ shcore::Value Upgrade_metadata::execute() { if (!m_abort_rolling_upgrade) { metadata::upgrade_or_restore_schema(m_target_instance, m_dry_run); } return shcore::Value(); } void Upgrade_metadata::rollback() {} void Upgrade_metadata::finish() { if (m_target_instance) { // Release locks at the end. m_target_instance->release_lock(); } } } // namespace dba } // namespace mysqlsh
37.47505
80
0.596218
mueller
120b366f5428ed1a54fb4067419c09d17a495ecd
535
cpp
C++
minorGems/graphics/openGL/testNavigatorGL.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
1
2020-01-16T00:07:11.000Z
2020-01-16T00:07:11.000Z
minorGems/graphics/openGL/testNavigatorGL.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
null
null
null
minorGems/graphics/openGL/testNavigatorGL.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
2
2019-09-17T12:08:20.000Z
2020-09-26T00:54:48.000Z
/* * Modification History * * 2001-August-29 Jason Rohrer * Created. */ #include "TestSceneHandlerGL.h" #include "SceneNavigatorDisplayGL.h" #include "minorGems/util/random/StdRandomSource.h" // simple test function int main() { StdRandomSource *randSource = new StdRandomSource( 2 ); TestSceneHandlerGL *handler = new TestSceneHandlerGL(); char *name = "test window"; SceneNavigatorDisplayGL *screen = new SceneNavigatorDisplayGL( 200, 200, false, name, handler ); screen->start(); return 0; }
15.735294
64
0.702804
PhilipLudington
120be8ab8a37116dd6b5bdd6e96a9695587aff54
7,011
cpp
C++
lib/inputdev/DolphinSmashAdapter.cpp
AxioDL/boo2
c49c028a38b12746ca60c0db6dd7a25d85851856
[ "MIT" ]
null
null
null
lib/inputdev/DolphinSmashAdapter.cpp
AxioDL/boo2
c49c028a38b12746ca60c0db6dd7a25d85851856
[ "MIT" ]
null
null
null
lib/inputdev/DolphinSmashAdapter.cpp
AxioDL/boo2
c49c028a38b12746ca60c0db6dd7a25d85851856
[ "MIT" ]
2
2020-05-05T04:04:34.000Z
2022-02-01T12:45:17.000Z
#include "boo2/inputdev/DolphinSmashAdapter.hpp" #include "boo2/inputdev/DeviceSignature.hpp" namespace boo2 { /* * Reference: https://github.com/ToadKing/wii-u-gc-adapter/blob/master/wii-u-gc-adapter.c */ DolphinSmashAdapter::DolphinSmashAdapter(DeviceToken* token) : TDeviceBase<IDolphinSmashAdapterCallback>(dev_typeid(DolphinSmashAdapter), token) {} DolphinSmashAdapter::~DolphinSmashAdapter() {} static constexpr EDolphinControllerType parseType(unsigned char status) { const auto type = EDolphinControllerType(status) & (EDolphinControllerType::Normal | EDolphinControllerType::Wavebird); switch (type) { case EDolphinControllerType::Normal: case EDolphinControllerType::Wavebird: return type; default: return EDolphinControllerType::None; } } static EDolphinControllerType parseState(DolphinControllerState* stateOut, const uint8_t* payload, bool& rumble) { const unsigned char status = payload[0]; const EDolphinControllerType type = parseType(status); rumble = ((status & 0x04) != 0) ? true : false; stateOut->m_btns = static_cast<uint16_t>(payload[1]) << 8 | static_cast<uint16_t>(payload[2]); stateOut->m_leftStick[0] = payload[3]; stateOut->m_leftStick[1] = payload[4]; stateOut->m_rightStick[0] = payload[5]; stateOut->m_rightStick[1] = payload[6]; stateOut->m_analogTriggers[0] = payload[7]; stateOut->m_analogTriggers[1] = payload[8]; return type; } void DolphinSmashAdapter::initialCycle() { constexpr std::array<uint8_t, 1> handshakePayload{0x13}; sendUSBInterruptTransfer(handshakePayload.data(), handshakePayload.size()); } void DolphinSmashAdapter::transferCycle() { std::array<uint8_t, 37> payload; const size_t recvSz = receiveUSBInterruptTransfer(payload.data(), payload.size()); if (recvSz != payload.size() || payload[0] != 0x21) { return; } // fmt::print("RECEIVED DATA {} {:02X}\n", recvSz, payload[0]); std::lock_guard<std::mutex> lk(m_callbackLock); if (!m_callback) { return; } /* Parse controller states */ const uint8_t* controller = &payload[1]; uint8_t rumbleMask = 0; for (uint32_t i = 0; i < 4; i++, controller += 9) { DolphinControllerState state; bool rumble = false; const EDolphinControllerType type = parseState(&state, controller, rumble); if (True(type) && (m_knownControllers & (1U << i)) == 0) { m_leftStickCal = state.m_leftStick; m_rightStickCal = state.m_rightStick; m_triggersCal = state.m_analogTriggers; m_knownControllers |= 1U << i; m_callback->controllerConnected(i, type); } else if (False(type) && (m_knownControllers & (1U << i)) != 0) { m_knownControllers &= ~(1U << i); m_callback->controllerDisconnected(i); } if ((m_knownControllers & (1U << i)) != 0) { state.m_leftStick[0] = state.m_leftStick[0] - m_leftStickCal[0]; state.m_leftStick[1] = state.m_leftStick[1] - m_leftStickCal[1]; state.m_rightStick[0] = state.m_rightStick[0] - m_rightStickCal[0]; state.m_rightStick[1] = state.m_rightStick[1] - m_rightStickCal[1]; state.m_analogTriggers[0] = state.m_analogTriggers[0] - m_triggersCal[0]; state.m_analogTriggers[1] = state.m_analogTriggers[1] - m_triggersCal[1]; m_callback->controllerUpdate(i, type, state); } rumbleMask |= rumble ? 1U << i : 0; } /* Send rumble message (if needed) */ const uint8_t rumbleReq = m_rumbleRequest & rumbleMask; if (rumbleReq != m_rumbleState) { std::array<uint8_t, 5> rumbleMessage{0x11, 0, 0, 0, 0}; for (size_t i = 0; i < 4; ++i) { if ((rumbleReq & (1U << i)) != 0) { rumbleMessage[i + 1] = 1; } else if (m_hardStop[i]) { rumbleMessage[i + 1] = 2; } else { rumbleMessage[i + 1] = 0; } } sendUSBInterruptTransfer(rumbleMessage.data(), rumbleMessage.size()); m_rumbleState = rumbleReq; } } void DolphinSmashAdapter::finalCycle() { constexpr std::array<uint8_t, 5> rumbleMessage{0x11, 0, 0, 0, 0}; sendUSBInterruptTransfer(rumbleMessage.data(), sizeof(rumbleMessage)); } void DolphinSmashAdapter::deviceDisconnected() { for (uint32_t i = 0; i < 4; i++) { if ((m_knownControllers & (1U << i)) != 0) { m_knownControllers &= ~(1U << i); std::lock_guard<std::mutex> lk(m_callbackLock); if (m_callback) { m_callback->controllerDisconnected(i); } } } } /* The following code is derived from pad.c in libogc * * Copyright (C) 2004 - 2009 * Michael Wiedenbauer (shagkur) * Dave Murphy (WinterMute) * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * 3. This notice may not be removed or altered from any source * distribution. */ constexpr std::array<int16_t, 8> pad_clampregion{ 30, 180, 15, 72, 40, 15, 59, 31, }; static void pad_clampstick(int16_t& px, int16_t& py, int16_t max, int16_t xy, int16_t min) { int x = px; int y = py; int signX; if (x > 0) { signX = 1; } else { signX = -1; x = -x; } int signY; if (y > 0) { signY = 1; } else { signY = -1; y = -y; } if (x <= min) { x = 0; } else { x -= min; } if (y <= min) { y = 0; } else { y -= min; } if (x == 0 && y == 0) { px = py = 0; return; } if (xy * y <= xy * x) { const int d = xy * x + (max - xy) * y; if (xy * max < d) { x = int16_t(xy * max * x / d); y = int16_t(xy * max * y / d); } } else { const int d = xy * y + (max - xy) * x; if (xy * max < d) { x = int16_t(xy * max * x / d); y = int16_t(xy * max * y / d); } } px = int16_t(signX * x); py = int16_t(signY * y); } static void pad_clamptrigger(int16_t& trigger) { const int16_t min = pad_clampregion[0]; const int16_t max = pad_clampregion[1]; if (min > trigger) { trigger = 0; } else { if (max < trigger) { trigger = max; } trigger -= min; } } void DolphinControllerState::clamp() { pad_clampstick(m_leftStick[0], m_leftStick[1], pad_clampregion[3], pad_clampregion[4], pad_clampregion[2]); pad_clampstick(m_rightStick[0], m_rightStick[1], pad_clampregion[6], pad_clampregion[7], pad_clampregion[5]); pad_clamptrigger(m_analogTriggers[0]); pad_clamptrigger(m_analogTriggers[1]); } } // namespace boo2
29.834043
114
0.652831
AxioDL
120c9a15d1170b44e6762a65e790124e76ae44dd
6,062
cpp
C++
ELV_wrapper/elf.cpp
solhuebner/ID-18-Elventure
90419d7dfbc852b3512a06a43843aeb899465256
[ "MIT" ]
1
2020-09-05T20:13:25.000Z
2020-09-05T20:13:25.000Z
ELV_wrapper/elf.cpp
solhuebner/ID-18-Elventure
90419d7dfbc852b3512a06a43843aeb899465256
[ "MIT" ]
null
null
null
ELV_wrapper/elf.cpp
solhuebner/ID-18-Elventure
90419d7dfbc852b3512a06a43843aeb899465256
[ "MIT" ]
1
2020-06-13T13:39:09.000Z
2020-06-13T13:39:09.000Z
#include <avr/pgmspace.h> #include <string.h> #include "ArduboyGamby.h" #include "elf.h" #include "elf_bitmap.h" #include "map_bitmap.h" #include "map.h" #include "room.h" #include "item.h" #include "display.h" #include "sound.h" extern GambyGraphicsMode gamby; #define SIZEOF_ELF_RECORD 10 Elf elf = {FACING_DOWN, 1, 36, 24, 3, {0,0,0,0}, ELFSTATE_PLAYING}; void resetElf(bool reset_items) { elf.facing = FACING_DOWN; elf.step = 1; elf.x = 36; elf.y = 24; elf.hearts = 3; elf.state = ELFSTATE_PLAYING; if (reset_items) memset(elf.items, 0, sizeof(elf.items)); } void showElf() { moveElf(elf.facing); } void moveElf(unsigned char facing) { //erase the old elf image (using blank map tile) gamby.drawSprite(elf.x, elf.y, map_bitmap); gamby.drawSprite(elf.x, elf.y + 8, map_bitmap); //if it is a new facing, then reset the step if (facing != elf.facing) { elf.step = 1; } else { elf.step++; if (elf.step > 2) elf.step = 1; } elf.facing = facing; switch (facing) { case FACING_DOWN: if (elf.y < 48) { if (checkMapRoomMove(elf.x, elf.y + 16) == 0) if (checkMapRoomMove(elf.x+4, elf.y + 16) == 0) elf.y += STEP_LENGTH; } else { scrollMap(SCROLL_DOWN); // elf.x = 40; elf.y = 0; elf.facing = FACING_DOWN; } break; case FACING_UP: if (elf.y > 4) { if (checkMapRoomMove(elf.x, elf.y - 4) == 0) if (checkMapRoomMove(elf.x + 4, elf.y - 4) == 0) elf.y -= STEP_LENGTH; } else { scrollMap(SCROLL_UP); // elf.x = 40; elf.y = 48; elf.facing = FACING_UP; } break; case FACING_LEFT: if (elf.x > 4) { if (checkMapRoomMove(elf.x - 8, elf.y) == 0) if (checkMapRoomMove(elf.x - 8, elf.y+8) == 0) if (checkMapRoomMove(elf.x - 8, elf.y + 12) == 0) elf.x -= STEP_LENGTH; } else { scrollMap(SCROLL_LEFT); elf.x = 88; // elf.y = 24; elf.facing = FACING_LEFT; } break; case FACING_RIGHT: if (elf.x < 84) { if (checkMapRoomMove(elf.x + 8, elf.y) == 0) if(checkMapRoomMove(elf.x + 8, elf.y+8) == 0) if (checkMapRoomMove(elf.x + 8, elf.y + 12) == 0) elf.x += STEP_LENGTH; } else { scrollMap(SCROLL_RIGHT); elf.x = 0; // elf.y = 24; elf.facing = FACING_RIGHT; } break; } //draw new elf bitmap gamby.drawSprite(elf.x, elf.y, elf_bitmap, elf.facing ); gamby.drawSprite(elf.x, elf.y+8, elf_bitmap, elf.facing + elf.step); } void throwSword() { //retrieve the sword room element RoomElement element = getRoomElement(0); //if it is already active, do nothing, otherwise //initiate the sword being thrown if (element.state == STATE_HIDDEN) { switch (elf.facing) { case FACING_DOWN: element.state = STATE_MOVE_DOWN; element.x = elf.x; // +16, don't want to hit out feet element.y = elf.y + 16; break; case FACING_UP: element.state = STATE_MOVE_UP; element.x = elf.x; element.y = elf.y - 8; break; case FACING_LEFT: element.state = STATE_MOVE_LEFT; element.x = elf.x - 8; element.y = elf.y; break; case FACING_RIGHT: element.state = STATE_MOVE_RIGHT; element.x = elf.x + 8; element.y = elf.y; break; } if (checkMapRoomMove(element.x, element.y)==0) { updateRoomElement(element); } } } RoomElement hitElf(RoomElement element) { //hit by a monster if (element.type < 50) { //check the counter, so hearts are not //removed unless the monster has not been 'hit' //already if (element.counter == 0) { element.counter = COUNTER_START; elf.hearts--; if (elf.hearts < 1) { //game over elf.state = ELFSTATE_DEAD; } } //when the elf and a monster 'bump,' move the monster //in the opposite direction switch (element.state) { case STATE_MOVE_UP: element.state = STATE_MOVE_DOWN; break; case STATE_MOVE_DOWN: element.state = STATE_MOVE_UP; break; case STATE_MOVE_LEFT: element.state = STATE_MOVE_RIGHT; break; case STATE_MOVE_RIGHT: element.state = STATE_MOVE_LEFT; break; } } else { switch (element.type) { case ITEM_HEART: if (elf.hearts < MAX_HEARTS) elf.hearts++; //handle the rest of the item hit element = hitItem(element); play_sfx(5); break; case ITEM_CRYSTAL: case ITEM_ORB: case ITEM_ARMOR: case ITEM_STAFF: addElfItem(element.type); //handle the rest of the item hit element = hitItem(element); break; case ITEM_PORTAL: //handle the rest of the item hit element = hitItem(element); if (getMapCurrentRoom() > 63) { //go to the bottom half of the map (underworld) setMapRoom(0); play_song(0); } else { //back to top half of the map (overworld) setMapRoom(64); play_song(1); } elf.x = 36; elf.y = 24; elf.facing = FACING_DOWN; showElf(); break; } } return element; } Elf getElf() { return elf; } //adds the item in the elf's inventory void addElfItem(char type) { char count = 0; for (char i=0; i< MAX_ITEMS; i++) { if (elf.items[i] == 0) { elf.items[i] = type; break; } else { count++; } } if (count == MAX_ITEMS) { //won game elf.state = ELFSTATE_WON; } else { //otherwise, play the sound effect play_sfx(6); } } //check the elf's inventory for a specific item bool elfHasItem(char type) { for (char i=0; i< MAX_ITEMS; i++) { if ((elf.items[i] > 50) && (elf.items[i] == type)) return true; } return false; } //check the elf's current state char getElfState() { return elf.state; }
21.195804
89
0.5645
solhuebner
120efb8217919a11260f48ea71db2767e661803e
1,323
hpp
C++
lab2/13_documentpermissions/application.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
2
2015-10-08T15:07:07.000Z
2017-09-17T10:08:36.000Z
lab2/13_documentpermissions/application.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
lab2/13_documentpermissions/application.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
// (C) 2013-2014, Sergei Zaychenko, KNURE, Kharkiv, Ukraine #ifndef _APPLICATION_HPP_ #define _APPLICATION_HPP_ /*****************************************************************************/ class Document; class User; /*****************************************************************************/ class Application { /*-----------------------------------------------------------------*/ public: /*-----------------------------------------------------------------*/ Application (); ~ Application (); void generateTestModel (); void printUserPermissionsReport () const; void printDocumentsNotHavingPermittedUsers () const; void printUsersNotHavingPermittedDocuments () const; void printDocumentsHavingMultipleWriteUsers () const; /*-----------------------------------------------------------------*/ private: /*-----------------------------------------------------------------*/ Application ( const Application & ); Application & operator = ( const Application & ); /*-----------------------------------------------------------------*/ // TODO ... declare the top of the object model hierarchy here ... /*-----------------------------------------------------------------*/ }; /*****************************************************************************/ #endif // _APPLICATION_HPP_
22.810345
79
0.368103
zaychenko-sergei
1210d99a23384b0d94d7d60e0274abd5d0ce428f
554
cpp
C++
Source/FactoryGame/Buildables/FGBuildableStorage.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/Buildables/FGBuildableStorage.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/Buildables/FGBuildableStorage.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
// This file has been automatically generated by the Unreal Header Implementation tool #include "FGBuildableStorage.h" void AFGBuildableStorage::GetLifetimeReplicatedProps( TArray< FLifetimeProperty >& OutLifetimeProps) const{ } AFGBuildableStorage::AFGBuildableStorage(){ } void AFGBuildableStorage::BeginPlay(){ } void AFGBuildableStorage::GetDismantleRefund_Implementation( TArray< FInventoryStack >& out_refund) const{ } void AFGBuildableStorage::Factory_CollectInput_Implementation(){ } void AFGBuildableStorage::OnRep_ReplicationDetailActor(){ }
50.363636
109
0.833935
iam-Legend
1213695b88aeaa91464de5a855a802bb62ce1a17
16,234
cc
C++
base/threading/hang_watcher.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/threading/hang_watcher.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/threading/hang_watcher.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/threading/hang_watcher.h" #include <algorithm> #include <atomic> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/debug/crash_logging.h" #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/no_destructor.h" #include "base/strings/string_number_conversions.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_checker.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "build/build_config.h" namespace base { // static const base::Feature HangWatcher::kEnableHangWatcher{ "EnableHangWatcher", base::FEATURE_DISABLED_BY_DEFAULT}; const base::TimeDelta HangWatchScope::kDefaultHangWatchTime = base::TimeDelta::FromSeconds(10); namespace { HangWatcher* g_instance = nullptr; } constexpr const char* kThreadName = "HangWatcher"; // The time that the HangWatcher thread will sleep for between calls to // Monitor(). Increasing or decreasing this does not modify the type of hangs // that can be detected. It instead increases the probability that a call to // Monitor() will happen at the right time to catch a hang. This has to be // balanced with power/cpu use concerns as busy looping would catch amost all // hangs but present unacceptable overhead. const base::TimeDelta kMonitoringPeriod = base::TimeDelta::FromSeconds(10); HangWatchScope::HangWatchScope(TimeDelta timeout) { internal::HangWatchState* current_hang_watch_state = internal::HangWatchState::GetHangWatchStateForCurrentThread()->Get(); DCHECK(timeout >= base::TimeDelta()) << "Negative timeouts are invalid."; // TODO(crbug.com/1034046): Remove when all threads using HangWatchScope are // monitored. Thread is not monitored, noop. if (!current_hang_watch_state) { return; } DCHECK(current_hang_watch_state) << "A scope can only be used on a thread that " "registered for hang watching with HangWatcher::RegisterThread."; #if DCHECK_IS_ON() previous_scope_ = current_hang_watch_state->GetCurrentHangWatchScope(); current_hang_watch_state->SetCurrentHangWatchScope(this); #endif // TODO(crbug.com/1034046): Check whether we are over deadline already for the // previous scope here by issuing only one TimeTicks::Now() and resuing the // value. previous_deadline_ = current_hang_watch_state->GetDeadline(); TimeTicks deadline = TimeTicks::Now() + timeout; current_hang_watch_state->SetDeadline(deadline); } HangWatchScope::~HangWatchScope() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); internal::HangWatchState* current_hang_watch_state = internal::HangWatchState::GetHangWatchStateForCurrentThread()->Get(); // TODO(crbug.com/1034046): Remove when all threads using HangWatchScope are // monitored. Thread is not monitored, noop. if (!current_hang_watch_state) { return; } // If a hang is currently being captured we should block here so execution // stops and the relevant stack frames are recorded. base::HangWatcher::GetInstance()->BlockIfCaptureInProgress(); #if DCHECK_IS_ON() // Verify that no Scope was destructed out of order. DCHECK_EQ(this, current_hang_watch_state->GetCurrentHangWatchScope()); current_hang_watch_state->SetCurrentHangWatchScope(previous_scope_); #endif // Reset the deadline to the value it had before entering this scope. current_hang_watch_state->SetDeadline(previous_deadline_); // TODO(crbug.com/1034046): Log when a HangWatchScope exits after its deadline // and that went undetected by the HangWatcher. } HangWatcher::HangWatcher(RepeatingClosure on_hang_closure) : monitor_period_(kMonitoringPeriod), should_monitor_(WaitableEvent::ResetPolicy::AUTOMATIC), on_hang_closure_(std::move(on_hang_closure)), thread_(this, kThreadName) { // |thread_checker_| should not be bound to the constructing thread. DETACH_FROM_THREAD(thread_checker_); should_monitor_.declare_only_used_while_idle(); DCHECK(!g_instance); g_instance = this; Start(); } HangWatcher::~HangWatcher() { DCHECK_EQ(g_instance, this); DCHECK(watch_states_.empty()); g_instance = nullptr; Stop(); } void HangWatcher::Start() { thread_.Start(); } void HangWatcher::Stop() { keep_monitoring_.store(false, std::memory_order_relaxed); should_monitor_.Signal(); thread_.Join(); } bool HangWatcher::IsWatchListEmpty() { AutoLock auto_lock(watch_state_lock_); return watch_states_.empty(); } void HangWatcher::Run() { // Monitor() should only run on |thread_|. Bind |thread_checker_| here to make // sure of that. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); while (keep_monitoring_.load(std::memory_order_relaxed)) { // If there is nothing to watch sleep until there is. if (IsWatchListEmpty()) { should_monitor_.Wait(); } else { Monitor(); if (after_monitor_closure_for_testing_) { after_monitor_closure_for_testing_.Run(); } } if (keep_monitoring_.load(std::memory_order_relaxed)) { // Sleep until next scheduled monitoring. should_monitor_.TimedWait(monitor_period_); } } } // static HangWatcher* HangWatcher::GetInstance() { return g_instance; } // static void HangWatcher::RecordHang() { base::debug::DumpWithoutCrashing(); // Defining |inhibit_tail_call_optimization| *after* calling // DumpWithoutCrashing() prevents tail call optimization from omitting this // function's address on the stack. volatile int inhibit_tail_call_optimization = __LINE__; ALLOW_UNUSED_LOCAL(inhibit_tail_call_optimization); } ScopedClosureRunner HangWatcher::RegisterThread() { AutoLock auto_lock(watch_state_lock_); watch_states_.push_back( internal::HangWatchState::CreateHangWatchStateForCurrentThread()); // Now that there is a thread to monitor we wake the HangWatcher thread. if (watch_states_.size() == 1) { should_monitor_.Signal(); } return ScopedClosureRunner(BindOnce(&HangWatcher::UnregisterThread, Unretained(HangWatcher::GetInstance()))); } base::TimeTicks HangWatcher::WatchStateSnapShot::GetHighestDeadline() const { DCHECK(!hung_watch_state_copies_.empty()); // Since entries are sorted in increasing order the last entry is the largest // one. return hung_watch_state_copies_.back().deadline; } HangWatcher::WatchStateSnapShot::WatchStateSnapShot( const HangWatchStates& watch_states, base::TimeTicks snapshot_time, base::TimeTicks previous_latest_expired_deadline) : snapshot_time_(snapshot_time) { // Initial copy of the values. for (const auto& watch_state : watch_states) { base::TimeTicks deadline = watch_state.get()->GetDeadline(); // Some hangs that were already recorded are still live, snapshot is // not actionable. if (deadline <= previous_latest_expired_deadline) { hung_watch_state_copies_.clear(); return; } // Only copy hung threads. if (deadline <= snapshot_time) { hung_watch_state_copies_.push_back( WatchStateCopy{deadline, watch_state.get()->GetThreadID()}); } } // Sort |hung_watch_state_copies_| by order of decreasing hang severity so the // most severe hang is first in the list. std::sort(hung_watch_state_copies_.begin(), hung_watch_state_copies_.end(), [](const WatchStateCopy& lhs, const WatchStateCopy& rhs) { return lhs.deadline < rhs.deadline; }); } HangWatcher::WatchStateSnapShot::WatchStateSnapShot( const WatchStateSnapShot& other) = default; HangWatcher::WatchStateSnapShot::~WatchStateSnapShot() = default; std::string HangWatcher::WatchStateSnapShot::PrepareHungThreadListCrashKey() const { // Build a crash key string that contains the ids of the hung threads. constexpr char kSeparator{'|'}; std::string list_of_hung_thread_ids; // Add as many thread ids to the crash key as possible. for (const WatchStateCopy& copy : hung_watch_state_copies_) { std::string fragment = base::NumberToString(copy.thread_id) + kSeparator; if (list_of_hung_thread_ids.size() + fragment.size() < static_cast<std::size_t>(debug::CrashKeySize::Size256)) { list_of_hung_thread_ids += fragment; } else { // Respect the by priority ordering of thread ids in the crash key by // stopping the construction as soon as one does not fit. This avoids // including lesser priority ids while omitting more important ones. break; } } return list_of_hung_thread_ids; } HangWatcher::WatchStateSnapShot HangWatcher::GrabWatchStateSnapshotForTesting() const { WatchStateSnapShot snapshot(watch_states_, base::TimeTicks::Now(), latest_expired_deadline_); return snapshot; } void HangWatcher::Monitor() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); AutoLock auto_lock(watch_state_lock_); // If all threads unregistered since this function was invoked there's // nothing to do anymore. if (watch_states_.empty()) return; const base::TimeTicks now = base::TimeTicks::Now(); // See if any thread hung. We're holding |watch_state_lock_| so threads // can't register or unregister but their deadline still can change // atomically. This is fine. Detecting a hang is generally best effort and // if a thread resumes from hang in the time it takes to move on to // capturing then its ID will be absent from the crash keys. bool any_thread_hung = std::any_of( watch_states_.cbegin(), watch_states_.cend(), [this, now](const std::unique_ptr<internal::HangWatchState>& state) { base::TimeTicks deadline = state->GetDeadline(); return deadline > latest_expired_deadline_ && deadline < now; }); // If at least a thread is hung we need to capture. if (any_thread_hung) CaptureHang(now); } void HangWatcher::CaptureHang(base::TimeTicks capture_time) { capture_in_progress.store(true, std::memory_order_relaxed); base::AutoLock scope_lock(capture_lock_); WatchStateSnapShot watch_state_snapshot(watch_states_, capture_time, latest_expired_deadline_); // The hung thread(s) could detected at the start of Monitor() could have // moved on from their scopes. If that happened and there are no more hung // threads then abort capture. std::string list_of_hung_thread_ids = watch_state_snapshot.PrepareHungThreadListCrashKey(); if (list_of_hung_thread_ids.empty()) return; #if not defined(OS_NACL) static debug::CrashKeyString* crash_key = AllocateCrashKeyString( "list-of-hung-threads", debug::CrashKeySize::Size256); debug::ScopedCrashKeyString list_of_hung_threads_crash_key_string( crash_key, list_of_hung_thread_ids); #endif // To avoid capturing more than one hang that blames a subset of the same // threads it's necessary to keep track of what is the furthest deadline // that contributed to declaring a hang. Only once // all threads have deadlines past this point can we be sure that a newly // discovered hang is not directly related. // Example: // ********************************************************************** // Timeline A : L------1-------2----------3-------4----------N----------- // Timeline B : -------2----------3-------4----------L----5------N------- // Timeline C : L----------------------------5------6----7---8------9---N // ********************************************************************** // In the example when a Monitor() happens during timeline A // |latest_expired_deadline_| (L) is at time zero and deadlines (1-4) // are before Now() (N) . A hang is captured and L is updated. During // the next Monitor() (timeline B) a new deadline is over but we can't // capture a hang because deadlines 2-4 are still live and already counted // toward a hang. During a third monitor (timeline C) all live deadlines // are now after L and a second hang can be recorded. base::TimeTicks latest_expired_deadline = watch_state_snapshot.GetHighestDeadline(); on_hang_closure_.Run(); // Update after running the actual capture. latest_expired_deadline_ = latest_expired_deadline; capture_in_progress.store(false, std::memory_order_relaxed); } void HangWatcher::SetAfterMonitorClosureForTesting( base::RepeatingClosure closure) { after_monitor_closure_for_testing_ = std::move(closure); } void HangWatcher::SetMonitoringPeriodForTesting(base::TimeDelta period) { monitor_period_ = period; } void HangWatcher::SignalMonitorEventForTesting() { should_monitor_.Signal(); } void HangWatcher::BlockIfCaptureInProgress() { // Makes a best-effort attempt to block execution if a hang is currently being // captured.Only block on |capture_lock| if |capture_in_progress| hints that // it's already held to avoid serializing all threads on this function when no // hang capture is in-progress. if (capture_in_progress.load(std::memory_order_relaxed)) { base::AutoLock hang_lock(capture_lock_); } } void HangWatcher::UnregisterThread() { AutoLock auto_lock(watch_state_lock_); internal::HangWatchState* current_hang_watch_state = internal::HangWatchState::GetHangWatchStateForCurrentThread()->Get(); auto it = std::find_if(watch_states_.cbegin(), watch_states_.cend(), [current_hang_watch_state]( const std::unique_ptr<internal::HangWatchState>& state) { return state.get() == current_hang_watch_state; }); // Thread should be registered to get unregistered. DCHECK(it != watch_states_.end()); watch_states_.erase(it); } namespace internal { // |deadline_| starts at Max() to avoid validation problems // when setting the first legitimate value. HangWatchState::HangWatchState() : thread_id_(PlatformThread::CurrentId()) { // There should not exist a state object for this thread already. DCHECK(!GetHangWatchStateForCurrentThread()->Get()); // Bind the new instance to this thread. GetHangWatchStateForCurrentThread()->Set(this); } HangWatchState::~HangWatchState() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_EQ(GetHangWatchStateForCurrentThread()->Get(), this); GetHangWatchStateForCurrentThread()->Set(nullptr); #if DCHECK_IS_ON() // Destroying the HangWatchState should not be done if there are live // HangWatchScopes. DCHECK(!current_hang_watch_scope_); #endif } // static std::unique_ptr<HangWatchState> HangWatchState::CreateHangWatchStateForCurrentThread() { // Allocate a watch state object for this thread. std::unique_ptr<HangWatchState> hang_state = std::make_unique<HangWatchState>(); // Setting the thread local worked. DCHECK_EQ(GetHangWatchStateForCurrentThread()->Get(), hang_state.get()); // Transfer ownership to caller. return hang_state; } TimeTicks HangWatchState::GetDeadline() const { return deadline_.load(std::memory_order_relaxed); } void HangWatchState::SetDeadline(TimeTicks deadline) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); deadline_.store(deadline, std::memory_order_relaxed); } bool HangWatchState::IsOverDeadline() const { return TimeTicks::Now() > deadline_.load(std::memory_order_relaxed); } #if DCHECK_IS_ON() void HangWatchState::SetCurrentHangWatchScope(HangWatchScope* scope) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); current_hang_watch_scope_ = scope; } HangWatchScope* HangWatchState::GetCurrentHangWatchScope() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return current_hang_watch_scope_; } #endif // static ThreadLocalPointer<HangWatchState>* HangWatchState::GetHangWatchStateForCurrentThread() { static NoDestructor<ThreadLocalPointer<HangWatchState>> hang_watch_state; return hang_watch_state.get(); } PlatformThreadId HangWatchState::GetThreadID() const { return thread_id_; } } // namespace internal } // namespace base
34.394068
80
0.729272
sarang-apps
12218e1b49e132f99abf151cfeba03616ebf1392
1,752
hpp
C++
ext/src/javax/swing/JComponent_ActionStandin.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/javax/swing/JComponent_ActionStandin.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/javax/swing/JComponent_ActionStandin.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <java/awt/event/fwd-POI.hpp> #include <java/beans/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <javax/swing/fwd-POI.hpp> #include <java/lang/Object.hpp> #include <javax/swing/Action.hpp> struct default_init_tag; class javax::swing::JComponent_ActionStandin final : public virtual ::java::lang::Object , public Action { public: typedef ::java::lang::Object super; private: Action* action { }; ::java::awt::event::ActionListener* actionListener { }; ::java::lang::String* command { }; public: /* package */ JComponent* this$0 { }; protected: void ctor(::java::awt::event::ActionListener* actionListener, ::java::lang::String* command); public: void actionPerformed(::java::awt::event::ActionEvent* ae) override; void addPropertyChangeListener(::java::beans::PropertyChangeListener* listener) override; ::java::lang::Object* getValue(::java::lang::String* key) override; bool isEnabled() override; void putValue(::java::lang::String* key, ::java::lang::Object* value) override; void removePropertyChangeListener(::java::beans::PropertyChangeListener* listener) override; void setEnabled(bool b) override; // Generated public: /* package */ JComponent_ActionStandin(JComponent *JComponent_this, ::java::awt::event::ActionListener* actionListener, ::java::lang::String* command); protected: JComponent_ActionStandin(JComponent *JComponent_this, const ::default_init_tag&); public: static ::java::lang::Class *class_(); JComponent *JComponent_this; private: virtual ::java::lang::Class* getClass0(); };
30.206897
141
0.712329
pebble2015
1222bf42564258b8741d3a4e1ee4d04f8f9386e6
119
hpp
C++
src/TSBlank.hpp
miRackModular/trowaSoft-VCV
56ab2f95bcd0f788b3eb8714718c972cbb0546d9
[ "MIT" ]
91
2017-11-28T07:23:09.000Z
2022-03-28T08:31:51.000Z
src/TSBlank.hpp
miRackModular/trowaSoft-VCV
56ab2f95bcd0f788b3eb8714718c972cbb0546d9
[ "MIT" ]
59
2017-11-28T06:12:18.000Z
2022-03-18T09:00:59.000Z
src/TSBlank.hpp
miRackModular/trowaSoft-VCV
56ab2f95bcd0f788b3eb8714718c972cbb0546d9
[ "MIT" ]
15
2017-11-28T13:42:35.000Z
2021-12-26T08:03:37.000Z
#ifndef TSBLANK_HPP #define TSBLANK_HPP extern Model* modelBlank; struct TSBlankWidget; struct TSBlankModule; #endif
13.222222
25
0.823529
miRackModular
1225053037da458c0c3fde05f804d5b938bc682a
6,672
cc
C++
src/cxx/diclearn/libdiclearn/C_DENOISE_IMAGE.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
src/cxx/diclearn/libdiclearn/C_DENOISE_IMAGE.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
src/cxx/diclearn/libdiclearn/C_DENOISE_IMAGE.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
#include "C_DL1D.h" #include <vector> #include <MatrixOper.h> #include "IM_IO.h" #include "C_OMP.h" #include "C_DENOISE_IMAGE.h" using namespace std; #include <math.h> C_DENOISE_IMAGE::C_DENOISE_IMAGE(dblarray &NoisyImage,dblarray &Dico) { Npix = Dico.nx(); // atom size } C_DENOISE_IMAGE::~C_DENOISE_IMAGE() { } intarray C_DENOISE_IMAGE::compute_full_image_size(dblarray &Image, int &OverlapNumber) { dblarray full_image; // image extended using symmetric boundary conditions double patch_size = sqrt(Npix); // patch size, square root of atom size int delta = patch_size - 1; // size of the band to around Image to build full_image intarray full_image_dim(2); full_image.alloc(Image.nx() + 2*delta, Image.ny() + 2*delta); full_image_dim(0) = full_image.nx(); full_image_dim(1) = full_image.ny(); return full_image_dim; } dblarray C_DENOISE_IMAGE::extract_patches(dblarray &Image,int &OverlapNumber) { dblarray stacked_patches; // patches stacked as columns dblarray full_image; // image extended using symmetric boundary conditions double patch_size = sqrt(Npix); // patch size, square root of atom size int delta = patch_size - 1; // size of the band to around Image to build full_image int stackInd,patchInd; // indices used when stacking patches int Npatch = 0; // Number of patches extracted if (ceilf(patch_size) != patch_size) cout << "Error : atom size is not a square" << endl; else { // building full_image using symmetric boundary conditions full_image.alloc(Image.nx() + 2*delta, Image.ny() + 2*delta); // filling the center of full_image with the pixels of Image for (int i=0;i<Image.nx();i++) for (int j=0;j<Image.ny();j++) full_image(i+delta,j+delta) = Image(i,j); // filling top left corner for (int i=0;i<delta;i++) for (int j=0;j<delta;j++) full_image(i,j) = Image(delta-i-1,delta-j-1); // filling top right corner. BEWARE, start at the top right pixel of full_image for (int i=0;i<delta;i++) for (int j=0;j<delta;j++) full_image(i,2*delta+Image.ny()-j-1) = Image(delta-i-1,Image.ny()-delta+j); // filling bottom left corner. Once again, start at the bottom left pixel for (int i=0;i<delta;i++) for (int j=0;j<delta;j++) full_image(Image.nx()+2*delta-i-1,j) = Image(Image.nx()-delta+i,delta-j-1); // filling bottom right corner. Once again, start at the bottom right pixel for (int i=0;i<delta;i++) for (int j=0;j<delta;j++) full_image(Image.nx()+2*delta-i-1,Image.ny()+2*delta-j-1) = Image(Image.nx()-delta+i,Image.ny()-delta+j); // filling top side for (int i=0;i<delta;i++) for (int j=0;j<Image.ny();j++) full_image(i,delta+j) = Image(delta -i -1,j); // filling bottom side for (int i=0;i<delta;i++) for (int j=0;j<Image.ny();j++) full_image(Image.nx()+2*delta-i-1,delta+j) = Image(Image.nx()-delta+i,j); // filling left side for (int i=0;i<Image.nx();i++) for (int j=0;j<delta;j++) full_image(delta+i,j) = Image(i,delta-j-1); // filling bottom side for (int i=0;i<Image.nx();i++) for (int j=0;j<delta;j++) full_image(delta+i,Image.ny()+2*delta-j-1) = Image(i,Image.ny()-delta+j); // Computing number of patches to be extracted for (int i=0;i<full_image.nx()-delta;i+=OverlapNumber) for (int j=0;j<full_image.ny()-delta;j+=OverlapNumber) Npatch++; // Reading patches, where (i,j) is used as the top left pixel of each patch stacked_patches.alloc(patch_size*patch_size,Npatch); patchInd = 0; for (int i=0;i<full_image.nx()-delta;i+=OverlapNumber) { for (int j=0;j<full_image.ny()-delta;j+=OverlapNumber) { // stacking patch (i,j) stackInd = 0; for (int q=0;q<patch_size;q++) for (int p=0;p<patch_size;p++) { stacked_patches(stackInd,patchInd) = full_image(i+p,j+q); stackInd++; } patchInd++; } } } return stacked_patches; } dblarray C_DENOISE_IMAGE::denoise_image(dblarray &stacked_patches, dblarray &Dico, int OverlapNumber,int SparsityTarget,double ErrorTarget,intarray full_image_size,bool Verb) { dblarray X; // sparse coding coefficients matrix dblarray weights; // weights use to average patches. The weight of a pixel in the image is the number of patches where it is present. dblarray denoised_patches(stacked_patches.nx(),stacked_patches.ny()); int Npatch = stacked_patches.ny(); // number of stacked patches dblarray patch_mean(Npatch); // mean of all patches dblarray temp_patch(Npix); // temporary patch, used for mean removal int patch_size = sqrt(Npix); // length of each patch int patchInd, stackInd; // indices used for reading stacked patches int delta = patch_size - 1; // size of the band to around Image to build full_image int nx = full_image_size(0); int ny = full_image_size(1); dblarray full_denoised_image(nx,ny); dblarray denoised_image(nx - 2*delta,ny - 2*delta); //dblarray Image_out // Builder coder object C_OMP coder(Dico); // Removing mean from each patch for (int i=0;i<Npatch;i++) { // loading current patch for (int j=0;j<Npix;j++) temp_patch(j) = stacked_patches(j,i); patch_mean(i) = temp_patch.mean(); // Removing mean for (int j=0;j<Npix;j++) stacked_patches(j,i) = stacked_patches(j,i) - patch_mean(i); } // Sparse coding stacked patches in the dictionary // X.alloc(Dico.ny(),Npatch); X = coder.omp(stacked_patches,SparsityTarget,ErrorTarget,Verb); // Denoising stacked patches by computing DX for (int p=0;p<Npix;p++) for (int q=0;q<Npatch;q++) { denoised_patches(p,q) = 0; for (int k=0;k<Dico.ny();k++) denoised_patches(p,q) += Dico(p,k)*X(k,q); } // Initializing weights to 0 weights.alloc(nx,ny); for (int i=0;i<nx;i++) for (int j=0;j<ny;j++) weights(i,j) = 0; // Averaging patches back together to build an image patchInd = 0; // Initializing denoised image with 0 for (int i=0;i<nx;i++) for (int j=0;j<ny;j++) full_denoised_image(i,j) = 0; for (int i=0;i<nx-delta;i+=OverlapNumber) { for (int j=0;j<ny-delta;j+=OverlapNumber) { // Reading patch (i,j) stackInd = 0; for (int q=0;q<patch_size;q++) for (int p=0;p<patch_size;p++) { // full_denoised_image(i+p,j+q) += denoised_patches(stackInd,patchInd); full_denoised_image(i+p,j+q) += denoised_patches(stackInd,patchInd) + patch_mean(patchInd); weights(i+p,j+q) = weights(i+p,j+q) + 1; stackInd++; } patchInd++; } } // Extracting the center of full_image to remove the symetric boundaries condition pixels for (int i=0;i<denoised_image.nx();i++) for (int j=0;j<denoised_image.nx();j++) denoised_image(i,j) = full_denoised_image(delta+i,delta+j)/weights(delta+i,delta+j); return denoised_image; }
33.029703
174
0.680905
sfarrens
12282f70ba99bdfd96964f5135a3aef17678e1d3
1,015
cpp
C++
Heap/2/Phase3Main.cpp
PeterTheAmazingAsian/ProjectTestCases
85ddd13216d65267cbf0ea76ea014af902f3d9da
[ "MIT" ]
1
2021-08-20T03:01:16.000Z
2021-08-20T03:01:16.000Z
Heap/2/Phase3Main.cpp
PeterTheAmazingAsian/ProjectTestCases
85ddd13216d65267cbf0ea76ea014af902f3d9da
[ "MIT" ]
null
null
null
Heap/2/Phase3Main.cpp
PeterTheAmazingAsian/ProjectTestCases
85ddd13216d65267cbf0ea76ea014af902f3d9da
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #include "Heap.cpp" int main() { Heap<short int> A; Heap<double> B; Heap<unsigned long long int> C; Heap<long double> D; Heap<string> E; A.insert(4); A.insert(9); A.insert(3); A.insert(5); A.insert(100); A.printKey(); Heap<short int> AA(A); Heap<short int> AAA(AA); AA.printKey(); AAA.printKey(); AAA.extractMin(); AA.extractMin(); AA.extractMin(); AAA.printKey(); AA.printKey(); A.printKey(); string alphabet[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; Heap<string> F(alphabet, 26); F.printKey(); Heap<string> FF = F; Heap<string> FFF = FF; FF.printKey(); FFF.printKey(); FFF.extractMin(); FF.extractMin(); FF.extractMin(); FFF.printKey(); FF.printKey(); F.printKey(); return 0; }
19.150943
69
0.483744
PeterTheAmazingAsian
1228306b07197609b134f9c0c3cd7bc9b598adba
13,063
cpp
C++
call_stats5.cpp
juan2357/call_stats5
0eb23f66ab5f4e8c60f16072ba784f9e03ee6589
[ "MIT" ]
null
null
null
call_stats5.cpp
juan2357/call_stats5
0eb23f66ab5f4e8c60f16072ba784f9e03ee6589
[ "MIT" ]
null
null
null
call_stats5.cpp
juan2357/call_stats5
0eb23f66ab5f4e8c60f16072ba784f9e03ee6589
[ "MIT" ]
null
null
null
/* Name: Juan Perez Z#:23026404 Course: COP 3014 Professor: Dr. Lofton Bullard Due Date: 3/20/18 Due Time: 11:59 Total Points: 20 Assignment 8: call_stats5.cpp Description 1. Read the contents of a data file one record at a time in a dynamic array; 2. Process the data that was read from the data file one record at a time, into a dynamic array; 3. Print the records in a dynamic array to a datafile using an ofstream object; 4. Use the operator new to allocate memory for a dynamic array; 5. Use the operator delete to de-allocate the memory allocated by the new; (basically, making previously used memory available for use again) 6. Copy the content of one dynamic array into another dynamic array (basically, copying memory from one location to another) 4. Be able to use the fstream library; 5. Be able to use a dynamic array of record records; 6. Be able to use an ifstream object; 7. Be able to use an ofstream object; */ #include <iostream> #include <string> #include <fstream> #include <iostream> using namespace std; //sample record (class with no functionality) class call_record { public: string firstname; string lastname; string cell_number; int relays; int call_length; double net_cost; double tax_rate; double call_tax; double total_cost; }; //Function Prototypes void Initialize(call_record *& call_DB, int & count, int & size); bool Is_empty(const int count); //inline implementation bool Is_full(const int count, int size);//inline implementation int Search(const call_record *call_DB, const int count, const string key);//returns location if item in listl; otherwise return -1 void Add(call_record * &call_DB, int & count, int & size, const string key); //adds item inorder to the list void Remove(call_record *call_DB, int & count, const string key); //removes an item from the list void Double_size(call_record * &call_DB, int & count, int & size); void Process(call_record *call_DB, const int & count); void Print(const call_record *call_DB, int & count); //prints all the elements in the list to the screen void Destroy_call_DB(call_record * &call_DB); //de-allocates all memory allocate to call_DB by operator new. /************************************************************************************************************************************/ //Name: Initialize //Precondition: The varialbes firstname, lastname, cell_num, relays, and call_length have not been initialized //Postcondition: The variables have been initialized by data file. //Decription: Reads the data file of call information (firstname, lastname, cell number, relays and call length) into the dynamic array of call record, //call_DB. If the count because equal to the size the function double_size is called and the memory allocated to call_DB is doubled. /************************************************************************************************************************************/ void Initialize(call_record * & call_DB, int & count, int & size) { ifstream in; //input file stream object declaration in.open("callstats_data.txt"); //bind the file "call_data.txt" to the input count = 0; //remember to initialize count before the first come if (in.fail()) //if file not found print message and exit program { cout << "Input file did not open correctly" << endl; exit(1); } //Remember to use a while loop when reading from a file because //you do not know how many records you will be reading. while (!in.eof()) { if (Is_full(count, size)) { Double_size(call_DB, count, size); } in >> call_DB[count].firstname; in >> call_DB[count].lastname; in >> call_DB[count].cell_number; in >> call_DB[count].relays; in >> call_DB[count].call_length; count++; } in.close();//file stream "in" closes. } /***********************************************************************************************************************************/ //Name: Is_empty //Precondition: Checks to see if call_DB is empty //Postcondition: call_DB status verifeid. //Decription: returns true if call_DB is empty /**********************************************************************************************************************************/ //ONE WAY TO MAKE A FUNCTION INLINE IS TO PUT THE KEYWORD "inline" in from of the //FUNCTION HEADER AS SHOWN BELOW: inline bool Is_empty(const int count) { if (count == 0){ return 0; } else { return -1; } } //ONE WAY TO MAKE A FUNCTION INLINE IS TO PUT THE KEYWORD "inline" in from of the //FUNCTION HEADER AS SHOWN BELOW: /**********************************************************************************************************************************/ //Name: Is_full //Precondition: Checks to see if call_DB is full //Postcondition: call_DB status verifeid. //Decription: returns true if call_DB is full /*********************************************************************************************************************************/ inline bool Is_full(const int count, int size) { if (count == size){ return 0; } else { return -1; } } /**********************************************************************************************************************************/ //Name: search //Precondition: Checks to see if there is a call_DB //Postcondition: call_DB status verifeid. //Decription: locates key in call_DB if it is there; otherwise -1 is returned /*********************************************************************************************************************************/ int Search(const call_record *call_DB, const int count, const string key) { for (int i = 0; i < count; i++){ if (call_DB[i].cell_number == key) { return i; } else { return -1; } } return 0; } /*********************************************************************************************************************************/ //Name: Add //Precondition: Checks memory of call_DB //Postcondition: Increase call_DB size if full. //Decription: add key to call_DB; if call_DB is full, double_size is called to increase the size of call_DB. /********************************************************************************************************************************/ void Add(call_record * &call_DB, int & count, int & size, const string key) { int index = count; if (Is_full(count, size)) { Double_size(call_DB, count, size); call_DB[index].cell_number = key; std::cout << "Enter First Name" << '\n'; std::cin >> call_DB[index].firstname; std::cout << "Enter Last Name" << '\n'; std::cin >> call_DB[index].lastname; std::cout << "Enter number of Relays" << '\n'; std::cin >> call_DB[index].relays; std::cout << "Enter Call Length" << '\n'; std::cin >> call_DB[index].call_length; count++; } return; } /********************************************************************************************************************************/ //Name: Remove //Precondition: Checks location of call_DB //Postcondition: call_DB is removed if exists. //Decription: remove key from call_DB if it is there. /*******************************************************************************************************************************/ void Remove(call_record *call_DB, int & count, const string key) { if (Is_empty(count) == 0) { return; } int location = Search(call_DB, count, key); if (location == -1) { std::cout << "Location" << location << '\n'; return; } else if (location != -1){ for (int j = location; j < count - 1; j++) { call_DB[j] = call_DB[j+1]; } count = count - 1; } } /******************************************************************************************************************************/ //Name: Double_Size //Precondition: Checks capacity of call_DB //Postcondition: capacity doubled. //Decription: doubles the size (capacity) of call_DB /******************************************************************************************************************************/ void Double_size(call_record * &call_DB, int & count, int & size) { size *= 2; call_record * temp = new call_record[size]; for (int i = 0; i < count; i++) { temp[i] = call_DB[i]; } std::cout << "Size: " << size << '\n'; delete[] call_DB; call_DB = temp; return; } /******************************************************************************************************************************/ //Name: Process //Precondition: The variables have been initialized by the data file. //Postcondition: Conditional statements initialize relay variables. //Decription: calculate the net cost, tax rate, call tax and total cost for every call record in call_DB. /*****************************************************************************************************************************/ void Process(call_record *call_DB, const int & count) { //Remember to use a "for" loop when you know how many items //you will be processing. Use the dot operator when you are //accessing fields in a record. For example, when we need //to access the relay field in the first record in the array use //call_DB[0].relay for (int i = 0; i < count; i++) { call_DB[i].net_cost = call_DB[i].relays / 50.0 * .40 * call_DB[i].call_length; call_DB[i].call_tax = call_DB[i].net_cost * call_DB[i].tax_rate; call_DB[i].total_cost = call_DB[i].net_cost + call_DB[i].call_tax; //Conditional statements to determine tax rates if (call_DB[i].relays <= 0 && call_DB[i].relays <=5) { call_DB[i].tax_rate = 0.01; } else if (call_DB[i].relays <= 6 && call_DB[i].relays <=11) { call_DB[i].tax_rate = 0.03; } else if (call_DB[i].relays <= 12 && call_DB[i].relays <=20) { call_DB[i].tax_rate = 0.05; } else if (call_DB[i].relays <= 21 && call_DB[i].relays <=50) { call_DB[i].tax_rate = 0.08; } else { call_DB[i].tax_rate = 0.12; } } return; } /****************************************************************************************************************************/ //Name: Print //Precondition: The variables have been initialized and calculated //Postcondition: Results are displayed. //Decription: prints every field of every call_record in call_DB formatted to the screen. /***************************************************************************************************************************/ void Print(const call_record *call_DB, int & count) { ofstream out; //declare the output file stream "out". //bind the file "weekly4_call_info.txt" to //to the output file stream "out". out.open("weekly5_call_info.txt"); //Magic Formula out.setf(ios::showpoint); out.precision(2); out.setf(ios::fixed); if (out.fail()) // if problem opening file, print message and exit program { cout << "Output file did not open correctly" << endl; exit(1); } // use a "for" loop here to // print the output to file for (int i = 0; i < count; i++) { out << "First Name " <<call_DB[i].firstname<<" "<<endl; out << "Last Name " <<call_DB[i].lastname<<" "<<endl; out << "Cell Phone " <<call_DB[i].cell_number<<" "<<endl; out << "Number of Relay Stations " <<call_DB[i].relays<<" "<<endl; out << "Minutes Used " <<call_DB[i].call_length<<endl; out << "Net Cost " <<call_DB[i].net_cost<<endl; out << "Tax Rate " <<call_DB[i].tax_rate<<endl; out << "Call Tax " <<call_DB[i].call_tax<<endl; out << "Total Cost of Call " <<call_DB[i].total_cost<<endl<<endl; } out.close(); return; } /****************************************************************************************************************************/ //Name: Destroy_call_DB //Precondition: Checks to see if call_DB exists //Postcondition: Deletes call_DB. //Decription: de-allocates all memory allocated to call_DB. This should be the last function to be called before the program // is exited. /***************************************************************************************************************************/ void Destroy_call_DB(call_record * &call_DB) { delete[] call_DB; return; } //Main Function int main() { int size = 5; //total amount of memory (cells) allocated for the dynamic array of call records int count = 0; call_record *call_DB = new call_record[size]; string key; //put code here to test your funcitons Initialize(call_DB, count, size); Is_empty(count); //inline implementation Is_full(count, size);//inline implementation Search(call_DB, count, key);//returns location if item in listl; otherwise return -1 Add(call_DB, count, size, key); //adds item inorder to the list Remove(call_DB, count, key); //removes an item from the list Double_size(call_DB, count, size); Process(call_DB, count); Print(call_DB, count); //prints all the elements in the list to the screen Destroy_call_DB(call_DB); //de-allocates all memory allocate to call_DB by operator new. return 0; }
44.431973
152
0.548572
juan2357
122b3d46f5c89cdda5ccfe72d125564b950dd318
1,062
hpp
C++
boost/network/uri/directives/port.hpp
ccnyou/cpp-netlib-stable
2697b391032bce52a5b1e6ecddf98b92fe468afa
[ "BSL-1.0" ]
132
2017-03-22T03:46:38.000Z
2022-03-08T15:08:16.000Z
boost/network/uri/directives/port.hpp
ccnyou/cpp-netlib-stable
2697b391032bce52a5b1e6ecddf98b92fe468afa
[ "BSL-1.0" ]
4
2017-04-06T17:46:10.000Z
2018-08-08T18:27:59.000Z
boost/network/uri/directives/port.hpp
ccnyou/cpp-netlib-stable
2697b391032bce52a5b1e6ecddf98b92fe468afa
[ "BSL-1.0" ]
30
2017-03-26T22:38:17.000Z
2021-11-21T20:50:17.000Z
// Copyright (c) Glyn Matthews 2011, 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_NETWORK_URI_DIRECTIVES_PORT_INC__ #define BOOST_NETWORK_URI_DIRECTIVES_PORT_INC__ #include <cstdint> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> namespace boost { namespace network { namespace uri { struct port_directive { explicit port_directive(std::string port) : port_(std::move(port)) {} explicit port_directive(std::uint16_t port) : port_(std::to_string(port)) {} template <class Uri> void operator()(Uri &uri) const { uri.append(":"); uri.append(port_); } std::string port_; }; inline port_directive port(const std::string &port) { return port_directive(port); } inline port_directive port(std::uint16_t port) { return port_directive(port); } } // namespace uri } // namespace network } // namespace boost #endif // BOOST_NETWORK_URI_DIRECTIVES_PORT_INC__
23.6
71
0.717514
ccnyou
122c7874cc4a80a35bbb7aeb6e489bef86c8e356
837
cpp
C++
libraries/clock/rtcClock.cpp
PetrakovKirill/nixie_hrono
0eff6aa253b84294dd41c6f233a00dd035514b07
[ "MIT" ]
null
null
null
libraries/clock/rtcClock.cpp
PetrakovKirill/nixie_hrono
0eff6aa253b84294dd41c6f233a00dd035514b07
[ "MIT" ]
null
null
null
libraries/clock/rtcClock.cpp
PetrakovKirill/nixie_hrono
0eff6aa253b84294dd41c6f233a00dd035514b07
[ "MIT" ]
null
null
null
#include "rtc_clock.h" #include <stdio.h> #define SEC_24_HOURS (86400) #define SEC_1_HOUR ( 3600) #define SEC_1_MIN ( 60) rtcClock :: rtcClock(display *pDisplay, rtc *pRtc) { displ = pDisplay; time = pRtc; } void rtcClock :: ShowTime(void) { char printString[5] = {0}; uint32_t currentTime; uint16_t hour, min; time->ReadTime(); currentTime = time->GetTime(); hour = (currentTime % SEC_24_HOURS) / SEC_1_HOUR; min = (currentTime % SEC_1_HOUR) / SEC_1_MIN; snprintf(printString, sizeof(printString), "%02u%02u", hour, min); displ->Print(printString); } void rtcClock :: SetTime(uint32_t seconds) { time->SetTime(seconds); } uint32_t rtcClock :: GetTime(void) { return (time->GetTime()); }
19.465116
59
0.590203
PetrakovKirill
122e0365a281223a404404f59426e148cd88636f
3,356
cpp
C++
examples/07-editor.cpp
cyrilcode/cyfw-examples
18fde906b606ff0b9e589a4ef53125186fe5a578
[ "MIT" ]
null
null
null
examples/07-editor.cpp
cyrilcode/cyfw-examples
18fde906b606ff0b9e589a4ef53125186fe5a578
[ "MIT" ]
null
null
null
examples/07-editor.cpp
cyrilcode/cyfw-examples
18fde906b606ff0b9e589a4ef53125186fe5a578
[ "MIT" ]
null
null
null
#include <cyfw/main.h> #include <cyfw/Gui.h> #include <Resource.h> using namespace std; using namespace cy; class MyApp : public cy::App { Gui gui; bool guiOpen; char text[1024*16]; bool escPressed; bool shouldQuit; ImFont* font1; public: MyApp() : escPressed{false}, shouldQuit{false} { char * t = "rotate\nbox\0"; memcpy(text, t, 11); Resource fontdata = LOAD_RESOURCE(a_scp_r_ttf); auto font_cfg_template = ImFontConfig(); font_cfg_template.FontDataOwnedByAtlas = false; font1 = ImGui::GetIO().Fonts->AddFontFromMemoryTTF( (void*)fontdata.begin(), fontdata.size(), 32, &font_cfg_template); } void setup() { window->closeOnEscapeKey(false); window->setClearColor({0,0,0,1}); gui.init(window); ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = 0; style.WindowPadding = {0, 0}; style.Colors[ImGuiCol_Text] = {1,1,1,1}; style.Colors[ImGuiCol_WindowBg] = {0,0,0,0}; style.Colors[ImGuiCol_FrameBg] = {0,0,0,0}; } void draw() { window->clear(); gui.clear(); doGui(); gui.draw(); } void doGui() { ImGui::SetNextWindowPos(ImVec2(10,10)); ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse; if (!ImGui::Begin("Buffer", &guiOpen, windowFlags)) { ImGui::End(); return; } ImGui::PushFont(font1); vec2i dim = window->getWindowSize(); ImGui::SetWindowSize(ImVec2(dim.x() - 20, dim.y() - 20)); ImGui::InputTextMultiline("source", text, sizeof(text), ImVec2(-1.0f, -1.0f), 0); if (escPressed) ImGui::OpenPopup("Quit?"); if (ImGui::BeginPopupModal("Quit?", NULL, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoMove)) { ImGui::SetWindowFontScale(1.0f); ImGui::Text("Are you sure you want to quit?\n\n"); ImGui::Separator(); if (ImGui::Button("Quit", ImVec2(120,0))) { escPressed = false; shouldQuit = true; window->quit(); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel", ImVec2(120,0))) { escPressed = false; window->quit(false); ImGui::CloseCurrentPopup(); } if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::PopFont(); ImGui::End(); } bool quit() { escPressed = true; return shouldQuit; } void key(window::KeyEvent e) { if (e.key == window::key::ESCAPE && e.action == window::action::PRESSED) { escPressed = true; } gui.key(e); } void scroll(window::ScrollEvent e) { gui.scroll(e); } void textInput(window::CharEvent e) { gui.character(e); } void mouseButton(window::MouseButtonEvent e ) { gui.mouse(e); } }; int main() { cy::run<MyApp,ConsoleLogger>(640, 480, "testing editor"); }
28.440678
109
0.546782
cyrilcode
122eb35df8c2daab625ca0d367d1b40cf1bab474
1,393
cpp
C++
Tests/src/ColoredTriangleTest.cpp
kamil2789/LearnModernOpenGL
4eb234c15f41e3670db425680c95b46bb224a6c8
[ "MIT" ]
1
2021-12-04T21:16:57.000Z
2021-12-04T21:16:57.000Z
Tests/src/ColoredTriangleTest.cpp
kamil2789/LearnModernOpenGL
4eb234c15f41e3670db425680c95b46bb224a6c8
[ "MIT" ]
null
null
null
Tests/src/ColoredTriangleTest.cpp
kamil2789/LearnModernOpenGL
4eb234c15f41e3670db425680c95b46bb224a6c8
[ "MIT" ]
null
null
null
#include "EndToEndTests.h" #include <glad/glad.h> #include <GLFW/glfw3.h> #include "config/GlfwConfig.h" #include "config/GlfwWindowManager.h" #include "config/GladConfig.h" #include "entities/ShaderFileReader.h" #include "entities/ShaderProgram.h" #include "entities/ColoredTriangle.h" bool EndToEndTest::ColoredTriangleTest() { GlfwConfig glfwConfig{}; glfwConfig.setDefaultWindowOptions(); GlfwWindowManager windowManager{800, 600, "ColoredTriangle"}; windowManager.setContextCurrent(); GladConfig gladConfig{}; glViewport(0, 0, 800, 600); ShaderProgram simpleTriangleShader{ ShaderFileReader::readSrcFromFile("colorVertex.vert"), ShaderFileReader::readSrcFromFile("colorFragment.frag") }; simpleTriangleShader.compile(); simpleTriangleShader.run(); std::array<float, 18> vertices = { 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f }; ColoredTriangle triangle{vertices}; triangle.init(); glClearColor(0.2f, 0.3f, 0.0f, 1.0f); while(windowManager.isRunningWindow()) { windowManager.processInput(); //rendering glClear(GL_COLOR_BUFFER_BIT); triangle.draw(); //rendering end windowManager.swapWindowBuffer(); glfwPollEvents(); } return true; }
24.017241
65
0.662599
kamil2789
1238246444b1e6a69dd23a19a4a5c6434680c633
5,567
cpp
C++
SLAM/kalmanSLAM.cpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
2
2015-04-02T21:45:49.000Z
2018-09-19T01:59:02.000Z
SLAM/kalmanSLAM.cpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
null
null
null
SLAM/kalmanSLAM.cpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
null
null
null
/* * Bayes++ the Bayesian Filtering Library * Copyright (c) 2004 Michael Stevens * See accompanying Bayes++.htm for terms and conditions of use. * * $Id$ */ /* * SLAM : Simultaneous Locatization and Mapping * Kalman filter representing representation of SLAM */ // Bayes++ Bayesian filtering schemes #include "BayesFilter/bayesFlt.hpp" // Bayes++ SLAM #include "SLAM.hpp" #include "kalmanSLAM.hpp" #include <iostream> #include <boost/numeric/ublas/io.hpp> namespace SLAM_filter { template <class Base> inline void zero(FM::ublas::matrix_range<Base> A) // Zero a matrix_range { // Note A cannot be a reference typedef typename Base::value_type Base_value_type; FM::noalias(A) = FM::ublas::scalar_matrix<Base_value_type>(A.size1(),A.size2(), Base_value_type()); } Kalman_SLAM::Kalman_SLAM( Kalman_filter_generator& filter_generator ) : SLAM(), fgenerator(filter_generator), loc(0), full(0) { nL = 0; nM = 0; } Kalman_SLAM::~Kalman_SLAM() { fgenerator.dispose (loc); fgenerator.dispose (full); } void Kalman_SLAM::init_kalman (const FM::Vec& x, const FM::SymMatrix& X) { // TODO maintain map states nL = x.size(); nM = 0; if (loc) fgenerator.dispose (loc); if (full) fgenerator.dispose (full); // generate a location filter for prediction loc = fgenerator.generate(nL); // generate full filter full = fgenerator.generate(nL); // initialise location states full->x.sub_range(0,nL) = x; full->X.sub_matrix(0,nL,0,nL) = X; full->init(); } void Kalman_SLAM::predict( BF::Linrz_predict_model& lpred ) { // extract location part of full loc->x = full->x.sub_range(0,nL); loc->X = full->X.sub_matrix(0,nL,0,nL); // predict location, independent of map loc->init(); loc->predict (lpred); loc->update(); // return location to full full->x.sub_range(0,nL) = loc->x; full->X.sub_matrix(0,nL,0,nL) = loc->X; full->init(); } void Kalman_SLAM::observe( unsigned feature, const Feature_observe& fom, const FM::Vec& z ) { // Assume features added sequentially if (feature >= nM) { error (BF::Logic_exception("Observe non existing feature")); return; } // TODO Implement nonlinear form // Create a augmented sparse observe model for full states BF::Linear_uncorrelated_observe_model fullm(full->x.size(), 1); fullm.Hx.clear(); fullm.Hx.sub_matrix(0,nL, 0,nL) = fom.Hx.sub_matrix(0,nL, 0,nL); fullm.Hx(0,nL+feature) = fom.Hx(0,nL); fullm.Zv = fom.Zv; full->observe(fullm, z); } void Kalman_SLAM::observe_new( unsigned feature, const Feature_observe_inverse& fom, const FM::Vec& z ) // fom: must have a the special form required for SLAM::obeserve_new { // size consistency, single state feature if (fom.Hx.size1() != 1) error (BF::Logic_exception("observation and model size inconsistent")); // make new filter with additional (uninitialized) feature state if (feature >= nM) { nM = feature+1; Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+nM); FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x; FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X; fgenerator.dispose(full); full = nf; } // build augmented location and observation FM::Vec sz(nL+z.size()); sz.sub_range(0,nL) = full->x.sub_range(0,nL); sz.sub_range(nL,nL+z.size() )= z; // TODO use named references rather then explict Ha Hb FM::Matrix Ha (fom.Hx.sub_matrix(0,1, 0,nL) ); FM::Matrix Hb (fom.Hx.sub_matrix(0,1, nL,nL+z.size()) ); FM::Matrix tempHa (1,nL); FM::Matrix tempHb (1,sz.size()); // feature covariance with existing location and features // X+ = [0 Ha] X [0 Ha]' + Hb Z Hb' // - zero existing feature covariance zero( full->X.sub_matrix(0,full->X.size1(), nL+feature,nL+feature+1) ); full->X.sub_matrix(nL+feature,nL+feature+1,0,nL+nM) = FM::prod(Ha,full->X.sub_matrix(0,nL, 0,nL+nM) ); // feature state and variance full->x[nL+feature] = fom.h(sz)[0]; full->X(nL+feature,nL+feature) = ( FM::prod_SPD(Ha,full->X.sub_matrix(0,nL, 0,nL),tempHa) + FM::prod_SPD(Hb,fom.Zv,tempHb) ) (0,0); full->init (); } void Kalman_SLAM::observe_new( unsigned feature, const FM::Float& t, const FM::Float& T ) { // Make space in scheme for feature, requires the scheme can deal with resized state if (feature >= nM) { Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+feature+1); FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x; FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X; zero( nf->X.sub_matrix(0,nf->X.size1(), nL+nM,nf->X.size2()) ); nf->x[nL+feature] = t; nf->X(nL+feature,nL+feature) = T; nf->init (); fgenerator.dispose(full); full = nf; nM = feature+1; } else { full->x[nL+feature] = t; full->X(nL+feature,nL+feature) = T; full->init (); } } void Kalman_SLAM::forget( unsigned feature, bool must_exist ) { full->x[nL+feature] = 0.; // ISSUE uBLAS has problems accessing the lower symmetry via a sub_matrix proxy, there two two parts seperately zero( full->X.sub_matrix(0,nL+feature, nL+feature,nL+feature+1) ); zero( full->X.sub_matrix(nL+feature,nL+feature+1, nL+feature,full->X.size1()) ); full->init(); } void Kalman_SLAM::decorrelate( Bayesian_filter::Bayes_base::Float d ) // Reduce correlation by scaling cross-correlation terms { std::size_t i,j; const std::size_t n = full->X.size1(); for (i = 1; i < n; ++i) { FM::SymMatrix::Row Xi(full->X,i); for (j = 0; j < i; ++j) { Xi[j] *= d; } for (j = i+1; j < n; ++j) { Xi[j] *= d; } } full->init(); } }//namespace SLAM
28.548718
114
0.668762
Exadios
1238d54423bef55f07f43bb2b2a02aa12a6bed08
6,656
cc
C++
tuplex/test/core/FallbackMode.cc
ms705/tuplex
c395041934768e51952c4fa783775b810b2fdec8
[ "Apache-2.0" ]
null
null
null
tuplex/test/core/FallbackMode.cc
ms705/tuplex
c395041934768e51952c4fa783775b810b2fdec8
[ "Apache-2.0" ]
null
null
null
tuplex/test/core/FallbackMode.cc
ms705/tuplex
c395041934768e51952c4fa783775b810b2fdec8
[ "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------------------------------------------------// // // // Tuplex: Blazing Fast Python Data Science // // // // // // (c) 2017 - 2021, Tuplex team // // Created by Leonhard Spiegelberg first on 1/1/2021 // // License: Apache 2.0 // //--------------------------------------------------------------------------------------------------------------------// #include "gtest/gtest.h" #include "TestUtils.h" class FallbackTest : public PyTest {}; TEST_F(FallbackTest, Numpy_objects) { using namespace std; using namespace tuplex; Context c(microTestOptions()); ClosureEnvironment ce; ce.importModuleAs("np", "numpy"); // misleading name?? // this is an example of attribute error // auto v = c.parallelize({Row(10), Row(20), Row(1)}) // .map(UDF("lambda x: np.zeroes(x)", "", ce)) // .collectAsVector(); // run here auto v = c.parallelize({Row(10), Row(20), Row(1)}) .map(UDF("lambda x: np.zeros(x)", "", ce)) .collectAsVector(); ASSERT_EQ(v.size(), 3); vector<int> ref_sizes{10, 20, 1}; python::lockGIL(); // now fetch python objects for(int i = 0; i < v.size(); ++i) { auto row = v[i]; ASSERT_EQ(row.getType(0), python::Type::PYOBJECT); // get object auto f = row.get(0); auto obj = python::deserializePickledObject(python::getMainModule(), static_cast<const char *>(f.getPtr()), f.getPtrSize()); ASSERT_TRUE(obj); // compute len auto len = PyObject_Length(obj); EXPECT_EQ(len, ref_sizes[i]); } python::unlockGIL(); } TEST_F(FallbackTest, NonusedExternalMod) { using namespace std; using namespace tuplex; Context c(microTestOptions()); ClosureEnvironment ce; ce.importModuleAs("np", "numpy"); // misleading name?? auto v = c.parallelize({Row(10), Row(20), Row(1)}) .map(UDF("lambda x: x + 1", "", ce)) .collectAsVector(); } TEST_F(FallbackTest, ArbitraryPyObjectSerialization) { using namespace std; using namespace tuplex; python::lockGIL(); auto np_obj = python::runAndGet("import numpy as np; X = np.zeros(100)", "X"); auto np_obj_type = PyObject_Type(np_obj); auto np_obj_type_name = python::PyString_AsString(np_obj_type); PyObject_Print(np_obj, stdout, 0); cout<<endl; // convert to tuplex Field (--> PYOBJECT!) auto f = python::pythonToField(np_obj); EXPECT_EQ(f.getType(), python::Type::PYOBJECT); // mapped to arbitrary python object // test fieldToPython... auto conv_obj = python::fieldToPython(f); ASSERT_TRUE(conv_obj); // check it's nd array! auto type_obj = PyObject_Type(conv_obj); auto name = python::PyString_AsString(type_obj); EXPECT_EQ(name, np_obj_type_name); PyObject_Print(conv_obj, stdout, 0); cout<<endl; python::unlockGIL(); } TEST_F(FallbackTest, NonAccessedPyObjectInPipeline) { using namespace std; using namespace tuplex; python::lockGIL(); auto np_obj = python::runAndGet("import numpy as np; X = np.zeros(100)", "X"); auto np_obj_type = PyObject_Type(np_obj); auto np_obj_type_name = python::PyString_AsString(np_obj_type); PyObject_Print(np_obj, stdout, 0); cout << endl; // convert to tuplex Field (--> PYOBJECT!) auto f = python::pythonToField(np_obj); python::unlockGIL(); // create a simple pipeline, which performs some work but leaves a pyobject untouched... Context c(microTestOptions()); auto v = c.parallelize({Row(10, 20, f), Row(30, 3, f)}) .map(UDF("lambda a, b, c: (a + b, c)")) .collectAsVector(); ASSERT_EQ(v.size(), 2); EXPECT_EQ(v[0].getType(1), python::Type::PYOBJECT); EXPECT_EQ(v[1].getType(1), python::Type::PYOBJECT); EXPECT_EQ(v[0].getInt(0), 30); EXPECT_EQ(v[1].getInt(0), 33); // because of the tuple flattening, nesting should work as well! auto v2 = c.parallelize({Row(10, 20, f), Row(30, 3, f)}) .map(UDF("lambda a, b, c: (a + b, (c, b))")) .collectAsVector(); ASSERT_EQ(v2.size(), 2); } TEST_F(FallbackTest, InvokingNumpyFunctions) { // c.parallelize([1, 2, 3, 4]).map(lambda x: [x, x*x, x*x*x]) \ // .map(lambda x: (np.array(x).sum(), np.array(x).mean())).collect() using namespace std; using namespace tuplex; Context c(microTestOptions()); ClosureEnvironment ce; ce.importModuleAs("np", "numpy"); auto res = c.parallelize({Row(1), Row(2), Row(3), Row(4)}) .map(UDF("lambda x: [x, x*x, x*x*x]")) .map(UDF("lambda x: (np.array(x).sum(), np.array(x).mean())", "", ce)) .map(UDF("lambda x: (int(x[0]), float(x[1]))")) // cast to regular python objects to trigger compilation. .map(UDF("lambda a, b: a if a > b else b")) .collectAsVector(); vector<Row> ref{Row(3), Row(14), Row(39), Row(84)}; ASSERT_EQ(res.size(), ref.size()); for(int i = 0; i < ref.size(); ++i) { EXPECT_EQ(ref[i].toPythonString(), res[i].toPythonString()); } } TEST_F(FallbackTest, InvokingNumpyFunctionsTwoParamLambda) { using namespace std; using namespace tuplex; Context c(microTestOptions()); ClosureEnvironment ce; ce.importModuleAs("np", "numpy"); auto res = c.parallelize({Row(1), Row(2), Row(3), Row(4)}) .map(UDF("lambda x: [x, x*x, x*x*x]")) .map(UDF("lambda x: (np.array(x).sum(), np.array(x).mean())", "", ce)) .map(UDF("lambda a, b: (int(a), float(b))")) // cast to regular python objects to trigger compilation. .map(UDF("lambda a, b: a if a > b else b")) .collectAsVector(); vector<Row> ref{Row(3), Row(14), Row(39), Row(84)}; ASSERT_EQ(res.size(), ref.size()); for(int i = 0; i < ref.size(); ++i) { EXPECT_EQ(ref[i].toPythonString(), res[i].toPythonString()); } }
34.666667
132
0.519231
ms705
72ef5a55e638abecb5f3325ad152379d41c70d6f
51,660
cc
C++
src/visualisers/Akima760.cc
dtip/magics
3247535760ca962f859c203295b508d442aca4ed
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/visualisers/Akima760.cc
dtip/magics
3247535760ca962f859c203295b508d442aca4ed
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/visualisers/Akima760.cc
dtip/magics
3247535760ca962f859c203295b508d442aca4ed
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * (C) Copyright 1996-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ /*! \file Akima760.cc Implementation of Akima760 class. Magics Team - ECMWF 2004 Created: Fri 12-Mar-2004 */ #include "Akima760Method.h" #include "MagLog.h" #include "Timer.h" using namespace magics; Akima760::Akima760(const AbstractMatrix& matrix, const Akima760MethodAttributes& attr) : MatrixHandler(matrix), attr_(attr) { MagLog::debug() << "Akima760 Constructor" << "\n"; int j; // monoColumns_ = MatrixHandler::columns(); //syntax also valid monoColumns_ = this->matrix_.columns(); monoRows_ = this->matrix_.rows(); // Compute matrix output sizes double aux = (this->matrix_.regular_column(monoColumns_ - 1) - this->matrix_.regular_column(0)) / attr_.resolutionX_; if ((double)(int(aux)) != aux) aux += 1.; // next integer number ncols_ = int(aux + 1.); // must include the first and the last input coordinates aux = (this->matrix_.regular_row(monoRows_ - 1) - this->matrix_.regular_row(0)) / attr_.resolutionY_; if ((double)(int(aux)) != aux) aux += 1.; // next integer number nrows_ = int(aux + 1.); // must include the first and the last input coordinates // Allocate 3 auxiliary arrays where the estimated zx, zy, and zxy // values at the input-grid data points are to be stored. WKZX_ = new double*[monoRows_]; WKZY_ = new double*[monoRows_]; WKZXY_ = new double*[monoRows_]; for (j = 0; j < monoRows_; j++) { WKZX_[j] = new double[monoColumns_]; WKZY_[j] = new double[monoColumns_]; WKZXY_[j] = new double[monoColumns_]; } // Check for missing values missingValues_ = this->matrix_.hasMissingValues(); // Estimates partial derivatives at all input-grid data points //{ Timer timer("Akima", "Time spent in interpolation"); rgpd3p(); //} double from = this->matrix_.regular_row(0); for (int i = 0; i < nrows_; i++) { double pos = from + i * attr_.resolutionY_; rowsMap_.insert(make_pair(pos, i)); rows_.push_back(pos); } from = this->matrix_.regular_column(0); for (int i = 0; i < ncols_; i++) { double pos = from + i * attr_.resolutionX_; columnsMap_.insert(make_pair(pos, i)); columns_.push_back(pos); } #if 0 // Print partial derivatives int i; MagLog::debug() << "WKZX" << "\n";; for (i = 0; i < this->matrix_.rows(); i++) { MagLog::debug() << "\n";; for (j = 0; j < this->matrix_.columns(); j++) MagLog::debug() << WKZX_[i][j] << " "; } MagLog::debug() << "\n" << "WKZY" << "\n";; for (i = 0; i < this->matrix_.rows(); i++) { MagLog::debug() << "\n";; for (j = 0; j < this->matrix_.columns(); j++) MagLog::debug() << WKZY_[i][j] << " "; } MagLog::debug() << "\n" << "WKZXY" << "\n";; for (i = 0; i < this->matrix_.rows(); i++) { MagLog::debug() << "\n";; for (j = 0; j < this->matrix_.columns(); j++) MagLog::debug() << WKZXY_[i][j] << " "; } #endif } Akima760::~Akima760() { int j; // release memory for (j = 0; j < monoRows_; j++) { delete[] WKZX_[j]; delete[] WKZY_[j]; delete[] WKZXY_[j]; WKZX_[j] = NULL; WKZY_[j] = NULL; WKZXY_[j] = NULL; } delete[] WKZX_; delete[] WKZY_; delete[] WKZXY_; WKZX_ = NULL; WKZY_ = NULL; WKZXY_ = NULL; } double Akima760::regular_row(int i) const { // Remove later. Why this function is called so many times ??? // static long itest=0; // MagLog::debug() << "Akima760 row=" << itest++ << "\n"; // Check if the coordinate does not go beyond the upper limit double aux = i * attr_.resolutionY_ + this->matrix_.regular_row(0); return (aux > this->matrix_.regular_row(monoRows_ - 1) ? this->matrix_.regular_row(monoRows_ - 1) : aux); } double Akima760::row(int i, int j) const { return regular_row(i); } double Akima760::regular_column(int j) const { // Remove later. Why this function is called so many times ??? // static long jtest=0; // MagLog::debug() << "Akima760 column=" << jtest++ << "\n"; // Check if the coordinate does not go beyond the upper limit double aux = j * attr_.resolutionX_ + this->matrix_.regular_column(0); return (aux > this->matrix_.regular_column(monoColumns_ - 1) ? this->matrix_.regular_column(monoColumns_ - 1) : aux); } double Akima760::column(int i, int j) const { return regular_column(j); } double Akima760::operator()(int i, int j) const { double value = rgbi3p(regular_column(j), regular_row(i)); return value; } void Akima760::rgpd3p() { //* //* Partial derivatives of a bivariate function on a rectangular grid //* (a supporting subroutine of the RGBI3P/RGSF3P subroutine package) //* //* Hiroshi Akima //* U.S. Department of Commerce, NTIA/ITS //* Version of 1995/08 //* //* This subroutine estimates three partial derivatives, zx, zy, and //* zxy, of a bivariate function, z(x,y), on a rectangular grid in //* the x-y plane. It is based on the revised Akima method that has //* the accuracy of a bicubic polynomial. //* //* The input arguments are //* NXDF = number of the input-grid data points in the x //* coordinate (must be 2 or greater), //* NYDF = number of the input-grid data points in the y //* coordinate (must be 2 or greater), //* XD = array of dimension NXDF containing the x coordinates //* of the input-grid data points (must be in a //* monotonic increasing order), //* YD = array of dimension NYDF containing the y coordinates //* of the input-grid data points (must be in a //* monotonic increasing order), //* ZD = two-dimensional array of dimension NXDF*NYDF //* containing the z(x,y) values at the input-grid data //* points. //* //* The output argument is //* PDD = three-dimensional array of dimension 3*NXDF*NYDF, //* where the estimated zx, zy, and zxy values at the //* input-grid data points are to be stored. //* //* This routine was adapted to C++ by Fernando Ii, 02/04 //* double B00 = 0., B00X = 0., B00Y = 0., B01 = 0., B10 = 0., B11 = 0., CX1 = 0., CX2 = 0., CX3 = 0., CY1 = 0., CY2 = 0., CY3 = 0., DISF = 0., DNM = 0., DZ00 = 0., DZ01 = 0., DZ02 = 0., DZ03 = 0., DZ10 = 0., DZ11 = 0., DZ12 = 0., DZ13 = 0., DZ20 = 0., DZ21 = 0., DZ22 = 0., DZ23 = 0., DZ30 = 0., DZ31 = 0., DZ32 = 0., DZ33 = 0., DZX10 = 0., DZX20 = 0., DZX30 = 0., DZXY11 = 0., DZXY12 = 0., DZXY13 = 0., DZXY21 = 0., DZXY22 = 0., DZXY23 = 0., DZXY31 = 0., DZXY32 = 0., DZXY33 = 0., DZY01 = 0., DZY02 = 0., DZY03 = 0., EPSLN = 0., PEZX = 0., PEZXY = 0., PEZY = 0., SMPEF = 0., SMPEI = 0., SMWTF = 0., SMWTI = 0., SX = 0., SXX = 0., SXXY = 0., SXXYY = 0., SXY = 0., SXYY = 0., SXYZ = 0., SXZ = 0., SY = 0., SYY = 0., // SYZ,SZ,VOLF,WT,X0,X1,X2,X3,XX1,XX2,XX3,Y0,Y1,Y2, SYZ = 0., SZ = 0., VOLF = 0., WT = 0., X0 = 0., X1 = 0., X2 = 0., X3 = 0., Y0 = 0., Y1 = 0., Y2 = 0., Y3 = 0., Z00 = 0., Z01 = 0., Z02 = 0., Z03 = 0., Z10 = 0., Z11 = 0., Z12 = 0., Z13 = 0., Z20 = 0., Z21 = 0., Z22 = 0., // Z23,Z30,Z31,Z32,Z33,ZXDI,ZXYDI,ZYDI,ZZ0,ZZ1,ZZ2; Z23 = 0., Z30 = 0., Z31 = 0., Z32 = 0., Z33 = 0., ZXDI = 0., ZXYDI = 0., ZYDI = 0.0; int IPEX, IPEY, IX0, IX1, IX2, IX3, IY0, IY1, IY2, IY3, NX0, NY0; int NXDF, NYDF; // input matrix dimensions //* .. Local Arrays . double B00XA[4], B00YA[4], B01A[4], B10A[4], CXA[3][4], CYA[3][4], SXA[4], SXXA[4], SYA[4], SYYA[4], XA[3][4], YA[3][4], Z0IA[3][4], ZI0A[3][4]; int IDLT[3][4] = {{-3, -2, -1, 1}, {-2, -1, 1, 2}, {-1, 1, 2, 3}}; //* Statement Function definitions #define Z2F(XX1, XX2, ZZ0, ZZ1) ((ZZ1 - ZZ0) * XX2 / XX1 + ZZ0) #define Z3F(XX1, XX2, XX3, ZZ0, ZZ1, ZZ2) \ (((ZZ2 - ZZ0) * (XX3 - XX1) / XX2 - (ZZ1 - ZZ0) * (XX3 - XX2) / XX1) * (XX3 / (XX2 - XX1)) + ZZ0) //* Initial setting of some local variables NXDF = this->matrix_.columns(); NYDF = this->matrix_.rows(); NX0 = std::max((int)4, NXDF); NY0 = std::max((int)4, NYDF); //* Double DO-loop with respect to the input grid points for (IY0 = 0; IY0 < NYDF; IY0++) { for (IX0 = 0; IX0 < NXDF; IX0++) { // Check for missing values if (missingValues_) { if (CheckMissingValues(IX0, IY0) == 0) { WKZX_[IY0][IX0] = missing(); WKZY_[IY0][IX0] = missing(); WKZXY_[IY0][IX0] = missing(); continue; } } X0 = this->matrix_.regular_column(IX0); Y0 = this->matrix_.regular_row(IY0); Z00 = this->matrix_(IY0, IX0); // Z00 = this->matrix_.operator()(IY0,IX0); //also valid //* Part 1. Estimation of ZXDI //* Initial setting SMPEF = 0.0; SMWTF = 0.0; SMPEI = 0.0; SMWTI = 0.0; //* DO-loop with respect to the primary estimate for (IPEX = 0; IPEX < 4; IPEX++) { //* Selects necessary grid points in the x direction IX1 = IX0 + IDLT[0][IPEX]; IX2 = IX0 + IDLT[1][IPEX]; IX3 = IX0 + IDLT[2][IPEX]; if ((IX1 < 0) || (IX2 < 0) || (IX3 < 0) || (IX1 >= NX0) || (IX2 >= NX0) || (IX3 >= NX0)) continue; //* Selects and/or supplements the x and z values X1 = this->matrix_.regular_column(IX1) - X0; Z10 = this->matrix_(IY0, IX1); if (NXDF >= 4) { X2 = this->matrix_.regular_column(IX2) - X0; X3 = this->matrix_.regular_column(IX3) - X0; Z20 = this->matrix_(IY0, IX2); Z30 = this->matrix_(IY0, IX3); } else if (NXDF == 3) { X2 = this->matrix_.regular_column(IX2) - X0; Z20 = this->matrix_(IY0, IX2); X3 = 2 * this->matrix_.regular_column(2) - this->matrix_.regular_column(1) - X0; Z30 = Z3F(X1, X2, X3, Z00, Z10, Z20); } else if (NXDF == 2) { X2 = 2 * this->matrix_.regular_column(1) - this->matrix_.regular_column(0) - X0; Z20 = Z2F(X1, X2, Z00, Z10); X3 = 2 * this->matrix_.regular_column(0) - this->matrix_.regular_column(1) - X0; Z30 = Z2F(X1, X3, Z00, Z10); } DZX10 = (Z10 - Z00) / X1; DZX20 = (Z20 - Z00) / X2; DZX30 = (Z30 - Z00) / X3; //* Calculates the primary estimate of partial derivative zx as //* the coefficient of the bicubic polynomial CX1 = X2 * X3 / ((X1 - X2) * (X1 - X3)); CX2 = X3 * X1 / ((X2 - X3) * (X2 - X1)); CX3 = X1 * X2 / ((X3 - X1) * (X3 - X2)); PEZX = CX1 * DZX10 + CX2 * DZX20 + CX3 * DZX30; //* Calculates the volatility factor and distance factor in the x //* direction for the primary estimate of zx SX = X1 + X2 + X3; SZ = Z00 + Z10 + Z20 + Z30; SXX = X1 * X1 + X2 * X2 + X3 * X3; SXZ = X1 * Z10 + X2 * Z20 + X3 * Z30; DNM = 4.0 * SXX - SX * SX; B00 = (SXX * SZ - SX * SXZ) / DNM; B10 = (4.0 * SXZ - SX * SZ) / DNM; DZ00 = Z00 - B00; DZ10 = Z10 - (B00 + B10 * X1); DZ20 = Z20 - (B00 + B10 * X2); DZ30 = Z30 - (B00 + B10 * X3); VOLF = DZ00 * DZ00 + DZ10 * DZ10 + DZ20 * DZ20 + DZ30 * DZ30; DISF = SXX; //* Calculates the EPSLN value, which is used to decide whether or //* not the volatility factor is essentially zero EPSLN = (Z00 * Z00 + Z10 * Z10 + Z20 * Z20 + Z30 * Z30) * 1.0E-12; //* Accumulates the weighted primary estimates of zx and their weights if (VOLF > EPSLN) { //* - For a finite weight WT = 1.0 / (VOLF * DISF); SMPEF = SMPEF + WT * PEZX; SMWTF = SMWTF + WT; } else { //* - For an infinite weight SMPEI = SMPEI + PEZX; SMWTI = SMWTI + 1.0; } //* Saves the necessary values for estimating zxy XA[0][IPEX] = X1; XA[1][IPEX] = X2; XA[2][IPEX] = X3; ZI0A[0][IPEX] = Z10; ZI0A[1][IPEX] = Z20; ZI0A[2][IPEX] = Z30; CXA[0][IPEX] = CX1; CXA[1][IPEX] = CX2; CXA[2][IPEX] = CX3; SXA[IPEX] = SX; SXXA[IPEX] = SXX; B00XA[IPEX] = B00; B10A[IPEX] = B10; } // end for IPX //* Calculates the final estimate of zx if (SMWTI < 0.5) ZXDI = SMPEF / SMWTF; // When no infinite weights exist else ZXDI = SMPEI / SMWTI; // When infinite weights exist //* End of Part 1 //* Part 2. Estimation of ZYDI //* Initial setting SMPEF = 0.0; SMWTF = 0.0; SMPEI = 0.0; SMWTI = 0.0; //* DO-loop with respect to the primary estimate for (IPEY = 0; IPEY < 4; IPEY++) { //* Selects necessary grid points in the y direction IY1 = IY0 + IDLT[0][IPEY]; IY2 = IY0 + IDLT[1][IPEY]; IY3 = IY0 + IDLT[2][IPEY]; if ((IY1 < 0) || (IY2 < 0) || (IY3 < 0) || (IY1 >= NY0) || (IY2 >= NY0) || (IY3 >= NY0)) continue; //* Selects and/or supplements the y and z values Y1 = this->matrix_.regular_row(IY1) - Y0; Z01 = this->matrix_(IY1, IX0); if (NYDF >= 4) { Y2 = this->matrix_.regular_row(IY2) - Y0; Y3 = this->matrix_.regular_row(IY3) - Y0; Z02 = this->matrix_(IY2, IX0); Z03 = this->matrix_(IY3, IX0); } else if (NYDF == 3) { Y2 = this->matrix_.regular_row(IY2) - Y0; Z02 = this->matrix_(IY2, IX0); Y3 = 2 * this->matrix_.regular_row(2) - this->matrix_.regular_row(1) - Y0; Z03 = Z3F(Y1, Y2, Y3, Z00, Z01, Z02); } else if (NYDF == 2) { Y2 = 2 * this->matrix_.regular_row(1) - this->matrix_.regular_row(0) - Y0; Z02 = Z2F(Y1, Y2, Z00, Z01); Y3 = 2 * this->matrix_.regular_row(0) - this->matrix_.regular_row(1) - Y0; Z03 = Z2F(Y1, Y3, Z00, Z01); } DZY01 = (Z01 - Z00) / Y1; DZY02 = (Z02 - Z00) / Y2; DZY03 = (Z03 - Z00) / Y3; //* Calculates the primary estimate of partial derivative zy as //* the coefficient of the bicubic polynomial CY1 = Y2 * Y3 / ((Y1 - Y2) * (Y1 - Y3)); CY2 = Y3 * Y1 / ((Y2 - Y3) * (Y2 - Y1)); CY3 = Y1 * Y2 / ((Y3 - Y1) * (Y3 - Y2)); PEZY = CY1 * DZY01 + CY2 * DZY02 + CY3 * DZY03; //* Calculates the volatility factor and distance factor in the y //* direction for the primary estimate of zy SY = Y1 + Y2 + Y3; SZ = Z00 + Z01 + Z02 + Z03; SYY = Y1 * Y1 + Y2 * Y2 + Y3 * Y3; SYZ = Y1 * Z01 + Y2 * Z02 + Y3 * Z03; DNM = 4.0 * SYY - SY * SY; B00 = (SYY * SZ - SY * SYZ) / DNM; B01 = (4.0 * SYZ - SY * SZ) / DNM; DZ00 = Z00 - B00; DZ01 = Z01 - (B00 + B01 * Y1); DZ02 = Z02 - (B00 + B01 * Y2); DZ03 = Z03 - (B00 + B01 * Y3); VOLF = DZ00 * DZ00 + DZ01 * DZ01 + DZ02 * DZ02 + DZ03 * DZ03; DISF = SYY; //* Calculates the EPSLN value, which is used to decide whether or //* not the volatility factor is essentially zero EPSLN = (Z00 * Z00 + Z01 * Z01 + Z02 * Z02 + Z03 * Z03) * 1.0E-12; //* Accumulates the weighted primary estimates of zy and their weights if (VOLF > EPSLN) { //* - For a finite weight WT = 1.0 / (VOLF * DISF); SMPEF = SMPEF + WT * PEZY; SMWTF = SMWTF + WT; } else { //* - For an infinite weight SMPEI = SMPEI + PEZY; SMWTI = SMWTI + 1.0; } //* Saves the necessary values for estimating zxy YA[0][IPEY] = Y1; YA[1][IPEY] = Y2; YA[2][IPEY] = Y3; Z0IA[0][IPEY] = Z01; Z0IA[1][IPEY] = Z02; Z0IA[2][IPEY] = Z03; CYA[0][IPEY] = CY1; CYA[1][IPEY] = CY2; CYA[2][IPEY] = CY3; SYA[IPEY] = SY; SYYA[IPEY] = SYY; B00YA[IPEY] = B00; B01A[IPEY] = B01; } // end for IPEY //* Calculates the final estimate of zy if (SMWTI < 0.5) // When no infinite weights exist ZYDI = SMPEF / SMWTF; else // When infinite weights exist ZYDI = SMPEI / SMWTI; //* End of Part 2 //* Part 3. Estimation of ZXYDI //* Initial setting SMPEF = 0.0; SMWTF = 0.0; SMPEI = 0.0; SMWTI = 0.0; //* Outer DO-loops with respect to the primary estimates in the x direction for (IPEX = 0; IPEX < 4; IPEX++) { IX1 = IX0 + IDLT[0][IPEX]; IX2 = IX0 + IDLT[1][IPEX]; IX3 = IX0 + IDLT[2][IPEX]; if ((IX1 < 0) || (IX2 < 0) || (IX3 < 0) || (IX1 >= NX0) || (IX2 >= NX0) || (IX3 >= NX0)) continue; //* Retrieves the necessary values for estimating zxy in the x direction X1 = XA[0][IPEX]; X2 = XA[1][IPEX]; X3 = XA[2][IPEX]; Z10 = ZI0A[0][IPEX]; Z20 = ZI0A[1][IPEX]; Z30 = ZI0A[2][IPEX]; CX1 = CXA[0][IPEX]; CX2 = CXA[1][IPEX]; CX3 = CXA[2][IPEX]; SX = SXA[IPEX]; SXX = SXXA[IPEX]; B00X = B00XA[IPEX]; B10 = B10A[IPEX]; //* Inner DO-loops with respect to the primary estimates in the y direction for (IPEY = 0; IPEY < 4; IPEY++) { IY1 = IY0 + IDLT[0][IPEY]; IY2 = IY0 + IDLT[1][IPEY]; IY3 = IY0 + IDLT[2][IPEY]; if ((IY1 < 0) || (IY2 < 0) || (IY3 < 0) || (IY1 >= NY0) || (IY2 >= NY0) || (IY3 >= NY0)) continue; //* Retrieves the necessary values for estimating zxy in the y direction. Y1 = YA[0][IPEY]; Y2 = YA[1][IPEY]; Y3 = YA[2][IPEY]; Z01 = Z0IA[0][IPEY]; Z02 = Z0IA[1][IPEY]; Z03 = Z0IA[2][IPEY]; CY1 = CYA[0][IPEY]; CY2 = CYA[1][IPEY]; CY3 = CYA[2][IPEY]; SY = SYA[IPEY]; SYY = SYYA[IPEY]; B00Y = B00YA[IPEY]; B01 = B01A[IPEY]; //* Selects and/or supplements the z values if (NYDF >= 4) { Z11 = this->matrix_(IY1, IX1); Z12 = this->matrix_(IY2, IX1); Z13 = this->matrix_(IY3, IX1); if (NXDF >= 4) { Z21 = this->matrix_(IY1, IX2); Z22 = this->matrix_(IY2, IX2); Z23 = this->matrix_(IY3, IX2); Z31 = this->matrix_(IY1, IX3); Z32 = this->matrix_(IY2, IX3); Z33 = this->matrix_(IY3, IX3); } else if (NXDF == 3) { Z21 = this->matrix_(IY1, IX2); Z22 = this->matrix_(IY2, IX2); Z23 = this->matrix_(IY3, IX2); Z31 = Z3F(X1, X2, X3, Z01, Z11, Z21); Z32 = Z3F(X1, X2, X3, Z02, Z12, Z22); Z33 = Z3F(X1, X2, X3, Z03, Z13, Z23); } else if (NXDF == 2) { Z21 = Z2F(X1, X2, Z01, Z11); Z22 = Z2F(X1, X2, Z02, Z12); Z23 = Z2F(X1, X2, Z03, Z13); Z31 = Z2F(X1, X3, Z01, Z11); Z32 = Z2F(X1, X3, Z02, Z12); Z33 = Z2F(X1, X3, Z03, Z13); } } else if (NYDF == 3) { Z11 = this->matrix_(IY1, IX1); Z12 = this->matrix_(IY2, IX1); Z13 = Z3F(Y1, Y2, Y3, Z10, Z11, Z12); if (NXDF >= 4) { Z21 = this->matrix_(IY1, IX2); Z22 = this->matrix_(IY2, IX2); Z31 = this->matrix_(IY1, IX3); Z32 = this->matrix_(IY2, IX3); } else if (NXDF == 3) { Z21 = this->matrix_(IY1, IX2); Z22 = this->matrix_(IY2, IX2); Z31 = Z3F(X1, X2, X3, Z01, Z11, Z21); Z32 = Z3F(X1, X2, X3, Z02, Z12, Z22); } else if (NXDF == 2) { Z21 = Z2F(X1, X2, Z01, Z11); Z22 = Z2F(X1, X2, Z02, Z12); Z31 = Z2F(X1, X3, Z01, Z11); Z32 = Z2F(X1, X3, Z02, Z12); } Z23 = Z3F(Y1, Y2, Y3, Z20, Z21, Z22); Z33 = Z3F(Y1, Y2, Y3, Z30, Z31, Z32); } else if (NYDF == 2) { Z11 = this->matrix_(IY1, IX1); Z12 = Z2F(Y1, Y2, Z10, Z11); Z13 = Z2F(Y1, Y3, Z10, Z11); if (NXDF >= 4) { Z21 = this->matrix_(IY1, IX2); Z31 = this->matrix_(IY1, IX3); } else if (NXDF == 3) { Z21 = this->matrix_(IY1, IX2); Z31 = Z3F(X1, X2, X3, Z01, Z11, Z21); } else if (NXDF == 2) { Z21 = Z2F(X1, X2, Z01, Z11); Z31 = Z2F(X1, X3, Z01, Z11); } Z22 = Z2F(Y1, Y2, Z20, Z21); Z23 = Z2F(Y1, Y3, Z20, Z21); Z32 = Z2F(Y1, Y2, Z30, Z31); Z33 = Z2F(Y1, Y3, Z30, Z31); } //* Calculates the primary estimate of partial derivative zxy as //* the coefficient of the bicubic polynomial DZXY11 = (Z11 - Z10 - Z01 + Z00) / (X1 * Y1); DZXY12 = (Z12 - Z10 - Z02 + Z00) / (X1 * Y2); DZXY13 = (Z13 - Z10 - Z03 + Z00) / (X1 * Y3); DZXY21 = (Z21 - Z20 - Z01 + Z00) / (X2 * Y1); DZXY22 = (Z22 - Z20 - Z02 + Z00) / (X2 * Y2); DZXY23 = (Z23 - Z20 - Z03 + Z00) / (X2 * Y3); DZXY31 = (Z31 - Z30 - Z01 + Z00) / (X3 * Y1); DZXY32 = (Z32 - Z30 - Z02 + Z00) / (X3 * Y2); DZXY33 = (Z33 - Z30 - Z03 + Z00) / (X3 * Y3); PEZXY = CX1 * (CY1 * DZXY11 + CY2 * DZXY12 + CY3 * DZXY13) + CX2 * (CY1 * DZXY21 + CY2 * DZXY22 + CY3 * DZXY23) + CX3 * (CY1 * DZXY31 + CY2 * DZXY32 + CY3 * DZXY33); //* Calculates the volatility factor and distance factor in the x //* and y directions for the primary estimate of zxy B00 = (B00X + B00Y) / 2.0; SXY = SX * SY; SXXY = SXX * SY; SXYY = SX * SYY; SXXYY = SXX * SYY; SXYZ = X1 * (Y1 * Z11 + Y2 * Z12 + Y3 * Z13) + X2 * (Y1 * Z21 + Y2 * Z22 + Y3 * Z23) + X3 * (Y1 * Z31 + Y2 * Z32 + Y3 * Z33); B11 = (SXYZ - B00 * SXY - B10 * SXXY - B01 * SXYY) / SXXYY; DZ00 = Z00 - B00; DZ01 = Z01 - (B00 + B01 * Y1); DZ02 = Z02 - (B00 + B01 * Y2); DZ03 = Z03 - (B00 + B01 * Y3); DZ10 = Z10 - (B00 + B10 * X1); DZ11 = Z11 - (B00 + B01 * Y1 + X1 * (B10 + B11 * Y1)); DZ12 = Z12 - (B00 + B01 * Y2 + X1 * (B10 + B11 * Y2)); DZ13 = Z13 - (B00 + B01 * Y3 + X1 * (B10 + B11 * Y3)); DZ20 = Z20 - (B00 + B10 * X2); DZ21 = Z21 - (B00 + B01 * Y1 + X2 * (B10 + B11 * Y1)); DZ22 = Z22 - (B00 + B01 * Y2 + X2 * (B10 + B11 * Y2)); DZ23 = Z23 - (B00 + B01 * Y3 + X2 * (B10 + B11 * Y3)); DZ30 = Z30 - (B00 + B10 * X3); DZ31 = Z31 - (B00 + B01 * Y1 + X3 * (B10 + B11 * Y1)); DZ32 = Z32 - (B00 + B01 * Y2 + X3 * (B10 + B11 * Y2)); DZ33 = Z33 - (B00 + B01 * Y3 + X3 * (B10 + B11 * Y3)); VOLF = DZ00 * DZ00 + DZ01 * DZ01 + DZ02 * DZ02 + DZ03 * DZ03 + DZ10 * DZ10 + DZ11 * DZ11 + DZ12 * DZ12 + DZ13 * DZ13 + DZ20 * DZ20 + DZ21 * DZ21 + DZ22 * DZ22 + DZ23 * DZ23 + DZ30 * DZ30 + DZ31 * DZ31 + DZ32 * DZ32 + DZ33 * DZ33; DISF = SXX * SYY; //* Calculates EPSLN EPSLN = (Z00 * Z00 + Z01 * Z01 + Z02 * Z02 + Z03 * Z03 + Z10 * Z10 + Z11 * Z11 + Z12 * Z12 + Z13 * Z13 + Z20 * Z20 + Z21 * Z21 + Z22 * Z22 + Z23 * Z23 + Z30 * Z30 + Z31 * Z31 + Z32 * Z32 + Z33 * Z33) * 1.0E-12; //* Accumulates the weighted primary estimates of zxy and their weights if (VOLF > EPSLN) { //* - For a finite weight WT = 1.0 / (VOLF * DISF); SMPEF = SMPEF + WT * PEZXY; SMWTF = SMWTF + WT; } else { //* - For an infinite weight SMPEI = SMPEI + PEZXY; SMWTI = SMWTI + 1.0; } } // end for IPEY } // end for IPEX //* Calculates the final estimate of zxy if (SMWTI < 0.5) // When no infinite weights exist ZXYDI = SMPEF / SMWTF; else // When infinite weights exist ZXYDI = SMPEI / SMWTI; //* End of Part 3 WKZX_[IY0][IX0] = ZXDI; WKZY_[IY0][IX0] = ZYDI; WKZXY_[IY0][IX0] = ZXYDI; } // end for IX0 } // end for IY0 return; } // A 7x7 area surround the point is searched int Akima760::CheckMissingValues(int col, int lin) const { int i, j, NXDF, NYDF; //* Initial setting of some local variables NXDF = std::max(4, this->matrix_.columns()); NYDF = std::max(4, this->matrix_.rows()); // Check a 7x7 area for (i = lin - 3; i <= lin + 3; i++) { if (i < 0 || i >= NYDF) continue; for (j = col - 3; j <= col + 3; j++) { if (j < 0 || j >= NXDF) continue; if (this->matrix_(i, j) == this->matrix_.missing()) return 0; } } return 1; } #if 0 // This subroutine is obsolet, no longer needed void Akima760::rglctn(double XII, double YII, int& INXI, int& INYI) const { //* //* Location of the desired points in a rectangular grid //* (a supporting subroutine of the RGBI3P/RGSF3P subroutine package) //* //* Hiroshi Akima //* U.S. Department of Commerce, NTIA/ITS //* Version of 1995/08 //* //* This subroutine locates the desired point in a rectangular grid //* in the x-y plane. //* //* The grid lines can be unevenly spaced. //* //* The input arguments are //* NXD = number of the input-grid data points in the x //* coordinate (must be 2 or greater), //* NYDF = number of the input-grid data points in the y //* coordinate (must be 2 or greater), //* XD = array of dimension NXD containing the x coordinates //* of the input-grid data points (must be in a //* monotonic increasing order), //* YD = array of dimension NYDF containing the y coordinates //* of the input-grid data points (must be in a //* monotonic increasing order), //* XI = x coordinate of the output point to be located //* YI = y coordinate of the output point to be located //* //* The output arguments are //* INXI = integer where the interval number of the element is to be stored //* INYI = integer where the interval number of the element is to be stored //* //* The external arguments are //* NXD = number of the input-grid data points in the x //* coordinate (must be 2 or greater), //* NYDF = number of the input-grid data points in the y //* coordinate (must be 2 or greater), //* column = array of dimension NXD containing the x coordinates //* of the input-grid data points (must be in a //* monotonic increasing order), //* row = array of dimension NYDF containing the y coordinates //* of the input-grid data points (must be in a //* monotonic increasing order) //* //* The interval numbers are between 0 and NXD and between 0 and NYDF, //* respectively. //* //* This routine was adapted to C++ by Fernando Ii, 02/04 //* //* int NXDF,NYDF; // input matrix dimensions int IMD,IMN,IMX; // aixiliary variables //* Locates the output point by binary search. Determines INXI //* for which XII lies between XD(INXI) and XD(INXI+1) //??????????????????????????? // IMPORTANT IMPORTANT IMPORTANT // THE OLD FORTRAN STYLE CODE ROUTINE IS RUNNING IN // PARALLEL WITH THE C++ CODE, TO MAKE SURE THAT THE // C++ CODE IS CORRECT. REMOVE THE FORTRAN STYLE CODE // LATER. //??????????????????????????? // IX/IY POINT TO 2 POSITIONS AHEAD IN THE ARRAY BECAUSE: // 1. FORTRAN STYLE INDEX (START WITH 1, INSTEAD OF 0) // THIS IS COMPENSATE LATER IN THE CODE. // 2. ROUTINE 'lowerColumn' AND 'lowerRow' RETURNS THE // 'LOWER' VALUE INDEX, WHICH MEANS X(IX-1) OR Y(IY-1), // INSTEAD OF X(IX) OR Y(IY) NXDF = this->matrix_.columns(); NYDF = this->matrix_.rows(); int ji; if (XII <= this->matrix_.regular_column(0)) INXI = -1; else if (XII < this->matrix_.regular_column(NXDF-1)) { #if 1 // REMOVE LATER IMN = 0; IMX = NXDF-1; IMD = (IMN+IMX)/2; ll: if (XII >= this->matrix_.regular_column(IMD)) IMN = IMD; else IMX = IMD; IMD = (IMN+IMX)/2; if (IMD > IMN) goto ll; INXI = IMD; #endif ji = this->matrix_.lowerColumn(XII); #if 0 // REMOVE LATER if (JX1 != IX){ MagLog::dev()<< "SERIOUS ERROR FINDING INDEXES" << endl; return -9999999.; } #endif // MagLog::dev()<< XII << " " << INXI << " " << ji << endl; } else INXI = NXDF-1; //* Locates the output point by binary search. Determines INYI //*for which YII lies between YD(INYI) and YD(INYI+1) if (YII <= this->matrix_.regular_row(0)) INYI = -1; else if (YII < this->matrix_.regular_row(NYDF-1)) { #if 1 // REMOVE LATER IMN = 0; IMX = NYDF-1; IMD = (IMN+IMX)/2; ll1: if (YII >= this->matrix_.regular_row(IMD)) IMN = IMD; else IMX = IMD; IMD = (IMN+IMX)/2; if (IMD > IMN) goto ll1; INYI = IMD; #endif ji = this->matrix_.lowerRow(YII); #if 1 // REMOVE LATER if (ji != INYI){ MagLog::dev()<< "SERIOUS ERROR FINDING INDEXES" << ji << " " << INYI << endl; return -9999999.; } #endif // MagLog::dev()<< YII << " " << INYI << " " << ji << endl; } else INYI = NYDF-1; return; } #endif void Akima760::rgplnl(double XII, double YII, int IXDI, int IYDI, double& ZII) const { ////* ////* Polynomials for rectangular-grid bivariate interpolation and ////* surface fitting ////* (a supporting subroutine of the RGBI3P/RGSF3P subroutine package) ////* ////* Hiroshi Akima ////* U.S. Department of Commerce, NTIA/ITS ////* Version of 1995/08 ////* ////* This subroutine determines a polynomial in x and y for a rectangle ////* of the input grid in the x-y plane and calculates the z value for ////* the desired points by evaluating the polynomial for rectangular- ////* grid bivariate interpolation and surface fitting. ////* ////* The input arguments are ////* NXD = number of the input-grid data points in the x ////* coordinate (must be 2 or greater), ////* NYDF = number of the input-grid data points in the y ////* coordinate (must be 2 or greater), ////* XD = array of dimension NXDF containing the x coordinates ////* of the input-grid data points (must be in a ////* monotonic increasing order), ////* YD = array of dimension NYDF containing the y coordinates ////* of the input-grid data points (must be in a ////* monotonic increasing order), ////* ZD = two-dimensional array of dimension NXDF*NYDF ////* containing the z(x,y) values at the input-grid data ////* points, ////* PDD = three-dimensional array of dimension 3*NXDF*NYDF ////* containing the estimated zx, zy, and zxy values ////* at the input-grid data points, ////* NIP = number of the output points at which interpolation ////* is to be performed, ////* XII = x coordinate of the output point, ////* YII = y coordinate of the output points, ////* IXDXI = interval number of the input grid interval in the ////* x direction where the x coordinate of the output ////* point lie, ////* IYDI = interval number of the input grid interval in the ////* y direction where the y coordinate of the output ////* point lie. ////* ////* The output argument is ////* ZII = interpolated z value at the output point. ////* ////* This routine was adapted to C++ by Fernando Ii, 02/04 ////* ////* // // // Check for missing values: only need to check one of the three // arrays (WKZX_,WKZY_,WKZXY_), since if there is a missing value // within a 7x7 region surround the central point, all the three // arrays point to a missing value. // Variables definition double P00, P01, P02, P03, P10, P11; double P12, P13, P20, P21, P22, P23, P30, P31, P32, P33, Q0, Q1, Q2; double Q3, U, V, X0, Y0, Z00, Z01, Z0DX, Z0DY, Z10, Z11; double Z1DX, Z1DY, ZDXDY, ZX00, ZX01, ZX0DY, ZX10, ZX11; double ZX1DY, ZXY00, ZXY01, ZXY10, ZXY11, ZY00, ZY01, ZY0DX; double ZY10, ZY11, ZY1DX; double A; double B; double C; double DF; double DX; double DXSQ; double DY; double DYSQ; int IXD0, IXD1, IYD0, IYD1; int NXDF, NYDF; //* Retrieves the z and partial derivative values at the origin of //* the coordinate for the rectangle NXDF = monoColumns_; NYDF = monoRows_; IXD0 = std::max(0, IXDI); IYD0 = std::max(0, IYDI); X0 = this->matrix_.regular_column(IXD0); Y0 = this->matrix_.regular_row(IYD0); Z00 = this->matrix_(IYD0, IXD0); ZX00 = WKZX_[IYD0][IXD0]; ZY00 = WKZY_[IYD0][IXD0]; ZXY00 = WKZXY_[IYD0][IXD0]; if (ZX00 == missing()) { ZII = missing(); return; } // CHECK THESE INDEXES LATER ???????????????????????????? //* Case 1. When the rectangle is inside the data area in both the //* x and y directions if (IXDI >= 0 && IXDI < NXDF - 1 && IYDI >= 0 && IYDI < NYDF - 1) { //* Retrieves the z and partial derivative values at the other three //* vertexes of the rectangle IXD1 = IXD0 + 1; DX = this->matrix_.regular_column(IXD1) - X0; DXSQ = DX * DX; IYD1 = IYD0 + 1; DY = this->matrix_.regular_row(IYD1) - Y0; DYSQ = DY * DY; Z10 = this->matrix_(IYD0, IXD1); Z01 = this->matrix_(IYD1, IXD0); Z11 = this->matrix_(IYD1, IXD1); ZX10 = WKZX_[IYD0][IXD1]; ZX01 = WKZX_[IYD1][IXD0]; ZX11 = WKZX_[IYD1][IXD1]; ZY10 = WKZY_[IYD0][IXD1]; ZY01 = WKZY_[IYD1][IXD0]; ZY11 = WKZY_[IYD1][IXD1]; ZXY10 = WKZXY_[IYD0][IXD1]; ZXY01 = WKZXY_[IYD1][IXD0]; ZXY11 = WKZXY_[IYD1][IXD1]; if (ZX10 == missing() || ZX01 == missing() || ZX11 == missing()) { ZII = missing(); return; } //* Calculates the polynomial coefficients Z0DX = (Z10 - Z00) / DX; Z1DX = (Z11 - Z01) / DX; Z0DY = (Z01 - Z00) / DY; Z1DY = (Z11 - Z10) / DY; ZX0DY = (ZX01 - ZX00) / DY; ZX1DY = (ZX11 - ZX10) / DY; ZY0DX = (ZY10 - ZY00) / DX; ZY1DX = (ZY11 - ZY01) / DX; ZDXDY = (Z1DY - Z0DY) / DX; A = ZDXDY - ZX0DY - ZY0DX + ZXY00; B = ZX1DY - ZX0DY - ZXY10 + ZXY00; C = ZY1DX - ZY0DX - ZXY01 + ZXY00; DF = ZXY11 - ZXY10 - ZXY01 + ZXY00; P00 = Z00; P01 = ZY00; P02 = (2.0 * (Z0DY - ZY00) + Z0DY - ZY01) / DY; P03 = (-2.0 * Z0DY + ZY01 + ZY00) / DYSQ; P10 = ZX00; P11 = ZXY00; P12 = (2.0 * (ZX0DY - ZXY00) + ZX0DY - ZXY01) / DY; P13 = (-2.0 * ZX0DY + ZXY01 + ZXY00) / DYSQ; P20 = (2.0 * (Z0DX - ZX00) + Z0DX - ZX10) / DX; P21 = (2.0 * (ZY0DX - ZXY00) + ZY0DX - ZXY10) / DX; P22 = (3.0 * (3.0 * A - B - C) + DF) / (DX * DY); P23 = (-6.0 * A + 2.0 * B + 3.0 * C - DF) / (DX * DYSQ); P30 = (-2.0 * Z0DX + ZX10 + ZX00) / DXSQ; P31 = (-2.0 * ZY0DX + ZXY10 + ZXY00) / DXSQ; P32 = (-6.0 * A + 3.0 * B + 2.0 * C - DF) / (DXSQ * DY); P33 = (2.0 * (2.0 * A - B - C) + DF) / (DXSQ * DYSQ); //* Evaluates the polynomial U = XII - X0; V = YII - Y0; Q0 = P00 + V * (P01 + V * (P02 + V * P03)); Q1 = P10 + V * (P11 + V * (P12 + V * P13)); Q2 = P20 + V * (P21 + V * (P22 + V * P23)); Q3 = P30 + V * (P31 + V * (P32 + V * P33)); ZII = Q0 + U * (Q1 + U * (Q2 + U * Q3)); } //* End of Case 1 //* Case 2. When the rectangle is inside the data area in the x //* direction but outside in the y direction else if ((IXDI >= 0 && IXDI < NXDF - 1) && (IYDI < 0 || IYDI >= NYDF - 1)) { //* Retrieves the z and partial derivative values at the other //* vertex of the semi-infinite rectangle IXD1 = IXD0 + 1; DX = this->matrix_.regular_column(IXD1) - X0; DXSQ = DX * DX; Z10 = this->matrix_(IYD0, IXD1); ZX10 = WKZX_[IYD0][IXD1]; ZY10 = WKZY_[IYD0][IXD1]; ZXY10 = WKZXY_[IYD0][IXD1]; if (ZX10 == missing()) { ZII = missing(); return; } //* Calculates the polynomial coefficients Z0DX = (Z10 - Z00) / DX; ZY0DX = (ZY10 - ZY00) / DX; P00 = Z00; P01 = ZY00; P10 = ZX00; P11 = ZXY00; P20 = (2.0 * (Z0DX - ZX00) + Z0DX - ZX10) / DX; P21 = (2.0 * (ZY0DX - ZXY00) + ZY0DX - ZXY10) / DX; P30 = (-2.0 * Z0DX + ZX10 + ZX00) / DXSQ; P31 = (-2.0 * ZY0DX + ZXY10 + ZXY00) / DXSQ; //* Evaluates the polynomial U = XII - X0; V = YII - Y0; Q0 = P00 + V * P01; Q1 = P10 + V * P11; Q2 = P20 + V * P21; Q3 = P30 + V * P31; ZII = Q0 + U * (Q1 + U * (Q2 + U * Q3)); } //* End of Case 2 //* Case 3. When the rectangle is outside the data area in the x //* direction but inside in the y direction else if ((IXDI < 0 || IXDI >= NXDF - 1) && (IYDI >= 0 && IYDI < NYDF - 1)) { //* Retrieves the z and partial derivative values at the other //* vertex of the semi-infinite rectangle IYD1 = IYD0 + 1; DY = this->matrix_.regular_row(IYD1) - Y0; DYSQ = DY * DY; Z01 = this->matrix_(IYD1, IXD0); ZX01 = WKZX_[IYD1][IXD0]; ZY01 = WKZY_[IYD1][IXD0]; ZXY01 = WKZXY_[IYD1][IXD0]; if (ZX01 == missing()) { ZII = missing(); return; } //* Calculates the polynomial coefficients Z0DY = (Z01 - Z00) / DY; ZX0DY = (ZX01 - ZX00) / DY; P00 = Z00; P01 = ZY00; P02 = (2.0 * (Z0DY - ZY00) + Z0DY - ZY01) / DY; P03 = (-2.0 * Z0DY + ZY01 + ZY00) / DYSQ; P10 = ZX00; P11 = ZXY00; P12 = (2.0 * (ZX0DY - ZXY00) + ZX0DY - ZXY01) / DY; P13 = (-2.0 * ZX0DY + ZXY01 + ZXY00) / DYSQ; //* Evaluates the polynomial U = XII - X0; V = YII - Y0; Q0 = P00 + V * (P01 + V * (P02 + V * P03)); Q1 = P10 + V * (P11 + V * (P12 + V * P13)); ZII = Q0 + U * Q1; } //* End of Case 3 //* Case 4. When the rectangle is outside the data area in both the //* x and y direction else if ((IXDI < 0 || IXDI >= NXDF - 1) && (IYDI < 0 || IYDI >= NYDF - 1)) { //* Calculates the polynomial coefficients P00 = Z00; P01 = ZY00; P10 = ZX00; P11 = ZXY00; //* Evaluates the polynomial U = XII - X0; V = YII - Y0; Q0 = P00 + V * P01; Q1 = P10 + V * P11; ZII = Q0 + U * Q1; } //* End of Case 4 return; } double Akima760::rgbi3p(double XI, double YI) const { //* //* Rectangular-grid bivariate interpolation //* (a master subroutine of the RGBI3P/RGSF3P subroutine package) //* //* Hiroshi Akima //* U.S. Department of Commerce, NTIA/ITS //* Version of 1995/08 //* //* This subroutine performs interpolation of a bivariate function, //* z(x,y), on a rectangular grid in the x-y plane. It is based on //* the revised Akima method. //* //* In this subroutine, the interpolating function is a piecewise //* function composed of a set of bicubic (bivariate third-degree) //* polynomials, each applicable to a rectangle of the input grid //* in the x-y plane. Each polynomial is determined locally. //* //* This subroutine has the accuracy of a bicubic polynomial, i.e., //* it interpolates accurately when all data points lie on a //* surface of a bicubic polynomial. //* //* The grid lines can be unevenly spaced. //* //* The input arguments are //* MD = mode of computation //* = 1 for new XD, YD, or ZD data (default) //* = 2 for old XD, YD, and ZD data, //* NXDF = number of the input-grid data points in the x //* coordinate (must be 2 or greater), //* NYDF = number of the input-grid data points in the y //* coordinate (must be 2 or greater), //* XD = array of dimension NXDF containing the x coordinates //* of the input-grid data points (must be in a //* monotonic increasing order), //* YD = array of dimension NYDF containing the y coordinates //* of the input-grid data points (must be in a //* monotonic increasing order), //* ZD = two-dimensional array of dimension NXDF*NYDF //* containing the z(x,y) values at the input-grid data //* points, //* NIP = number of the output points at which interpolation //* of the z value is desired (must be 1 or greater), //* XI = array of dimension NIP containing the x coordinates //* of the output points, //* YI = array of dimension NIP containing the y coordinates //* of the output points. //* //* The output arguments are //* ZI = array of dimension NIP where the interpolated z //* values at the output points are to be stored, //* IER = error flag //* = 0 for no errors //* = 1 for NXDF = 1 or less //* = 2 for NYDF = 1 or less //* = 3 for identical XD values or //* XD values out of sequence //* = 4 for identical YD values or //* YD values out of sequence //* = 5 for NIP = 0 or less. //* //* The other argument is //* WK = three dimensional array of dimension 3*NXDF*NYDF used //* internally as a work area. //* //* The very fisrt call to this subroutine and the call with a new //* XD, YD, and ZD array must be made with MD=1. The call with MD=2 //* must be preceded by another call with the same XD, YD, and ZD //* arrays. Between the call with MD=2 and its preceding call, the //* WK array must not be disturbed. //* //* The constant in the PARAMETER statement below is //* NIPIMX = maximum number of output points to be processed //* at a time. //* The constant value has been selected empirically. //* //* This subroutine calls the RGLCTN and RGPLNL subroutines. //* //* This routine was adapted to C++ by Fernando Ii, 02/04 //* //* Specification statements //* .. Parameters .. // //* .. Scalar Arguments .. // int IER,MD,NIP,NXDF,NYDF; //* .. Array Arguments .. // double WK[NYDF][NXDF][3],XD[NXDF],XI[NIP],YD[NYDF],YI[NIP], // ZD[NYDF][NXDF],ZI[NIP]; int INXI, INYI; // input point double ZI; // interpolated value // Locates the output point // It is not called anymore, but it is kept here // for test purpose // int col, row; // rglctn(XI,YI,col,row ); if (XI <= this->matrix_.regular_column(0)) INXI = -1; else if (XI < this->matrix_.regular_column(this->matrix_.columns() - 1)) INXI = this->matrix_.lowerColumn(XI); else INXI = this->matrix_.columns() - 1; if (YI <= this->matrix_.regular_row(0)) INYI = -1; else if (YI < this->matrix_.regular_row(this->matrix_.rows() - 1)) INYI = this->matrix_.lowerRow(YI); else INYI = this->matrix_.rows() - 1; // MagLog::dev()<< XI << " " << YI << " " << INXI << " " << INYI << " " << col << " " << row << endl; // Calculates the z values at the output point rgplnl(XI, YI, INXI, INYI, ZI); return ZI; } int Akima760::rowIndex(double row) const { map<double, int>::const_iterator i = rowsMap_.find(row); if (i != rowsMap_.end()) return (*i).second; return -1; } int Akima760::columnIndex(double row) const { map<double, int>::const_iterator i = columnsMap_.find(row); if (i != columnsMap_.end()) return (*i).second; return -1; } void Akima760::boundRow(double r, double& row1, int& index1, double& row2, int& index2) const { // unsigned int nb = rows_.size(); // first test if increasing! if (same(r, rows_.back())) { index1 = index2 = -1; row1 = row2 = rows_.back(); return; } if (rows_.back() - rows_.front() > 0) { index2 = 0; while (index2 < rows_.size() && rows_[index2] < r) { index2++; } index1 = (index2) ? index2 - 1 : 0; row1 = rows_[index1]; row2 = rows_[index2]; } else { index1 = 0; while (index1 < rows_.size() && rows_[index1] > r) { index1++; } index2 = (index1 == rows_.size() - 1) ? index1 : index1 + 1; row1 = rows_[index1]; row2 = rows_[index2]; } } void Akima760::boundColumn(double r, double& column1, int& index1, double& column2, int& index2) const { // unsigned int nb = rows_.size(); if (same(r, columns_.back())) { index1 = index2 = -1; return; } // first test if increasing! if (columns_.back() - columns_.front() > 0) { index2 = 0; while (index2 < columns_.size() && columns_[index2] < r) { index2++; } index1 = (index2) ? index2 - 1 : 0; column1 = columns_[index1]; column2 = columns_[index2]; } else { index1 = 0; while (index1 < columns_.size() && columns_[index1] > r) { index1++; } index2 = (index1 == columns_.size() - 1) ? index1 : index1 + 1; column1 = columns_[index1]; column2 = columns_[index2]; } }
39.047619
120
0.46837
dtip
72f3015cd3c5e5c58ff6aae96895e781fb045bbe
275
cpp
C++
service/src/log.cpp
SibirCTF/2016-service-loogles
0a5a834fc38c6eb8b9a19d780655b377b2c54653
[ "MIT" ]
null
null
null
service/src/log.cpp
SibirCTF/2016-service-loogles
0a5a834fc38c6eb8b9a19d780655b377b2c54653
[ "MIT" ]
null
null
null
service/src/log.cpp
SibirCTF/2016-service-loogles
0a5a834fc38c6eb8b9a19d780655b377b2c54653
[ "MIT" ]
null
null
null
#include "log.h" #include <iostream> void Log::i(QString tag, QString message){ std::cout << tag.toStdString() << " " << message.toStdString() << "\n"; } void Log::e(QString tag, QString message){ std::cerr << tag.toStdString() << " " << message.toStdString() << "\n"; }
25
72
0.618182
SibirCTF
72f8429a44a95ec4749b9e5c7bd48217e42167bc
1,051
cpp
C++
haiku/submissions/time_limit_exceeded/js1.cpp
jsannemo/hiq-challenge-2017
8271c716fe249674d585731f472b64616370300a
[ "Apache-2.0" ]
null
null
null
haiku/submissions/time_limit_exceeded/js1.cpp
jsannemo/hiq-challenge-2017
8271c716fe249674d585731f472b64616370300a
[ "Apache-2.0" ]
null
null
null
haiku/submissions/time_limit_exceeded/js1.cpp
jsannemo/hiq-challenge-2017
8271c716fe249674d585731f472b64616370300a
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for(int i = a; i < (b); ++i) #define trav(a, x) for(auto& a : x) #define all(x) x.begin(), x.end() #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; unordered_set<string> has; bool rec(const string& line, int at, int left) { if (at == sz(line)) return !left; if (line[at] == ' ') return rec(line, at + 1, left); rep(i,1,min(8, sz(line) - at + 1)) { if (has.find(line.substr(at, i)) != has.end() && rec(line, at + i, left - 1)) return true; } return false; } int main() { cin.sync_with_stdio(0); cin.tie(0); cin.exceptions(cin.failbit); int S; cin >> S; rep(i,0,S) { string syl; cin >> syl; has.insert(syl); } cin.ignore(); vi want = {5, 7, 5}; rep(i,0,3) { string s; getline(cin, s); if (!rec(s, 0, want[i])) goto die; } cout << "haiku" << endl; return 0; die: cout << "come back next year" << endl; }
22.361702
98
0.532826
jsannemo
72f979d27bb89787db23fcd6df1ca466cf339883
315
hpp
C++
include/kx/gui/gadget.hpp
kod-kristoff/kx
bc6ec4ad3720234ac6ae7e90343809a67c0fab27
[ "MIT" ]
null
null
null
include/kx/gui/gadget.hpp
kod-kristoff/kx
bc6ec4ad3720234ac6ae7e90343809a67c0fab27
[ "MIT" ]
null
null
null
include/kx/gui/gadget.hpp
kod-kristoff/kx
bc6ec4ad3720234ac6ae7e90343809a67c0fab27
[ "MIT" ]
null
null
null
#ifndef KX_GUI_GADGET_HPP #define KX_GUI_GADGET_HPP #include "kx/view/view_fwd.hpp" namespace kx { namespace gui { class InputMap; class Gadget { public: virtual ~Gadget(); private: InputMap * _input_map; View * _view; }; } } #endif // KX_GUI_GADGET_HPP
13.695652
33
0.609524
kod-kristoff
72f986ce1b9ac5cf5b8ad328d9f9f992f988a04d
16,776
cpp
C++
willow/src/subgraph/algo1.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/subgraph/algo1.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/subgraph/algo1.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include <popart/logging.hpp> #include <popart/subgraph/algo1.hpp> #include <popart/subgraph/match.hpp> #include <popart/subgraph/suffixtree.hpp> namespace fwtools { namespace subgraph { namespace algo1 { void Algo1Base::emplace(Match match) { // Check: // Base case where this Match is too small if (match.starts.size() <= 1 || match.length < 1) { return; } setVal(match); // Check: // Has this Match been enqueued in the past? if (everEnqueued.count(match) != 0) { return; } // Check: // Is there a currently enqueued Match which is has the same key (length + // first 5 chars) and contains all of this Match's starts. auto currentEnqueueKey = getCurrentEnqueueKey(match.starts[0], match.length); if (isDominatingEnqueued(currentEnqueueKey, match.starts)) { return; } // Check: // Is this Match subsumed by an accepted Match for (auto &acc : accepted) { if (acc.subsumes(match)) { return; } } // Checks passed, will enqueue this Match matchQueue.emplace(match); everEnqueued.emplace(match); auto found = currentlyEnqueued.find(currentEnqueueKey); if (found == currentlyEnqueued.end()) { currentlyEnqueued[currentEnqueueKey] = {match.starts}; } else { found->second.emplace(match.starts); } } Algo1Base::Algo1Base(const std::vector<int> &intSched_, int schedSize_) : intSched(intSched_), schedSize(schedSize_) { // Add to the end of sequence a "$" to // make an implicit tree into an explicit tree intSched.push_back(-1); } void Algo1Base::init() { // we insert boundaries to reduce edge condition checks. edgeLocs = {}; edgeLocs.emplace(-1000); edgeLocs.emplace(schedSize + 1000); // get internal nodes, sorted in decreasing order of length initMatches = fwtools::subgraph::suffixtree::getInternal(intSched); for (auto &m : initMatches) { bool subsumed = false; for (auto &mInQueue : everEnqueued) { if (mInQueue.subsumes(m)) { subsumed = true; break; } } // if it subsumed, it will be generated later if needed if (!subsumed) { setVal(m); emplace(m); } } } std::vector<Match> Algo1Base::getPreThresholded() { while (!matchQueue.empty()) { auto match = matchQueue.top(); // remove Match from queue matchQueue.pop(); auto currentEnqueueKey = getCurrentEnqueueKey(match.starts[0], match.length); currentlyEnqueued[currentEnqueueKey].erase(match.starts); if (currentlyEnqueued[currentEnqueueKey].size() == 0) { currentlyEnqueued.erase(currentEnqueueKey); } // Check if this Match is a valid addition to accepted, // generating smaller Matches where appropriate // if not a valid addition. process(match); } std::reverse(accepted.begin(), accepted.end()); return accepted; } bool Algo1Base::noCrossingsWithAccepted(const Match &match) { // Check for crossings with already accepted matches. // Consider an interval of length 4: // .....XXXX.... // .....^^^..... // the region to check for crosses in // .....012..... // ...-1...3.... // // s0---^ // ^---- s0 + length - 2 // we check if any indexes stored in edgeLocs are any of the ^^^ indices if (match.length == 1) { // there are no ^^^ (as the number of indices to check is length - 1) // this is not strictly necessary, as the code below does handle this case. return true; } int minFirstAbove = match.length - 1; int maxLastBelow = -1; std::vector<int> crossFreeMatches; for (int i = 0; i < match.starts.size(); ++i) { auto s0 = match.starts[i]; // first element greater than s0-1 auto firstAbove = *(edgeLocs.upper_bound(s0 - 1)) - s0; minFirstAbove = std::min<int>(minFirstAbove, firstAbove); // first element greater than s0 + length - 2 auto iter = edgeLocs.upper_bound(s0 + match.length - 2); // last element less than or equal to s0 + match.size - 2 --iter; auto lastBelow = *iter - s0; maxLastBelow = std::max<int>(maxLastBelow, lastBelow); if (firstAbove >= match.length - 1 && lastBelow < 0) { crossFreeMatches.push_back(match.starts[i]); } } if (crossFreeMatches.size() == match.starts.size()) { return true; } // Add the matches which are cross free // (keeping length, reducing match size) if (crossFreeMatches.size() > 1) { Match reduced_count(crossFreeMatches, match.length); emplace(reduced_count); } // Example: // ...........xxxxxxxxxxxxxxxxx.......... // .............^........................ // // ...........xxxxxxxxxxxxxxxxx.......... // .............^^....................... // // ...........xxxxxxxxxxxxxxxxx.......... // ............^.^....................... // // ...........xxxxxxxxxxxxxxxxx.......... // .................^.^.................. // ^-- s0 + length - 1 // ^------------------ s0 // ^----------------- minFirstAbove // ^---------- maxLastBelow // Match left_child(match.starts, maxLastBelow + 1); emplace(left_child); int right_length = match.length - 1 - minFirstAbove; std::vector<int> right_child_starts(match.starts); for (auto &x : right_child_starts) { x += (match.length - right_length); } Match right_child(right_child_starts, right_length); emplace(right_child); return false; } bool Algo1Base::allIsomorphic(const Match &match) { // if not all isomorphic, try left and right int min_delta = match.length; for (int i = 1; i < match.starts.size(); ++i) { int this_delta = isoTil(match.length, match.starts[0], match.starts[i]); min_delta = std::min<int>(min_delta, this_delta); } if (min_delta == match.length) { return true; } if (match.length > 1) { // For now, adding tight left and tight right. // TODO (T7779) we can do better than this // (consider noCrossingsWithAccepted) Match match_left = match; match_left.length = match.length - 1; emplace(match_left); auto right_starts = match.starts; for (auto &x : right_starts) { x += 1; } Match match_right(right_starts, match.length - 1); emplace(match_right); } // adding same lengths, partitioned into isomorphisms for (auto &partitioned_match : partitionedByIsomorphism(match)) { if (partitioned_match.starts.size() > 1) { emplace(partitioned_match); } } // also adding shifted to right if the next chars the same bool final_chars_equiv = true; for (auto &s : match.starts) { if ((s + match.length >= schedSize) || (intSched[s + match.length] != intSched[match.starts[0] + match.length])) { final_chars_equiv = false; break; } } if (final_chars_equiv) { Match shift_right = match; for (auto &x : shift_right.starts) { ++x; } emplace(shift_right); } return false; } Algo1Base::CurrentEnqueueKey Algo1Base::getCurrentEnqueueKey(Start s0, int len) { CurrentEnqueueKey key; for (int i = 0; i < std::get<1>(key).size(); ++i) { std::get<1>(key)[i] = -7; } for (int i = 0; i < std::min<int>(len, static_cast<int>(std::get<1>(key).size())); ++i) { std::get<1>(key)[i] = intSched[s0 + i]; } std::get<0>(key) = len; return key; } // is there an enqueued Match of length at least "l0", and // starting indices which are a superset of "starts" bool Algo1Base::isDominatingEnqueued(const CurrentEnqueueKey &key, const std::vector<Start> &starts) { auto found = currentlyEnqueued.find(key); if (found == currentlyEnqueued.end()) { return false; } // going through the enqueued vectors in order of // decreasing number of starts for (auto iter = found->second.rbegin(); iter != found->second.rend(); ++iter) { if (iter->size() < starts.size()) { break; } if (firstContainsSecond(*iter, starts)) { return true; } } return false; } bool Algo1Base::noOverlapping(const Match &match) { // If overlapping, try emplacing smaller sub-Matches. // all distances between overlapping Matches: std::set<int> interStartDistances; for (int i = 1; i < match.starts.size(); ++i) { for (int j = i - 1; j >= 0; --j) { auto delta = match.starts[i] - match.starts[j]; if (delta >= match.length) { break; } interStartDistances.emplace(delta); } } // The case where there are no overlaps if (interStartDistances.size() == 0) { return true; } int maxInterStartDistance = *interStartDistances.rbegin(); // We will be creating non-overlapping Matches for each of the lengths // in interStartDistances. But first, we check for an early exit option: // Is there an enqueued Match which is not-shorter than // maxInterStartDistance, and contains all the starts of this Match? auto cekey = getCurrentEnqueueKey(match.starts[0], maxInterStartDistance); // Is an early exit if (isDominatingEnqueued(cekey, match.starts)) { interStartDistances = {}; } // No early exit else { } // Irrespective of the early exit clause, process the case // of retaining the full match length if (match.starts.back() - match.starts[0] >= match.length) { interStartDistances.emplace(match.length); } // Of all the accepted matches whose intervals contain // all of the starts in match, which one has // the most starts? There may be no such accepted matches. Match best_accepted({}, 2); Match this_dummy(match); this_dummy.length = 1; for (auto &acc : accepted) { if (acc.starts.size() > best_accepted.starts.size() && acc.contains(this_dummy)) { best_accepted = acc; } } // Before emplacing a new Match below, we will check that // it contains more than 2X - 1 starts than this: int containment_factor = static_cast<int>(best_accepted.starts.size()); // When partitioning a Match into non-overlapping Matches, // we greedily add starts to the first new Match it doesn't overlap with. // This generates just 1 partitioning (of exponentially many). To generate // more partitions, we consider starting the process with start indices: // [0, ... nFirstSetters) int nFirstSetters = std::min<int>(3, static_cast<int>(match.starts.size()) - 1); for (auto sub_length : interStartDistances) { // for each firstSetter, what do the matches // (up to index nFirstSetters) look like? We use // a std::set, to remove duplicates std::set<std::vector<Match>> initial_locals; std::vector<Start> initialOtherStarts = std::vector<int>( match.starts.begin() + 1, match.starts.begin() + nFirstSetters); // as we proceed through this loop, initialOtherStarts has match starts, // @iteration 0 [1,2,3,....n-1,n] // @iteration 1 [0,2,3,....n-1,n] // @iteration 2 [0,1,3,....n-1,n] // . // . // @iteration n-1 [0,1,2,....n-2,n] // @iteration n [0,1,2,....n-2, n-1] for (int firstSetter = 0; firstSetter < nFirstSetters; ++firstSetter) { if (firstSetter > 0) { initialOtherStarts[firstSetter - 1] = match.starts[firstSetter - 1]; } std::vector<Match> local = {{{match.starts[firstSetter]}, sub_length}}; completeLocalUnsorted(local, initialOtherStarts, sub_length); initial_locals.emplace(local); } std::vector<int> otherStarts = std::vector<int>( match.starts.begin() + nFirstSetters, match.starts.end()); for (auto &match_set : initial_locals) { std::vector<Match> sub_matches; for (auto m : match_set) { sub_matches.push_back(m); } completeLocalSorted(sub_matches, otherStarts, sub_length); for (auto m : sub_matches) { if (m.starts.size() >= 2 * std::max(1, containment_factor)) { emplace(m); } else { // not emplacing, as it is dominated by best_accepted } } } } return false; } void Algo1Base::completeLocalSorted(std::vector<Match> &local, const std::vector<Start> &otherStarts, int sub_length) const { for (auto &s : otherStarts) { bool matchFound = false; for (auto &m : local) { bool withinDistance = (s - m.starts.back()) < sub_length; if (!withinDistance) { matchFound = true; m.starts.push_back(s); // break from loop over local break; } } if (matchFound == false) { local.push_back({{s}, sub_length}); } } } void Algo1Base::completeLocalUnsorted(std::vector<Match> &local, const std::vector<Start> &otherStarts, int sub_length) const { for (auto &s : otherStarts) { bool matchFound = false; for (auto &m : local) { bool withinDistance = false; for (auto s0 : m.starts) { int d0 = std::abs(s - s0); if (d0 < sub_length) { withinDistance = true; // break from loop over m.starts break; } } if (!withinDistance) { matchFound = true; m.starts.push_back(s); // break from loop over local break; } } if (matchFound == false) { local.push_back({{s}, sub_length}); } } for (auto &m : local) { std::sort(m.starts.begin(), m.starts.end()); // local.push_back(m); } } // how to process the top of the priority queue void Algo1Base::process(const Match &match) { if (match.length < 1 || match.starts.size() < 2) { // base case return; } if (match.getDiscountedValue() < 0.0) { // match has negative value popart::logging::trace( "[RINSE Algo1] Negative discounted value: {} (value: {}, length: {})", match.getDiscountedValue(), match.getValue(), match.length); // Child matches can have a higher subgraph value than the parent match auto left_starts = match.starts; auto right_starts = match.starts; for (size_t i = 0; i < right_starts.size(); ++i) { ++right_starts[i]; } Match left_child(left_starts, match.length - 1); Match right_child(right_starts, match.length - 1); emplace(left_child); emplace(right_child); return; } for (auto &acc : accepted) { if (acc.length == match.length && acc.startsIntersect(match.starts)) { // same length as accepted with intersecting starts popart::logging::trace("[RINSE Algo1] Intersecting starts, same length."); return; } // if "subsumed", discard this match, // don't generate smaller cases as // they will also be subsumed if (acc.subsumes(match)) { popart::logging::trace("[RINSE Algo1] Subsumed."); return; } if (acc.contains(match) && (2 * acc.starts.size() > match.starts.size())) { // contained by accepted with at least 1/2X the starts popart::logging::trace("[RINSE Algo1] Contained (1/2x starts)."); return; } } if (!noCrossingsWithAccepted(match)) { popart::logging::trace("[RINSE Algo1] Crossing."); return; } if (!noOverlapping(match)) { popart::logging::trace("[RINSE Algo1] Overlapping."); return; } if (!allIsomorphic(match)) { popart::logging::trace("[RINSE Algo1] Not isomorphic."); return; } for (auto &acc : accepted) { if (acc.intersects(match)) { popart::logging::trace("[RINSE Algo1] Intersects."); // the only type of intersection which can be // accepted is a "clean fit" (see definition) if (!acc.fitsCleanly(match)) { // contained but not cleanly popart::logging::trace("[RINSE Algo1] Not contained cleanly."); return; } } } popart::logging::trace( "[RINSE Algo1] Accepting [{}, [{}]]", match.length, popart::logging::join(match.starts.begin(), match.starts.end(), ", ")); accepted.push_back(match); if (match.length > 1) { for (auto &s0 : match.starts) { edgeLocs.emplace(s0 - 1); edgeLocs.emplace(s0 + match.length - 1); } } } std::vector<int> getSequenceBreaks(const std::vector<std::pair<size_t, size_t>> &sequences_) { std::vector<int> breaks(sequences_.size() + 1); for (auto &seq : sequences_) { if (seq.second - seq.first > 1) { ++breaks.at(seq.first); ++breaks.at(seq.second); } } for (size_t i = 1; i < breaks.size(); ++i) { breaks[i] += breaks[i - 1]; } return breaks; } } // namespace algo1 } // namespace subgraph } // namespace fwtools
28.433898
80
0.606998
gglin001
72fbaee8098ffe01eb5148f295cc0fabc31cab62
3,523
cpp
C++
MCGIDI/Test/productIndices/productAverageMultiplicities.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
MCGIDI/Test/productIndices/productAverageMultiplicities.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
MCGIDI/Test/productIndices/productAverageMultiplicities.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
/* # <<BEGIN-copyright>> # Copyright 2019, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # <<END-copyright>> */ #include <stdlib.h> #include <iostream> #include <iomanip> #include <set> #include "MCGIDI.hpp" #include "GIDI_testUtilities.hpp" static char const *description = "Loops over energy, reaction and particle ids, printing the multiplicity for each particle."; void main2( int argc, char **argv ); /* ========================================================= */ int main( int argc, char **argv ) { try { main2( argc, argv ); } catch (std::exception &exception) { std::cerr << exception.what( ) << std::endl; exit( EXIT_FAILURE ); } catch (char const *str) { std::cerr << str << std::endl; exit( EXIT_FAILURE ); } catch (std::string &str) { std::cerr << str << std::endl; exit( EXIT_FAILURE ); } exit( EXIT_SUCCESS ); } /* ========================================================= */ void main2( int argc, char **argv ) { PoPI::Database pops; argvOptions argv_options( __FILE__, description ); ParseTestOptions parseTestOptions( argv_options, argc, argv ); parseTestOptions.parse( ); GIDI::Construction::Settings construction( GIDI::Construction::ParseMode::all, parseTestOptions.photonMode( ) ); GIDI::Protare *protare = parseTestOptions.protare( pops, "../../../GIDI/Test/pops.xml", "../../../GIDI/Test/Data/MG_MC/all_maps.map", construction, PoPI::IDs::neutron, "O16" ); std::cout << " " << stripDirectoryBase( protare->fileName( ) ) << std::endl; GIDI::Styles::TemperatureInfos temperatures = protare->temperatures( ); std::string label( temperatures[0].heatedCrossSection( ) ); MCGIDI::Transporting::MC settings( pops, protare->projectile( ).ID( ), &protare->styles( ), label, GIDI::Transporting::DelayedNeutrons::on, 20.0 ); GIDI::Transporting::Particles particles; GIDI::Transporting::Particle neutron( PoPI::IDs::neutron ); particles.add( neutron ); GIDI::Transporting::Particle photon( PoPI::IDs::photon ); particles.add( photon ); MCGIDI::DomainHash domainHash( 4000, 1e-8, 10 ); std::set<int> reactionsToExclude; MCGIDI::Protare *MCProtare = MCGIDI::protareFromGIDIProtare( *protare, pops, settings, particles, domainHash, temperatures, reactionsToExclude ); for( double energy = 2e-11; energy < 21.0; energy *= 1e3 ) { std::cout << std::endl << " energy = " << doubleToString( "%14.6e", energy ) << std::endl; for( std::size_t reactionIndex = 0; reactionIndex < MCProtare->numberOfReactions( ); ++reactionIndex ) { MCGIDI::Reaction const *reaction = MCProtare->reaction( reactionIndex ); std::cout << " " << reaction->label( ).c_str( ) << std::endl; auto indices = reaction->productIndices( ); for( MCGIDI_VectorSizeType productIndex = 0; productIndex < indices.size( ); ++productIndex ) { int index = indices[productIndex]; PoPI::Particle const &particle = pops.get<PoPI::Particle>( index ); std::cout << " " << std::left << std::setw( 10 ) << particle.ID( ) << " " << std::setw( 5 ) << index << " " << doubleToString( "%14.6e", reaction->productAverageMultiplicity( index, energy ) ) << std::endl; } } } delete MCProtare; delete protare; }
36.319588
151
0.600624
Mathnerd314
72fd6a23da1e678d99fdd25220a3f160f47805be
1,031
cpp
C++
modules/bio_format/corrected_reads.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
16
2021-07-14T23:32:31.000Z
2022-03-24T16:25:15.000Z
modules/bio_format/corrected_reads.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-20T20:39:47.000Z
2021-09-16T20:57:59.000Z
modules/bio_format/corrected_reads.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-15T19:38:35.000Z
2022-01-31T19:24:56.000Z
#include "modules/bio_format/corrected_reads.h" #include "modules/bio_base/corrected_read.h" #include "modules/io/log.h" #include "modules/io/registry.h" #include <boost/format.hpp> REGISTER_3(exporter, corrected_reads, writable&, bool, const std::string&); void corrected_reads_exporter::write(const std::string& key, const std::string& value) { std::string name; corrected_reads the_reads; msgpack_deserialize(name, key); msgpack_deserialize(the_reads, value); for(size_t i = 0; i < the_reads.size(); i++) { const corrected_read& the_read = the_reads[i]; std::string a_line = boost::str(boost::format("%1%\t%2%\t%3%\t%4%\t%5%\n") //boost::str(boost::format("%1%\t%2%\t%3%\t%4%\t%5%\t%6%\t%7%\t%8%\n") % name % the_read.sequence.as_string() % the_read.corrected.as_string() % the_read.quality % the_read.trace_me ) ; m_sink.write(a_line.c_str(), a_line.size()); //m_sink.print("@%s\n%s\n+\n%s\n", name.c_str(), the_read.corrected.as_string().c_str(), the_read.quality.c_str()); } }
30.323529
117
0.683802
spiralgenetics
72fe0f933d4d81e493dcce8390c0bb2d8df81482
7,838
cpp
C++
cpp/tests/strings/chars_types_tests.cpp
IbrahimBRammaha/cudf
57ddd5ed0cd7a24500adfc208a08075843f70979
[ "Apache-2.0" ]
1
2020-04-18T23:47:25.000Z
2020-04-18T23:47:25.000Z
cpp/tests/strings/chars_types_tests.cpp
benfred/cudf
3cd4c9f0602840dddb9a0e247d5a0bcf3d7266e1
[ "Apache-2.0" ]
null
null
null
cpp/tests/strings/chars_types_tests.cpp
benfred/cudf
3cd4c9f0602840dddb9a0e247d5a0bcf3d7266e1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019-2020, NVIDIA CORPORATION. * * 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 <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/strings/char_types/char_types.hpp> #include <tests/utilities/base_fixture.hpp> #include <tests/utilities/column_wrapper.hpp> #include <tests/utilities/column_utilities.hpp> #include <tests/strings/utilities.h> #include <vector> struct StringsCharsTest : public cudf::test::BaseFixture {}; class StringsCharsTestTypes : public StringsCharsTest, public testing::WithParamInterface<cudf::strings::string_character_types> {}; TEST_P(StringsCharsTestTypes, AllTypes) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; bool expecteds[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, // decimal 0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0, // numeric 0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0, // digit 1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0, // alpha 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, // space 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, // upper 0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0 }; // lower auto is_parm = GetParam(); cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto results = cudf::strings::all_characters_of_type(strings_view,is_parm); int x = static_cast<int>(is_parm); int index = 0; int strings_count = static_cast<int>(h_strings.size()); while( x >>= 1 ) ++index; bool* sub_expected = &expecteds[index * strings_count]; cudf::test::fixed_width_column_wrapper<bool> expected( sub_expected, sub_expected + strings_count, thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } INSTANTIATE_TEST_CASE_P(StringsCharsTestAllTypes, StringsCharsTestTypes, testing::ValuesIn(std::array<cudf::strings::string_character_types,7> { cudf::strings::string_character_types::DECIMAL, cudf::strings::string_character_types::NUMERIC, cudf::strings::string_character_types::DIGIT, cudf::strings::string_character_types::ALPHA, cudf::strings::string_character_types::SPACE, cudf::strings::string_character_types::UPPER, cudf::strings::string_character_types::LOWER })); TEST_F(StringsCharsTest, LowerUpper) { cudf::test::strings_column_wrapper strings( {"a1","A1","a!","A!","!1","aA"} ); auto strings_view = cudf::strings_column_view(strings); auto verify_types = cudf::strings::string_character_types::LOWER | cudf::strings::string_character_types::UPPER; { auto results = cudf::strings::all_characters_of_type(strings_view, cudf::strings::string_character_types::LOWER, verify_types); cudf::test::fixed_width_column_wrapper<bool> expected( {1,0,1,0,0,0} ); cudf::test::expect_columns_equal(*results,expected); } { auto results = cudf::strings::all_characters_of_type(strings_view, cudf::strings::string_character_types::UPPER, verify_types); cudf::test::fixed_width_column_wrapper<bool> expected( {0,1,0,1,0,0} ); cudf::test::expect_columns_equal(*results,expected); } } TEST_F(StringsCharsTest, Alphanumeric) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto results = cudf::strings::all_characters_of_type(strings_view,cudf::strings::string_character_types::ALPHANUM); std::vector<bool> h_expected{ 1,1,0,1,0,0,0,0,0,1,1,1,0,1,1,0 }; cudf::test::fixed_width_column_wrapper<bool> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } TEST_F(StringsCharsTest, AlphaNumericSpace) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto types = cudf::strings::string_character_types::ALPHANUM | cudf::strings::string_character_types::SPACE; auto results = cudf::strings::all_characters_of_type(strings_view, (cudf::strings::string_character_types)types); std::vector<bool> h_expected{ 1,1,0,1,1,0,0,0,0,1,1,1,1,1,1,1 }; cudf::test::fixed_width_column_wrapper<bool> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } TEST_F(StringsCharsTest, Numerics) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto types = cudf::strings::string_character_types::DIGIT | cudf::strings::string_character_types::DECIMAL | cudf::strings::string_character_types::NUMERIC; auto results = cudf::strings::all_characters_of_type(strings_view, (cudf::strings::string_character_types)types); std::vector<bool> h_expected{ 0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0 }; cudf::test::fixed_width_column_wrapper<bool> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } TEST_F(StringsCharsTest, EmptyStringsColumn) { cudf::column_view zero_size_strings_column( cudf::data_type{cudf::STRING}, 0, nullptr, nullptr, 0); auto strings_view = cudf::strings_column_view(zero_size_strings_column); auto results = cudf::strings::all_characters_of_type(strings_view,cudf::strings::string_character_types::ALPHANUM); auto view = results->view(); EXPECT_EQ(cudf::BOOL8, view.type().id()); EXPECT_EQ(0,view.size()); EXPECT_EQ(0,view.null_count()); EXPECT_EQ(0,view.num_children()); }
47.216867
119
0.666114
IbrahimBRammaha
f4013b1436ccb84c56d4c239ae243343fd6a9ede
2,627
cpp
C++
usystem/tests/kernel_api_tests/src/pgrp.cpp
heatd/Onyx
404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d
[ "MIT" ]
44
2017-02-16T20:48:09.000Z
2022-03-14T17:58:57.000Z
usystem/tests/kernel_api_tests/src/pgrp.cpp
heatd/Onyx
404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d
[ "MIT" ]
72
2017-02-16T20:22:10.000Z
2022-03-31T21:17:06.000Z
usystem/tests/kernel_api_tests/src/pgrp.cpp
heatd/Onyx
404fce9c89a1d4ab561b5be63bd9bc68a6c9d91d
[ "MIT" ]
10
2017-04-07T19:20:14.000Z
2021-12-16T03:31:14.000Z
/* * Copyright (c) 2020 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <unistd.h> #include <fcntl.h> #include <gtest/gtest.h> #include <cstring> #include <sys/wait.h> #include <string> #include "../include/child_process_helper.h" #include <limits> TEST(SetPgrpTest, WorksForSelf) { auto pid = getpid(); ASSERT_NE(pid, -1); ASSERT_EQ(setpgid(0, 0), 0); ASSERT_EQ(getpgid(0), pid); } TEST(SetPgrpTest, WorksForChild) { ChildProcessHelper h; auto status = h([](const ChildProcessHelper& context) { setpgid(context.pid, context.pid); EXPECT_EQ(getpgid(context.pid), context.pid); }, [](const ChildProcessHelper& context) -> int { return getpgid(0) == getpid(); }); EXPECT_EQ(status, true); } TEST(SetPgrpTest, HandlesBadPids) { EXPECT_EQ(setpgid(1, 0), -1); EXPECT_EQ(errno, ESRCH); /* Ugh, PRAY THAT WE HAVEN'T WRAPPED PIDS WHEN WE RUN THIS */ /* Why is there no permanently invalid pid that isn't 0? :(((( */ EXPECT_EQ(setpgid(std::numeric_limits<pid_t>::max(), 0), -1); EXPECT_EQ(errno, ESRCH); } TEST(SetPgrpTest, HandlesChildExec) { ChildProcessHelper h; Waiter child_out; auto status = h([&](const ChildProcessHelper& context) { }, [&](const ChildProcessHelper& context) -> int { const auto &w = context.w; w.RemapToStdin(); child_out.RemapToStdout(); w.Close(); child_out.Close(); if(execlp("cat", "cat", NULL) < 0) { return -127; } return 0; }, [&](const ChildProcessHelper& context) { const auto &w = context.w; child_out.CloseWriteEnd(); /* cat will echo our stuff when it sees the newline - it's a way for us to know for * sure it has been exec'd. */ w.Write("Test\n", strlen("Test\n")); child_out.Wait(); EXPECT_EQ(setpgid(context.pid, context.pid), -1); EXPECT_EQ(errno, EACCES); w.Close(); }); } TEST(SetPgrpTest, HandlesNegativeInput) { EXPECT_EQ(setpgid(0, -1), -1); EXPECT_EQ(errno, EINVAL); } TEST(SetPgrpTest, HandlesEPerm) { // Create multiple children Waiter w; Waiter parent_wake; pid_t pid = fork(); ASSERT_NE(pid, -1); if(pid == 0) { parent_wake.CloseReadEnd(); w.CloseWriteEnd(); w.Wait(); // Create a new session EXPECT_EQ(setsid(), getpid()); parent_wake.Wake(); w.Wait(); exit(0); } w.CloseReadEnd(); w.Wake(); parent_wake.Wait(); // We're in a different session // Testing all EPERMs // TODO: Add separate tests for the separate EPERM conditions? EXPECT_EQ(setpgid(pid, getpid()), -1); EXPECT_EQ(errno, EPERM); w.Wake(); wait(nullptr); }
18.243056
85
0.668824
heatd
f4028f4be7455f0dd024dc1540899f9ff825af06
12,047
cc
C++
tests/unit/machine/gp/EPInferenceMethod_unittest.cc
tallamjr/shogun
c964c9d1aab4bc1cf9133baf14d3bd5b96ba42de
[ "BSD-3-Clause" ]
2,753
2015-01-02T11:34:13.000Z
2022-03-25T07:04:27.000Z
tests/unit/machine/gp/EPInferenceMethod_unittest.cc
tallamjr/shogun
c964c9d1aab4bc1cf9133baf14d3bd5b96ba42de
[ "BSD-3-Clause" ]
2,404
2015-01-02T19:31:41.000Z
2022-03-09T10:58:22.000Z
tests/unit/machine/gp/EPInferenceMethod_unittest.cc
tallamjr/shogun
c964c9d1aab4bc1cf9133baf14d3bd5b96ba42de
[ "BSD-3-Clause" ]
1,156
2015-01-03T01:57:21.000Z
2022-03-26T01:06:28.000Z
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Roman Votyakov, Wu Lin, Pan Deng */ #include <gtest/gtest.h> #include <shogun/lib/config.h> #include <shogun/labels/BinaryLabels.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/machine/gp/EPInferenceMethod.h> #include <shogun/machine/gp/ZeroMean.h> #include <shogun/machine/gp/ProbitLikelihood.h> using namespace shogun; TEST(EPInferenceMethod,get_cholesky_probit_likelihood) { // create some easy random classification data index_t n=5; SGMatrix<float64_t> feat_train(2, n); SGVector<float64_t> lab_train(n); feat_train(0,0)=-1.07932; feat_train(0,1)=1.15768; feat_train(0,2)=3.26631; feat_train(0,3)=1.79009; feat_train(0,4)=-3.66051; feat_train(1,0)=-1.83544; feat_train(1,1)=2.91702; feat_train(1,2)=-3.85663; feat_train(1,3)=0.11949; feat_train(1,4)=1.75159; lab_train[0]=-1.0; lab_train[1]=1.0; lab_train[2]=1.0; lab_train[3]=1.0; lab_train[4]=-1.0; // shogun representation of features and labels auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto labels_train=std::make_shared<BinaryLabels>(lab_train); // choose Gaussian kernel with width = 2*2^2 and zero mean function auto kernel=std::make_shared<GaussianKernel>(10, 8.0); auto mean=std::make_shared<ZeroMean>(); // probit likelihood auto likelihood=std::make_shared<ProbitLikelihood>(); // specify GP classification with EP inference and kernel scale=1.5 auto inf=std::make_shared<EPInferenceMethod>(kernel, features_train, mean, labels_train, likelihood); inf->set_scale(1.5); // comparison of cholesky with result from GPML package SGMatrix<float64_t> L=inf->get_cholesky(); EXPECT_NEAR(L(0,0), 1.358253004928362, 1E-3); EXPECT_NEAR(L(0,1), 0.018316522108192, 1E-3); EXPECT_NEAR(L(0,2), 0.033812347702551, 1E-3); EXPECT_NEAR(L(0,3), 0.130014750307937, 1E-3); EXPECT_NEAR(L(0,4), 0.051980118062897, 1E-3); EXPECT_NEAR(L(1,0), 0.000000000000000, 1E-3); EXPECT_NEAR(L(1,1), 1.313315812622500, 1E-3); EXPECT_NEAR(L(1,2), 0.000588353671333, 1E-3); EXPECT_NEAR(L(1,3), 0.199232686436273, 1E-3); EXPECT_NEAR(L(1,4), 0.025787680602556, 1E-3); EXPECT_NEAR(L(2,0), 0.000000000000000, 1E-3); EXPECT_NEAR(L(2,1), 0.000000000000000, 1E-3); EXPECT_NEAR(L(2,2), 1.333160257955935, 1E-3); EXPECT_NEAR(L(2,3), 0.057177746824419, 1E-3); EXPECT_NEAR(L(2,4), -0.001301272388376, 1E-3); EXPECT_NEAR(L(3,0), 0.000000000000000, 1E-3); EXPECT_NEAR(L(3,1), 0.000000000000000, 1E-3); EXPECT_NEAR(L(3,2), 0.000000000000000, 1E-3); EXPECT_NEAR(L(3,3), 1.300708604766544, 1E-3); EXPECT_NEAR(L(3,4), 0.001192632066695, 1E-3); EXPECT_NEAR(L(4,0), 0.000000000000000, 1E-3); EXPECT_NEAR(L(4,1), 0.000000000000000, 1E-3); EXPECT_NEAR(L(4,2), 0.000000000000000, 1E-3); EXPECT_NEAR(L(4,3), 0.000000000000000, 1E-3); EXPECT_NEAR(L(4,4), 1.332317592760179, 1E-3); } TEST(EPInferenceMethod,get_negative_marginal_likelihood_probit_likelihood) { // create some easy random classification data index_t n=5; SGMatrix<float64_t> feat_train(2, n); SGVector<float64_t> lab_train(n); feat_train(0,0)=-1.07932; feat_train(0,1)=1.15768; feat_train(0,2)=3.26631; feat_train(0,3)=1.79009; feat_train(0,4)=-3.66051; feat_train(1,0)=-1.83544; feat_train(1,1)=2.91702; feat_train(1,2)=-3.85663; feat_train(1,3)=0.11949; feat_train(1,4)=1.75159; lab_train[0]=-1.0; lab_train[1]=1.0; lab_train[2]=1.0; lab_train[3]=1.0; lab_train[4]=-1.0; // shogun representation of features and labels auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto labels_train=std::make_shared<BinaryLabels>(lab_train); // choose Gaussian kernel with width = 2*2^2 and zero mean function auto kernel=std::make_shared<GaussianKernel>(10, 8.0); auto mean=std::make_shared<ZeroMean>(); // probit likelihood auto likelihood=std::make_shared<ProbitLikelihood>(); // specify GP classification with EP inference and kernel scale=1.5 auto inf=std::make_shared<EPInferenceMethod>(kernel, features_train, mean, labels_train, likelihood); inf->set_scale(1.5); // comparison of negative marginal likelihood with result from GPML package float64_t nlZ=inf->get_negative_log_marginal_likelihood(); EXPECT_NEAR(nlZ, 3.38359489001561, 1E-3); } TEST(EPInferenceMethod,get_alpha_probit_likelihood) { // create some easy random classification data index_t n=5; SGMatrix<float64_t> feat_train(2, n); SGVector<float64_t> lab_train(n); feat_train(0,0)=-1.07932; feat_train(0,1)=1.15768; feat_train(0,2)=3.26631; feat_train(0,3)=1.79009; feat_train(0,4)=-3.66051; feat_train(1,0)=-1.83544; feat_train(1,1)=2.91702; feat_train(1,2)=-3.85663; feat_train(1,3)=0.11949; feat_train(1,4)=1.75159; lab_train[0]=-1.0; lab_train[1]=1.0; lab_train[2]=1.0; lab_train[3]=1.0; lab_train[4]=-1.0; // shogun representation of features and labels auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto labels_train=std::make_shared<BinaryLabels>(lab_train); // choose Gaussian kernel with width = 2*2^2 and zero mean function auto kernel=std::make_shared<GaussianKernel>(10, 8.0); auto mean=std::make_shared<ZeroMean>(); // probit likelihood auto likelihood=std::make_shared<ProbitLikelihood>(); // specify GP classification with EP inference and kernel scale=1.5 auto inf=std::make_shared<EPInferenceMethod>(kernel, features_train, mean, labels_train, likelihood); inf->set_scale(1.5); // comparison of alpha with result from GPML package SGVector<float64_t> alpha=inf->get_alpha(); EXPECT_NEAR(alpha[0], -0.481804252788557, 1E-3); EXPECT_NEAR(alpha[1], 0.392192885549848, 1E-3); EXPECT_NEAR(alpha[2], 0.435105219728697, 1E-3); EXPECT_NEAR(alpha[3], 0.407811602073545, 1E-3); EXPECT_NEAR(alpha[4], -0.435104577247077, 1E-3); } TEST(EPInferenceMethod,get_marginal_likelihood_derivatives_probit_likelihood) { // create some easy random classification data index_t n=5; SGMatrix<float64_t> feat_train(2, n); SGVector<float64_t> lab_train(n); feat_train(0,0)=-1.07932; feat_train(0,1)=1.15768; feat_train(0,2)=3.26631; feat_train(0,3)=1.79009; feat_train(0,4)=-3.66051; feat_train(1,0)=-1.83544; feat_train(1,1)=2.91702; feat_train(1,2)=-3.85663; feat_train(1,3)=0.11949; feat_train(1,4)=1.75159; lab_train[0]=-1.0; lab_train[1]=1.0; lab_train[2]=1.0; lab_train[3]=1.0; lab_train[4]=-1.0; // shogun representation of features and labels auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto labels_train=std::make_shared<BinaryLabels>(lab_train); float64_t ell=2.0; // choose Gaussian kernel with width = 2*2^2 and zero mean function auto kernel=std::make_shared<GaussianKernel>(10, 2*Math::sq(ell)); auto mean=std::make_shared<ZeroMean>(); // probit likelihood auto likelihood=std::make_shared<ProbitLikelihood>(); // specify GP classification with EP inference and kernel scale=1.5 auto inf=std::make_shared<EPInferenceMethod>(kernel, features_train, mean, labels_train, likelihood); inf->set_scale(1.5); // build parameter dictionary std::map<SGObject::Parameters::value_type, std::shared_ptr<SGObject>> parameter_dictionary; inf->build_gradient_parameter_dictionary(parameter_dictionary); // compute derivatives wrt parameters auto gradient= inf->get_negative_log_marginal_likelihood_derivatives(parameter_dictionary); // get parameters to compute derivatives float64_t dnlZ_ell=gradient["width"][0]; float64_t dnlZ_sf2=gradient["log_scale"][0]; // comparison of partial derivatives of negative marginal likelihood with // result from GPML package: EXPECT_NEAR(dnlZ_ell, -0.0551896689012401, 1E-3); EXPECT_NEAR(dnlZ_sf2, -0.0535698533526804, 1E-3); } TEST(EPInferenceMethod, get_posterior_mean_probit_likelihood) { // create some easy random classification data index_t n=5; SGMatrix<float64_t> feat_train(2, n); SGVector<float64_t> lab_train(n); feat_train(0,0)=-1.07932; feat_train(0,1)=1.15768; feat_train(0,2)=3.26631; feat_train(0,3)=1.79009; feat_train(0,4)=-3.66051; feat_train(1,0)=-1.83544; feat_train(1,1)=2.91702; feat_train(1,2)=-3.85663; feat_train(1,3)=0.11949; feat_train(1,4)=1.75159; lab_train[0]=-1.0; lab_train[1]=1.0; lab_train[2]=1.0; lab_train[3]=1.0; lab_train[4]=-1.0; // shogun representation of features and labels auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto labels_train=std::make_shared<BinaryLabels>(lab_train); // choose Gaussian kernel with width = 2*2^2 and zero mean function auto kernel=std::make_shared<GaussianKernel>(10, 8.0); auto mean=std::make_shared<ZeroMean>(); // probit likelihood auto likelihood=std::make_shared<ProbitLikelihood>(); // specify GP classification with EP inference and kernel scale=1.5 auto inf=std::make_shared<EPInferenceMethod>(kernel, features_train, mean, labels_train, likelihood); inf->set_scale(1.5); // comparison of posterior approximation mean with result from GPML package SGVector<float64_t> mu=inf->get_posterior_mean(); EXPECT_NEAR(mu[0], -0.882471450365118, 1E-3); EXPECT_NEAR(mu[1], 1.132570041978009, 1E-3); EXPECT_NEAR(mu[2], 1.016031341665029, 1E-3); EXPECT_NEAR(mu[3], 1.079152436021026, 1E-3); EXPECT_NEAR(mu[4], -1.016378075891627, 1E-3); } TEST(EPInferenceMethod, get_posterior_covariance_probit_likelihood) { // create some easy random classification data index_t n=5; SGMatrix<float64_t> feat_train(2, n); SGVector<float64_t> lab_train(n); feat_train(0,0)=-1.07932; feat_train(0,1)=1.15768; feat_train(0,2)=3.26631; feat_train(0,3)=1.79009; feat_train(0,4)=-3.66051; feat_train(1,0)=-1.83544; feat_train(1,1)=2.91702; feat_train(1,2)=-3.85663; feat_train(1,3)=0.11949; feat_train(1,4)=1.75159; lab_train[0]=-1.0; lab_train[1]=1.0; lab_train[2]=1.0; lab_train[3]=1.0; lab_train[4]=-1.0; // shogun representation of features and labels auto features_train=std::make_shared<DenseFeatures<float64_t>>(feat_train); auto labels_train=std::make_shared<BinaryLabels>(lab_train); // choose Gaussian kernel with width = 2*2^2 and zero mean function auto kernel=std::make_shared<GaussianKernel>(10, 8.0); auto mean=std::make_shared<ZeroMean>(); // probit likelihood auto likelihood=std::make_shared<ProbitLikelihood>(); // specify GP classification with EP inference and kernel scale=1.5 auto inf=std::make_shared<EPInferenceMethod>(kernel, features_train, mean, labels_train, likelihood); inf->set_scale(1.5); // comparison of posterior approximation covariance with result from GPML // package SGMatrix<float64_t> Sigma=inf->get_posterior_covariance(); EXPECT_NEAR(Sigma(0,0), 1.20274103263760379, 1E-3); EXPECT_NEAR(Sigma(0,1), -0.00260850144375850, 1E-3); EXPECT_NEAR(Sigma(0,2), 0.03239746041777301, 1E-3); EXPECT_NEAR(Sigma(0,3), 0.15449141486321272, 1E-3); EXPECT_NEAR(Sigma(0,4), 0.05930784879253234, 1E-3); EXPECT_NEAR(Sigma(1,0), -0.00260850144375854, 1E-3); EXPECT_NEAR(Sigma(1,1), 1.26103532435204135, 1E-3); EXPECT_NEAR(Sigma(1,2), -0.01072708038072782, 1E-3); EXPECT_NEAR(Sigma(1,3), 0.27319700541557035, 1E-3); EXPECT_NEAR(Sigma(1,4), 0.03289357125150720, 1E-3); EXPECT_NEAR(Sigma(2,0), 0.03239746041777301, 1E-3); EXPECT_NEAR(Sigma(2,1), -0.01072708038072782, 1E-3); EXPECT_NEAR(Sigma(2,2), 1.26094966657088081, 1E-3); EXPECT_NEAR(Sigma(2,3), 0.07456464702006255, 1E-3); EXPECT_NEAR(Sigma(2,4), -0.00165339284404121, 1E-3); EXPECT_NEAR(Sigma(3,0), 0.15449141486321255, 1E-3); EXPECT_NEAR(Sigma(3,1), 0.27319700541557035, 1E-3); EXPECT_NEAR(Sigma(3,2), 0.07456464702006255, 1E-3); EXPECT_NEAR(Sigma(3,3), 1.22399410182504154, 1E-3); EXPECT_NEAR(Sigma(3,4), 0.00151934275843193, 1E-3); EXPECT_NEAR(Sigma(4,0), 0.05930784879253234, 1E-3); EXPECT_NEAR(Sigma(4,1), 0.03289357125150720, 1E-3); EXPECT_NEAR(Sigma(4,2), -0.00165339284404121, 1E-3); EXPECT_NEAR(Sigma(4,3), 0.00151934275843193, 1E-3); EXPECT_NEAR(Sigma(4,4), 1.26206797645117108, 1E-3); }
31.372396
92
0.742093
tallamjr
f40922ee3bec89387527ae072474ccee975d5071
33,388
cpp
C++
app_skeleton_shadow.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
3
2018-09-03T20:55:24.000Z
2020-10-04T04:36:30.000Z
app_skeleton_shadow.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
4
2018-09-06T04:12:41.000Z
2020-10-06T14:43:14.000Z
app_skeleton_shadow.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
null
null
null
#if PLATFORM_GL #include <GL/gl.h> #include <GL/glext.h> #include "gles_gl_mapping.hpp" #else #include <EGL/egl.h> #include <GLES3/gl3.h> #include "gles_ext.h" #if GL_OES_depth_texture == 0 #error Missing required extension GL_OES_depth_texture. #endif #if GL_OES_depth24 == 0 #error Missing required extension GL_OES_depth24. #endif #if GL_OES_packed_depth_stencil == 0 #error Missing required extension GL_OES_packed_depth_stencil. #endif #endif // PLATFORM_GL #include <unistd.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <cmath> #include <string> #include <sstream> #include "scoped.hpp" #include "stream.hpp" #include "vectsimd.hpp" #include "rendIndexedTrilist.hpp" #include "rendSkeleton.hpp" #include "util_tex.hpp" #include "util_misc.hpp" #include "pure_macro.hpp" #include "rendVertAttr.hpp" using util::scoped_ptr; using util::scoped_functor; using util::deinit_resources_t; namespace sk { #define SETUP_VERTEX_ATTR_POINTERS_MASK ( \ SETUP_VERTEX_ATTR_POINTERS_MASK_vertex | \ SETUP_VERTEX_ATTR_POINTERS_MASK_normal | \ SETUP_VERTEX_ATTR_POINTERS_MASK_blendw | \ SETUP_VERTEX_ATTR_POINTERS_MASK_tcoord) #include "rendVertAttr_setupVertAttrPointers.hpp" #undef SETUP_VERTEX_ATTR_POINTERS_MASK struct Vertex { GLfloat pos[3]; GLfloat bon[4]; GLfloat nrm[3]; GLfloat txc[2]; }; } // namespace sk namespace st { #define SETUP_VERTEX_ATTR_POINTERS_MASK ( \ SETUP_VERTEX_ATTR_POINTERS_MASK_vertex) #include "rendVertAttr_setupVertAttrPointers.hpp" #undef SETUP_VERTEX_ATTR_POINTERS_MASK struct Vertex { GLfloat pos[3]; }; } // namespace st #define DRAW_SKELETON 0 #define DEPTH_PRECISION_24 0 namespace { // anonymous const char arg_prefix[] = "-"; const char arg_app[] = "app"; const char arg_normal[] = "normal_map"; const char arg_albedo[] = "albedo_map"; const char arg_anim_step[] = "anim_step"; const char arg_shadow_res[] = "shadow_res"; struct TexDesc { const char* filename; unsigned w; unsigned h; }; TexDesc g_normal = { "asset/texture/unperturbed_normal.raw", 8, 8 }; TexDesc g_albedo = { "none", 16, 16 }; float g_anim_step = .0125f; simd::matx4 g_matx_fit; const unsigned fbo_default_res = 2048; GLsizei g_fbo_res = fbo_default_res; enum { BONE_CAPACITY = 32 }; unsigned g_bone_count; rend::Bone g_bone[BONE_CAPACITY + 1]; rend::Bone* g_root_bone = g_bone + BONE_CAPACITY; rend::dense_matx4 g_bone_mat[BONE_CAPACITY]; std::vector< std::vector< rend::Track > > g_animations; std::vector< float > g_durations; } // namespace namespace anim { static std::vector< std::vector< rend::Track > >::const_iterator at; static std::vector< float >::const_iterator dt; static float animTime; static float duration; } // namespace anim namespace { // anonymous #if DRAW_SKELETON st::Vertex g_stick[BONE_CAPACITY][2]; #endif #if PLATFORM_EGL EGLDisplay g_display = EGL_NO_DISPLAY; EGLContext g_context = EGL_NO_CONTEXT; #endif enum { TEX_NORMAL, TEX_ALBEDO, TEX_SHADOW, TEX_COUNT, TEX_FORCE_UINT = -1U }; enum { PROG_SKIN, PROG_SKEL, PROG_SHADOW, PROG_COUNT, PROG_FORCE_UINT = -1U }; enum { UNI_SAMPLER_NORMAL, UNI_SAMPLER_ALBEDO, UNI_SAMPLER_SHADOW, UNI_LP_OBJ, UNI_VP_OBJ, UNI_SOLID_COLOR, UNI_BONE, UNI_MVP, UNI_MVP_LIT, UNI_COUNT, UNI_FORCE_UINT = -1U }; enum { MESH_SKIN, MESH_COUNT, MESH_FORCE_UINT = -1U }; enum { VBO_SKIN_VTX, VBO_SKIN_IDX, VBO_SKEL_VTX, /* VBO_SKEL_IDX not required */ VBO_COUNT, VBO_FORCE_UINT = -1U }; GLint g_uni[PROG_COUNT][UNI_COUNT]; #if PLATFORM_GL_OES_vertex_array_object GLuint g_vao[PROG_COUNT]; #endif GLuint g_fbo; // single GLuint g_tex[TEX_COUNT]; GLuint g_vbo[VBO_COUNT]; GLuint g_shader_vert[PROG_COUNT]; GLuint g_shader_frag[PROG_COUNT]; GLuint g_shader_prog[PROG_COUNT]; unsigned g_num_faces[MESH_COUNT]; GLenum g_index_type; rend::ActiveAttrSemantics g_active_attr_semantics[PROG_COUNT]; } // namespace bool hook::set_num_drawcalls( const unsigned) { return false; } unsigned hook::get_num_drawcalls() { return 1; } bool hook::requires_depth() { return true; } static bool parse_cli( const unsigned argc, const char* const* argv) { bool cli_err = false; const unsigned prefix_len = strlen(arg_prefix); for (unsigned i = 1; i < argc && !cli_err; ++i) { if (strncmp(argv[i], arg_prefix, prefix_len) || strcmp(argv[i] + prefix_len, arg_app)) { continue; } if (++i < argc) { if (i + 3 < argc && !strcmp(argv[i], arg_normal)) { if (1 == sscanf(argv[i + 2], "%u", &g_normal.w) && 1 == sscanf(argv[i + 3], "%u", &g_normal.h)) { g_normal.filename = argv[i + 1]; i += 3; continue; } } else if (i + 3 < argc && !strcmp(argv[i], arg_albedo)) { if (1 == sscanf(argv[i + 2], "%u", &g_albedo.w) && 1 == sscanf(argv[i + 3], "%u", &g_albedo.h)) { g_albedo.filename = argv[i + 1]; i += 3; continue; } } else if (i + 1 < argc && !strcmp(argv[i], arg_anim_step)) { if (1 == sscanf(argv[i + 1], "%f", &g_anim_step) && 0.f < g_anim_step) { i += 1; continue; } } else if (i + 1 < argc && !strcmp(argv[i], arg_shadow_res)) { if (1 == sscanf(argv[i + 1], "%u", &g_fbo_res) && 0 == (g_fbo_res & g_fbo_res - 1)) { i += 1; continue; } } } cli_err = true; } if (cli_err) { stream::cerr << "app options:\n" "\t" << arg_prefix << arg_app << " " << arg_normal << " <filename> <width> <height>\t: use specified raw file and dimensions as source of normal map\n" "\t" << arg_prefix << arg_app << " " << arg_albedo << " <filename> <width> <height>\t: use specified raw file and dimensions as source of albedo map\n" "\t" << arg_prefix << arg_app << " " << arg_anim_step << " <step>\t\t\t\t: use specified animation step; entire animation is 1.0\n" "\t" << arg_prefix << arg_app << " " << arg_shadow_res << " <pot>\t\t\t\t: use specified shadow buffer resolution (POT); default is " << fbo_default_res << "\n\n"; } return !cli_err; } namespace { // anonymous template < unsigned PROG_T > inline bool bindVertexBuffersAndPointers() { assert(false); return false; } template <> inline bool bindVertexBuffersAndPointers< PROG_SKIN >() { glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKIN_VTX]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_vbo[VBO_SKIN_IDX]); DEBUG_GL_ERR() return sk::setupVertexAttrPointers< sk::Vertex >(g_active_attr_semantics[PROG_SKIN]); } #if DRAW_SKELETON template <> inline bool bindVertexBuffersAndPointers< PROG_SKEL >() { glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKEL_VTX]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); DEBUG_GL_ERR() return st::setupVertexAttrPointers< st::Vertex >(g_active_attr_semantics[PROG_SKEL]); } #endif // DRAW_SKELETON template <> inline bool bindVertexBuffersAndPointers< PROG_SHADOW >() { glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKIN_VTX]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_vbo[VBO_SKIN_IDX]); DEBUG_GL_ERR() return sk::setupVertexAttrPointers< sk::Vertex >(g_active_attr_semantics[PROG_SHADOW]); } bool check_context( const char* prefix) { bool context_correct = true; #if PLATFORM_EGL if (g_display != eglGetCurrentDisplay()) { stream::cerr << prefix << " encountered foreign display\n"; context_correct = false; } if (g_context != eglGetCurrentContext()) { stream::cerr << prefix << " encountered foreign context\n"; context_correct = false; } #endif return context_correct; } } // namespace bool hook::deinit_resources() { if (!check_context(__FUNCTION__)) return false; for (unsigned i = 0; i < sizeof(g_shader_prog) / sizeof(g_shader_prog[0]); ++i) { glDeleteProgram(g_shader_prog[i]); g_shader_prog[i] = 0; } for (unsigned i = 0; i < sizeof(g_shader_vert) / sizeof(g_shader_vert[0]); ++i) { glDeleteShader(g_shader_vert[i]); g_shader_vert[i] = 0; } for (unsigned i = 0; i < sizeof(g_shader_frag) / sizeof(g_shader_frag[0]); ++i) { glDeleteShader(g_shader_frag[i]); g_shader_frag[i] = 0; } glDeleteFramebuffers(1, &g_fbo); g_fbo = 0; glDeleteTextures(sizeof(g_tex) / sizeof(g_tex[0]), g_tex); memset(g_tex, 0, sizeof(g_tex)); #if PLATFORM_GL_OES_vertex_array_object glDeleteVertexArraysOES(sizeof(g_vao) / sizeof(g_vao[0]), g_vao); memset(g_vao, 0, sizeof(g_vao)); #endif glDeleteBuffers(sizeof(g_vbo) / sizeof(g_vbo[0]), g_vbo); memset(g_vbo, 0, sizeof(g_vbo)); #if PLATFORM_EGL g_display = EGL_NO_DISPLAY; g_context = EGL_NO_CONTEXT; #endif return true; } namespace { // anonymous #if DEBUG && PLATFORM_GL_KHR_debug void debugProc( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { fprintf(stderr, "log: %s\n", message); } #endif } // namespace bool hook::init_resources( const unsigned argc, const char* const * argv) { if (!parse_cli(argc, argv)) return false; #if DEBUG && PLATFORM_GL_KHR_debug glDebugMessageCallbackKHR(debugProc, NULL); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR); glEnable(GL_DEBUG_OUTPUT_KHR); DEBUG_GL_ERR() glDebugMessageInsertKHR( GL_DEBUG_SOURCE_APPLICATION_KHR, GL_DEBUG_TYPE_OTHER_KHR, GLuint(42), GL_DEBUG_SEVERITY_HIGH_KHR, GLint(-1), "testing 1, 2, 3"); DEBUG_GL_ERR() #endif #if PLATFORM_EGL g_display = eglGetCurrentDisplay(); if (EGL_NO_DISPLAY == g_display) { stream::cerr << __FUNCTION__ << " encountered nil display\n"; return false; } g_context = eglGetCurrentContext(); if (EGL_NO_CONTEXT == g_context) { stream::cerr << __FUNCTION__ << " encountered nil context\n"; return false; } #endif scoped_ptr< deinit_resources_t, scoped_functor > on_error(deinit_resources); ///////////////////////////////////////////////////////////////// // set up various patches to the shaders std::ostringstream patch_res[2]; patch_res[0] << "const float shadow_res = " << fbo_default_res << ".0;"; patch_res[1] << "const float shadow_res = " << g_fbo_res << ".0;"; const std::string patch[] = { patch_res[0].str(), patch_res[1].str() }; ///////////////////////////////////////////////////////////////// // set up misc control bits and values glEnable(GL_CULL_FACE); const GLclampf red = 0.f; const GLclampf green = 0.f; const GLclampf blue = 0.f; const GLclampf alpha = 0.f; glClearColor(red, green, blue, alpha); glClearDepthf(1.f); // for shadow map generation: push back by 64 ULPs glPolygonOffset(1.f, 64.f); ///////////////////////////////////////////////////////////////// // reserve all necessary texture objects glGenTextures(sizeof(g_tex) / sizeof(g_tex[0]), g_tex); for (unsigned i = 0; i < sizeof(g_tex) / sizeof(g_tex[0]); ++i) assert(g_tex[i]); ///////////////////////////////////////////////////////////////// // load textures if (!util::setupTexture2D(g_tex[TEX_NORMAL], g_normal.filename, g_normal.w, g_normal.h)) { stream::cerr << __FUNCTION__ << " failed at setupTexture2D\n"; return false; } if (!util::setupTexture2D(g_tex[TEX_ALBEDO], g_albedo.filename, g_albedo.w, g_albedo.h)) { stream::cerr << __FUNCTION__ << " failed at setupTexture2D\n"; return false; } ///////////////////////////////////////////////////////////////// // init the program/uniforms matrix to all empty for (unsigned i = 0; i < PROG_COUNT; ++i) for (unsigned j = 0; j < UNI_COUNT; ++j) g_uni[i][j] = -1; ///////////////////////////////////////////////////////////////// // create shader program SKIN from two shaders g_shader_vert[PROG_SKIN] = glCreateShader(GL_VERTEX_SHADER); assert(g_shader_vert[PROG_SKIN]); if (!util::setupShader(g_shader_vert[PROG_SKIN], "asset/shader/blinn_shadow_skinning.glslv")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_frag[PROG_SKIN] = glCreateShader(GL_FRAGMENT_SHADER); assert(g_shader_frag[PROG_SKIN]); if (!util::setupShaderWithPatch(g_shader_frag[PROG_SKIN], "asset/shader/blinn_shadow.glslf", sizeof(patch) / sizeof(patch[0]) / 2, patch)) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_prog[PROG_SKIN] = glCreateProgram(); assert(g_shader_prog[PROG_SKIN]); if (!util::setupProgram( g_shader_prog[PROG_SKIN], g_shader_vert[PROG_SKIN], g_shader_frag[PROG_SKIN])) { stream::cerr << __FUNCTION__ << " failed at setupProgram\n"; return false; } ///////////////////////////////////////////////////////////////// // query the program about known uniform vars and vertex attribs g_uni[PROG_SKIN][UNI_MVP] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "mvp"); g_uni[PROG_SKIN][UNI_MVP_LIT] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "mvp_lit"); g_uni[PROG_SKIN][UNI_BONE] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "bone"); g_uni[PROG_SKIN][UNI_LP_OBJ] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "lp_obj"); g_uni[PROG_SKIN][UNI_VP_OBJ] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "vp_obj"); g_uni[PROG_SKIN][UNI_SAMPLER_NORMAL] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "normal_map"); g_uni[PROG_SKIN][UNI_SAMPLER_ALBEDO] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "albedo_map"); g_uni[PROG_SKIN][UNI_SAMPLER_SHADOW] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "shadow_map"); g_active_attr_semantics[PROG_SKIN].registerVertexAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_Vertex")); g_active_attr_semantics[PROG_SKIN].registerNormalAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_Normal")); g_active_attr_semantics[PROG_SKIN].registerBlendWAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_Weight")); g_active_attr_semantics[PROG_SKIN].registerTCoordAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_MultiTexCoord0")); ///////////////////////////////////////////////////////////////// // create shader program SKEL from two shaders g_shader_vert[PROG_SKEL] = glCreateShader(GL_VERTEX_SHADER); assert(g_shader_vert[PROG_SKEL]); if (!util::setupShader(g_shader_vert[PROG_SKEL], "asset/shader/mvp.glslv")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_frag[PROG_SKEL] = glCreateShader(GL_FRAGMENT_SHADER); assert(g_shader_frag[PROG_SKEL]); if (!util::setupShader(g_shader_frag[PROG_SKEL], "asset/shader/basic.glslf")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_prog[PROG_SKEL] = glCreateProgram(); assert(g_shader_prog[PROG_SKEL]); if (!util::setupProgram( g_shader_prog[PROG_SKEL], g_shader_vert[PROG_SKEL], g_shader_frag[PROG_SKEL])) { stream::cerr << __FUNCTION__ << " failed at setupProgram\n"; return false; } ///////////////////////////////////////////////////////////////// // query the program about known uniform vars and vertex attribs g_uni[PROG_SKEL][UNI_MVP] = glGetUniformLocation(g_shader_prog[PROG_SKEL], "mvp"); g_uni[PROG_SKEL][UNI_SOLID_COLOR] = glGetUniformLocation(g_shader_prog[PROG_SKEL], "solid_color"); g_active_attr_semantics[PROG_SKEL].registerVertexAttr(glGetAttribLocation(g_shader_prog[PROG_SKEL], "at_Vertex")); ///////////////////////////////////////////////////////////////// // create shader program SHADOW from two shaders g_shader_vert[PROG_SHADOW] = glCreateShader(GL_VERTEX_SHADER); assert(g_shader_vert[PROG_SHADOW]); if (!util::setupShader(g_shader_vert[PROG_SHADOW], "asset/shader/mvp_skinning.glslv")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_frag[PROG_SHADOW] = glCreateShader(GL_FRAGMENT_SHADER); assert(g_shader_frag[PROG_SHADOW]); if (!util::setupShader(g_shader_frag[PROG_SHADOW], "asset/shader/depth.glslf")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_prog[PROG_SHADOW] = glCreateProgram(); assert(g_shader_prog[PROG_SHADOW]); if (!util::setupProgram( g_shader_prog[PROG_SHADOW], g_shader_vert[PROG_SHADOW], g_shader_frag[PROG_SHADOW])) { stream::cerr << __FUNCTION__ << " failed at setupProgram\n"; return false; } ///////////////////////////////////////////////////////////////// // query the program about known uniform vars and vertex attribs g_uni[PROG_SHADOW][UNI_MVP] = glGetUniformLocation(g_shader_prog[PROG_SHADOW], "mvp"); g_uni[PROG_SHADOW][UNI_BONE] = glGetUniformLocation(g_shader_prog[PROG_SHADOW], "bone"); g_active_attr_semantics[PROG_SHADOW].registerVertexAttr(glGetAttribLocation(g_shader_prog[PROG_SHADOW], "at_Vertex")); g_active_attr_semantics[PROG_SHADOW].registerBlendWAttr(glGetAttribLocation(g_shader_prog[PROG_SHADOW], "at_Weight")); ///////////////////////////////////////////////////////////////// // load the skeleton for the main geometric asset g_bone_count = BONE_CAPACITY; const char* const skeleton_filename = "asset/mesh/Ahmed_GEO.skeleton"; if (!rend::loadSkeletonAnimationABE(skeleton_filename, &g_bone_count, g_bone_mat, g_bone, g_animations, g_durations)) { stream::cerr << __FUNCTION__ << " failed to load skeleton file " << skeleton_filename << '\n'; return false; } assert(g_animations.size()); assert(g_durations.size()); anim::at = g_animations.begin(); anim::dt = g_durations.begin(); anim::animTime = 0.f; anim::duration = *anim::dt; ///////////////////////////////////////////////////////////////// // reserve VAO (if available) and all necessary VBOs #if PLATFORM_GL_OES_vertex_array_object glGenVertexArraysOES(sizeof(g_vao) / sizeof(g_vao[0]), g_vao); for (unsigned i = 0; i < sizeof(g_vao) / sizeof(g_vao[0]); ++i) assert(g_vao[i]); #endif glGenBuffers(sizeof(g_vbo) / sizeof(g_vbo[0]), g_vbo); for (unsigned i = 0; i < sizeof(g_vbo) / sizeof(g_vbo[0]); ++i) assert(g_vbo[i]); ///////////////////////////////////////////////////////////////// // load the main geometric asset float bbox_min[3]; float bbox_max[3]; const uintptr_t semantics_offset[4] = { offsetof(sk::Vertex, pos), offsetof(sk::Vertex, bon), offsetof(sk::Vertex, nrm), offsetof(sk::Vertex, txc) }; const char* const mesh_filename = "asset/mesh/Ahmed_GEO.mesh"; if (!util::fill_indexed_trilist_from_file_ABE( mesh_filename, g_vbo[VBO_SKIN_VTX], g_vbo[VBO_SKIN_IDX], semantics_offset, g_num_faces[MESH_SKIN], g_index_type, bbox_min, bbox_max)) { stream::cerr << __FUNCTION__ << " failed at fill_indexed_trilist_from_file_ABE\n"; return false; } const float centre[3] = { (bbox_min[0] + bbox_max[0]) * .5f, (bbox_min[1] + bbox_max[1]) * .5f, (bbox_min[2] + bbox_max[2]) * .5f }; const float extent[3] = { (bbox_max[0] - bbox_min[0]) * .5f, (bbox_max[1] - bbox_min[1]) * .5f, (bbox_max[2] - bbox_min[2]) * .5f }; const float rcp_extent = 1.f / fmaxf(fmaxf(extent[0], extent[1]), extent[2]); g_matx_fit = simd::matx4( rcp_extent, 0.f, 0.f, 0.f, 0.f, rcp_extent, 0.f, 0.f, 0.f, 0.f, rcp_extent, 0.f, -centre[0] * rcp_extent, -centre[1] * rcp_extent, -centre[2] * rcp_extent, 1.f); #if DRAW_SKELETON ///////////////////////////////////////////////////////////////// // forward-declare VBO_SKEL_VTX; dynamically updated per frame glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKEL_VTX]); glBufferData(GL_ARRAY_BUFFER, sizeof(g_stick[0]) * g_bone_count, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SKIN]); if (!bindVertexBuffersAndPointers< PROG_SKIN >() || (DEBUG_LITERAL && util::reportGLError())) { stream::cerr << __FUNCTION__ << "failed at bindVertexBuffersAndPointers for PROG_SKIN\n"; return false; } for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]); DEBUG_GL_ERR() #if DRAW_SKELETON glBindVertexArrayOES(g_vao[PROG_SKEL]); if (!bindVertexBuffersAndPointers< PROG_SKEL >() || (DEBUG_LITERAL && util::reportGLError())) { stream::cerr << __FUNCTION__ << "failed at bindVertexBuffersAndPointers for PROG_SKEL\n"; return false; } for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKEL].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKEL].active_attr[i]); DEBUG_GL_ERR() #endif glBindVertexArrayOES(g_vao[PROG_SHADOW]); if (!bindVertexBuffersAndPointers< PROG_SHADOW >() || (DEBUG_LITERAL && util::reportGLError())) { stream::cerr << __FUNCTION__ << "failed at bindVertexBuffersAndPointers for PROG_SHADOW\n"; return false; } for (unsigned i = 0; i < g_active_attr_semantics[PROG_SHADOW].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SHADOW].active_attr[i]); DEBUG_GL_ERR() glBindVertexArrayOES(0); #endif ///////////////////////////////////////////////////////////////// // set up the texture to be used as depth in the single FBO glBindTexture(GL_TEXTURE_2D, g_tex[TEX_SHADOW]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #if DEPTH_PRECISION_24 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL_OES, g_fbo_res, g_fbo_res, 0, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, 0); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, g_fbo_res, g_fbo_res, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 0); #endif if (util::reportGLError()) { stream::cerr << __FUNCTION__ << " failed at shadow texture setup\n"; return false; } glBindTexture(GL_TEXTURE_2D, 0); ///////////////////////////////////////////////////////////////// // set up the single FBO glGenFramebuffers(1, &g_fbo); assert(g_fbo); glBindFramebuffer(GL_FRAMEBUFFER, g_fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, g_tex[TEX_SHADOW], 0); #if DEPTH_PRECISION_24 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, g_tex[TEX_SHADOW], 0); #endif const GLenum fbo_success = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (GL_FRAMEBUFFER_COMPLETE != fbo_success) { stream::cerr << __FUNCTION__ << " failed at glCheckFramebufferStatus\n"; return false; } glDrawBuffers(0, nullptr); glBindFramebuffer(GL_FRAMEBUFFER, 0); on_error.reset(); return true; } class matx4_ortho : public simd::matx4 { matx4_ortho(); matx4_ortho(const matx4_ortho&); public: matx4_ortho( const float l, const float r, const float b, const float t, const float n, const float f) { static_cast< simd::matx4& >(*this) = simd::matx4( 2.f / (r - l), 0.f, 0.f, 0.f, 0.f, 2.f / (t - b), 0.f, 0.f, 0.f, 0.f, 2.f / (n - f), 0.f, (r + l) / (l - r), (t + b) / (b - t), (f + n) / (n - f), 1.f); } }; class matx4_persp : public simd::matx4 { matx4_persp(); matx4_persp(const matx4_persp&); public: matx4_persp( const float l, const float r, const float b, const float t, const float n, const float f) { static_cast< simd::matx4& >(*this) = simd::matx4( 2.f * n / (r - l), 0.f, 0.f, 0.f, 0.f, 2.f * n / (t - b), 0.f, 0.f, (r + l) / (r - l), (t + b) / (t - b), (f + n) / (n - f), -1.f, 0.f, 0.f, 2.f * f * n / (n - f), 0.f); } }; bool hook::render_frame(GLuint primary_fbo) { if (!check_context(__FUNCTION__)) return false; ///////////////////////////////////////////////////////////////// // fast-forward the skeleton animation to current time while (anim::duration <= anim::animTime) { if (g_animations.end() == ++anim::at) anim::at = g_animations.begin(); if (g_durations.end() == ++anim::dt) anim::dt = g_durations.begin(); anim::animTime -= anim::duration; anim::duration = *anim::dt; rend::resetSkeletonAnimProgress(*anim::at); } rend::animateSkeleton(g_bone_count, g_bone_mat, g_bone, *anim::at, anim::animTime, g_root_bone); anim::animTime += g_anim_step; #if DRAW_SKELETON ///////////////////////////////////////////////////////////////// // produce line segments from the bones of the animated skeleton assert(255 == g_bone[0].parent_idx); for (unsigned i = 1; i < g_bone_count; ++i) { const unsigned j = g_bone[i].parent_idx; const simd::vect4::basetype& pos0 = 255 != j ? g_bone[j].to_model[3] : g_root_bone->to_model[3]; // accommodate multi-root skeletons const simd::vect4::basetype& pos1 = g_bone[i].to_model[3]; g_stick[i][0].pos[0] = pos0[0]; g_stick[i][0].pos[1] = pos0[1]; g_stick[i][0].pos[2] = pos0[2]; g_stick[i][1].pos[0] = pos1[0]; g_stick[i][1].pos[1] = pos1[1]; g_stick[i][1].pos[2] = pos1[2]; } #endif ///////////////////////////////////////////////////////////////// // compute two MVPs: one for screen space and one for light space const float z_offset = -2.125f; const float shadow_extent = 1.5f; const simd::vect4 translate(0.f, 0.f, z_offset, 0.f); simd::matx4 mv = simd::matx4().mul(g_root_bone->to_model, g_matx_fit); mv.set(3, simd::vect4().add(mv[3], translate)); const float l = -.5f; const float r = .5f; const float b = -.5f; const float t = .5f; const float n = 1.f; const float f = 4.f; const matx4_persp proj(l, r, b, t, n, f); const matx4_ortho proj_lit( -shadow_extent, shadow_extent, -shadow_extent, shadow_extent, 0.f, 4.f); // light-space basis vectors const simd::vect3 x_lit(0.707107, 0.0, -0.707107); // x-axis rotated at pi/4 around y-axis const simd::vect3 y_lit(0.0, 1.0, 0.0); // y-axis const simd::vect3 z_lit(0.707107, 0.0, 0.707107); // z-axis rotated at pi/4 around y-axis const simd::matx4 world_lit( x_lit[0], x_lit[1], x_lit[2], 0.f, y_lit[0], y_lit[1], y_lit[2], 0.f, z_lit[0], z_lit[1], z_lit[2], 0.f, z_lit[0] * 2.f, z_lit[1] * 2.f, z_lit[2] * 2.f + z_offset, 1.f); const simd::matx4 local_lit = simd::matx4().inverse(world_lit); const simd::matx4 viewproj_lit = simd::matx4().mul(local_lit, proj_lit); const float depth_compensation = 1.f / 1024.f; // slope-invariant compensation const simd::matx4 bias( .5f, 0.f, 0.f, 0.f, 0.f, .5f, 0.f, 0.f, 0.f, 0.f, .5f, 0.f, .5f, .5f, .5f - depth_compensation, 1.f); const simd::matx4 mvp = simd::matx4().mul(mv, proj); const simd::matx4 mvp_lit = simd::matx4().mul(mv, viewproj_lit); const simd::matx4 biased_lit = simd::matx4().mul(mv, viewproj_lit).mulr(bias); const simd::vect3 lp_obj = simd::vect3( mv[0][0] + mv[0][2], mv[1][0] + mv[1][2], mv[2][0] + mv[2][2]).normalise(); GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); const float aspect = float(vp[3]) / vp[2]; const rend::dense_matx4 dense_mvp = rend::dense_matx4( mvp[0][0] * aspect, mvp[0][1], mvp[0][2], mvp[0][3], mvp[1][0] * aspect, mvp[1][1], mvp[1][2], mvp[1][3], mvp[2][0] * aspect, mvp[2][1], mvp[2][2], mvp[2][3], mvp[3][0] * aspect, mvp[3][1], mvp[3][2], mvp[3][3]); const rend::dense_matx4 dense_mvp_lit = rend::dense_matx4( mvp_lit[0][0], mvp_lit[0][1], mvp_lit[0][2], mvp_lit[0][3], mvp_lit[1][0], mvp_lit[1][1], mvp_lit[1][2], mvp_lit[1][3], mvp_lit[2][0], mvp_lit[2][1], mvp_lit[2][2], mvp_lit[2][3], mvp_lit[3][0], mvp_lit[3][1], mvp_lit[3][2], mvp_lit[3][3]); const rend::dense_matx4 dense_biased_lit = rend::dense_matx4( biased_lit[0][0], biased_lit[0][1], biased_lit[0][2], biased_lit[0][3], biased_lit[1][0], biased_lit[1][1], biased_lit[1][2], biased_lit[1][3], biased_lit[2][0], biased_lit[2][1], biased_lit[2][2], biased_lit[2][3], biased_lit[3][0], biased_lit[3][1], biased_lit[3][2], biased_lit[3][3]); ///////////////////////////////////////////////////////////////// // render the shadow of the geometric asset into the FBO glBindFramebuffer(GL_FRAMEBUFFER, g_fbo); glViewport(0, 0, g_fbo_res, g_fbo_res); DEBUG_GL_ERR() glEnable(GL_DEPTH_TEST); glEnable(GL_POLYGON_OFFSET_FILL); glClear(GL_DEPTH_BUFFER_BIT); glUseProgram(g_shader_prog[PROG_SHADOW]); DEBUG_GL_ERR() if (-1 != g_uni[PROG_SHADOW][UNI_MVP]) { glUniformMatrix4fv(g_uni[PROG_SHADOW][UNI_MVP], 1, GL_FALSE, static_cast< const GLfloat* >(dense_mvp_lit)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SHADOW][UNI_BONE]) { glUniformMatrix4fv(g_uni[PROG_SHADOW][UNI_BONE], g_bone_count, GL_FALSE, static_cast< const GLfloat* >(g_bone_mat[0])); DEBUG_GL_ERR() } #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SHADOW]); DEBUG_GL_ERR() #else if (!bindVertexBuffersAndPointers< PROG_SHADOW >()) return false; for (unsigned i = 0; i < g_active_attr_semantics[PROG_SHADOW].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SHADOW].active_attr[i]); DEBUG_GL_ERR() #endif glDrawElements(GL_TRIANGLES, g_num_faces[MESH_SKIN] * 3, g_index_type, 0); DEBUG_GL_ERR() #if PLATFORM_GL_OES_vertex_array_object == 0 for (unsigned i = 0; i < g_active_attr_semantics[PROG_SHADOW].num_active_attr; ++i) glDisableVertexAttribArray(g_active_attr_semantics[PROG_SHADOW].active_attr[i]); DEBUG_GL_ERR() #endif ///////////////////////////////////////////////////////////////// // render the geometric asset into the main framebuffer glBindFramebuffer(GL_FRAMEBUFFER, primary_fbo); glViewport(vp[0], vp[1], vp[2], vp[3]); DEBUG_GL_ERR() glDisable(GL_POLYGON_OFFSET_FILL); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(g_shader_prog[PROG_SKIN]); DEBUG_GL_ERR() if (-1 != g_uni[PROG_SKIN][UNI_MVP]) { glUniformMatrix4fv(g_uni[PROG_SKIN][UNI_MVP], 1, GL_FALSE, static_cast< const GLfloat* >(dense_mvp)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_MVP_LIT]) { glUniformMatrix4fv(g_uni[PROG_SKIN][UNI_MVP_LIT], 1, GL_FALSE, static_cast< const GLfloat* >(dense_biased_lit)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_BONE]) { glUniformMatrix4fv(g_uni[PROG_SKIN][UNI_BONE], g_bone_count, GL_FALSE, static_cast< const GLfloat* >(g_bone_mat[0])); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_LP_OBJ]) { const GLfloat nonlocal_light[4] = { lp_obj[0], lp_obj[1], lp_obj[2], 0.f }; glUniform4fv(g_uni[PROG_SKIN][UNI_LP_OBJ], 1, nonlocal_light); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_VP_OBJ]) { const GLfloat nonlocal_viewer[4] = { mv[0][2], mv[1][2], mv[2][2], 0.f }; glUniform4fv(g_uni[PROG_SKIN][UNI_VP_OBJ], 1, nonlocal_viewer); DEBUG_GL_ERR() } if (0 != g_tex[TEX_NORMAL] && -1 != g_uni[PROG_SKIN][UNI_SAMPLER_NORMAL]) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_tex[TEX_NORMAL]); glUniform1i(g_uni[PROG_SKIN][UNI_SAMPLER_NORMAL], 0); DEBUG_GL_ERR() } if (0 != g_tex[TEX_ALBEDO] && -1 != g_uni[PROG_SKIN][UNI_SAMPLER_ALBEDO]) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, g_tex[TEX_ALBEDO]); glUniform1i(g_uni[PROG_SKIN][UNI_SAMPLER_ALBEDO], 1); DEBUG_GL_ERR() } if (0 != g_tex[TEX_SHADOW] && -1 != g_uni[PROG_SKIN][UNI_SAMPLER_SHADOW]) { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, g_tex[TEX_SHADOW]); glUniform1i(g_uni[PROG_SKIN][UNI_SAMPLER_SHADOW], 2); DEBUG_GL_ERR() } #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SKIN]); DEBUG_GL_ERR() #else if (!bindVertexBuffersAndPointers< PROG_SKIN >()) return false; for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]); DEBUG_GL_ERR() #endif glDrawElements(GL_TRIANGLES, g_num_faces[MESH_SKIN] * 3, g_index_type, 0); DEBUG_GL_ERR() #if PLATFORM_GL_OES_vertex_array_object == 0 for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i) glDisableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]); DEBUG_GL_ERR() #endif #if DRAW_SKELETON ///////////////////////////////////////////////////////////////// // render the skeleton into the main framebuffer glDisable(GL_DEPTH_TEST); glUseProgram(g_shader_prog[PROG_SKEL]); DEBUG_GL_ERR() if (-1 != g_uni[PROG_SKEL][UNI_MVP]) { glUniformMatrix4fv(g_uni[PROG_SKEL][UNI_MVP], 1, GL_FALSE, static_cast< const GLfloat* >(dense_mvp)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKEL][UNI_SOLID_COLOR]) { const GLfloat solid_color[4] = { 0.f, 1.f, 0.f, 1.f }; glUniform4fv(g_uni[PROG_SKEL][UNI_SOLID_COLOR], 1, solid_color); DEBUG_GL_ERR() } #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SKEL]); DEBUG_GL_ERR() #else if (!bindVertexBuffersAndPointers< PROG_SKEL >()) return false; for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKEL].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKEL].active_attr[i]); DEBUG_GL_ERR() #endif glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKEL_VTX]); glBufferSubData(GL_ARRAY_BUFFER, GLintptr(0), sizeof(g_stick[0]) * g_bone_count, g_stick); DEBUG_GL_ERR() glDrawArrays(GL_LINES, 0, g_bone_count * 2); DEBUG_GL_ERR() #if PLATFORM_GL_OES_vertex_array_object == 0 for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKEL].num_active_attr; ++i) glDisableVertexAttribArray(g_active_attr_semantics[PROG_SKEL].active_attr[i]); DEBUG_GL_ERR() #endif #endif // DRAW_SKELETON return true; }
26.689049
134
0.674614
blu
f40a05ac70e14bd8959617d5aad8327fb48c28d6
4,066
hpp
C++
source/Euclid/Numerics/Matrix.Inverse.hpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
7
2015-10-16T20:49:20.000Z
2019-04-17T09:34:35.000Z
source/Euclid/Numerics/Matrix.Inverse.hpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
null
null
null
source/Euclid/Numerics/Matrix.Inverse.hpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
null
null
null
// // Matrix.Inverse.h // Euclid // // Created by Samuel Williams on 27/11/12. // Copyright (c) 2012 Samuel Williams. All rights reserved. // #ifndef _EUCLID_NUMERICS_MATRIX_INVERSE_H #define _EUCLID_NUMERICS_MATRIX_INVERSE_H #include "Matrix.hpp" namespace Euclid { namespace Numerics { template <typename NumericT> void invert_matrix_4x4 (const NumericT * mat, NumericT * dst) { // Temp array for pairs NumericT tmp[12]; // Array of transpose source matrix NumericT src[16]; // Determinant NumericT det; // transpose matrix for (int i = 0; i < 4; i++) { src[i] = mat[i*4]; src[i + 4] = mat[i*4 + 1]; src[i + 8] = mat[i*4 + 2]; src[i + 12] = mat[i*4 + 3]; } // calculate pairs for first 8 elements (cofactors) tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; // calculate first 8 elements (cofactors) dst[0] = tmp[0]*src[5] + tmp[3]*src[6] + tmp[4]*src[7]; dst[0] -= tmp[1]*src[5] + tmp[2]*src[6] + tmp[5]*src[7]; dst[1] = tmp[1]*src[4] + tmp[6]*src[6] + tmp[9]*src[7]; dst[1] -= tmp[0]*src[4] + tmp[7]*src[6] + tmp[8]*src[7]; dst[2] = tmp[2]*src[4] + tmp[7]*src[5] + tmp[10]*src[7]; dst[2] -= tmp[3]*src[4] + tmp[6]*src[5] + tmp[11]*src[7]; dst[3] = tmp[5]*src[4] + tmp[8]*src[5] + tmp[11]*src[6]; dst[3] -= tmp[4]*src[4] + tmp[9]*src[5] + tmp[10]*src[6]; dst[4] = tmp[1]*src[1] + tmp[2]*src[2] + tmp[5]*src[3]; dst[4] -= tmp[0]*src[1] + tmp[3]*src[2] + tmp[4]*src[3]; dst[5] = tmp[0]*src[0] + tmp[7]*src[2] + tmp[8]*src[3]; dst[5] -= tmp[1]*src[0] + tmp[6]*src[2] + tmp[9]*src[3]; dst[6] = tmp[3]*src[0] + tmp[6]*src[1] + tmp[11]*src[3]; dst[6] -= tmp[2]*src[0] + tmp[7]*src[1] + tmp[10]*src[3]; dst[7] = tmp[4]*src[0] + tmp[9]*src[1] + tmp[10]*src[2]; dst[7] -= tmp[5]*src[0] + tmp[8]*src[1] + tmp[11]*src[2]; // calculate pairs for second 8 elements (cofactors) tmp[0] = src[2]*src[7]; tmp[1] = src[3]*src[6]; tmp[2] = src[1]*src[7]; tmp[3] = src[3]*src[5]; tmp[4] = src[1]*src[6]; tmp[5] = src[2]*src[5]; tmp[6] = src[0]*src[7]; tmp[7] = src[3]*src[4]; tmp[8] = src[0]*src[6]; tmp[9] = src[2]*src[4]; tmp[10] = src[0]*src[5]; tmp[11] = src[1]*src[4]; // calculate second 8 elements (cofactors) dst[8] = tmp[0]*src[13] + tmp[3]*src[14] + tmp[4]*src[15]; dst[8] -= tmp[1]*src[13] + tmp[2]*src[14] + tmp[5]*src[15]; dst[9] = tmp[1]*src[12] + tmp[6]*src[14] + tmp[9]*src[15]; dst[9] -= tmp[0]*src[12] + tmp[7]*src[14] + tmp[8]*src[15]; dst[10] = tmp[2]*src[12] + tmp[7]*src[13] + tmp[10]*src[15]; dst[10]-= tmp[3]*src[12] + tmp[6]*src[13] + tmp[11]*src[15]; dst[11] = tmp[5]*src[12] + tmp[8]*src[13] + tmp[11]*src[14]; dst[11]-= tmp[4]*src[12] + tmp[9]*src[13] + tmp[10]*src[14]; dst[12] = tmp[2]*src[10] + tmp[5]*src[11] + tmp[1]*src[9]; dst[12]-= tmp[4]*src[11] + tmp[0]*src[9] + tmp[3]*src[10]; dst[13] = tmp[8]*src[11] + tmp[0]*src[8] + tmp[7]*src[10]; dst[13]-= tmp[6]*src[10] + tmp[9]*src[11] + tmp[1]*src[8]; dst[14] = tmp[6]*src[9] + tmp[11]*src[11] + tmp[3]*src[8]; dst[14]-= tmp[10]*src[11] + tmp[2]*src[8] + tmp[7]*src[9]; dst[15] = tmp[10]*src[10] + tmp[4]*src[8] + tmp[9]*src[9]; dst[15]-= tmp[8]*src[9] + tmp[11]*src[10] + tmp[5]*src[8]; // calculate determinant det = src[0]*dst[0]+src[1]*dst[1]+src[2]*dst[2]+src[3]*dst[3]; // calculate matrix inverse det = 1.0/det; for (int j = 0; j < 16; j++) dst[j] *= det; } template <typename NumericT> Matrix<4, 4, NumericT> inverse (const Matrix<4, 4, NumericT> & source) { Matrix<4, 4, NumericT> result; invert_matrix_4x4(source.data(), result.data()); return result; } } } #endif
33.603306
72
0.522873
kurocha
f40aaf4be64190fb4792a1aafd922d6c9ee31ad7
102
cpp
C++
c/prueba_static/src/main.cpp
joseluis8906/tests
df222f4bbef0ed4a3bfb53ebc2d1fd44179551f4
[ "MIT" ]
null
null
null
c/prueba_static/src/main.cpp
joseluis8906/tests
df222f4bbef0ed4a3bfb53ebc2d1fd44179551f4
[ "MIT" ]
null
null
null
c/prueba_static/src/main.cpp
joseluis8906/tests
df222f4bbef0ed4a3bfb53ebc2d1fd44179551f4
[ "MIT" ]
null
null
null
#include <iostream> int main (int args, char* argv[]) { std::printf ("Hello world\n"); return 0; }
12.75
33
0.627451
joseluis8906
f40c03f4a2fc28db7e123d10b0a5a822cb457ba0
307
cpp
C++
aql/benchmark/lib_7/class_0.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_7/class_0.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_7/class_0.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
#include "class_0.h" #include "class_5.h" #include "class_2.h" #include "class_9.h" #include "class_3.h" #include "class_4.h" #include <lib_4/class_4.h> #include <lib_4/class_9.h> #include <lib_5/class_0.h> #include <lib_2/class_5.h> #include <lib_4/class_7.h> class_0::class_0() {} class_0::~class_0() {}
20.466667
26
0.710098
menify
f40db6282a73b8a62b79be6856c0180e3e15b08e
25
cpp
C++
Projects/engine/helpers/hcs_helpers.cpp
Octdoc/SevenDeities
648324b6b9fb907df93fdf2dfab7379369bdfe9e
[ "MIT" ]
null
null
null
Projects/engine/helpers/hcs_helpers.cpp
Octdoc/SevenDeities
648324b6b9fb907df93fdf2dfab7379369bdfe9e
[ "MIT" ]
null
null
null
Projects/engine/helpers/hcs_helpers.cpp
Octdoc/SevenDeities
648324b6b9fb907df93fdf2dfab7379369bdfe9e
[ "MIT" ]
null
null
null
#include "hcs_helpers.h"
12.5
24
0.76
Octdoc
f40f2f5135a7008195368cd891aeb07bfe50573a
4,098
cpp
C++
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPAllowCrafting // (Native, Event, NetResponse, Static, MulticastDelegate, Public, Private, Delegate, NetClient, BlueprintPure, Const, NetValidate) // Parameters: // class AShooterPlayerController** ForPC (Parm, ZeroConstructor, IsPlainOldData) // class FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm) class FString UPrimalItem_Spawner_HoverSkiff_C::STATIC_BPAllowCrafting(class AShooterPlayerController** ForPC) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPAllowCrafting"); UPrimalItem_Spawner_HoverSkiff_C_BPAllowCrafting_Params params; params.ForPC = ForPC; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.GetValidSpawnTransform // (NetRequest, Native, NetMulticast, MulticastDelegate, Public, Private, Delegate, NetClient, BlueprintPure, Const, NetValidate) // Parameters: // struct UObject_FTransform SpawnTransform (Parm, OutParm, IsPlainOldData) // bool SpawnValid (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UPrimalItem_Spawner_HoverSkiff_C::GetValidSpawnTransform(struct UObject_FTransform* SpawnTransform, bool* SpawnValid) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.GetValidSpawnTransform"); UPrimalItem_Spawner_HoverSkiff_C_GetValidSpawnTransform_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (SpawnTransform != nullptr) *SpawnTransform = params.SpawnTransform; if (SpawnValid != nullptr) *SpawnValid = params.SpawnValid; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPCrafted // () void UPrimalItem_Spawner_HoverSkiff_C::BPCrafted() { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPCrafted"); UPrimalItem_Spawner_HoverSkiff_C_BPCrafted_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.SpawnCraftedSkiff // () void UPrimalItem_Spawner_HoverSkiff_C::SpawnCraftedSkiff() { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.SpawnCraftedSkiff"); UPrimalItem_Spawner_HoverSkiff_C_SpawnCraftedSkiff_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UPrimalItem_Spawner_HoverSkiff_C::ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff"); UPrimalItem_Spawner_HoverSkiff_C_ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
33.048387
170
0.756467
2bite
f4145c53e429367e61c94cfa6f344dc2276b91be
751
hpp
C++
source/cppx-core-language/bit-level/Bit_width.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
3
2020-05-24T16:29:42.000Z
2021-09-10T13:33:15.000Z
source/cppx-core-language/bit-level/Bit_width.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
source/cppx-core-language/bit-level/Bit_width.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
#pragma once // Source encoding: UTF-8 with BOM (π is a lowercase Greek "pi"). #include <cppx-core-language/assert-cpp/is-c++17-or-later.hpp> #include <cppx-core-language/bit-level/bits_per_.hpp> // cppx::bits_per_ namespace cppx::_ { struct Bit_width{ enum Enum { _8 = 8, _16 = 16, _32 = 32, _64 = 64, _128 = 128, system = bits_per_<void*> }; }; static_assert( Bit_width::system == 16 or Bit_width::system == 32 or Bit_width::system == 64 or Bit_width::system == 128 ); } // namespace cppx::_ // Exporting namespaces: namespace cppx { namespace bit_level { using _::Bit_width; } // namespace bit_level using namespace bit_level; } // namespace cppx
27.814815
83
0.612517
alf-p-steinbach
f414c2ac74d2c1baf8725351082e81ddb361e112
5,319
hpp
C++
example/gmres/KokkosSparse_MatrixPrec.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
null
null
null
example/gmres/KokkosSparse_MatrixPrec.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
7
2020-05-04T16:43:08.000Z
2022-01-13T16:31:17.000Z
example/gmres/KokkosSparse_MatrixPrec.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
null
null
null
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Jennifer Loe (jloe@sandia.gov) // // ************************************************************************ //@HEADER */ /// @file KokkosKernels_MatrixPrec.hpp #ifndef KK_MATRIX_PREC_HPP #define KK_MATRIX_PREC_HPP #include<KokkosSparse_Preconditioner.hpp> #include<Kokkos_Core.hpp> #include<KokkosBlas.hpp> #include<KokkosSparse_spmv.hpp> namespace KokkosSparse{ namespace Experimental{ /// \class MatrixPrec /// \brief This is a simple class to use if one /// already has a matrix representation of their /// preconditioner M. The class applies an /// SpMV with M as the preconditioning step. /// \tparam ScalarType Type of the matrix's entries /// \tparam Layout Kokkos layout of vectors X and Y to which /// the preconditioner is applied /// \tparam EXSP Execution space for the preconditioner apply /// \tparam Ordinal Type of the matrix's indices; /// /// Preconditioner provides the following methods /// - initialize() Does nothing; Matrix initialized upon object construction. /// - isInitialized() returns true /// - compute() Does nothing; Matrix initialized upon object construction. /// - isComputed() returns true /// template< class ScalarType, class Layout, class EXSP, class OrdinalType = int > class MatrixPrec : virtual public KokkosSparse::Experimental::Preconditioner<ScalarType, Layout, EXSP, OrdinalType> { private: using crsMat_t = KokkosSparse::CrsMatrix<ScalarType, OrdinalType, EXSP>; crsMat_t A; bool isInitialized_ = true; bool isComputed_ = true; public: //! Constructor: MatrixPrec<ScalarType, Layout, EXSP, OrdinalType> (const KokkosSparse::CrsMatrix<ScalarType, OrdinalType, EXSP> &mat) : A(mat) {} //! Destructor. virtual ~MatrixPrec(){} ///// \brief Apply the preconditioner to X, putting the result in Y. ///// ///// \tparam XViewType Input vector, as a 1-D Kokkos::View ///// \tparam YViewType Output vector, as a nonconst 1-D Kokkos::View ///// ///// \param transM [in] "N" for non-transpose, "T" for transpose, "C" ///// for conjugate transpose. All characters after the first are ///// ignored. This works just like the BLAS routines. ///// \param alpha [in] Input coefficient of M*x ///// \param beta [in] Input coefficient of Y ///// ///// If the result of applying this preconditioner to a vector X is ///// \f$M \cdot X\f$, then this method computes \f$Y = \beta Y + \alpha M \cdot X\f$. ///// The typical case is \f$\beta = 0\f$ and \f$\alpha = 1\f$. // void apply (const Kokkos::View<ScalarType*, Layout, EXSP> &X, Kokkos::View<ScalarType*, Layout, EXSP> &Y, const char transM[] = "N", ScalarType alpha = Kokkos::Details::ArithTraits<ScalarType>::one(), ScalarType beta = Kokkos::Details::ArithTraits<ScalarType>::zero()) const { KokkosSparse::spmv(transM, alpha, A, X, beta, Y); }; //@} //! Set this preconditioner's parameters. void setParameters () {} void initialize() { } //! True if the preconditioner has been successfully initialized, else false. bool isInitialized() const { return isInitialized_;} void compute(){ } //! True if the preconditioner has been successfully computed, else false. bool isComputed() const {return isComputed_;} //! True if the preconditioner implements a transpose operator apply. bool hasTransposeApply() const { return true; } }; } //End Experimental } //End namespace KokkosSparse #endif
38.266187
122
0.686595
NexGenAnalytics
f4159273b922c3fe27b033cb6da52b8575f29052
1,013
hpp
C++
libs/rucksack/include/sge/rucksack/axis_policy2.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/rucksack/include/sge/rucksack/axis_policy2.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/rucksack/include/sge/rucksack/axis_policy2.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_RUCKSACK_AXIS_POLICY2_HPP_INCLUDED #define SGE_RUCKSACK_AXIS_POLICY2_HPP_INCLUDED #include <sge/rucksack/axis_fwd.hpp> #include <sge/rucksack/axis_policy.hpp> #include <sge/rucksack/axis_policy2_fwd.hpp> #include <sge/rucksack/detail/symbol.hpp> namespace sge::rucksack { class axis_policy2 { public: SGE_RUCKSACK_DETAIL_SYMBOL axis_policy2(sge::rucksack::axis_policy const &, sge::rucksack::axis_policy const &); [[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::axis_policy const &x() const; [[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::axis_policy const &y() const; [[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::axis_policy const & operator[](sge::rucksack::axis) const; private: sge::rucksack::axis_policy x_, y_; }; } #endif
27.378378
87
0.757157
cpreh
f416863d0f5f143e1f642bf2d3f786a52418e4d9
7,340
cpp
C++
mapnikvt/src/mapnikvt/CSSColorParser.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
6
2018-06-27T17:43:35.000Z
2021-06-29T18:50:49.000Z
mapnikvt/src/mapnikvt/CSSColorParser.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
22
2019-04-10T06:38:09.000Z
2022-01-20T08:12:02.000Z
mapnikvt/src/mapnikvt/CSSColorParser.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
5
2019-03-12T10:25:20.000Z
2021-12-28T10:18:56.000Z
#include "CSSColorParser.h" #include "StringUtils.h" #include <array> #include <sstream> #include <iomanip> #include <algorithm> namespace carto { namespace mvt { bool parseCSSColor(std::string name, unsigned int& value) { static const struct ColorEntry { const char* name; unsigned int value; } colorEntries[] = { { "aliceblue", 0xf0f8ff }, { "antiquewhite", 0xfaebd7 }, { "aqua", 0x00ffff }, { "aquamarine", 0x7fffd4 }, { "azure", 0xf0ffff }, { "beige", 0xf5f5dc }, { "bisque", 0xffe4c4 }, { "black", 0x000000 }, { "blanchedalmond", 0xffebcd }, { "blue", 0x0000ff }, { "blueviolet", 0x8a2be2 }, { "brown", 0xa52a2a }, { "burlywood", 0xdeb887 }, { "cadetblue", 0x5f9ea0 }, { "chartreuse", 0x7fff00 }, { "chocolate", 0xd2691e }, { "coral", 0xff7f50 }, { "cornflowerblue", 0x6495ed }, { "cornsilk", 0xfff8dc }, { "crimson", 0xdc143c }, { "cyan", 0x00ffff }, { "darkblue", 0x00008b }, { "darkcyan", 0x008b8b }, { "darkgoldenrod", 0xb8860b }, { "darkgray", 0xa9a9a9 }, { "darkgreen", 0x006400 }, { "darkkhaki", 0xbdb76b }, { "darkmagenta", 0x8b008b }, { "darkolivegreen", 0x556b2f }, { "darkorange", 0xff8c00 }, { "darkorchid", 0x9932cc }, { "darkred", 0x8b0000 }, { "darksalmon", 0xe9967a }, { "darkseagreen", 0x8fbc8f }, { "darkslateblue", 0x483d8b }, { "darkslategray", 0x2f4f4f }, { "darkturquoise", 0x00ced1 }, { "darkviolet", 0x9400d3 }, { "deeppink", 0xff1493 }, { "deepskyblue", 0x00bfff }, { "dimgray", 0x696969 }, { "dodgerblue", 0x1e90ff }, { "firebrick", 0xb22222 }, { "floralwhite", 0xfffaf0 }, { "forestgreen", 0x228b22 }, { "fuchsia", 0xff00ff }, { "gainsboro", 0xdcdcdc }, { "ghostwhite", 0xf8f8ff }, { "gold", 0xffd700 }, { "goldenrod", 0xdaa520 }, { "gray", 0x808080 }, { "green", 0x008000 }, { "greenyellow", 0xadff2f }, { "honeydew", 0xf0fff0 }, { "hotpink", 0xff69b4 }, { "indianred", 0xcd5c5c }, { "indigo", 0x4b0082 }, { "ivory", 0xfffff0 }, { "khaki", 0xf0e68c }, { "lavender", 0xe6e6fa }, { "lavenderblush", 0xfff0f5 }, { "lawngreen", 0x7cfc00 }, { "lemonchiffon", 0xfffacd }, { "lightblue", 0xadd8e6 }, { "lightcoral", 0xf08080 }, { "lightcyan", 0xe0ffff }, { "lightgoldenrodyellow", 0xfafad2 }, { "lightgreen", 0x90ee90 }, { "lightgrey", 0xd3d3d3 }, { "lightpink", 0xffb6c1 }, { "lightsalmon", 0xffa07a }, { "lightseagreen", 0x20b2aa }, { "lightskyblue", 0x87cefa }, { "lightslategray", 0x778899 }, { "lightsteelblue", 0xb0c4de }, { "lightyellow", 0xffffe0 }, { "lime", 0x00ff00 }, { "limegreen", 0x32cd32 }, { "linen", 0xfaf0e6 }, { "magenta", 0xff00ff }, { "maroon", 0x800000 }, { "mediumaquamarine", 0x66cdaa }, { "mediumblue", 0x0000cd }, { "mediumorchid", 0xba55d3 }, { "mediumpurple", 0x9370db }, { "mediumseagreen", 0x3cb371 }, { "mediumslateblue", 0x7b68ee }, { "mediumspringgreen", 0x00fa9a }, { "mediumturquoise", 0x48d1cc }, { "mediumvioletred", 0xc71585 }, { "midnightblue", 0x191970 }, { "mintcream", 0xf5fffa }, { "mistyrose", 0xffe4e1 }, { "moccasin", 0xffe4b5 }, { "navajowhite", 0xffdead }, { "navy", 0x000080 }, { "oldlace", 0xfdf5e6 }, { "olive", 0x808000 }, { "olivedrab", 0x6b8e23 }, { "orange", 0xffa500 }, { "orangered", 0xff4500 }, { "orchid", 0xda70d6 }, { "palegoldenrod", 0xeee8aa }, { "palegreen", 0x98fb98 }, { "paleturquoise", 0xafeeee }, { "palevioletred", 0xdb7093 }, { "papayawhip", 0xffefd5 }, { "peachpuff", 0xffdab9 }, { "peru", 0xcd853f }, { "pink", 0xffc0cb }, { "plum", 0xdda0dd }, { "powderblue", 0xb0e0e6 }, { "purple", 0x800080 }, { "red", 0xff0000 }, { "rosybrown", 0xbc8f8f }, { "royalblue", 0x4169e1 }, { "saddlebrown", 0x8b4513 }, { "salmon", 0xfa8072 }, { "sandybrown", 0xf4a460 }, { "seagreen", 0x2e8b57 }, { "seashell", 0xfff5ee }, { "sienna", 0xa0522d }, { "silver", 0xc0c0c0 }, { "skyblue", 0x87ceeb }, { "slateblue", 0x6a5acd }, { "slategray", 0x708090 }, { "snow", 0xfffafa }, { "springgreen", 0x00ff7f }, { "steelblue", 0x4682b4 }, { "tan", 0xd2b48c }, { "teal", 0x008080 }, { "thistle", 0xd8bfd8 }, { "tomato", 0xff6347 }, { "turquoise", 0x40e0d0 }, { "violet", 0xee82ee }, { "wheat", 0xf5deb3 }, { "white", 0xffffff }, { "whitesmoke", 0xf5f5f5 }, { "yellow", 0xffff00 }, { "yellowgreen", 0x9acd32 }, }; name = toLower(name); auto begin = &colorEntries[0]; auto end = &colorEntries[0] + sizeof(colorEntries) / sizeof(ColorEntry); auto it = std::lower_bound(begin, end, name, [](const ColorEntry& entry, const std::string& entryName) { return entry.name < entryName; }); if (it != end) { if (it->name == name) { value = it->value | 0xff000000; return true; } } if (name == "transparent") { value = 0; return true; } if (name.substr(0, 1) == "#") { std::string code(name.begin() + 1, name.end()); if (code.size() == 3 || code.size() == 4) { code.clear(); for (std::size_t i = 1; i < name.size(); i++) { code += name[i]; code += name[i]; } } else if (code.size() != 6 && code.size() != 8) { return false; } std::array<unsigned int, 4> components{ { 0, 0, 0, 255 } }; for (std::size_t i = 0; i < code.size() / 2; i++) { std::istringstream ss(code.substr(i * 2, 2)); ss >> std::hex >> components[i]; if (ss.bad()) { return false; } } value = (components[3] << 24) | (components[0] << 16) | (components[1] << 8) | components[2]; return true; } return false; } } }
37.44898
112
0.440054
farfromrefug
f41820289cc4554b54692b66b714c05a14cf0815
1,733
cc
C++
ProSupplementalData.cc
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
2
2018-11-14T11:18:49.000Z
2018-11-17T05:13:52.000Z
ProSupplementalData.cc
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
null
null
null
ProSupplementalData.cc
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
null
null
null
#include "ProSupplementalData.h" using namespace std; using namespace domtools; using namespace eppobject::epp; epp_string ProSupplementalData::toXML() { domtools::xml_string_output xmltext; xmltext.setWhitespace(false); xmltext.beginTag("supplementalData:"+(*m_op)); xmltext.putAttribute("xmlns:supplementalData","urn:afilias:params:xml:ns:supplementalData-1.0"); //xmltext.putAttribute("xsi:schemaLocation","urn:afilias:params:xml:ns:supplementalData-1.0 supplementalData-1.0.xsd"); epp_string json = "{"+ quoted("profession") + ": " + quoted(*m_profession) + ", " + quoted("authorityName") + ": " + quoted(*m_authorityName) + ", " + quoted("authorityUrl") + ": " + quoted(*m_authorityUrl) + ", " + quoted("licenseNumber") + ": " + quoted(*m_licenseNumber) + "}"; xmltext.beginTag("supplementalData:value"); xmltext.putCDATA(json); /// XXX xmltext.endTag("supplementalData:value"); xmltext.endTag("supplementalData:"+(*m_op)); printf("EXT XML: %s\n",xmltext.getString().c_str()); return xmltext.getString(); }; epp_string ProSupplementalData::quoted (const epp_string & str) { return "\""+str+"\""; } void ProSupplementalData::fromXML (const epp_string & xml) { printf("fromXML: %s",xml.c_str()); DOM_Document doc = createDOM_Document(xml); DOM_Node dataNode = domtools::getSingleTag(doc, "supplementalData:infData"); if (!dataNode.isNull()) { string nodeValue; DOM_Node valueNode = domtools::getSingleTag(doc, "supplementalData:value"); if (!valueNode.isNull()) { getNodeData(valueNode, nodeValue); m_profession.ref(new epp_string(nodeValue)); }; }; };
32.092593
123
0.661281
hiqsol
f419dab890a8d3c824b32aa5b2db4bf503e94e88
436
cpp
C++
PathTracer/src/platform/opengl/rendering/pipeline/GLPipeline.cpp
Andrispowq/PathTracer
8965ddf5c70f55740955e24242981633f000a354
[ "Apache-2.0" ]
1
2020-12-04T13:36:03.000Z
2020-12-04T13:36:03.000Z
PathTracer/src/platform/opengl/rendering/pipeline/GLPipeline.cpp
Andrispowq/PathTracer
8965ddf5c70f55740955e24242981633f000a354
[ "Apache-2.0" ]
null
null
null
PathTracer/src/platform/opengl/rendering/pipeline/GLPipeline.cpp
Andrispowq/PathTracer
8965ddf5c70f55740955e24242981633f000a354
[ "Apache-2.0" ]
null
null
null
#include "Includes.hpp" #include "GLPipeline.h" namespace Prehistoric { GLPipeline::GLPipeline(Window* window, AssetManager* manager, ShaderHandle shader) : Pipeline(window, manager, shader) { } void GLPipeline::BindPipeline(CommandBuffer* buffer) const { this->buffer = buffer; shader->Bind(buffer); } void GLPipeline::RenderPipeline() const { } void GLPipeline::UnbindPipeline() const { shader->Unbind(); } };
16.769231
83
0.715596
Andrispowq
f41d2ebfcd0b9298fbc806df961d0606b68acc6b
2,321
cpp
C++
src/tests/mkdarts.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
null
null
null
src/tests/mkdarts.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
null
null
null
src/tests/mkdarts.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
1
2018-05-18T17:17:35.000Z
2018-05-18T17:17:35.000Z
/* Darts -- Double-ARray Trie System $Id: mkdarts.cpp 1674 2008-03-22 11:21:34Z taku $; Copyright(C) 2001-2007 Taku Kudo <taku@chasen.org> All rights reserved. */ #include <darts.h> #include <cstdio> #include <fstream> #include <iostream> #include <vector> #include <string> #include <set> using namespace std; int progress_bar(size_t current, size_t total) { static char bar[] = "*******************************************"; static int scale = sizeof(bar) - 1; static int prev = 0; int cur_percentage = static_cast<int>(100.0 * current/total); int bar_len = static_cast<int>(1.0 * current*scale/total); if (prev != cur_percentage) { printf("Making Double Array: %3d%% |%.*s%*s| ", cur_percentage, bar_len, bar, scale - bar_len, ""); if (cur_percentage == 100) printf("\n"); else printf("\r"); fflush(stdout); } prev = cur_percentage; return 1; }; int main(int argc, char **argv) { if (argc < 3) { std::cerr << "Usage: " << argv[0] << " File Index" << std::endl; return -1; } std::string file = argv[argc-2]; std::string index = argv[argc-1]; Darts::DoubleArray da; //Darts::DoubleArrayUint16 da2; std::vector<const char *> key; std::istream *is; if (file == "-") { is = &std::cin; } else { is = new std::ifstream(file.c_str()); } if (!*is) { std::cerr << "Cannot Open: " << file << std::endl; return -1; } set<string> keyset; std::string line; while (std::getline(*is, line)) { keyset.insert(line); } if (file != "-") delete is; printf("vector size: %zu\n", keyset.size()); set<string>::iterator itr = keyset.begin(); set<string>::iterator itrEnd= keyset.end(); while (itr!=itrEnd) { char *tmp = new char[itr->size()+1]; std::strcpy(tmp, itr->c_str()); key.push_back(tmp); printf("%s\n", itr->c_str()); itr++; } if (da.build(key.size(), &key[0], 0, 0, &progress_bar) != 0 || da.save(index.c_str()) != 0) { std::cerr << "Error: cannot build double array " << file << std::endl; return -1; }; for (unsigned int i = 0; i < key.size(); i++) delete [] key[i]; std::cout << "Done!, Compression Ratio: " << 100.0 * da.nonzero_size() / da.size() << " %" << std::endl; return 0; }
22.533981
75
0.559673
lzzgeo
f41f3dd5a0605c7a6f8926f698142e78dfd77be3
7,526
cpp
C++
yave/renderer/LightingPass.cpp
ValtoGameEngines/Yave-Engine
aa8850c1e46ba2017db799eca43cee835db3d3b8
[ "MIT" ]
2
2020-07-20T19:05:26.000Z
2021-01-09T14:42:22.000Z
yave/renderer/LightingPass.cpp
ValtoGameEngines/Yave-Engine
aa8850c1e46ba2017db799eca43cee835db3d3b8
[ "MIT" ]
null
null
null
yave/renderer/LightingPass.cpp
ValtoGameEngines/Yave-Engine
aa8850c1e46ba2017db799eca43cee835db3d3b8
[ "MIT" ]
1
2020-06-29T08:05:53.000Z
2020-06-29T08:05:53.000Z
/******************************* Copyright (c) 2016-2020 Grégoire Angerand 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. **********************************/ #include "LightingPass.h" #include <yave/device/Device.h> #include <yave/framegraph/FrameGraph.h> #include <yave/ecs/EntityWorld.h> #include <yave/components/PointLightComponent.h> #include <yave/components/SpotLightComponent.h> #include <yave/components/TransformableComponent.h> #include <yave/components/DirectionalLightComponent.h> #include <yave/entities/entities.h> #include <yave/meshes/StaticMesh.h> #include <y/core/Chrono.h> #include <y/io2/File.h> namespace yave { static constexpr ImageFormat lighting_format = VK_FORMAT_R16G16B16A16_SFLOAT; static constexpr usize max_directional_lights = 16; static constexpr usize max_point_lights = 1024; static constexpr usize max_spot_lights = 1024; static constexpr usize max_shadow_lights = 128; static FrameGraphMutableImageId ambient_pass(FrameGraphPassBuilder& builder, const math::Vec2ui& size, const GBufferPass& gbuffer, const std::shared_ptr<IBLProbe>& ibl_probe) { y_debug_assert(ibl_probe != nullptr); struct PushData { u32 light_count; }; const SceneView& scene = gbuffer.scene_pass.scene_view; const auto lit = builder.declare_image(lighting_format, size); const auto directional_buffer = builder.declare_typed_buffer<uniform::DirectionalLight>(max_directional_lights); builder.add_uniform_input(gbuffer.depth, 0, PipelineStage::ComputeBit); builder.add_uniform_input(gbuffer.color, 0, PipelineStage::ComputeBit); builder.add_uniform_input(gbuffer.normal, 0, PipelineStage::ComputeBit); builder.add_uniform_input(*ibl_probe, 0, PipelineStage::ComputeBit); builder.add_uniform_input(builder.device()->device_resources().brdf_lut(), 0, PipelineStage::ComputeBit); builder.add_uniform_input(gbuffer.scene_pass.camera_buffer, 0, PipelineStage::ComputeBit); builder.add_storage_input(directional_buffer, 0, PipelineStage::ComputeBit); builder.add_storage_output(lit, 0, PipelineStage::ComputeBit); builder.map_update(directional_buffer); builder.set_render_func([=](CmdBufferRecorder& recorder, const FrameGraphPass* self) { PushData push_data{0}; TypedMapping<uniform::DirectionalLight> mapping = self->resources().mapped_buffer(directional_buffer); for(auto [l] : scene.world().view(DirectionalLightArchetype()).components()) { mapping[push_data.light_count++] = { -l.direction().normalized(), 0, l.color() * l.intensity(), 0 }; } const auto& program = recorder.device()->device_resources()[DeviceResources::DeferredAmbientProgram]; recorder.dispatch_size(program, size, {self->descriptor_sets()[0]}, push_data); }); return lit; } static void local_lights_pass(FrameGraphMutableImageId lit, FrameGraphPassBuilder& builder, const math::Vec2ui& size, const GBufferPass& gbuffer, const ShadowMapPass& shadow_pass) { struct PushData { u32 point_count = 0; u32 spot_count = 0; u32 shadow_count = 0; }; const SceneView& scene = gbuffer.scene_pass.scene_view; const auto point_buffer = builder.declare_typed_buffer<uniform::PointLight>(max_point_lights); const auto spot_buffer = builder.declare_typed_buffer<uniform::SpotLight>(max_spot_lights); const auto shadow_buffer = builder.declare_typed_buffer<uniform::ShadowMapParams>(max_shadow_lights); builder.add_uniform_input(gbuffer.depth, 0, PipelineStage::ComputeBit); builder.add_uniform_input(gbuffer.color, 0, PipelineStage::ComputeBit); builder.add_uniform_input(gbuffer.normal, 0, PipelineStage::ComputeBit); builder.add_uniform_input(shadow_pass.shadow_map, 0, PipelineStage::ComputeBit); builder.add_uniform_input(gbuffer.scene_pass.camera_buffer, 0, PipelineStage::ComputeBit); builder.add_storage_input(point_buffer, 0, PipelineStage::ComputeBit); builder.add_storage_input(spot_buffer, 0, PipelineStage::ComputeBit); builder.add_storage_input(shadow_buffer, 0, PipelineStage::ComputeBit); builder.add_storage_output(lit, 0, PipelineStage::ComputeBit); builder.map_update(point_buffer); builder.map_update(spot_buffer); builder.map_update(shadow_buffer); builder.set_render_func([=](CmdBufferRecorder& recorder, const FrameGraphPass* self) { PushData push_data{0, 0, 0}; { TypedMapping<uniform::PointLight> mapping = self->resources().mapped_buffer(point_buffer); for(auto [t, l] : scene.world().view(PointLightArchetype()).components()) { mapping[push_data.point_count++] = { t.position(), l.radius(), l.color() * l.intensity(), std::max(math::epsilon<float>, l.falloff()) }; } } { TypedMapping<uniform::SpotLight> mapping = self->resources().mapped_buffer(spot_buffer); TypedMapping<uniform::ShadowMapParams> shadow_mapping = self->resources().mapped_buffer(shadow_buffer); for(auto spot : scene.world().view(SpotLightArchetype())) { auto [t, l] = spot.components(); u32 shadow_index = u32(-1); if(l.cast_shadow()) { if(const auto it = shadow_pass.sub_passes->lights.find(spot.index()); it != shadow_pass.sub_passes->lights.end()) { shadow_mapping[shadow_index = push_data.shadow_count++] = it->second; } } mapping[push_data.spot_count++] = { t.position(), l.radius(), l.color() * l.intensity(), std::max(math::epsilon<float>, l.falloff()), -t.forward(), std::cos(l.half_angle()), std::max(math::epsilon<float>, l.angle_exponent()), shadow_index, {} }; } } if(push_data.point_count || push_data.spot_count) { const auto& program = recorder.device()->device_resources()[DeviceResources::DeferredLocalsProgram]; recorder.dispatch_size(program, size, {self->descriptor_sets()[0]}, push_data); } }); } LightingPass LightingPass::create(FrameGraph& framegraph, const GBufferPass& gbuffer, const std::shared_ptr<IBLProbe>& ibl_probe, const ShadowMapPassSettings& settings) { const math::Vec2ui size = framegraph.image_size(gbuffer.depth); const SceneView& scene = gbuffer.scene_pass.scene_view; LightingPass pass; pass.shadow_pass = ShadowMapPass::create(framegraph, scene, settings); FrameGraphPassBuilder ambient_builder = framegraph.add_pass("Ambient/Sun pass"); const auto lit = ambient_pass(ambient_builder, size, gbuffer, ibl_probe); FrameGraphPassBuilder local_builder = framegraph.add_pass("Lighting pass"); local_lights_pass(lit, local_builder, size, gbuffer, pass.shadow_pass); pass.lit = lit; return pass; } }
38.397959
170
0.751395
ValtoGameEngines
f41f552ef840bfc505608ad093bcab39b1b2860c
4,975
cpp
C++
src/plugins/playback/adplug/adplug_lib/src/raw.cpp
emoon/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
67
2018-01-17T17:18:37.000Z
2020-08-24T23:45:56.000Z
src/plugins/playback/adplug/adplug_lib/src/raw.cpp
emoon/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
132
2018-01-17T17:43:25.000Z
2020-09-01T07:41:17.000Z
src/plugins/playback/adplug/adplug_lib/src/raw.cpp
HippoPlayer/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
5
2021-02-12T15:23:31.000Z
2022-01-09T15:16:21.000Z
/* * Adplug - Replayer for many OPL2/OPL3 audio file formats. * Copyright (C) 1999 - 2005 Simon Peter, <dn.tlp@gmx.net>, et al. * * This library 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 2.1 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * raw.c - RAW Player by Simon Peter <dn.tlp@gmx.net> */ /* * Copyright (c) 2015 - 2017 Wraithverge <liam82067@yahoo.com> * - Preliminary support for displaying arbitrary Tag data. (2015) * - Realigned to Tabs. (2017) * - Added Member pointers. (2017) * - Finalized Tag support. (2017) */ #include <cstring> #include "raw.h" /*** public methods *************************************/ CPlayer *CrawPlayer::factory(Copl *newopl) { return new CrawPlayer(newopl); } bool CrawPlayer::load(const std::string &filename, const CFileProvider &fp) { binistream *f = fp.open(filename); if (!f) return false; char id[8]; unsigned long i = 0; // file validation section f->readString(id, 8); if (strncmp(id,"RAWADATA",8)) { fp.close (f); return false; } // load section this->clock = f->readInt(2); // clock speed this->length = fp.filesize(f); if (this->length <= 10) { fp.close (f); return false; } this->length = (this->length - 10) / 2; // Wraithverge: total data-size. this->data = new Tdata [this->length]; bool tagdata = false; title[0] = 0; author[0] = 0; desc[0] = 0; for (i = 0; i < this->length; i++) { // Do not store tag data in track data. this->data[i].param = (tagdata ? 0xFF : f->readInt(1)); this->data[i].command = (tagdata ? 0xFF : f->readInt(1)); // Continue trying to stop at the RAW EOF data marker. if (!tagdata && this->data[i].param == 0xFF && this->data[i].command == 0xFF) { unsigned char tagCode = f->readInt(1); if (tagCode == 0x1A) { // Tag marker found. tagdata = true; } else if (tagCode == 0) { // Old comment (music archive 2004) f->readString(desc, 1023, 0); } else { // This is not tag marker, revert. f->seek(-1, binio::Add); } } } if (tagdata) { // The arbitrary Tag Data section begins here. // "title" is maximum 40 characters long. f->readString(title, 40, 0); // Skip "author" if Tag marker byte is missing. if (f->readInt(1) != 0x1B) { f->seek(-1, binio::Add); // Check for older version tag (e.g. stunts.raw) if (f->readInt(1) >= 0x20) { f->seek(-1, binio::Add); f->readString(author, 60, 0); f->readString(desc, 1023, 0); goto end_section; } else f->seek(-1, binio::Add); goto desc_section; } // "author" is maximum 40 characters long. f->readString(author, 40, 0); desc_section: // Skip "desc" if Tag marker byte is missing. if (f->readInt(1) != 0x1C) { goto end_section; } // "desc" is now maximum 1023 characters long (it was 140). f->readString(desc, 1023, 0); } end_section: fp.close(f); rewind(0); return true; } bool CrawPlayer::update() { bool setspeed = 0; if (this->pos >= this->length) return false; if (this->del) { del--; return !songend; } do { setspeed = false; if (this->pos >= this->length) return false; switch(this->data[this->pos].command) { case 0: this->del = this->data[this->pos].param - 1; break; case 2: if (!this->data[this->pos].param) { pos++; if (this->pos >= this->length) return false; this->speed = this->data[this->pos].param + (this->data[this->pos].command << 8); setspeed = true; } else opl->setchip(this->data[this->pos].param - 1); break; case 0xff: if (this->data[this->pos].param == 0xff) { rewind(0); // auto-rewind song songend = true; return !songend; } break; default: opl->write(this->data[this->pos].command, this->data[this->pos].param); break; } } while (this->data[this->pos++].command || setspeed); return !songend; } void CrawPlayer::rewind(int subsong) { pos = del = 0; speed = clock; songend = false; opl->init(); opl->write(1, 32); // go to 9 channel mode } float CrawPlayer::getrefresh() { // timer oscillator speed / wait register = clock frequency return 1193180.0 / (speed ? speed : 0xffff); }
27.185792
89
0.602211
emoon
f421240c152d166a0e6e1371ea7c5f68e3181aba
333
cpp
C++
PS_I_2.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
PS_I_2.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
PS_I_2.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; long taskOfPairing(vector<long> freq) { long ans(0),temp(0); for(long i=0;i<freq.size();i++) { ans += freq[i]/2; temp += freq[i]%2; if(temp==2) { ans++; temp=0; } } return ans; }
15.136364
39
0.417417
prameetu
f421db30335dc6621ce478e934a26609a36b2a70
6,624
cpp
C++
GlobalIllumination/ObjLoader.cpp
wzchua/graphic
71d154b56a268cce6a1b06e275083210e205aa60
[ "Apache-2.0" ]
null
null
null
GlobalIllumination/ObjLoader.cpp
wzchua/graphic
71d154b56a268cce6a1b06e275083210e205aa60
[ "Apache-2.0" ]
null
null
null
GlobalIllumination/ObjLoader.cpp
wzchua/graphic
71d154b56a268cce6a1b06e275083210e205aa60
[ "Apache-2.0" ]
null
null
null
#include "ObjLoader.h" static bool fileExists(const std::string & fileName) { struct stat info; int ret = -1; ret = stat(fileName.c_str(), &info); return 0 == ret; } bool ObjLoader::loadObj(const std::string & path, SceneMaterialManager & sceneMatManager, glm::vec3 & min, glm::vec3 & max) { tinyobj::attrib_t attrib; min = glm::vec3(std::numeric_limits<float>::max()); max = -min; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto lastIndex = path.find_last_of('/'); std::string baseDir = path.substr(0, lastIndex + 1); std::cout << baseDir << '\n'; stbi_set_flip_vertically_on_load(true); bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, path.c_str(), baseDir.c_str()); if (!err.empty()) { std::cerr << err << std::endl; } if (!ret) { std::cerr << "Load failed: " << path << std::endl; return false; } printf("# of vertices = %d\n", (int)(attrib.vertices.size()) / 3); printf("# of normals = %d\n", (int)(attrib.normals.size()) / 3); printf("# of texcoords = %d\n", (int)(attrib.texcoords.size()) / 2); printf("# of materials = %d\n", (int)materials.size()); printf("# of shapes = %d\n", (int)shapes.size()); materials.push_back(tinyobj::material_t()); for (size_t i = 0; i < materials.size(); i++) { printf("material[%d].diffuse_texname = %s\n", int(i), materials[i].diffuse_texname.c_str()); } std::cout << baseDir << "\n"; for (auto const& m : materials) { printf("material name: %s\n", m.name.c_str()); if (m.ambient_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.ambient_texname, baseDir); } if (m.diffuse_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.diffuse_texname, baseDir); } if (m.bump_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.bump_texname, baseDir); } if (m.alpha_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.alpha_texname, baseDir); } if (m.specular_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.specular_texname, baseDir); } } for (auto const& shape : shapes) { std::vector<tinyobj::material_t> matList; std::map<int, size_t> matMap; if (shape.mesh.material_ids.size() == 0) { matList.push_back(materials[materials.size() - 1]); } else { for (auto const & id : shape.mesh.material_ids) { if (matMap.find(id) == matMap.end()) { matMap[id] = matList.size(); matList.push_back(materials[id]); } } } if (matList.size() > 1) { // break different material faces into different shapes std::vector<tinyobj::shape_t> newShapes; newShapes.reserve(matList.size()); for (int i = 0; i < matList.size(); i++) { newShapes.push_back(tinyobj::shape_t()); newShapes[i].name = shape.name; } for (int i = 0; i < shape.mesh.material_ids.size(); i++) { int id = shape.mesh.material_ids[i]; size_t index = matMap[id]; newShapes[index].mesh.material_ids.push_back(shape.mesh.material_ids[i]); newShapes[index].mesh.num_face_vertices.push_back(shape.mesh.num_face_vertices[i]); newShapes[index].mesh.indices.push_back(shape.mesh.indices[i * 3 + 0]); newShapes[index].mesh.indices.push_back(shape.mesh.indices[i * 3 + 1]); newShapes[index].mesh.indices.push_back(shape.mesh.indices[i * 3 + 2]); } for (int i = 0; i < matList.size(); i++) { GLuint64 texAmbient, texDiffuse, texAlpha, texHeight; sceneMatManager.getTextureHandles(matList[i], texAmbient, texDiffuse, texAlpha, texHeight); GLuint64 texHandles[4] = { texAmbient, texDiffuse, texAlpha, texHeight }; sceneMatManager.addMaterialShapeGroup(newShapes[i], attrib, matList[i], texHandles); } } else { GLuint64 texAmbient, texDiffuse, texAlpha, texHeight; sceneMatManager.getTextureHandles(matList[0], texAmbient, texDiffuse, texAlpha, texHeight); GLuint64 texHandles[4] = { texAmbient, texDiffuse, texAlpha, texHeight }; sceneMatManager.addMaterialShapeGroup(shape, attrib, matList[0], texHandles); } } return true; } void ObjLoader::loadTexture(std::map<std::string, GLuint>& textureMap, const std::string & textureFilename, const std::string & baseDir) { //load if not loaded if (textureMap.find(textureFilename) == textureMap.end()) { GLuint texture_id; int w, h; int comp; std::string texture_filename = baseDir + textureFilename; if (!fileExists(texture_filename)) { std::cerr << "Unable to find file " << textureFilename << std::endl; exit(-1); } unsigned char* image = stbi_load(texture_filename.c_str(), &w, &h, &comp, STBI_default); if (!image) { std::cerr << "Unable to load texture: " << texture_filename << std::endl; exit(1); } std::cout << "Loaded texture: " << texture_filename << ", w = " << w << ", h = " << h << ", comp = " << comp << std::endl; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (comp == 1) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, image); } else if (comp == 2) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RG, w, h, 0, GL_RG, GL_UNSIGNED_BYTE, image); } else if (comp == 3) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, image); } else if (comp == 4) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); } else { assert(0); // TODO } glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); stbi_image_free(image); textureMap.insert(std::make_pair(textureFilename, texture_id)); } }
40.638037
136
0.581824
wzchua
f422ca1e05962361f69734a30a796b7f17fbfcf5
4,762
cpp
C++
src/he_plain_tensor.cpp
jopasserat/he-transformer
d2865be507d2e20568ca5289513925c813aa59e6
[ "Apache-2.0" ]
null
null
null
src/he_plain_tensor.cpp
jopasserat/he-transformer
d2865be507d2e20568ca5289513925c813aa59e6
[ "Apache-2.0" ]
null
null
null
src/he_plain_tensor.cpp
jopasserat/he-transformer
d2865be507d2e20568ca5289513925c813aa59e6
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2018-2019 Intel Corporation // // 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 <cstring> #include "he_plain_tensor.hpp" #include "seal/he_seal_backend.hpp" ngraph::he::HEPlainTensor::HEPlainTensor(const element::Type& element_type, const Shape& shape, const HESealBackend* he_seal_backend, const bool batched, const std::string& name) : ngraph::he::HETensor(element_type, shape, he_seal_backend, batched, name) { m_num_elements = m_descriptor->get_tensor_layout()->get_size() / m_batch_size; m_plaintexts.resize(m_num_elements); } void ngraph::he::HEPlainTensor::write(const void* source, size_t tensor_offset, size_t n) { check_io_bounds(source, tensor_offset, n / m_batch_size); const element::Type& element_type = get_tensor_layout()->get_element_type(); size_t type_byte_size = element_type.size(); size_t dst_start_idx = tensor_offset / type_byte_size; size_t num_elements_to_write = n / (type_byte_size * m_batch_size); if (num_elements_to_write == 1) { const void* src_with_offset = (void*)((char*)source); size_t dst_idx = dst_start_idx; if (m_batch_size > 1 && is_batched()) { std::vector<float> values(m_batch_size); for (size_t j = 0; j < m_batch_size; ++j) { const void* src = (void*)((char*)source + type_byte_size * (j * num_elements_to_write)); float val = *(float*)(src); values[j] = val; } m_plaintexts[dst_idx].set_values(values); } else { float f = *(float*)(src_with_offset); m_plaintexts[dst_idx].set_values({f}); } } else { #pragma omp parallel for for (size_t i = 0; i < num_elements_to_write; ++i) { const void* src_with_offset = (void*)((char*)source + i * type_byte_size); size_t dst_idx = dst_start_idx + i; if (m_batch_size > 1) { std::vector<float> values(m_batch_size); for (size_t j = 0; j < m_batch_size; ++j) { const void* src = (void*)((char*)source + type_byte_size * (i + j * num_elements_to_write)); float val = *(float*)(src); values[j] = val; } m_plaintexts[dst_idx].set_values(values); } else { float f = *(float*)(src_with_offset); m_plaintexts[dst_idx].set_values({f}); } } } } void ngraph::he::HEPlainTensor::read(void* target, size_t tensor_offset, size_t n) const { NGRAPH_CHECK(tensor_offset == 0, "Only support reading from beginning of tensor"); check_io_bounds(target, tensor_offset, n); const element::Type& element_type = get_tensor_layout()->get_element_type(); NGRAPH_CHECK(element_type == element::f32, "Only support float32"); size_t type_byte_size = element_type.size(); size_t src_start_idx = tensor_offset / type_byte_size; size_t num_elements_to_read = n / (type_byte_size * m_batch_size); if (num_elements_to_read == 1) { void* dst_with_offset = (void*)((char*)target); size_t src_idx = src_start_idx; std::vector<float> values = m_plaintexts[src_idx].get_values(); memcpy(dst_with_offset, &values[0], type_byte_size * m_batch_size); } else { #pragma omp parallel for for (size_t i = 0; i < num_elements_to_read; ++i) { size_t src_idx = src_start_idx + i; std::vector<float> values = m_plaintexts[src_idx].get_values(); NGRAPH_CHECK(values.size() >= m_batch_size, "values size ", values.size(), " is smaller than batch size ", m_batch_size); for (size_t j = 0; j < m_batch_size; ++j) { void* dst_with_offset = (void*)((char*)target + type_byte_size * (i + j * num_elements_to_read)); const void* src = (void*)(&values[j]); memcpy(dst_with_offset, src, type_byte_size); } } } }
39.032787
80
0.599748
jopasserat
f424130cbd1912eb611a58dc95b3f24218a124c6
29,370
cpp
C++
face-liveness/face2/LandmarkDetectorFunc.cpp
ForrestPi/FaceSolution
cf19b2916a8bf285e457903e8d202055b092fc73
[ "MIT" ]
1
2022-01-04T02:24:48.000Z
2022-01-04T02:24:48.000Z
face-liveness/face2/LandmarkDetectorFunc.cpp
ForrestPi/FaceSolution
cf19b2916a8bf285e457903e8d202055b092fc73
[ "MIT" ]
null
null
null
face-liveness/face2/LandmarkDetectorFunc.cpp
ForrestPi/FaceSolution
cf19b2916a8bf285e457903e8d202055b092fc73
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2016, Carnegie Mellon University and University of Cambridge, // all rights reserved. // // THIS SOFTWARE IS PROVIDED �AS IS� FOR ACADEMIC USE ONLY AND ANY EXPRESS // OR IMPLIED WARRANTIES WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY. // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Notwithstanding the license granted herein, Licensee acknowledges that certain components // of the Software may be covered by so-called �open source� software licenses (�Open Source // Components�), which means any software licenses approved as open source licenses by the // Open Source Initiative or any substantially similar licenses, including without limitation any // license that, as a condition of distribution of the software licensed under such license, // requires that the distributor make the software available in source code format. Licensor shall // provide a list of Open Source Components for a particular version of the Software upon // Licensee�s request. Licensee will comply with the applicable terms of such licenses and to // the extent required by the licenses covering Open Source Components, the terms of such // licenses will apply in lieu of the terms of this Agreement. To the extent the terms of the // licenses applicable to Open Source Components prohibit any of the restrictions in this // License Agreement with respect to such Open Source Component, such restrictions will not // apply to such Open Source Component. To the extent the terms of the licenses applicable to // Open Source Components require Licensor to make an offer to provide source code or // related information in connection with the Software, such offer is hereby made. Any request // for source code or related information should be directed to cl-face-tracker-distribution@lists.cam.ac.uk // Licensee acknowledges receipt of notices for the Open Source Components for the initial // delivery of the Software. // * Any publications arising from the use of this software, including but // not limited to academic journal and conference publications, technical // reports and manuals, must cite at least one of the following works: // // OpenFace: an open source facial behavior analysis toolkit // Tadas Baltru�aitis, Peter Robinson, and Louis-Philippe Morency // in IEEE Winter Conference on Applications of Computer Vision, 2016 // // Rendering of Eyes for Eye-Shape Registration and Gaze Estimation // Erroll Wood, Tadas Baltru�aitis, Xucong Zhang, Yusuke Sugano, Peter Robinson, and Andreas Bulling // in IEEE International. Conference on Computer Vision (ICCV), 2015 // // Cross-dataset learning and person-speci?c normalisation for automatic Action Unit detection // Tadas Baltru�aitis, Marwa Mahmoud, and Peter Robinson // in Facial Expression Recognition and Analysis Challenge, // IEEE International Conference on Automatic Face and Gesture Recognition, 2015 // // Constrained Local Neural Fields for robust facial landmark detection in the wild. // Tadas Baltru�aitis, Peter Robinson, and Louis-Philippe Morency. // in IEEE Int. Conference on Computer Vision Workshops, 300 Faces in-the-Wild Challenge, 2013. // /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "LandmarkDetectorFunc.h" // OpenCV includes #include <opencv2/core/core.hpp> #include <opencv2/calib3d.hpp> #include <opencv2/imgproc.hpp> // System includes #include <vector> using namespace LandmarkDetector; // Getting a head pose estimate from the currently detected landmarks (rotation with respect to point camera) // The format returned is [Tx, Ty, Tz, Eul_x, Eul_y, Eul_z] cv::Vec6d LandmarkDetector::GetPoseCamera(const CLNF& clnf_model, double fx, double fy, double cx, double cy) { if(!clnf_model.detected_landmarks.empty() && clnf_model.params_global[0] != 0) { double Z = fx / clnf_model.params_global[0]; double X = ((clnf_model.params_global[4] - cx) * (1.0/fx)) * Z; double Y = ((clnf_model.params_global[5] - cy) * (1.0/fy)) * Z; return cv::Vec6d(X, Y, Z, clnf_model.params_global[1], clnf_model.params_global[2], clnf_model.params_global[3]); } else { return cv::Vec6d(0,0,0,0,0,0); } } // Getting a head pose estimate from the currently detected landmarks (rotation in world coordinates) // The format returned is [Tx, Ty, Tz, Eul_x, Eul_y, Eul_z] cv::Vec6d LandmarkDetector::GetPoseWorld(const CLNF& clnf_model, double fx, double fy, double cx, double cy) { if(!clnf_model.detected_landmarks.empty() && clnf_model.params_global[0] != 0) { double Z = fx / clnf_model.params_global[0]; double X = ((clnf_model.params_global[4] - cx) * (1.0/fx)) * Z; double Y = ((clnf_model.params_global[5] - cy) * (1.0/fy)) * Z; // Here we correct for the camera orientation, for this need to determine the angle the camera makes with the head pose double z_x = cv::sqrt(X * X + Z * Z); double eul_x = atan2(Y, z_x); double z_y = cv::sqrt(Y * Y + Z * Z); double eul_y = -atan2(X, z_y); cv::Matx33d camera_rotation = LandmarkDetector::Euler2RotationMatrix(cv::Vec3d(eul_x, eul_y, 0)); cv::Matx33d head_rotation = LandmarkDetector::AxisAngle2RotationMatrix(cv::Vec3d(clnf_model.params_global[1], clnf_model.params_global[2], clnf_model.params_global[3])); cv::Matx33d corrected_rotation = camera_rotation.t() * head_rotation; cv::Vec3d euler_corrected = LandmarkDetector::RotationMatrix2Euler(corrected_rotation); return cv::Vec6d(X, Y, Z, euler_corrected[0], euler_corrected[1], euler_corrected[2]); } else { return cv::Vec6d(0,0,0,0,0,0); } } // Getting a head pose estimate from the currently detected landmarks, with appropriate correction due to orthographic camera issue // This is because rotation estimate under orthographic assumption is only correct close to the centre of the image // This method returns a corrected pose estimate with respect to world coordinates (Experimental) // The format returned is [Tx, Ty, Tz, Eul_x, Eul_y, Eul_z] cv::Vec6d LandmarkDetector::GetCorrectedPoseWorld(const CLNF& clnf_model, double fx, double fy, double cx, double cy) { if(!clnf_model.detected_landmarks.empty() && clnf_model.params_global[0] != 0) { // This is used as an initial estimate for the iterative PnP algorithm double Z = fx / clnf_model.params_global[0]; double X = ((clnf_model.params_global[4] - cx) * (1.0/fx)) * Z; double Y = ((clnf_model.params_global[5] - cy) * (1.0/fy)) * Z; // Correction for orientation // 2D points cv::Mat_<double> landmarks_2D = clnf_model.detected_landmarks; landmarks_2D = landmarks_2D.reshape(1, 2).t(); // 3D points cv::Mat_<double> landmarks_3D; clnf_model.pdm.CalcShape3D(landmarks_3D, clnf_model.params_local); landmarks_3D = landmarks_3D.reshape(1, 3).t(); // Solving the PNP model // The camera matrix cv::Matx33d camera_matrix(fx, 0, cx, 0, fy, cy, 0, 0, 1); cv::Vec3d vec_trans(X, Y, Z); cv::Vec3d vec_rot(clnf_model.params_global[1], clnf_model.params_global[2], clnf_model.params_global[3]); cv::solvePnP(landmarks_3D, landmarks_2D, camera_matrix, cv::Mat(), vec_rot, vec_trans, true); cv::Vec3d euler = LandmarkDetector::AxisAngle2Euler(vec_rot); return cv::Vec6d(vec_trans[0], vec_trans[1], vec_trans[2], vec_rot[0], vec_rot[1], vec_rot[2]); } else { return cv::Vec6d(0,0,0,0,0,0); } } // Getting a head pose estimate from the currently detected landmarks, with appropriate correction due to perspective projection // This method returns a corrected pose estimate with respect to a point camera (NOTE not the world coordinates) (Experimental) // The format returned is [Tx, Ty, Tz, Eul_x, Eul_y, Eul_z] cv::Vec6d LandmarkDetector::GetCorrectedPoseCamera(const CLNF& clnf_model, double fx, double fy, double cx, double cy) { if(!clnf_model.detected_landmarks.empty() && clnf_model.params_global[0] != 0) { double Z = fx / clnf_model.params_global[0]; double X = ((clnf_model.params_global[4] - cx) * (1.0/fx)) * Z; double Y = ((clnf_model.params_global[5] - cy) * (1.0/fy)) * Z; // Correction for orientation // 3D points cv::Mat_<double> landmarks_3D; clnf_model.pdm.CalcShape3D(landmarks_3D, clnf_model.params_local); landmarks_3D = landmarks_3D.reshape(1, 3).t(); // 2D points cv::Mat_<double> landmarks_2D = clnf_model.detected_landmarks; landmarks_2D = landmarks_2D.reshape(1, 2).t(); // Solving the PNP model // The camera matrix cv::Matx33d camera_matrix(fx, 0, cx, 0, fy, cy, 0, 0, 1); cv::Vec3d vec_trans(X, Y, Z); cv::Vec3d vec_rot(clnf_model.params_global[1], clnf_model.params_global[2], clnf_model.params_global[3]); cv::solvePnP(landmarks_3D, landmarks_2D, camera_matrix, cv::Mat(), vec_rot, vec_trans, true); // Here we correct for the camera orientation, for this need to determine the angle the camera makes with the head pose double z_x = cv::sqrt(vec_trans[0] * vec_trans[0] + vec_trans[2] * vec_trans[2]); double eul_x = atan2(vec_trans[1], z_x); double z_y = cv::sqrt(vec_trans[1] * vec_trans[1] + vec_trans[2] * vec_trans[2]); double eul_y = -atan2(vec_trans[0], z_y); cv::Matx33d camera_rotation = LandmarkDetector::Euler2RotationMatrix(cv::Vec3d(eul_x, eul_y, 0)); cv::Matx33d head_rotation = LandmarkDetector::AxisAngle2RotationMatrix(vec_rot); cv::Matx33d corrected_rotation = camera_rotation * head_rotation; cv::Vec3d euler_corrected = LandmarkDetector::RotationMatrix2Euler(corrected_rotation); return cv::Vec6d(vec_trans[0], vec_trans[1], vec_trans[2], euler_corrected[0], euler_corrected[1], euler_corrected[2]); } else { return cv::Vec6d(0,0,0,0,0,0); } } // If landmark detection in video succeeded create a template for use in simple tracking void UpdateTemplate(const cv::Mat_<uchar> &grayscale_image, CLNF& clnf_model) { cv::Rect bounding_box; clnf_model.pdm.CalcBoundingBox(bounding_box, clnf_model.params_global, clnf_model.params_local); // Make sure the box is not out of bounds bounding_box = bounding_box & cv::Rect(0, 0, grayscale_image.cols, grayscale_image.rows); clnf_model.face_template = grayscale_image(bounding_box).clone(); clnf_model.face_x_pos = bounding_box.x; clnf_model.face_y_pos = bounding_box.y; clnf_model.face_width = bounding_box.width; clnf_model.face_height = bounding_box.height; } // This method uses basic template matching in order to allow for better tracking of fast moving faces void CorrectGlobalParametersVideo(const cv::Mat_<uchar> &grayscale_image, CLNF& clnf_model, const FaceModelParameters& params) { cv::Rect init_box; clnf_model.pdm.CalcBoundingBox(init_box, clnf_model.params_global, clnf_model.params_local); cv::Rect roi(init_box.x - init_box.width/2, init_box.y - init_box.height/2, init_box.width * 2, init_box.height * 2); roi = roi & cv::Rect(0, 0, grayscale_image.cols, grayscale_image.rows); int off_x = roi.x; int off_y = roi.y; double scaling = params.face_template_scale / clnf_model.params_global[0]; cv::Mat_<uchar> image; if(scaling < 1) { cv::resize(clnf_model.face_template, clnf_model.face_template, cv::Size(), scaling, scaling); cv::resize(grayscale_image(roi), image, cv::Size(), scaling, scaling); } else { scaling = 1; image = grayscale_image(roi).clone(); } // Resizing the template cv::Mat corr_out; cv::matchTemplate(image, clnf_model.face_template, corr_out, CV_TM_CCOEFF_NORMED); // Actually matching it //double min, max; int max_loc[2]; cv::minMaxIdx(corr_out, NULL, NULL, NULL, max_loc); cv::Rect_<double> out_bbox(max_loc[1]/scaling + off_x, max_loc[0]/scaling + off_y, clnf_model.face_template.rows / scaling, clnf_model.face_template.cols / scaling); double shift_x = out_bbox.x - (double)init_box.x; double shift_y = out_bbox.y - (double)init_box.y; clnf_model.params_global[4] = clnf_model.params_global[4] + shift_x; clnf_model.params_global[5] = clnf_model.params_global[5] + shift_y; } bool LandmarkDetector::DetectLandmarksInVideo(const cv::Mat_<uchar> &grayscale_image, const cv::Mat_<float> &depth_image, CLNF& clnf_model, FaceModelParameters& params) { // First need to decide if the landmarks should be "detected" or "tracked" // Detected means running face detection and a larger search area, tracked means initialising from previous step // and using a smaller search area // Indicating that this is a first detection in video sequence or after restart bool initial_detection = !clnf_model.tracking_initialised; // Only do it if there was a face detection at all if(clnf_model.tracking_initialised) { // The area of interest search size will depend if the previous track was successful if(!clnf_model.detection_success) { params.window_sizes_current = params.window_sizes_init; } else { params.window_sizes_current = params.window_sizes_small; } // Before the expensive landmark detection step apply a quick template tracking approach if(params.use_face_template && !clnf_model.face_template.empty() && clnf_model.detection_success) { CorrectGlobalParametersVideo(grayscale_image, clnf_model, params); } bool track_success = clnf_model.DetectLandmarks(grayscale_image, depth_image, params); if(!track_success) { // Make a record that tracking failed clnf_model.failures_in_a_row++; } else { // indicate that tracking is a success clnf_model.failures_in_a_row = -1; UpdateTemplate(grayscale_image, clnf_model); } } // This is used for both detection (if it the tracking has not been initialised yet) or if the tracking failed (however we do this every n frames, for speed) // This also has the effect of an attempt to reinitialise just after the tracking has failed, which is useful during large motions if((!clnf_model.tracking_initialised && (clnf_model.failures_in_a_row + 1) % (params.reinit_video_every * 6) == 0) || (clnf_model.tracking_initialised && !clnf_model.detection_success && params.reinit_video_every > 0 && clnf_model.failures_in_a_row % params.reinit_video_every == 0)) { cv::Rect_<double> bounding_box; // If the face detector has not been initialised read it in if(clnf_model.face_detector_HAAR.empty()) { clnf_model.face_detector_HAAR.load(params.face_detector_location); clnf_model.face_detector_location = params.face_detector_location; } // If the face detector has not been initialised read it in if(clnf_model.seetaface_detector == NULL) { clnf_model.seetaface_detector = new seeta::FaceDetection(params.seetaface_detector_location.c_str()); clnf_model.seetaface_detector_location = params.seetaface_detector_location; } cv::Point preference_det(-1, -1); if(clnf_model.preference_det.x != -1 && clnf_model.preference_det.y != -1) { preference_det.x = clnf_model.preference_det.x * grayscale_image.cols; preference_det.y = clnf_model.preference_det.y * grayscale_image.rows; clnf_model.preference_det = cv::Point(-1, -1); } bool face_detection_success; // if(params.curr_face_detector == FaceModelParameters::HOG_SVM_DETECTOR) // { // double confidence; // face_detection_success = LandmarkDetector::DetectSingleFaceHOG(bounding_box, grayscale_image, clnf_model.face_detector_HOG, confidence, preference_det); // } // else if(params.curr_face_detector == FaceModelParameters::HAAR_DETECTOR) { face_detection_success = LandmarkDetector::DetectSingleFace(bounding_box, grayscale_image, clnf_model.face_detector_HAAR, preference_det); clnf_model.face_x_pos = bounding_box.x; } else if(params.curr_face_detector == FaceModelParameters::SEETAFACE_DETECTOR) { face_detection_success = LandmarkDetector::DetectSingleFaceSeetaFace(bounding_box, grayscale_image, clnf_model.seetaface_detector, preference_det); } // Attempt to detect landmarks using the detected face (if unseccessful the detection will be ignored) if(face_detection_success) { // Indicate that tracking has started as a face was detected clnf_model.tracking_initialised = true; // Keep track of old model values so that they can be restored if redetection fails cv::Vec6d params_global_init = clnf_model.params_global; cv::Mat_<double> params_local_init = clnf_model.params_local.clone(); double likelihood_init = clnf_model.model_likelihood; cv::Mat_<double> detected_landmarks_init = clnf_model.detected_landmarks.clone(); cv::Mat_<double> landmark_likelihoods_init = clnf_model.landmark_likelihoods.clone(); // Use the detected bounding box and empty local parameters clnf_model.params_local.setTo(0); clnf_model.pdm.CalcParams(clnf_model.params_global, bounding_box, clnf_model.params_local); // Make sure the search size is large params.window_sizes_current = params.window_sizes_init; // Do the actual landmark detection (and keep it only if successful) bool landmark_detection_success = clnf_model.DetectLandmarks(grayscale_image, depth_image, params); // If landmark reinitialisation unsucessful continue from previous estimates // if it's initial detection however, do not care if it was successful as the validator might be wrong, so continue trackig // regardless if(!initial_detection && !landmark_detection_success) { // Restore previous estimates clnf_model.params_global = params_global_init; clnf_model.params_local = params_local_init.clone(); clnf_model.pdm.CalcShape2D(clnf_model.detected_landmarks, clnf_model.params_local, clnf_model.params_global); clnf_model.model_likelihood = likelihood_init; clnf_model.detected_landmarks = detected_landmarks_init.clone(); clnf_model.landmark_likelihoods = landmark_likelihoods_init.clone(); return false; } else { clnf_model.failures_in_a_row = -1; UpdateTemplate(grayscale_image, clnf_model); return true; } } } // if the model has not been initialised yet class it as a failure if(!clnf_model.tracking_initialised) { clnf_model.failures_in_a_row++; } // un-initialise the tracking if( clnf_model.failures_in_a_row > 100) { clnf_model.tracking_initialised = false; } return clnf_model.detection_success; } bool LandmarkDetector::DetectLandmarksInVideo(const cv::Mat_<uchar> &grayscale_image, const cv::Mat_<float> &depth_image, const cv::Rect_<double> bounding_box, CLNF& clnf_model, FaceModelParameters& params) { if(bounding_box.width > 0) { // calculate the local and global parameters from the generated 2D shape (mapping from the 2D to 3D because camera params are unknown) clnf_model.params_local.setTo(0); clnf_model.pdm.CalcParams(clnf_model.params_global, bounding_box, clnf_model.params_local); // indicate that face was detected so initialisation is not necessary clnf_model.tracking_initialised = true; } return DetectLandmarksInVideo(grayscale_image, depth_image, clnf_model, params); } bool LandmarkDetector::DetectLandmarksInVideo(const cv::Mat_<uchar> &grayscale_image, CLNF& clnf_model, FaceModelParameters& params) { return DetectLandmarksInVideo(grayscale_image, cv::Mat_<float>(), clnf_model, params); } bool LandmarkDetector::DetectLandmarksInVideo(const cv::Mat_<uchar> &grayscale_image, const cv::Rect_<double> bounding_box, CLNF& clnf_model, FaceModelParameters& params) { return DetectLandmarksInVideo(grayscale_image, cv::Mat_<float>(), clnf_model, params); } //================================================================================================================ // Landmark detection in image, need to provide an image and optionally CLNF model together with parameters (default values work well) // Optionally can provide a bounding box in which detection is performed (this is useful if multiple faces are to be detected in images) //================================================================================================================ // This is the one where the actual work gets done, other DetectLandmarksInImage calls lead to this one bool LandmarkDetector::DetectLandmarksInImage(const cv::Mat_<uchar> &grayscale_image, const cv::Mat_<float> depth_image, const cv::Rect_<double> bounding_box, CLNF& clnf_model, FaceModelParameters& params) { // Can have multiple hypotheses std::vector<cv::Vec3d> rotation_hypotheses; if(params.multi_view) { // Try out different orientation initialisations // It is possible to add other orientation hypotheses easilly by just pushing to this vector rotation_hypotheses.push_back(cv::Vec3d(0,0,0)); rotation_hypotheses.push_back(cv::Vec3d(0,0.5236,0)); rotation_hypotheses.push_back(cv::Vec3d(0,-0.5236,0)); rotation_hypotheses.push_back(cv::Vec3d(0.5236,0,0)); rotation_hypotheses.push_back(cv::Vec3d(-0.5236,0,0)); } else { // Assume the face is close to frontal rotation_hypotheses.push_back(cv::Vec3d(0,0,0)); } // Use the initialisation size for the landmark detection params.window_sizes_current = params.window_sizes_init; // Store the current best estimate double best_likelihood; cv::Vec6d best_global_parameters; cv::Mat_<double> best_local_parameters; cv::Mat_<double> best_detected_landmarks; cv::Mat_<double> best_landmark_likelihoods; bool best_success; // The hierarchical model parameters std::vector<double> best_likelihood_h(clnf_model.hierarchical_models.size()); std::vector<cv::Vec6d> best_global_parameters_h(clnf_model.hierarchical_models.size()); std::vector<cv::Mat_<double>> best_local_parameters_h(clnf_model.hierarchical_models.size()); std::vector<cv::Mat_<double>> best_detected_landmarks_h(clnf_model.hierarchical_models.size()); std::vector<cv::Mat_<double>> best_landmark_likelihoods_h(clnf_model.hierarchical_models.size()); for(size_t hypothesis = 0; hypothesis < rotation_hypotheses.size(); ++hypothesis) { // Reset the potentially set clnf_model parameters clnf_model.params_local.setTo(0.0); for (size_t part = 0; part < clnf_model.hierarchical_models.size(); ++part) { clnf_model.hierarchical_models[part].params_local.setTo(0.0); } // calculate the local and global parameters from the generated 2D shape (mapping from the 2D to 3D because camera params are unknown) clnf_model.pdm.CalcParams(clnf_model.params_global, bounding_box, clnf_model.params_local, rotation_hypotheses[hypothesis]); bool success = clnf_model.DetectLandmarks(grayscale_image, depth_image, params); if(hypothesis == 0 || best_likelihood < clnf_model.model_likelihood) { best_likelihood = clnf_model.model_likelihood; best_global_parameters = clnf_model.params_global; best_local_parameters = clnf_model.params_local.clone(); best_detected_landmarks = clnf_model.detected_landmarks.clone(); best_landmark_likelihoods = clnf_model.landmark_likelihoods.clone(); best_success = success; } for (size_t part = 0; part < clnf_model.hierarchical_models.size(); ++part) { if (hypothesis == 0 || best_likelihood < clnf_model.hierarchical_models[part].model_likelihood) { best_likelihood_h[part] = clnf_model.hierarchical_models[part].model_likelihood; best_global_parameters_h[part] = clnf_model.hierarchical_models[part].params_global; best_local_parameters_h[part] = clnf_model.hierarchical_models[part].params_local.clone(); best_detected_landmarks_h[part] = clnf_model.hierarchical_models[part].detected_landmarks.clone(); best_landmark_likelihoods_h[part] = clnf_model.hierarchical_models[part].landmark_likelihoods.clone(); } } } // Store the best estimates in the clnf_model clnf_model.model_likelihood = best_likelihood; clnf_model.params_global = best_global_parameters; clnf_model.params_local = best_local_parameters.clone(); clnf_model.detected_landmarks = best_detected_landmarks.clone(); clnf_model.detection_success = best_success; clnf_model.landmark_likelihoods = best_landmark_likelihoods.clone(); for (size_t part = 0; part < clnf_model.hierarchical_models.size(); ++part) { clnf_model.hierarchical_models[part].params_global = best_global_parameters_h[part]; clnf_model.hierarchical_models[part].params_local = best_local_parameters_h[part].clone(); clnf_model.hierarchical_models[part].detected_landmarks = best_detected_landmarks_h[part].clone(); clnf_model.hierarchical_models[part].landmark_likelihoods = best_landmark_likelihoods_h[part].clone(); } return best_success; } bool LandmarkDetector::DetectLandmarksInImage(const cv::Mat_<uchar> &grayscale_image, const cv::Mat_<float> depth_image, CLNF& clnf_model, FaceModelParameters& params) { cv::Rect_<double> bounding_box; // If the face detector has not been initialised read it in if(clnf_model.face_detector_HAAR.empty()) { clnf_model.face_detector_HAAR.load(params.face_detector_location); clnf_model.face_detector_location = params.face_detector_location; } // Detect the face first // if(params.curr_face_detector == FaceModelParameters::HOG_SVM_DETECTOR) // { // double confidence; // LandmarkDetector::DetectSingleFaceHOG(bounding_box, grayscale_image, clnf_model.face_detector_HOG, confidence); // } // else if(params.curr_face_detector == FaceModelParameters::HAAR_DETECTOR) { LandmarkDetector::DetectSingleFace(bounding_box, grayscale_image, clnf_model.face_detector_HAAR); } if(bounding_box.width == 0) { return false; } else { return DetectLandmarksInImage(grayscale_image, depth_image, bounding_box, clnf_model, params); } } // Versions not using depth images bool LandmarkDetector::DetectLandmarksInImage(const cv::Mat_<uchar> &grayscale_image, const cv::Rect_<double> bounding_box, CLNF& clnf_model, FaceModelParameters& params) { return DetectLandmarksInImage(grayscale_image, cv::Mat_<float>(), bounding_box, clnf_model, params); } bool LandmarkDetector::DetectLandmarksInImage(const cv::Mat_<uchar> &grayscale_image, CLNF& clnf_model, FaceModelParameters& params) { return DetectLandmarksInImage(grayscale_image, cv::Mat_<float>(), clnf_model, params); }
47.21865
206
0.680899
ForrestPi
f4251b865ebba9a3180847e83af578779e06ce52
924
hpp
C++
include/luabind/register_lib.hpp
nfluxgb/luabind
1cb41ff15766b50d3ae09eb805a7087c1bca7738
[ "MIT" ]
null
null
null
include/luabind/register_lib.hpp
nfluxgb/luabind
1cb41ff15766b50d3ae09eb805a7087c1bca7738
[ "MIT" ]
null
null
null
include/luabind/register_lib.hpp
nfluxgb/luabind
1cb41ff15766b50d3ae09eb805a7087c1bca7738
[ "MIT" ]
null
null
null
#pragma once #include "method_definition.hpp" #include <lua.hpp> #include <vector> #include <tuple> #include <iostream> namespace luabind { namespace detail { template<typename CallbackT> struct definition_helper { public: typedef void result_type; definition_helper(std::vector<luaL_Reg>& definitions) : definitions_(definitions) {} void operator()() { definitions_.push_back(luaL_Reg{0, 0}); } template<typename Md, typename... Args> void operator()(Md, Args... defs) { definitions_.push_back(luaL_Reg{Md::name(), &CallbackT::template handle<Md>}); (*this)(defs...); } std::vector<luaL_Reg>& definitions_; }; } template<typename CallbackT, typename TupleT> void register_lib(lua_State* L, char const* name, TupleT dummy) { std::vector<luaL_Reg> definitions; detail::definition_helper<CallbackT> helper(definitions); std::apply(helper, dummy); luaL_register(L, name, definitions.data()); } }
20.533333
80
0.730519
nfluxgb
f426f608fb2b70cfd0b22993d0f1801305246e76
1,671
cpp
C++
Leetcode/res/Design Tic-Tac-Toe/2.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
1
2022-03-04T16:06:41.000Z
2022-03-04T16:06:41.000Z
Leetcode/res/Design Tic-Tac-Toe/2.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
Leetcode/res/Design Tic-Tac-Toe/2.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
\* Author: allannozomu Runtime: 960 ms Memory: 20 MB*\ class TicTacToe { private: vector<vector<int>> grid; int size; public: /** Initialize your data structure here. */ TicTacToe(int n) { grid = vector<vector<int>>(n, vector<int>(n)); size = n; } int win(int player){ for (int r = 0 ; r < size; ++r){ int counter = 0; int counter2 = 0; for (int c= 0 ; c < size; ++c){ if (grid[r,c] == player) counter++; if (grid[c,r] == player) counter2++; } if (counter == size || counter2 == size) return player; } int diagonal1 = 0; int diagonal2 = 0; for (int r = 0 ; r < size; ++r){ if (grid[r,r] == player) diagonal1++; if (grid[r,size - r - 1] == player) diagonal2++; } if (diagonal1 == size || diagonal2 == size) return player; return 0; } /** Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. */ int move(int row, int col, int player) { grid[row,col] = player; if (win(player)){ return player; } return 0; } }; /** * Your TicTacToe object will be instantiated and called as such: * TicTacToe* obj = new TicTacToe(n); * int param_1 = obj->move(row,col,player); */
27.85
67
0.495512
AllanNozomu
f4275a3221fe9f700acd759050a4d35b4a04ce9f
1,689
hh
C++
inc/Rt.hh
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
inc/Rt.hh
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
inc/Rt.hh
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
#ifndef RT_RT_HH #define RT_RT_HH #include "Camera.hh" #include "LightModel.hh" #include "Math.hh" #include "SceneObj.hh" #include <SFML/System.hpp> #include <memory> #include <utility> struct InterData { Vector ray; Vector normal; Position vecPos; Position impact; double k; std::shared_ptr<SceneObj> obj; InterData(const Vector &ray, const Position &pos, std::shared_ptr<SceneObj> obj, double k) : ray(ray), vecPos(pos), obj(obj), k(k) {} void calcImpact() { impact.x = vecPos.x + k * ray.x; impact.y = vecPos.y + k * ray.y; impact.z = vecPos.z + k * ray.z; } }; class Rt { public: Rt(const Camera &camera, const std::vector<std::shared_ptr<SceneObj>> &objects, const std::vector<std::shared_ptr<Light>> &lights); ~Rt() = default; Rt(const Rt &other) = default; Rt(Rt &&other) = default; Rt &operator=(const Rt &other) = default; Rt &operator=(Rt &&other) = default; unsigned int computePixelColor(const Vector &rayVec); void computeRayVec(Vector &rayVec, int x, int y, sf::Vector2i screenSize) const; private: std::pair<std::shared_ptr<SceneObj>, double> getClosestObj(const auto &rayVec, const Camera &camera); Color ComputeObjectColor(const InterData &origRay, InterData ray, int pass); Color getReflectedColor(const InterData &origRay, InterData ray, int pass); Color getRefractedColor(const InterData &origRay, InterData ray, int pass); private: static constexpr unsigned int Dist = 1000; private: const Camera &camera; const std::vector<std::shared_ptr<SceneObj>> &objects; LightModel lightModel; Math math; }; #endif /* end of include guard: RT_RT_HH */
25.984615
78
0.683245
Tastyep
f42762b5aa553ee5f9951dc37bd23689204b0a58
1,165
cpp
C++
tests/Test_Assert_Enabled.cpp
planar-foundry/PF_Debug
99208f11db21b0624a1fd8d44c62ac2d687c93a1
[ "MIT" ]
null
null
null
tests/Test_Assert_Enabled.cpp
planar-foundry/PF_Debug
99208f11db21b0624a1fd8d44c62ac2d687c93a1
[ "MIT" ]
null
null
null
tests/Test_Assert_Enabled.cpp
planar-foundry/PF_Debug
99208f11db21b0624a1fd8d44c62ac2d687c93a1
[ "MIT" ]
null
null
null
#include <PF_Test/UnitTest.hpp> #include <PF_Debug/Assert.hpp> #include <string.h> using namespace pf::debug; PFTEST_CREATE(Assert_Enabled) { static bool s_in_assert = false; static const char* s_condition; static const char* s_message; set_assert_handler([](const char* condition, const char*, int, const char* message) { s_in_assert = true; s_condition = condition; s_message = message; }); PFDEBUG_ASSERT(false); PFTEST_EXPECT(s_in_assert); PFTEST_EXPECT(strcmp(s_condition, "false") == 0); s_in_assert = false; PFDEBUG_ASSERT(true); PFTEST_EXPECT(!s_in_assert); s_in_assert = false; PFDEBUG_ASSERT_MSG(false, ""); PFTEST_EXPECT(s_in_assert); PFTEST_EXPECT(strcmp(s_condition, "false") == 0); PFTEST_EXPECT(*s_message == '\0'); s_in_assert = false; PFDEBUG_ASSERT_MSG(true, ""); PFTEST_EXPECT(!s_in_assert); s_in_assert = false; PFDEBUG_ASSERT_FAIL(); PFTEST_EXPECT(s_in_assert); s_in_assert = false; PFDEBUG_ASSERT_FAIL_MSG(""); PFTEST_EXPECT(s_in_assert); PFTEST_EXPECT(*s_message == '\0'); s_in_assert = false; }
23.77551
87
0.672961
planar-foundry
f42919927011cd787d4cc94f180db478649222c5
702
cpp
C++
D3D11_ColorFilter/src/main.cpp
ProjectAsura/D3D11Samples
fb715afc4718cbb657b5fb2f0885304b1967f55e
[ "MIT" ]
null
null
null
D3D11_ColorFilter/src/main.cpp
ProjectAsura/D3D11Samples
fb715afc4718cbb657b5fb2f0885304b1967f55e
[ "MIT" ]
null
null
null
D3D11_ColorFilter/src/main.cpp
ProjectAsura/D3D11Samples
fb715afc4718cbb657b5fb2f0885304b1967f55e
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // File : main.cpp // Desc : Main Entry Point. // Copyright(c) Project Asura. All right reserved. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #include <App.h> //----------------------------------------------------------------------------- // メインエントリーポイントです. //----------------------------------------------------------------------------- int main(int argc, char** argv) { App().Run(); return 0; }
33.428571
80
0.192308
ProjectAsura
f42bd0434943cfebef8687e5da991c62a42f66ac
44
hpp
C++
src/boost_fusion_include_advance.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_include_advance.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_include_advance.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/include/advance.hpp>
22
43
0.795455
miathedev
f42d046fbb7f4e92634549601b9ca25213de711a
7,708
cc
C++
src/math/transform.cc
sylvainbouxin/MiyukiRenderer
88242b9e18ca7eaa1c751ab07f585fac8b591b5a
[ "MIT" ]
null
null
null
src/math/transform.cc
sylvainbouxin/MiyukiRenderer
88242b9e18ca7eaa1c751ab07f585fac8b591b5a
[ "MIT" ]
null
null
null
src/math/transform.cc
sylvainbouxin/MiyukiRenderer
88242b9e18ca7eaa1c751ab07f585fac8b591b5a
[ "MIT" ]
1
2019-09-11T20:20:54.000Z
2019-09-11T20:20:54.000Z
// // Created by Shiina Miyuki on 2019/1/19. // #include "transform.h" using namespace Miyuki; Matrix4x4::Matrix4x4() { } Matrix4x4::Matrix4x4(Float _m[4][4]) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { m[i][j] = _m[i][j]; } } } Matrix4x4 &Matrix4x4::operator+=(const Matrix4x4 &rhs) { for (int i = 0; i < 4; i++) { m[i] += rhs.m[i]; } return *this; } Matrix4x4 &Matrix4x4::operator-=(const Matrix4x4 &rhs) { for (int i = 0; i < 4; i++) { m[i] -= rhs.m[i]; } return *this; } Matrix4x4 &Matrix4x4::operator*=(const Matrix4x4 &rhs) { for (int i = 0; i < 4; i++) { m[i] *= rhs.m[i]; } return *this; } Matrix4x4 &Matrix4x4::operator/=(const Matrix4x4 &rhs) { for (int i = 0; i < 4; i++) { m[i] /= rhs.m[i]; } return *this; } Matrix4x4 Matrix4x4::identity() { static Float I[4][4] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; return Matrix4x4(I); } Matrix4x4 Matrix4x4::operator+(const Matrix4x4 &rhs) const { auto m = *this; m += rhs; return m; } Matrix4x4 Matrix4x4::operator-(const Matrix4x4 &rhs) const { auto m = *this; m -= rhs; return m; } Matrix4x4 Matrix4x4::operator*(const Matrix4x4 &rhs) const { auto m = *this; m *= rhs; return m; } Matrix4x4 Matrix4x4::operator/(const Matrix4x4 &rhs) const { auto m = *this; m /= rhs; return m; } Vec3f Matrix4x4::mult(const Vec3f &rhs) const { Vec3f v = {Vec3f::matDot(m[0], rhs), Vec3f::matDot(m[1], rhs), Vec3f::matDot(m[2], rhs)}; v.w() = Vec3f::matDot(m[3], rhs); return v; } Matrix4x4 Matrix4x4::translation(const Vec3f &rhs) { Float m[4][4] = {{1, 0, 0, rhs.x()}, {0, 1, 0, rhs.y()}, {0, 0, 1, rhs.z()}, {0, 0, 0, 1}}; return {m}; } Matrix4x4 Matrix4x4::rotation(const Vec3f &axis, const Float angle) { const Float s = sin(angle); const Float c = cos(angle); const Float oc = Float(1.0) - c; Float m[4][4] = { {oc * axis.x() * axis.x() + c, oc * axis.x() * axis.y() - axis.z() * s, oc * axis.z() * axis.x() + axis.y() * s, 0}, {oc * axis.x() * axis.y() + axis.z() * s, oc * axis.y() * axis.y() + c, oc * axis.y() * axis.z() - axis.x() * s, 0}, {oc * axis.z() * axis.x() - axis.y() * s, oc * axis.y() * axis.z() + axis.x() * s, oc * axis.z() * axis.z() + c, 0}, {0, 0, 0, 1}}; return Matrix4x4(m); } Matrix4x4 Matrix4x4::mult(const Matrix4x4 &rhs) const { Matrix4x4 m; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { m.m[i][j] = 0; for (int k = 0; k < 4; k++) { m.m[i][j] += (*this).m[i][k] * rhs.m[k][j]; } } } return m; } Matrix4x4::Matrix4x4(const Vec3f &r1, const Vec3f &r2, const Vec3f &r3, const Vec3f &r4) { m[0] = r1; m[1] = r2; m[2] = r3; m[3] = r4; } bool Matrix4x4::inverse(const Matrix4x4 &in, Matrix4x4 &out) { double inv[16], det; int i; auto &m = in; inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]; inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]; inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]; inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]; inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]; inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]; inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]; inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]; inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]; inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]; inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]; inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]; inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]; inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]; inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]; inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]; det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]; if (det == 0) return false; det = 1.0 / det; for (i = 0; i < 16; i++) out[i] = inv[i] * det; return true; } Transform::Transform() : translation(), rotation(), scale(1) { } Transform::Transform(const Vec3f &t, const Vec3f &r, Float s) : translation(t), rotation(r), scale(s) { } Vec3f Transform::apply(const Vec3f &_v) const { auto v = _v * scale; v = rotate(v, Vec3f(1, 0, 0), -rotation.y()); v = rotate(v, Vec3f(0, 1, 0), rotation.x()); v = rotate(v, Vec3f(0, 0, 1), rotation.z()); return v + translation; } Vec3f Transform::applyRotation(const Vec3f &_v) const { auto v = _v; v = rotate(v, Vec3f(1, 0, 0), -rotation.y()); v = rotate(v, Vec3f(0, 1, 0), rotation.x()); v = rotate(v, Vec3f(0, 0, 1), rotation.z()); return v; }
26.57931
103
0.357421
sylvainbouxin
f42f3172f6ab385c2c34bedcaa7d40875335d458
7,461
hpp
C++
src/rectangle_base_cover.hpp
phillip-keldenich/circlecover-triangles
f4f0a9ebb30a6e0851410fc4b011471101886869
[ "MIT" ]
null
null
null
src/rectangle_base_cover.hpp
phillip-keldenich/circlecover-triangles
f4f0a9ebb30a6e0851410fc4b011471101886869
[ "MIT" ]
null
null
null
src/rectangle_base_cover.hpp
phillip-keldenich/circlecover-triangles
f4f0a9ebb30a6e0851410fc4b011471101886869
[ "MIT" ]
null
null
null
/* * Copyright 2022 Phillip Keldenich, Algorithms Department, TU Braunschweig * * 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. */ #pragma once #include "constraint.hpp" template<typename VariableSet> struct RectangleBaseRectangleCoverLemma4 : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with RC Lemma 4"; } IBool satisfied(const VariableSet& vars) override { IDouble r1 = vars.get_r1(), r2 = vars.get_r2(), r3 = vars.get_r3(); IDouble r1sq = ivarp::square(r1), r2sq = ivarp::square(r2), r3sq = ivarp::square(r3); IDouble remaining_weight = vars.weight; IDouble remaining_weight2 = vars.weight - r1sq; IDouble remaining_weight3 = remaining_weight2 - r2sq; IBool w3 = works_with(vars, r3, r3sq, remaining_weight3); if(definitely(w3)) { return {false, false}; } IBool w2 = works_with(vars, r2, r3sq, remaining_weight2); if(definitely(w2)) { return {false, false}; } return !w3 && !w2 && !works_with(vars, r1, r3sq, remaining_weight); } static IDouble inverse_lemma4_coefficient() noexcept { return {1.6393442622950817888494157159584574401378631591796875, // 1.63934426229508196721311475... // 1/0.61 1.63934426229508201089402064098976552486419677734375}; } static IDouble lemma4_coefficient() noexcept { return {0.60999999999999998667732370449812151491641998291015625, 0.6100000000000000976996261670137755572795867919921875}; } IBool works_with(const VariableSet& vars, IDouble largest_rect_disk, IDouble additional_weight, IDouble remaining_weight) { IDouble lambda_4_min = largest_rect_disk / 0.375; IDouble h4 = (ivarp::max)(IDouble(1.0), lambda_4_min); IDouble h4rc4 = lemma4_coefficient() * h4; IDouble width4plus = lambda_4_min + additional_weight / h4rc4; IDouble weight4plus = h4rc4 * lambda_4_min + additional_weight; IBool enough_weight = (weight4plus <= remaining_weight); IDouble efficiency = inverse_lemma4_coefficient() * (1.0 - width4plus * vars.tan_alpha_half); return enough_weight && efficiency >= vars.goal_efficiency; } }; /*template<typename VariableSet> struct RectangleBaseRectangleCoverLemma3 : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with RC Lemma 3"; } IBool satisfied(const VariableSet& vset) override { const IDouble lambda3_scaling_factor{ 1.0764854636994567460561711413902230560779571533203125, // 1.0764854636994569506... // sqrt(1/sigma_hat) 1.076485463699456968100776066421531140804290771484375 }; double lemma3_weight_per_area = 195.0 / 256; IDouble alpha = vset.get_alpha(); IDouble r1 = vset.get_r1(); IDouble r2 = vset.get_r2(); IDouble r2sq = ivarp::square(r2); IDouble lambda3min = r2 * lambda3_scaling_factor; IDouble lambda3max = lambda3min + r2sq / lemma3_weight_per_area; IDouble lemma3weight = lambda3max * lemma3_weight_per_area; IBool enough_without_r1 = (lemma3weight <= vset.weight - ivarp::square(r1)); if(!possibly(enough_without_r1)) { return {true, true}; } IDouble triangle_area_covered = lambda3max - vset.tan_alpha_half * ivarp::square(lambda3max); IDouble area_per_weight = triangle_area_covered / lemma3weight; return !enough_without_r1 || area_per_weight < vset.goal_efficiency; } }; */ template<typename VariableSet> struct R1R2RectangleBaseCover : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with r_1 and r_2"; } IBool satisfied(const VariableSet& vset) override { const IDouble alpha = vset.get_alpha(), r1 = vset.get_r1(), r2 = vset.get_r2(); IDouble r1sq = ivarp::square(r1); IDouble r2sq = ivarp::square(r2); IDouble covered_width_sq = -16*(ivarp::square(r1sq) + ivarp::square(r2sq)) + 32*r1sq*r2sq + 8*r1sq + 8*r2sq - 1; IBool can_cover_rect = (covered_width_sq >= 0); if(!possibly(can_cover_rect)) { return {true, true}; } covered_width_sq.restrict_lb(0.0); IDouble covered_width = 0.5 * ivarp::sqrt(covered_width_sq); IDouble rem_triangle_scale = 1.0 - (covered_width / vset.height); IDouble remaining_weight = vset.weight - r1sq - r2sq; IDouble required_weight = vset.weight * ivarp::square(rem_triangle_scale); return !can_cover_rect || remaining_weight < required_weight; } }; template<typename VariableSet> struct R1R2R3RectangleBaseCover : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with r_1, r_2 and r_3"; } IBool satisfied(const VariableSet& vset) override { IDouble r1 = vset.get_r1(), r2 = vset.get_r2(), r3 = vset.get_r3(); IDouble r1sq = ivarp::square(r1), r2sq = ivarp::square(r2), r3sq = ivarp::square(r3); IDouble remaining_weight = vset.weight - r1sq - r2sq - r3sq; IBool have_weight = (remaining_weight > 0); if(!possibly(have_weight)) { return {true, true}; } remaining_weight.restrict_lb(0.0); IDouble scale_factor = sqrt(remaining_weight / vset.weight); IDouble remaining_cov_height = scale_factor * vset.height; IDouble must_cover_height = vset.height - remaining_cov_height; IDouble mcsq = ivarp::square(must_cover_height); IDouble h3_sq = 4.0 * r3sq - mcsq; IBool h3_can_cover = (h3_sq >= 0); if(!possibly(h3_can_cover)) { return {true, true}; } h3_sq.restrict_lb(0.0); IDouble h2_sq = 4.0 * r2sq - mcsq; h2_sq.restrict_lb(0.0); IDouble h1_sq = 4.0 * r1sq - mcsq; h1_sq.restrict_lb(0.0); IDouble total_width = sqrt(h1_sq) + sqrt(h2_sq) + sqrt(h3_sq); return !h3_can_cover || (total_width < 1.0); } };
45.218182
130
0.67377
phillip-keldenich
f43c048e3700abac665c7a0c80b8c45f9d3cb295
801
cpp
C++
src/intersection.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
src/intersection.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
src/intersection.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
#include "intersection.h" // TODO: move this somewhere else static constexpr float SHADOW_EPSILON = 0.0001; Intersection::Intersection(const Point3f &p) : p(p), n(Normal3f()), wo(Vector3f()), time(0), entity(nullptr) { } Ray Intersection::spawn_ray(const Vector3f &d) const { // TODO: OffsetRayOrigin()? return Ray(p, d, INFINITY, time); } Ray Intersection::spawn_ray_to(const Intersection &p1) const { // TODO: improve, two sqrt() done here Vector3f d = normalize(p1.p - p); Point3f p_biased = p + d * SHADOW_EPSILON; float dist = distance(p1.p, p_biased); return Ray(p_biased, d, dist, time); // NOTE: this does not work if p is not biased (OffsetRayOrigin in pbrt). #if 0 Vector3f d = p1.p - p; return Ray(p, d, 1 - SHADOW_EPSILON, time); #endif }
25.03125
77
0.666667
kdbohne
f43d41f668104b3e2054e11f1d5a8ee843f1be9a
4,128
cpp
C++
webots_ros2_driver/src/plugins/dynamic/Ros2IMU.cpp
TaoYibo1866/webots_ros2
a72c164825663cebbfd27e0649ea51d3abf9bbed
[ "Apache-2.0" ]
176
2019-09-06T07:02:05.000Z
2022-03-27T12:41:10.000Z
webots_ros2_driver/src/plugins/dynamic/Ros2IMU.cpp
harshag37/webots_ros2
08a061e73e3b88d57cc27b662be0f907d8b9f15b
[ "Apache-2.0" ]
308
2019-08-20T12:56:23.000Z
2022-03-29T09:49:22.000Z
webots_ros2_driver/src/plugins/dynamic/Ros2IMU.cpp
omichel/webots_ros2
5b59d0b1fbeff4c3f75a447bd152c10853f4691b
[ "Apache-2.0" ]
67
2019-11-03T00:58:09.000Z
2022-03-18T07:11:28.000Z
// Copyright 1996-2021 Cyberbotics 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 <webots_ros2_driver/plugins/dynamic/Ros2IMU.hpp> #include <webots_ros2_driver/utils/Math.hpp> #include "pluginlib/class_list_macros.hpp" namespace webots_ros2_driver { void Ros2IMU::init(webots_ros2_driver::WebotsNode *node, std::unordered_map<std::string, std::string> &parameters) { Ros2SensorPlugin::init(node, parameters); mIsEnabled = false; mInertialUnit = NULL; mGyro = NULL; mAccelerometer = NULL; if (!parameters.count("inertialUnitName") && !parameters.count("gyroName") && !parameters.count("accelerometerName")) throw std::runtime_error("The IMU plugins has to contain at least of: <inertialUnitName>, <gyroName>, or <accelerometerName>"); if (parameters.count("inertialUnitName")) { mInertialUnit = mNode->robot()->getInertialUnit(parameters["inertialUnitName"]); if (mInertialUnit == NULL) throw std::runtime_error("Cannot find InertialUnit with name " + parameters["inertialUnitName"]); } if (parameters.count("gyroName")) { mGyro = mNode->robot()->getGyro(parameters["gyroName"]); if (mGyro == NULL) throw std::runtime_error("Cannot find Gyro with name " + parameters["gyroName"]); } if (parameters.count("accelerometerName")) { mAccelerometer = mNode->robot()->getAccelerometer(parameters["accelerometerName"]); if (mAccelerometer == NULL) throw std::runtime_error("Cannot find Accelerometer with name " + parameters["accelerometerName"]); } mPublisher = mNode->create_publisher<sensor_msgs::msg::Imu>(mTopicName, rclcpp::SensorDataQoS().reliable()); mMessage.header.frame_id = mFrameName; if (mAlwaysOn) { enable(); mIsEnabled = true; } } void Ros2IMU::enable() { if (mInertialUnit) mInertialUnit->enable(mPublishTimestepSyncedMs); if (mAccelerometer) mAccelerometer->enable(mPublishTimestepSyncedMs); if (mGyro) mGyro->enable(mPublishTimestepSyncedMs); } void Ros2IMU::disable() { if (mInertialUnit) mInertialUnit->disable(); if (mAccelerometer) mAccelerometer->disable(); if (mGyro) mGyro->disable(); } void Ros2IMU::step() { if (!preStep()) return; if (mIsEnabled) publishData(); if (mAlwaysOn) return; // Enable/Disable sensor const bool shouldBeEnabled = mPublisher->get_subscription_count() > 0; if (shouldBeEnabled != mIsEnabled) { if (shouldBeEnabled) enable(); else disable(); mIsEnabled = shouldBeEnabled; } } void Ros2IMU::publishData() { mMessage.header.stamp = mNode->get_clock()->now(); if (mAccelerometer) { const double *values = mAccelerometer->getValues(); mMessage.linear_acceleration.x = values[0]; mMessage.linear_acceleration.y = values[1]; mMessage.linear_acceleration.z = values[2]; } if (mGyro) { const double *values = mGyro->getValues(); mMessage.angular_velocity.x = values[0]; mMessage.angular_velocity.y = values[1]; mMessage.angular_velocity.z = values[2]; } if (mInertialUnit) { const double *values = mInertialUnit->getQuaternion(); mMessage.orientation.x = values[0]; mMessage.orientation.y = values[1]; mMessage.orientation.z = values[2]; mMessage.orientation.w = values[3]; } mPublisher->publish(mMessage); } } PLUGINLIB_EXPORT_CLASS(webots_ros2_driver::Ros2IMU, webots_ros2_driver::PluginInterface)
30.352941
133
0.674903
TaoYibo1866
f43e225c5d556ebd17e803de0f1456df2f0dfca6
447
cpp
C++
support_functions.cpp
AVDer/rpi_egl_tests
323d0f7e9926039d8a22f0eb5916d228ba260375
[ "MIT" ]
null
null
null
support_functions.cpp
AVDer/rpi_egl_tests
323d0f7e9926039d8a22f0eb5916d228ba260375
[ "MIT" ]
null
null
null
support_functions.cpp
AVDer/rpi_egl_tests
323d0f7e9926039d8a22f0eb5916d228ba260375
[ "MIT" ]
null
null
null
#include "support_functions.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "logger.h" size_t get_file_size(const std::string& filename) { struct stat file_stat; if (stat(filename.c_str(), &file_stat) == -1) { Logger::error("File: can't stat file %s", filename.c_str()); return 0; } Logger::info("File: File %s has size %d bytes", filename.c_str(), file_stat.st_size); return file_stat.st_size; }
24.833333
87
0.680089
AVDer
f444514f9ceba77d9059e382e7dcffebd313e78e
1,335
hpp
C++
module-services/service-gui/DrawCommandsQueue.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
module-services/service-gui/DrawCommandsQueue.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
module-services/service-gui/DrawCommandsQueue.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include "SynchronizationMechanism.hpp" #include <gui/core/DrawCommand.hpp> #include <cstdint> #include <list> #include <memory> #include <vector> namespace service::gui { class DrawCommandsQueue { public: using CommandList = std::list<std::unique_ptr<::gui::DrawCommand>>; struct QueueItem { CommandList commands; ::gui::RefreshModes refreshMode = ::gui::RefreshModes::GUI_REFRESH_FAST; }; using QueueContainer = std::vector<QueueItem>; explicit DrawCommandsQueue( std::size_t expectedSize, std::unique_ptr<SynchronizationMechanism> &&synchronization = getFreeRtosSynchronizationMechanism()); void enqueue(QueueItem &&item); [[nodiscard]] auto dequeue() -> QueueItem; [[nodiscard]] auto getMaxRefreshModeAndClear() -> ::gui::RefreshModes; void clear(); [[nodiscard]] auto size() const noexcept -> QueueContainer::size_type; private: QueueContainer queue; mutable cpp_freertos::MutexStandard queueMutex; std::unique_ptr<SynchronizationMechanism> synchronization; }; } // namespace service::gui
29.666667
113
0.66367
bitigchi
f44615163d2dd4bb3ad79dcbd576a7b5b757c61d
1,887
cpp
C++
RobWorkStudio/src/rwslibs/workcelleditor/FileDialogButton.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWorkStudio/src/rwslibs/workcelleditor/FileDialogButton.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWorkStudio/src/rwslibs/workcelleditor/FileDialogButton.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2019 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 "FileDialogButton.hpp" #include <rw/core/StringUtil.hpp> #include <QFileDialog> using namespace rw::core; FileDialogButton::FileDialogButton (QString path) : QPushButton () { setText ("Select CAD File"); _path = path; connect (this, SIGNAL (clicked ()), this, SLOT (selectFile ())); } void FileDialogButton::selectFile () { QString fullPath = QFileDialog::getOpenFileName ( this, tr ("Select CAD file"), _path, tr ("CAD Files (*.stl *.obj *.ac)")); std::string file_name = StringUtil::getFileName (fullPath.toStdString ()); std::string wcDir = _path.toStdString () + "/"; std::string relFilePath = StringUtil::getRelativeDirectoryName ( fullPath.toStdString (), StringUtil::getDirectoryName (wcDir)); std::string finalPath = relFilePath + file_name; if (relFilePath.empty ()) _filename = fullPath; else _filename = QString::fromStdString (finalPath); } const QString& FileDialogButton::getFilename () const { return _filename; }
36.288462
82
0.645469
ZLW07
f44b43a2412556f681c105ac2156a05b3be638c5
8,058
cpp
C++
src/replacement/Shell32ReplacementLibrary/Shell32ReplacementLibrary.cpp
SecurityInnovation/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
35
2015-05-16T06:36:47.000Z
2021-08-31T15:32:09.000Z
src_2_8/replacement/Shell32ReplacementLibrary/Shell32ReplacementLibrary.cpp
crypticterminal/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
3
2015-06-18T06:16:51.000Z
2017-11-16T23:23:59.000Z
src_2_8/replacement/Shell32ReplacementLibrary/Shell32ReplacementLibrary.cpp
crypticterminal/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
10
2015-04-07T14:45:48.000Z
2021-11-14T15:14:45.000Z
//************************************************************************* // Copyright (C) Security Innovation, LLC, 2002-2004 All Rights Reserved. // // FILE: Shell32ReplacementLibrary.cpp // // DESCRIPTION: Contains replacement library functions for shell32.dll // //========================================================================= // Modification History // // Date SCR Name Purpose // ----------- --- ----------- ------------------------------------------ // Generated 04/20/2004 02:48:51 PM //************************************************************************* #include "shell32replacementlibrary.h" //************************************************************************* // Method: ReplacementLibraryAttach // Description: Called when HEAT is attaching // Parameters: None // Return Value: None //************************************************************************* void ReplacementLibraryAttach() { ReplacementLibrary::DisableInterception(); if (library == NULL) { library = new ReplacementLibrary("shell32.dll"); logSender = &commonLogSender; if (!logSender->GetIsSendLogThreadRunning()) logSender->StartSendLogThread(); } ReplacementLibrary::EnableInterception(); } //************************************************************************* // Method: ReplacementLibraryDetach // Description: Called when HEAT is detaching // Parameters: None // Return Value: None //************************************************************************* void ReplacementLibraryDetach() { ReplacementLibrary::DisableInterception(); if (library != NULL) { if ((logSender != NULL) && (logSender->GetIsSendLogThreadRunning())) { logSender->StopSendLogThread(); logSender = NULL; } } ReplacementLibrary::EnableInterception(); } //************************************************************************* // Method: DllMain // Description: Entry point to this dll // Parameters: See MSDN DllMain function parameters // Return Value: See MSDN DllMain return value //************************************************************************* BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { ReplacementLibrary::DisableInterception(); switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: break; case DLL_PROCESS_DETACH: ReplacementLibraryDetach(); delete library; library = NULL; return TRUE; // Don't re-enable intercepts, as we are detaching default: break; } ReplacementLibrary::EnableInterception(); return TRUE; } //************************************************************************* // START OF ORIGINAL FUNCTION CALLER FUNCTIONS // For all functions in this section the following applies // Description: Calls the original function for a replacement function // Parameters: // numParams - the number of parameters in the params array // params - the parameters to pass to the original function // retVal - the return value from the original function // errCode - the error code from the original function // Return Value: true if the correct number of parameters were passed in, // false otherwise //************************************************************************* //************************************************************************* // Method: ShellExecuteACaller - See START OF ORIGINAL FUNCTION CALLER FUNCTIONS //************************************************************************* bool ShellExecuteACaller(int numParams, void **params, DWORD *retValue, DWORD *errCode) { if (numParams != 6) return false; HINSTANCE tempRetValue = realShellExecuteA(*((HWND *)params[0]), *((SiString *)params[1]), *((SiString *)params[2]), *((SiString *)params[3]), *((SiString *)params[4]), *((int *)params[5])); memcpy(retValue, &tempRetValue, sizeof(DWORD)); *errCode = GetLastError(); return true; } //************************************************************************* // Method: ShellExecuteWCaller - See START OF ORIGINAL FUNCTION CALLER FUNCTIONS //************************************************************************* bool ShellExecuteWCaller(int numParams, void **params, DWORD *retValue, DWORD *errCode) { if (numParams != 6) return false; HINSTANCE tempRetValue = realShellExecuteW(*((HWND *)params[0]), *((SiString *)params[1]), *((SiString *)params[2]), *((SiString *)params[3]), *((SiString *)params[4]), *((int *)params[5])); memcpy(retValue, &tempRetValue, sizeof(DWORD)); *errCode = GetLastError(); return true; } //************************************************************************* // END OF ORIGINAL FUNCTION CALLER FUNCTIONS //************************************************************************* //************************************************************************* // START OF REPLACEMENT FUNCTIONS //************************************************************************* //************************************************************************* // Method: ShellExecuteAReplacement // Description: See MSDN ShellExecuteA function // Parameters: See MSDN ShellExecuteA parameters // Return Value: See MSDN ShellExecuteA return value //************************************************************************* HINSTANCE STDAPICALLTYPE ShellExecuteAReplacement(HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, int nShowCmd) { const int numParams = 6; char *functionName = "ShellExecuteA"; char *categoryName = "DANGEROUS"; SiString str[] = { (char *)lpOperation, (char *)lpFile, (char *)lpParameters, (char *)lpDirectory }; void *params[numParams] = { &hwnd, &str[0], &str[1], &str[2], &str[3], &nShowCmd }; ParameterType paramTypes[numParams] = { PointerType, StringType, StringType, StringType, StringType, IntegerType }; if (realShellExecuteA == NULL) realShellExecuteA = (ShellExecuteAFunction)library->GetOriginalFunction(functionName); if (realShellExecuteA != NULL) { DWORD errorCode, tempReturnValue = 0; HINSTANCE returnValue; if (library->RunStandardTestsAndGetResults(logSender, ShellExecuteACaller, categoryName, functionName, numParams, params, paramTypes, &tempReturnValue, "HINSTANCE", &errorCode, 0, true)) { } else { } memcpy(&returnValue, &tempReturnValue, sizeof(DWORD)); SetLastError(errorCode); return returnValue; } return 0; } //************************************************************************* // Method: ShellExecuteWReplacement // Description: See MSDN ShellExecuteW function // Parameters: See MSDN ShellExecuteW parameters // Return Value: See MSDN ShellExecuteW return value //************************************************************************* HINSTANCE STDAPICALLTYPE ShellExecuteWReplacement(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, int nShowCmd) { const int numParams = 6; char *functionName = "ShellExecuteW"; char *categoryName = "DANGEROUS"; SiString str[] = { (wchar_t *)lpOperation, (wchar_t *)lpFile, (wchar_t *)lpParameters, (wchar_t *)lpDirectory }; void *params[numParams] = { &hwnd, &str[0], &str[1], &str[2], &str[3], &nShowCmd }; ParameterType paramTypes[numParams] = { PointerType, WideStringType, WideStringType, WideStringType, WideStringType, IntegerType }; if (realShellExecuteW == NULL) realShellExecuteW = (ShellExecuteWFunction)library->GetOriginalFunction(functionName); if (realShellExecuteW != NULL) { DWORD errorCode, tempReturnValue = 0; HINSTANCE returnValue; if (library->RunStandardTestsAndGetResults(logSender, ShellExecuteWCaller, categoryName, functionName, numParams, params, paramTypes, &tempReturnValue, "HINSTANCE", &errorCode, 0, true)) { } else { } memcpy(&returnValue, &tempReturnValue, sizeof(DWORD)); SetLastError(errorCode); return returnValue; } return 0; } //************************************************************************* // END OF REPLACEMENT FUNCTIONS //*************************************************************************
38.740385
191
0.557707
SecurityInnovation
f44bd661137940eac42ce2db0c9c99fdc440d2db
956
cpp
C++
Greedy/Killjoy.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
Greedy/Killjoy.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
Greedy/Killjoy.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ll long long using namespace std; int32_t main() { ios::sync_with_stdio(0); cin.tie(0); ll t; cin >> t; while (t--) { ll n, x; cin >> n >> x; ll arr[n]; ll flag = 0; ll cnt = 0; for (ll i = 0; i < n; i++) { cin >>arr[i]; if (arr[i] == x) { flag = 1; cnt++; } } if (cnt == n) { cout << 0 << "\n"; continue; } if (flag == 1) { cout << 1 << "\n"; continue; } ll sum = 0; for (ll i = 0; i < n; i++) { sum += (arr[i] - x); } if (sum == 0) { cout << 1 << '\n'; } else { cout << 2 << '\n'; } } return 0; }
16.77193
34
0.264644
kothariji
f44f840ed5d865b2a221143e73a201cad44f358a
15,856
cc
C++
Mysql/sql/tc_log.cc
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T16:44:50.000Z
2015-12-24T16:44:50.000Z
Mysql/sql/tc_log.cc
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T18:23:56.000Z
2015-12-24T18:24:26.000Z
Mysql/sql/tc_log.cc
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tc_log.h" #include "log.h" // sql_print_error #include "sql_class.h" // THD #include "pfs_file_provider.h" #include "mysql/psi/mysql_file.h" TC_LOG::enum_result TC_LOG_DUMMY::commit(THD *thd, bool all) { return ha_commit_low(thd, all) ? RESULT_ABORTED : RESULT_SUCCESS; } int TC_LOG_DUMMY::rollback(THD *thd, bool all) { return ha_rollback_low(thd, all); } int TC_LOG_DUMMY::prepare(THD *thd, bool all) { return ha_prepare_low(thd, all); } /********* transaction coordinator log for 2pc - mmap() based solution *******/ /* the log consists of a file, mmapped to a memory. file is divided on pages of tc_log_page_size size. (usable size of the first page is smaller because of log header) there's PAGE control structure for each page each page (or rather PAGE control structure) can be in one of three states - active, syncing, pool. there could be only one page in active or syncing states, but many in pool - pool is fifo queue. usual lifecycle of a page is pool->active->syncing->pool "active" page - is a page where new xid's are logged. the page stays active as long as syncing slot is taken. "syncing" page is being synced to disk. no new xid can be added to it. when the sync is done the page is moved to a pool and an active page becomes "syncing". the result of such an architecture is a natural "commit grouping" - If commits are coming faster than the system can sync, they do not stall. Instead, all commit that came since the last sync are logged to the same page, and they all are synced with the next - one - sync. Thus, thought individual commits are delayed, throughput is not decreasing. when a xid is added to an active page, the thread of this xid waits for a page's condition until the page is synced. when syncing slot becomes vacant one of these waiters is awaken to take care of syncing. it syncs the page and signals all waiters that the page is synced. PAGE::waiters is used to count these waiters, and a page may never become active again until waiters==0 (that is all waiters from the previous sync have noticed the sync was completed) note, that the page becomes "dirty" and has to be synced only when a new xid is added into it. Removing a xid from a page does not make it dirty - we don't sync removals to disk. */ ulong tc_log_page_waits= 0; #define TC_LOG_HEADER_SIZE (sizeof(tc_log_magic)+1) static const char tc_log_magic[]={(char) 254, 0x23, 0x05, 0x74}; ulong opt_tc_log_size= TC_LOG_MIN_SIZE; ulong tc_log_max_pages_used=0, tc_log_page_size=0, tc_log_cur_pages_used=0; int TC_LOG_MMAP::open(const char *opt_name) { uint i; bool crashed=FALSE; PAGE *pg; DBUG_ASSERT(total_ha_2pc > 1); DBUG_ASSERT(opt_name && opt_name[0]); tc_log_page_size= my_getpagesize(); if (TC_LOG_PAGE_SIZE > tc_log_page_size) { DBUG_ASSERT(TC_LOG_PAGE_SIZE % tc_log_page_size == 0); } fn_format(logname,opt_name,mysql_data_home,"",MY_UNPACK_FILENAME); if ((fd= mysql_file_open(key_file_tclog, logname, O_RDWR, MYF(0))) < 0) { if (my_errno() != ENOENT) goto err; if (using_heuristic_recover()) return 1; if ((fd= mysql_file_create(key_file_tclog, logname, CREATE_MODE, O_RDWR, MYF(MY_WME))) < 0) goto err; inited=1; file_length= opt_tc_log_size; if (mysql_file_chsize(fd, file_length, 0, MYF(MY_WME))) goto err; } else { inited= 1; crashed= TRUE; sql_print_information("Recovering after a crash using %s", opt_name); if (tc_heuristic_recover != TC_HEURISTIC_NOT_USED) { sql_print_error("Cannot perform automatic crash recovery when " "--tc-heuristic-recover is used"); goto err; } file_length= mysql_file_seek(fd, 0L, MY_SEEK_END, MYF(MY_WME+MY_FAE)); if (file_length == MY_FILEPOS_ERROR || file_length % tc_log_page_size) goto err; } data= (uchar *)my_mmap(0, (size_t)file_length, PROT_READ|PROT_WRITE, MAP_NOSYNC|MAP_SHARED, fd, 0); if (data == MAP_FAILED) { set_my_errno(errno); goto err; } inited=2; npages=(uint)file_length/tc_log_page_size; DBUG_ASSERT(npages >= 3); // to guarantee non-empty pool if (!(pages=(PAGE *)my_malloc(key_memory_TC_LOG_MMAP_pages, npages*sizeof(PAGE), MYF(MY_WME|MY_ZEROFILL)))) goto err; inited=3; for (pg=pages, i=0; i < npages; i++, pg++) { pg->next=pg+1; pg->waiters=0; pg->state=PS_POOL; mysql_cond_init(key_PAGE_cond, &pg->cond); pg->size=pg->free=tc_log_page_size/sizeof(my_xid); pg->start= (my_xid *)(data + i*tc_log_page_size); pg->end= pg->start + pg->size; pg->ptr= pg->start; } pages[0].size=pages[0].free= (tc_log_page_size-TC_LOG_HEADER_SIZE)/sizeof(my_xid); pages[0].start=pages[0].end-pages[0].size; pages[npages-1].next=0; inited=4; if (crashed && recover()) goto err; memcpy(data, tc_log_magic, sizeof(tc_log_magic)); data[sizeof(tc_log_magic)]= (uchar)total_ha_2pc; my_msync(fd, data, tc_log_page_size, MS_SYNC); inited=5; mysql_mutex_init(key_LOCK_tc, &LOCK_tc, MY_MUTEX_INIT_FAST); mysql_cond_init(key_COND_active, &COND_active); mysql_cond_init(key_COND_pool, &COND_pool); inited=6; syncing= 0; active=pages; pool=pages+1; pool_last_ptr= &pages[npages-1].next; return 0; err: close(); return 1; } /** Get the total amount of potentially usable slots for XIDs in TC log. */ uint TC_LOG_MMAP::size() const { return (tc_log_page_size-TC_LOG_HEADER_SIZE)/sizeof(my_xid) + (npages - 1) * (tc_log_page_size/sizeof(my_xid)); } /** there is no active page, let's got one from the pool. Two strategies here: -# take the first from the pool -# if there're waiters - take the one with the most free space. @todo TODO page merging. try to allocate adjacent page first, so that they can be flushed both in one sync @returns Pointer to qualifying page or NULL if no page in the pool can be made active. */ TC_LOG_MMAP::PAGE* TC_LOG_MMAP::get_active_from_pool() { PAGE **best_p= &pool; if ((*best_p)->waiters != 0 || (*best_p)->free == 0) { /* if the first page can't be used try second strategy */ int best_free=0; PAGE **p= &pool; for (p=&(*p)->next; *p; p=&(*p)->next) { if ((*p)->waiters == 0 && (*p)->free > best_free) { best_free=(*p)->free; best_p=p; } } if (*best_p == NULL || best_free == 0) return NULL; } PAGE *new_active= *best_p; if (new_active->free == new_active->size) // we've chosen an empty page { tc_log_cur_pages_used++; set_if_bigger(tc_log_max_pages_used, tc_log_cur_pages_used); } *best_p= (*best_p)->next; if (! *best_p) pool_last_ptr= best_p; return new_active; } /** @todo perhaps, increase log size ? */ void TC_LOG_MMAP::overflow() { /* simple overflow handling - just wait TODO perhaps, increase log size ? let's check the behaviour of tc_log_page_waits first */ ulong old_log_page_waits= tc_log_page_waits; mysql_cond_wait(&COND_pool, &LOCK_tc); if (old_log_page_waits == tc_log_page_waits) { /* When several threads are waiting in overflow() simultaneously we want to increase counter only once and not for each thread. */ tc_log_page_waits++; } } /** Commit the transaction. @note When the TC_LOG inteface was changed, this function was added and uses the functions that were there with the old interface to implement the logic. */ TC_LOG::enum_result TC_LOG_MMAP::commit(THD *thd, bool all) { DBUG_ENTER("TC_LOG_MMAP::commit"); ulong cookie= 0; my_xid xid= thd->get_transaction()->xid_state()->get_xid()->get_my_xid(); if (all && xid) if (!(cookie= log_xid(xid))) DBUG_RETURN(RESULT_ABORTED); // Failed to log the transaction if (ha_commit_low(thd, all)) DBUG_RETURN(RESULT_INCONSISTENT); // Transaction logged, but not committed /* If cookie is non-zero, something was logged */ if (cookie) unlog(cookie, xid); DBUG_RETURN(RESULT_SUCCESS); } int TC_LOG_MMAP::rollback(THD *thd, bool all) { return ha_rollback_low(thd, all); } int TC_LOG_MMAP::prepare(THD *thd, bool all) { return ha_prepare_low(thd, all); } /** Record that transaction XID is committed on the persistent storage. This function is called in the middle of two-phase commit: First all resources prepare the transaction, then tc_log->log() is called, then all resources commit the transaction, then tc_log->unlog() is called. All access to active page is serialized but it's not a problem, as we're assuming that fsync() will be a main bottleneck. That is, parallelizing writes to log pages we'll decrease number of threads waiting for a page, but then all these threads will be waiting for a fsync() anyway If tc_log == MYSQL_BIN_LOG then tc_log writes transaction to binlog and records XID in a special Xid_log_event. If tc_log = TC_LOG_MMAP then xid is written in a special memory-mapped log. @retval 0 - error @retval \# - otherwise, "cookie", a number that will be passed as an argument to unlog() call. tc_log can define it any way it wants, and use for whatever purposes. TC_LOG_MMAP sets it to the position in memory where xid was logged to. */ ulong TC_LOG_MMAP::log_xid(my_xid xid) { mysql_mutex_lock(&LOCK_tc); while (true) { /* If active page is full - just wait... */ while (unlikely(active && active->free == 0)) mysql_cond_wait(&COND_active, &LOCK_tc); /* no active page ? take one from the pool. */ if (active == NULL) { active= get_active_from_pool(); /* There are no pages with free slots? Wait and retry. */ if (active == NULL) { overflow(); continue; } } break; } PAGE *p= active; ulong cookie= store_xid_in_empty_slot(xid, p, data); bool err; if (syncing) { // somebody's syncing. let's wait err= wait_sync_completion(p); if (p->state != PS_DIRTY) // page was synced { if (p->waiters == 0) mysql_cond_broadcast(&COND_pool); // in case somebody's waiting mysql_mutex_unlock(&LOCK_tc); goto done; // we're done } } // page was not synced! do it now DBUG_ASSERT(active == p && syncing == NULL); syncing= p; // place is vacant - take it active= NULL; // page is not active anymore mysql_cond_broadcast(&COND_active); // in case somebody's waiting mysql_mutex_unlock(&LOCK_tc); err= sync(); done: return err ? 0 : cookie; } /** Write the page data being synchronized to the disk. @return @retval false Success @retval true Failure */ bool TC_LOG_MMAP::sync() { DBUG_ASSERT(syncing != active); /* sit down and relax - this can take a while... note - no locks are held at this point */ int err= do_msync_and_fsync(fd, syncing->start, syncing->size*sizeof(my_xid), MS_SYNC); mysql_mutex_lock(&LOCK_tc); /* Page is synced. Let's move it to the pool. */ *pool_last_ptr= syncing; pool_last_ptr= &(syncing->next); syncing->next= NULL; syncing->state= err ? PS_ERROR : PS_POOL; mysql_cond_broadcast(&COND_pool); // in case somebody's waiting /* Wake-up all threads which are waiting for syncing of the same page. */ mysql_cond_broadcast(&syncing->cond); /* Mark syncing slot as free and wake-up new syncer. */ syncing= NULL; if (active) mysql_cond_signal(&active->cond); mysql_mutex_unlock(&LOCK_tc); return err != 0; } /** erase xid from the page, update page free space counters/pointers. cookie points directly to the memory where xid was logged. */ void TC_LOG_MMAP::unlog(ulong cookie, my_xid xid) { PAGE *p= pages + (cookie / tc_log_page_size); my_xid *x= (my_xid *)(data + cookie); DBUG_ASSERT(*x == xid); DBUG_ASSERT(x >= p->start && x < p->end); *x= 0; mysql_mutex_lock(&LOCK_tc); p->free++; DBUG_ASSERT(p->free <= p->size); set_if_smaller(p->ptr, x); if (p->free == p->size) // the page is completely empty tc_log_cur_pages_used--; if (p->waiters == 0) // the page is in pool and ready to rock mysql_cond_broadcast(&COND_pool); // ping ... for overflow() mysql_mutex_unlock(&LOCK_tc); } void TC_LOG_MMAP::close() { uint i; switch (inited) { case 6: mysql_mutex_destroy(&LOCK_tc); mysql_cond_destroy(&COND_pool); case 5: data[0]='A'; // garble the first (signature) byte, in case mysql_file_delete fails case 4: for (i=0; i < npages; i++) { if (pages[i].ptr == 0) break; mysql_cond_destroy(&pages[i].cond); } case 3: my_free(pages); case 2: my_munmap((char*)data, (size_t)file_length); case 1: mysql_file_close(fd, MYF(0)); } if (inited>=5) // cannot do in the switch because of Windows mysql_file_delete(key_file_tclog, logname, MYF(MY_WME)); inited=0; } int TC_LOG_MMAP::recover() { HASH xids; PAGE *p=pages, *end_p=pages+npages; if (memcmp(data, tc_log_magic, sizeof(tc_log_magic))) { sql_print_error("Bad magic header in tc log"); goto err1; } /* the first byte after magic signature is set to current number of storage engines on startup */ if (data[sizeof(tc_log_magic)] != total_ha_2pc) { sql_print_error("Recovery failed! You must enable " "exactly %d storage engines that support " "two-phase commit protocol", data[sizeof(tc_log_magic)]); goto err1; } if (my_hash_init(&xids, &my_charset_bin, tc_log_page_size/3, 0, sizeof(my_xid), 0, 0, MYF(0), PSI_INSTRUMENT_ME)) goto err1; for ( ; p < end_p ; p++) { for (my_xid *x=p->start; x < p->end; x++) if (*x && my_hash_insert(&xids, (uchar *)x)) goto err2; // OOM } if (ha_recover(&xids)) goto err2; my_hash_free(&xids); memset(data, 0, (size_t)file_length); return 0; err2: my_hash_free(&xids); err1: sql_print_error("Crash recovery failed. Either correct the problem " "(if it's, for example, out of memory error) and restart, " "or delete tc log and start mysqld with " "--tc-heuristic-recover={commit|rollback}"); return 1; } TC_LOG *tc_log; TC_LOG_DUMMY tc_log_dummy; TC_LOG_MMAP tc_log_mmap; bool TC_LOG::using_heuristic_recover() { if (tc_heuristic_recover == TC_HEURISTIC_NOT_USED) return false; sql_print_information("Heuristic crash recovery mode"); if (ha_recover(0)) sql_print_error("Heuristic crash recovery failed"); sql_print_information("Please restart mysqld without --tc-heuristic-recover"); return true; }
28.16341
86
0.659435
clockzhong
f450a114d249a8b268d08f4a270b3082634e4288
196
cpp
C++
src/noj_am/BOJ_14652.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
1
2020-06-01T12:19:31.000Z
2020-06-01T12:19:31.000Z
src/noj_am/BOJ_14652.cpp
ginami0129g/my-study-history
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
23
2020-11-08T07:14:02.000Z
2021-02-11T11:16:00.000Z
src/noj_am/BOJ_14652.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, m, k; int main(void) { cin.tie(NULL); ios_base::sync_with_stdio(false); cin >> n >> m >> k; cout << k / m << ' ' << k % m << '\n'; }
16.333333
40
0.52551
ginami0129g
f45115f9c1ec431a0b9a03f9e2a5e66585a43b7b
6,200
cpp
C++
SVEngine/src/rendercore/SVRenderer.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/rendercore/SVRenderer.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/rendercore/SVRenderer.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVRenderer.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVRenderer.h" #include "../app/SVInst.h" #include "../work/SVTdCore.h" #include "../mtl/SVTexMgr.h" #include "../mtl/SVTexture.h" #include "../mtl/SVTextureIOS.h" #include "SVRenderMgr.h" #include "SVRenderTarget.h" #include "SVRenderTexture.h" #include "SVRObjBase.h" #include "SVRenderState.h" SVRenderer::SVRenderer(SVInstPtr _app) :SVGBaseEx(_app) ,m_pRenderTex(nullptr) ,m_pRState(nullptr) ,m_inWidth(256) ,m_inHeight(256) ,m_outWidth(256) ,m_outHeight(256){ m_resLock = MakeSharedPtr<SVLock>(); for(s32 i=E_TEX_MAIN ;i<E_TEX_END;i++) { m_svTex[i] = nullptr; } } SVRenderer::~SVRenderer(){ m_resLock = nullptr; } void SVRenderer::init(s32 _w,s32 _h){ m_inWidth = _w; m_inHeight = _h; } void SVRenderer::destroy(){ m_pRenderTex = nullptr; for(s32 i=E_TEX_MAIN ;i<E_TEX_END;i++) { m_svTex[i] = nullptr; } clearRes(); m_stack_proj.destroy(); m_stack_view.destroy(); m_stack_vp.destroy(); m_resLock = nullptr; } // void SVRenderer::renderBegin() { } // void SVRenderer::renderEnd() { clearMatStack(); } //获取状态 SVRenderStatePtr SVRenderer::getState(){ return m_pRState; } //重置状态 void SVRenderer::resetState() { if(m_pRState){ m_pRState->resetState(); } } void SVRenderer::resize(s32 _w,s32 _) { } void SVRenderer::clearRes() { m_resLock->lock(); for(s32 i=0;i<m_robjList.size();i++) { SVRObjBasePtr t_robj = m_robjList[i]; t_robj->destroy(nullptr); } m_robjList.destroy(); m_resLock->unlock(); } void SVRenderer::addRes(SVRObjBasePtr _res) { m_resLock->lock(); m_robjList.append(_res); m_resLock->unlock(); } void SVRenderer::removeRes(SVRObjBasePtr _res) { m_resLock->lock(); for(s32 i=0;i<m_robjList.size();i++) { SVRObjBasePtr t_robj = m_robjList[i]; if(t_robj == _res) { t_robj->destroy(nullptr); m_robjList.removeForce(i); break; } } m_resLock->unlock(); } //移除不使用的资源 void SVRenderer::removeUnuseRes() { m_resLock->lock(); //小心复值引用计数会加 1!!!!!!!!!!!!!! 晓帆。。 for(s32 i=0;i<m_robjList.size();) { if(m_robjList[i].use_count() == 1) { m_robjList[i]->destroy(nullptr); m_robjList.remove(i); }else{ i++; } } m_robjList.reserveForce(m_robjList.size()); m_resLock->unlock(); } SVRenderTexturePtr SVRenderer::getRenderTexture() { return m_pRenderTex; } SVTexturePtr SVRenderer::getSVTex(SVTEXTYPE _type){ if(E_TEX_END == _type) { return nullptr; } return m_svTex[_type]; } bool SVRenderer::hasSVTex(SVTEXTYPE _type) { if( m_svTex[_type] ) return true; return false; } //创建内置纹理 有问题后期删掉 SVTexturePtr SVRenderer::createSVTex(SVTEXTYPE _type,s32 _w,s32 _h,s32 _formate, bool _enableMipMap) { // SVTexturePtr t_tex = MakeSharedPtr<SVTexture>(mApp);; // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // #if defined(SV_ANDROID) // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, GL_RGBA, GL_RGBA,_enableMipMap); // #else // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, GL_RGBA, GL_BGRA,_enableMipMap); // #endif // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; return nullptr; } //创建内置纹理 有问题后期删掉 SVTexturePtr SVRenderer::createSVTex(SVTEXTYPE _type,s32 _w,s32 _h,s32 _informate,s32 _daformate, bool _enableMipMap) { // SVTexturePtr t_tex = MakeSharedPtr<SVTexture>(mApp);; // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, _informate, _daformate,_enableMipMap); // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; return nullptr; } //创建内置纹理 IOS SVTexturePtr SVRenderer::createSVTexIOS(SVTEXTYPE _type,s32 _w,s32 _h,s32 _formate, bool _enableMipMap) { #if defined( SV_IOS ) // SVTexturePtr t_tex = MakeSharedPtr<SVTextureIOS>(mApp);; // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, GL_RGBA, GL_BGRA,_enableMipMap); // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; #endif return nullptr; } SVTexturePtr SVRenderer::createSVTexIOS(SVTEXTYPE _type,s32 _w,s32 _h,s32 _informate,s32 _daformate, bool _enableMipMap) { #if defined( SV_IOS ) // SVTexturePtr t_tex = MakeSharedPtr<SVTextureIOS>(mApp); // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, _informate, _daformate,_enableMipMap); // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; #endif return nullptr; } // void SVRenderer::destroySVTex(SVTEXTYPE _type) { m_svTex[_type] = nullptr; } //视口 void SVRenderer::svPushViewPort(u32 _x,u32 _y,u32 _w,u32 _h) { VPParam t_pm; t_pm.m_x = _x; t_pm.m_y = _y; t_pm.m_width = _w; t_pm.m_height = _h; m_vpStack.push(t_pm); } //退出视口 void SVRenderer::svPopViewPort() { m_vpStack.pop(); } // void SVRenderer::pushProjMat(FMat4 _mat){ FMat4 mat4 = _mat; m_stack_proj.push(mat4); } FMat4 SVRenderer::getProjMat(){ FMat4 mat4Proj = m_stack_proj.top(); return mat4Proj; } void SVRenderer::popProjMat(){ m_stack_proj.pop(); } // void SVRenderer::pushViewMat(FMat4 _mat){ FMat4 mat4 = _mat; m_stack_view.push(mat4); } FMat4 SVRenderer::getViewMat(){ FMat4 mat4View = m_stack_view.top();; return mat4View; } void SVRenderer::popViewMat(){ m_stack_view.pop(); } // void SVRenderer::pushVPMat(FMat4 _mat){ FMat4 mat4 = _mat; m_stack_vp.push(mat4); } FMat4 SVRenderer::getVPMat(){ FMat4 mat4VP = m_stack_vp.top();; return mat4VP; } void SVRenderer::popVPMat(){ m_stack_vp.pop(); } void SVRenderer::clearMatStack(){ m_stack_proj.clear(); m_stack_view.clear(); m_stack_vp.clear(); }
24.124514
122
0.659516
SVEChina
f45d57365119bcd630de4c8b05560130ca575bc5
3,172
cpp
C++
Code/Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#include "Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.hpp" //--------------------------------------------------------------------------------------------------------------------------- //STRUCTORS //--------------------------------------------------------------------------------------------------------------------------- ParticleEmitter2D::ParticleEmitter2D(ParticleEmitterDefinition2D* emitterDef, const String& layerName, const Vector2& position) : m_emitterDef(emitterDef) , m_layerName(layerName) , m_isPlaying(true) , m_currNumParticles(0) , m_age(0.f) , m_position(position) { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { m_particles[i] = nullptr; } SpawnParticles(); } ParticleEmitter2D::~ParticleEmitter2D() { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if (m_particles[i]) { delete m_particles[i]; m_particles[i] = nullptr; } } } //--------------------------------------------------------------------------------------------------------------------------- //UPDATE //--------------------------------------------------------------------------------------------------------------------------- void ParticleEmitter2D::Update(float deltaSeconds) { m_age += deltaSeconds; if (m_emitterDef->m_spawnRate == 0.f && m_currNumParticles == 0) { m_isPlaying = false; } UpdateParticles(deltaSeconds); DestroyParticles(); if (m_isPlaying) { SpawnParticles(); } } //--------------------------------------------------------------------------------------------------------------------------- //PRIVATE UPDATES //--------------------------------------------------------------------------------------------------------------------------- void ParticleEmitter2D::SpawnParticles() { if (m_age != 0.f && m_emitterDef->m_spawnRate == 0.f) return; uint numToSpawn = m_emitterDef->m_initialSpawnCount.Roll(); for (uint i = 0; i < numToSpawn; i++) { Vector2 startingVel = m_emitterDef->m_startVelocity.Roll() * m_emitterDef->m_velocityStrength.Roll(); Vector2 accel = m_emitterDef->m_acceleration.Roll(); float life = m_emitterDef->m_life.Roll(); float scale = m_emitterDef->m_initialScale.Roll(); Particle2D* particle = new Particle2D(m_emitterDef->m_resourceName, m_layerName, m_position, startingVel, accel, life, Vector2(scale, scale), m_emitterDef->m_tint); AddParticleToArray(particle); } } void ParticleEmitter2D::UpdateParticles(float deltaSeconds) { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if(m_particles[i]) m_particles[i]->Update(deltaSeconds); } } void ParticleEmitter2D::DestroyParticles() { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if (m_particles[i] && !m_particles[i]->m_isAlive) { delete m_particles[i]; m_particles[i] = nullptr; m_currNumParticles--; } } } void ParticleEmitter2D::AddParticleToArray(Particle2D* particle) { bool foundASpot = false; for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if (!m_particles[i]) { m_particles[i] = particle; m_currNumParticles++; foundASpot = true; break; } } ASSERT_OR_DIE(foundASpot, "ERROR: Particle buffer too small to add particle"); }
32.367347
166
0.546974
ntaylorbishop
f45e0b9877bd17daf15c3c560b5ff8ef4c6b8db3
11,652
cpp
C++
vegastrike/src/networking/lowlevel/packet.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/networking/lowlevel/packet.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/networking/lowlevel/packet.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#include <config.h> #if !defined (_WIN32) #include <unistd.h> #endif #include <math.h> //zlib is required for libpng, so these people must have one. #ifndef NO_GFX #ifndef HAVE_ZLIB_H #define HAVE_ZLIB_H 1 #endif #endif #ifdef HAVE_ZLIB_H #include <zlib.h> #endif /* HAVE_ZLIB_H */ #include "packet.h" #include "vsnet_debug.h" #include "vsnet_oss.h" #include "lin_time.h" LOCALCONST_DEF( Packet, unsigned short, header_length, sizeof (struct Header) ) #include <boost/version.hpp> #if defined (_WIN32) && defined (_MSC_VER) && BOOST_VERSION != 102800 //wierd error in MSVC # define __LINE__NOMSC 0 #else # define __LINE__NOMSC __LINE__ #endif Packet::Packet() { MAKE_VALID h.command = 0; h.serial = 0; h.timestamp = 0; h.data_length = 0; h.flags = NONE; } Packet::Packet( const void *buffer, size_t sz ) { MAKE_VALID if (sz >= header_length) { h.ntoh( buffer ); sz -= header_length; if (h.data_length > sz) { COUT<<"Packet not correctly received, not enough data for buffer"<<endl <<" should be still "<<h.data_length <<" but buffer has only "<<sz<<endl; display( __FILE__, __LINE__NOMSC ); h.data_length = sz; //Don't want game to crash later on! } else if (h.flags&COMPRESSED) { if (packet_uncompress( _packet, (const unsigned char*) buffer, h.data_length, h ) == false) display( __FILE__, __LINE__NOMSC ); } else { PacketMem mem( buffer, sz ); _packet = mem; #ifdef VSNET_DEBUG COUT<<"Parsed a packet with" <<" cmd="<<Cmd( h.command )<<"("<<(int) h.command<<")" <<" ser="<<h.serial <<" ts="<<h.timestamp <<" len="<<h.data_length <<endl; #endif } } else { COUT<<"Packet not correctly received, not enough data for header"<<endl; } } Packet::Packet( PacketMem &buffer ) { MAKE_VALID if (buffer.len() >= header_length) { h.ntoh( buffer.getConstBuf() ); size_t sz = buffer.len(); sz -= header_length; if (h.data_length > sz) { COUT<<"Packet not correctly received, not enough data for buffer"<<endl <<" should be still "<<h.data_length <<" but buffer has only "<<sz<<endl; display( __FILE__, __LINE__NOMSC ); h.data_length = sz; //Don't want game to crash later on! } else if (h.flags&COMPRESSED) { #ifdef HAVE_ZLIB_H if (packet_uncompress( _packet, (const unsigned char*) buffer.getConstBuf(), h.data_length, h ) == false) display( __FILE__, __LINE__NOMSC ); #else /* HAVE_ZLIB_H */ COUT<<"Received compressed packet, but compiled without zlib"<<endl; display( __FILE__, __LINE__NOMSC ); #endif /* HAVE_ZLIB_H */ } else { _packet = buffer; #ifdef VSNET_DEBUG COUT<<"Parsed a packet with" <<" cmd="<<Cmd( h.command )<<"("<<(int) h.command<<")" <<" ser="<<h.serial <<" ts="<<h.timestamp <<" len="<<h.data_length <<endl; #endif } } else { COUT<<"Packet not correctly received, not enough data for header"<<endl; } } Packet::Packet( const Packet &a ) { MAKE_VALID copyfrom( a ); } Packet::~Packet() { CHECK_VALID MAKE_INVALID } void Packet::copyfrom( const Packet &a ) { CHECK_VALID h.command = a.h.command; h.serial = a.h.serial; h.timestamp = a.h.timestamp; h.data_length = a.h.data_length; h.flags = a.h.flags; _packet = a._packet; } int Packet::send( Cmd cmd, ObjSerial nserial, const char *buf, unsigned int length, int prio, const AddressIP *dst, const SOCKETALT &sock, const char *caller_file, int caller_line ) { CHECK_VALID create( cmd, nserial, buf, length, prio, caller_file, caller_line ); return send( sock, dst ); } void Packet::create( Cmd cmd, ObjSerial nserial, const char *buf, unsigned int length, int prio, const char *caller_file, int caller_line ) { CHECK_VALID unsigned int microtime; //Get a timestamp for packet (used for interpolation on client side) double curtime = getNewTime(); microtime = (unsigned int) ( floor( curtime*1000 ) ); h.timestamp = microtime; #ifdef VSNET_DEBUG COUT<<"enter "<<__PRETTY_FUNCTION__<<endl <<" *** from "<<caller_file<<":"<<caller_line<<endl <<" *** create "<<cmd<<" ser="<<nserial<<", "<<length <<" *** curtime "<<curtime <<" microtime "<<microtime <<" timestamp "<<h.timestamp<<endl; #else //COUT << "*** create " << cmd << " ser=" << nserial << ", " << length << endl; #endif h.command = cmd; h.flags = prio; //buf is an allocated char * containing message h.serial = nserial; bool packet_filled = false; #ifdef HAVE_ZLIB_H #ifdef USE_COMPRESSED_PACKETS if (prio&COMPRESSED) { size_t sz; //complicated zlib rules for safety reasons sz = length+(length/10)+15+header_length; char *c = new char[sz]; unsigned long clen_l = length; unsigned int ulen_i; unsigned char *dest = (unsigned char*) &c[header_length+sizeof (ulen_i)]; int zlib_errcode; zlib_errcode = ::compress2( dest, &clen_l, (unsigned char*) buf, length, 9 ); if (zlib_errcode == Z_OK) { if (clen_l < length+2) { ulen_i = htonl( (unsigned int) length ); VsnetOSS::memcpy( &c[header_length], &ulen_i, sizeof (ulen_i) ); h.data_length = clen_l+sizeof (ulen_i); h.hton( c ); #ifdef VSNET_DEBUG COUT<<"Created a compressed packet of length " <<h.data_length+header_length<<" for sending"<<endl; #endif _packet.set( c, h.data_length+header_length, PacketMem::TakeOwnership ); packet_filled = true; } else { #ifdef VSNET_DEBUG COUT<<"Compressing "<<cmd <<" packet refused - bigger than original"<<std::endl; #endif delete[] c; _packet = PacketMem(); } } else { delete[] c; _packet = PacketMem(); } } #endif /* USED_COMPRESSED_PACKETS */ #endif /* HAVE_ZLIB_H */ if (packet_filled == false) { h.flags &= (~COMPRESSED); //make sure that it's never set here h.data_length = length; char *c = new char[length+header_length]; h.hton( c ); VsnetOSS::memcpy( &c[header_length], buf, length ); _packet.set( c, length+header_length, PacketMem::TakeOwnership ); #ifdef VSNET_DEBUG COUT<<"Created a packet of length " <<length+header_length<<" for sending"<<endl; #endif } } void Packet::display( const char *file, int line ) { CHECK_VALID cout<<"*** "<<file<<":"<<line<<" "<<endl; cout<<"*** Packet display -- Command : "<<Cmd( h.command ) <<" - Serial : "<<h.serial<<" - Flags : "<<h.flags<<endl; cout<<"*** Size : "<<getDataLength()+header_length<<endl; cout<<"*** Buffer : "<<endl; _packet.dump( cout, 4 ); } void Packet::displayHex() { CHECK_VALID cout<<"Packet : "<<h.command<<" | "<<h.serial<<" | "; const char *c = _packet.getConstBuf(); for (size_t i = 0; i < _packet.len(); i++) cout<<c[i]<<" "; cout<<endl; } void Packet::Header::ntoh( const void *buf ) { //TO CHANGE IF ObjSerial IS NOT A SHORT ANYMORE const Header *h = (const Header*) buf; command = h->command; serial = ntohs( h->serial ); timestamp = ntohl( h->timestamp ); data_length = ntohl( h->data_length ); flags = ntohs( h->flags ); } void Packet::Header::hton( char *buf ) { //TO CHANGE IF ObjSerial IS NOT A SHORT ANYMORE Header *h = (Header*) buf; h->command = command; h->serial = htons( serial ); h->timestamp = htonl( timestamp ); h->data_length = htonl( data_length ); h->flags = htons( flags ); } int Packet::send( SOCKETALT dst_s, const AddressIP *dst_a ) { CHECK_VALID #ifdef VSNET_DEBUG if (dst_a == NULL) COUT<<"sending "<<Cmd( h.command )<<" through "<<dst_s<<" to " <<"NULL"<<endl; else COUT<<"sending "<<Cmd( h.command )<<" through "<<dst_s<<" to " <<*dst_a<<endl; #endif int ret; //if( (ret = dst_s.sendbuf( _packet, dst_a, h.flags )) == -1) if ( ( ret = dst_s.sendbuf( this, dst_a, h.flags ) ) == -1 ) { h.ntoh( _packet.getConstBuf() ); perror( "Error sending packet " ); cout<<Cmd( h.command )<<endl; } else { #ifdef VSNET_DEBUG COUT<<"After successful sendbuf"<<endl; h.ntoh( _packet.getConstBuf() ); #if 0 PacketMem m( _packet.getVarBuf(), _packet.len(), PacketMem::LeaveOwnership ); m.dump( cout, 3 ); #endif #endif } return ret; } const char* Packet::getData() const { CHECK_VALID const char *c = _packet.getConstBuf(); c += header_length; return c; } unsigned int Packet::getDataLength() const { if ( h.data_length > _packet.len() ) return _packet.len(); else return h.data_length; } const char* Packet::getSendBuffer() const { CHECK_VALID const char *c = _packet.getConstBuf(); return c; } int Packet::getSendBufferLength() const { return h.data_length+header_length; } #ifdef HAVE_ZLIB_H bool Packet::packet_uncompress( PacketMem &outpacket, const unsigned char *src, size_t sz, Header &header ) { unsigned char *dest; unsigned int ulen_i; unsigned long ulen_l; int zlib_errcode; src += header_length; ulen_i = ntohl( *(unsigned int*) src ); src += sizeof (ulen_i); sz -= sizeof (ulen_i); PacketMem mem( ulen_i+header_length ); dest = (unsigned char*) mem.getVarBuf(); dest += header_length; ulen_l = ulen_i; zlib_errcode = ::uncompress( dest, &ulen_l, src, sz ); if (zlib_errcode != Z_OK) { COUT<<"Compressed packet not correctly received, " <<"decompression failed with zlib errcode " <<zlib_errcode<<endl; return false; } else if (ulen_l != ulen_i) { COUT<<"Compressed packet not correctly received, " <<"expected len "<<ulen_i<<", " <<"received len "<<ulen_l<<endl; return false; } else { outpacket = mem; header.data_length = ulen_i; #ifdef VSNET_DEBUG COUT<<"Parsed a compressed packet with" <<" cmd="<<Cmd( header.command )<<"("<<(int) header.command<<")" <<" ser="<<header.serial <<" ts="<<header.timestamp <<" len="<<header.data_length <<endl; #endif return true; } } #else /* HAVE_ZLIB_H */ bool Packet::packet_uncompress( PacketMem&, const unsigned char*, size_t, Header& ) { return false; } #endif /* HAVE_ZLIB_H */
28.558824
107
0.547717
Ezeer
f46045c8cd0a5d9e8c8ffe7ece82652884d27dcc
2,164
hpp
C++
Logger/include/Logger/sink/log_sink.hpp
tmiguelf/Logger
7cf568a97711480a7ba23d5f6adeb49d05cd6f78
[ "MIT" ]
null
null
null
Logger/include/Logger/sink/log_sink.hpp
tmiguelf/Logger
7cf568a97711480a7ba23d5f6adeb49d05cd6f78
[ "MIT" ]
null
null
null
Logger/include/Logger/sink/log_sink.hpp
tmiguelf/Logger
7cf568a97711480a7ba23d5f6adeb49d05cd6f78
[ "MIT" ]
null
null
null
//======== ======== ======== ======== ======== ======== ======== ======== /// \file /// /// \copyright /// Copyright (c) 2020 Tiago Miguel Oliveira Freire /// /// 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. //======== ======== ======== ======== ======== ======== ======== ======== #pragma once #include <cstdint> #include <string_view> #include <CoreLib/Core_Time.hpp> #include <CoreLib/Core_Thread.hpp> #include <CoreLib/string/core_os_string.hpp> #include <Logger/log_level.hpp> namespace logger { /// \brief Holds the Logging data information struct log_data { core::os_string_view m_file; std::u8string_view m_line; std::u8string_view m_column; std::u8string_view m_date; std::u8string_view m_time; std::u8string_view m_thread; std::u8string_view m_level; std::u8string_view m_message; core::DateTime m_timeStruct; core::thread_id_t m_threadId; uint32_t m_lineNumber; uint32_t m_columnNumber; Level m_levelNumber; }; /// \brief Created to do Logging streams class log_sink { public: virtual void output(const log_data& p_logData) = 0; }; } // namespace simLog
32.298507
83
0.692699
tmiguelf
f464332a6ff3c22a903eee8dc0556f596c8578a1
988
hpp
C++
tests/app/src/opengl2/mordaren/OpenGL2Renderer.hpp
Mactor2018/morda
7194f973783b4472b8671fbb52e8c96e8c972b90
[ "MIT" ]
1
2018-10-27T05:07:05.000Z
2018-10-27T05:07:05.000Z
tests/app/src/opengl2/mordaren/OpenGL2Renderer.hpp
Mactor2018/morda
7194f973783b4472b8671fbb52e8c96e8c972b90
[ "MIT" ]
null
null
null
tests/app/src/opengl2/mordaren/OpenGL2Renderer.hpp
Mactor2018/morda
7194f973783b4472b8671fbb52e8c96e8c972b90
[ "MIT" ]
null
null
null
#pragma once #include <GL/glew.h> #include <morda/render/Renderer.hpp> #include "OpenGL2Factory.hpp" namespace mordaren{ class OpenGL2Renderer : public morda::Renderer{ GLuint defaultFramebuffer; public: OpenGL2Renderer(std::unique_ptr<OpenGL2Factory> factory = utki::makeUnique<OpenGL2Factory>()); OpenGL2Renderer(const OpenGL2Renderer& orig) = delete; OpenGL2Renderer& operator=(const OpenGL2Renderer& orig) = delete; void setFramebufferInternal(morda::FrameBuffer* fb) override; void clearFramebuffer()override; bool isScissorEnabled() const override; void setScissorEnabled(bool enabled) override; kolme::Recti getScissorRect() const override; void setScissorRect(kolme::Recti r) override; kolme::Recti getViewport()const override; void setViewport(kolme::Recti r) override; void setBlendEnabled(bool enable) override; void setBlendFunc(BlendFactor_e srcClr, BlendFactor_e dstClr, BlendFactor_e srcAlpha, BlendFactor_e dstAlpha) override; }; }
23.52381
120
0.783401
Mactor2018
f46455af60b3482d696ecb4c42ed31fd0639761d
16,398
hh
C++
src/cpu/kvm/base.hh
joerocklin/gem5
bc199672491f16e678c35d2187917738c24d6628
[ "BSD-3-Clause" ]
null
null
null
src/cpu/kvm/base.hh
joerocklin/gem5
bc199672491f16e678c35d2187917738c24d6628
[ "BSD-3-Clause" ]
null
null
null
src/cpu/kvm/base.hh
joerocklin/gem5
bc199672491f16e678c35d2187917738c24d6628
[ "BSD-3-Clause" ]
2
2018-11-06T18:41:38.000Z
2019-01-30T00:51:40.000Z
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Andreas Sandberg */ #ifndef __CPU_KVM_BASE_HH__ #define __CPU_KVM_BASE_HH__ #include <memory> #include "base/statistics.hh" #include "cpu/kvm/perfevent.hh" #include "cpu/kvm/timer.hh" #include "cpu/kvm/vm.hh" #include "cpu/base.hh" #include "cpu/simple_thread.hh" /** Signal to use to trigger time-based exits from KVM */ #define KVM_TIMER_SIGNAL SIGRTMIN // forward declarations class ThreadContext; struct BaseKvmCPUParams; /** * Base class for KVM based CPU models * * All architecture specific KVM implementation should inherit from * this class. The most basic CPU models only need to override the * updateKvmState() and updateThreadContext() methods to implement * state synchronization between gem5 and KVM. * * The architecture specific implementation is also responsible for * delivering interrupts into the VM. This is typically done by * overriding tick() and checking the thread context before entering * into the VM. In order to deliver an interrupt, the implementation * then calls KvmVM::setIRQLine() or BaseKvmCPU::kvmInterrupt() * depending on the specifics of the underlying hardware/drivers. */ class BaseKvmCPU : public BaseCPU { public: BaseKvmCPU(BaseKvmCPUParams *params); virtual ~BaseKvmCPU(); void init(); void startup(); void regStats(); void serializeThread(std::ostream &os, ThreadID tid); void unserializeThread(Checkpoint *cp, const std::string &section, ThreadID tid); unsigned int drain(DrainManager *dm); void drainResume(); void switchOut(); void takeOverFrom(BaseCPU *cpu); void verifyMemoryMode() const; CpuPort &getDataPort() { return dataPort; } CpuPort &getInstPort() { return instPort; } void wakeup(); void activateContext(ThreadID thread_num, Cycles delay); void suspendContext(ThreadID thread_num); void deallocateContext(ThreadID thread_num); void haltContext(ThreadID thread_num); ThreadContext *getContext(int tn); Counter totalInsts() const; Counter totalOps() const; /** Dump the internal state to the terminal. */ virtual void dump(); /** * A cached copy of a thread's state in the form of a SimpleThread * object. * * Normally the actual thread state is stored in the KVM vCPU. If KVM has * been running this copy is will be out of date. If we recently handled * some events within gem5 that required state to be updated this could be * the most up-to-date copy. When getContext() or updateThreadContext() is * called this copy gets updated. The method syncThreadContext can * be used within a KVM CPU to update the thread context if the * KVM state is dirty (i.e., the vCPU has been run since the last * update). */ SimpleThread *thread; /** ThreadContext object, provides an interface for external * objects to modify this thread's state. */ ThreadContext *tc; KvmVM &vm; protected: enum Status { /** Context not scheduled in KVM */ Idle, /** Running normally */ Running, }; /** CPU run state */ Status _status; /** * Execute the CPU until the next event in the main event queue or * until the guest needs service from gem5. * * @note This method is virtual in order to allow implementations * to check for architecture specific events (e.g., interrupts) * before entering the VM. */ virtual void tick(); /** * Request KVM to run the guest for a given number of ticks. The * method returns the approximate number of ticks executed. * * @note The returned number of ticks can be both larger or * smaller than the requested number of ticks. A smaller number * can, for example, occur when the guest executes MMIO. A larger * number is typically due to performance counter inaccuracies. * * @param ticks Number of ticks to execute * @return Number of ticks executed (see note) */ Tick kvmRun(Tick ticks); /** * Get a pointer to the kvm_run structure containing all the input * and output parameters from kvmRun(). */ struct kvm_run *getKvmRunState() { return _kvmRun; }; /** * Retrieve a pointer to guest data stored at the end of the * kvm_run structure. This is mainly used for PIO operations * (KVM_EXIT_IO). * * @param offset Offset as specified by the kvm_run structure * @return Pointer to guest data */ uint8_t *getGuestData(uint64_t offset) const { return (uint8_t *)_kvmRun + offset; }; /** * @addtogroup KvmInterrupts * @{ */ /** * Send a non-maskable interrupt to the guest * * @note The presence of this call depends on Kvm::capUserNMI(). */ void kvmNonMaskableInterrupt(); /** * Send a normal interrupt to the guest * * @note Make sure that ready_for_interrupt_injection in kvm_run * is set prior to calling this function. If not, an interrupt * window must be requested by setting request_interrupt_window in * kvm_run to 1 and restarting the guest. * * @param interrupt Structure describing the interrupt to send */ void kvmInterrupt(const struct kvm_interrupt &interrupt); /** @} */ /** @{ */ /** * Get/Set the register state of the guest vCPU * * KVM has two different interfaces for accessing the state of the * guest CPU. One interface updates 'normal' registers and one * updates 'special' registers. The distinction between special * and normal registers isn't very clear and is architecture * dependent. */ void getRegisters(struct kvm_regs &regs) const; void setRegisters(const struct kvm_regs &regs); void getSpecialRegisters(struct kvm_sregs &regs) const; void setSpecialRegisters(const struct kvm_sregs &regs); /** @} */ /** @{ */ /** * Get/Set the guest FPU/vector state */ void getFPUState(struct kvm_fpu &state) const; void setFPUState(const struct kvm_fpu &state); /** @} */ /** @{ */ /** * Get/Set single register using the KVM_(SET|GET)_ONE_REG API. * * @note The presence of this call depends on Kvm::capOneReg(). */ void setOneReg(uint64_t id, const void *addr); void setOneReg(uint64_t id, uint64_t value) { setOneReg(id, &value); } void setOneReg(uint64_t id, uint32_t value) { setOneReg(id, &value); } void getOneReg(uint64_t id, void *addr) const; uint64_t getOneRegU64(uint64_t id) const { uint64_t value; getOneReg(id, &value); return value; } uint32_t getOneRegU32(uint64_t id) const { uint32_t value; getOneReg(id, &value); return value; } /** @} */ /** * Get and format one register for printout. * * This function call getOneReg() to retrieve the contents of one * register and automatically formats it for printing. * * @note The presence of this call depends on Kvm::capOneReg(). */ std::string getAndFormatOneReg(uint64_t id) const; /** @{ */ /** * Update the KVM state from the current thread context * * The base CPU calls this method before starting the guest CPU * when the contextDirty flag is set. The architecture dependent * CPU implementation is expected to update all guest state * (registers, special registers, and FPU state). */ virtual void updateKvmState() = 0; /** * Update the current thread context with the KVM state * * The base CPU after the guest updates any of the KVM state. In * practice, this happens after kvmRun is called. The architecture * dependent code is expected to read the state of the guest CPU * and update gem5's thread state. */ virtual void updateThreadContext() = 0; /** * Update a thread context if the KVM state is dirty with respect * to the cached thread context. */ void syncThreadContext(); /** * Update the KVM if the thread context is dirty. */ void syncKvmState(); /** @} */ /** @{ */ /** * Main kvmRun exit handler, calls the relevant handleKvmExit* * depending on exit type. * * @return Number of ticks spent servicing the exit request */ virtual Tick handleKvmExit(); /** * The guest performed a legacy IO request (out/inp on x86) * * @return Number of ticks spent servicing the IO request */ virtual Tick handleKvmExitIO(); /** * The guest requested a monitor service using a hypercall * * @return Number of ticks spent servicing the hypercall */ virtual Tick handleKvmExitHypercall(); /** * The guest exited because an interrupt window was requested * * The guest exited because an interrupt window was requested * (request_interrupt_window in the kvm_run structure was set to 1 * before calling kvmRun) and it is now ready to receive * * @return Number of ticks spent servicing the IRQ */ virtual Tick handleKvmExitIRQWindowOpen(); /** * An unknown architecture dependent error occurred when starting * the vCPU * * The kvm_run data structure contains the hardware error * code. The defaults behavior of this method just prints the HW * error code and panics. Architecture dependent implementations * may want to override this method to provide better, * hardware-aware, error messages. * * @return Number of ticks delay the next CPU tick */ virtual Tick handleKvmExitUnknown(); /** * An unhandled virtualization exception occured * * Some KVM virtualization drivers return unhandled exceptions to * the user-space monitor. This interface is currently only used * by the Intel VMX KVM driver. * * @return Number of ticks delay the next CPU tick */ virtual Tick handleKvmExitException(); /** * KVM failed to start the virtualized CPU * * The kvm_run data structure contains the hardware-specific error * code. * * @return Number of ticks delay the next CPU tick */ virtual Tick handleKvmExitFailEntry(); /** @} */ /** * Inject a memory mapped IO request into gem5 * * @param paddr Physical address * @param data Pointer to the source/destination buffer * @param size Memory access size * @param write True if write, False if read * @return Number of ticks spent servicing the memory access */ Tick doMMIOAccess(Addr paddr, void *data, int size, bool write); /** * @addtogroup KvmIoctl * @{ */ /** * vCPU ioctl interface. * * @param request KVM vCPU request * @param p1 Optional request parameter * * @return -1 on error (error number in errno), ioctl dependent * value otherwise. */ int ioctl(int request, long p1) const; int ioctl(int request, void *p1) const { return ioctl(request, (long)p1); } int ioctl(int request) const { return ioctl(request, 0L); } /** @} */ /** Port for data requests */ CpuPort dataPort; /** Unused dummy port for the instruction interface */ CpuPort instPort; /** Pre-allocated MMIO memory request */ Request mmio_req; /** * Is the gem5 context dirty? Set to true to force an update of * the KVM vCPU state upon the next call to kvmRun(). */ bool threadContextDirty; /** * Is the KVM state dirty? Set to true to force an update of * the KVM vCPU state upon the next call to kvmRun(). */ bool kvmStateDirty; /** KVM internal ID of the vCPU */ const long vcpuID; private: struct TickEvent : public Event { BaseKvmCPU &cpu; TickEvent(BaseKvmCPU &c) : Event(CPU_Tick_Pri), cpu(c) {} void process() { cpu.tick(); } const char *description() const { return "BaseKvmCPU tick"; } }; /** * Service MMIO requests in the mmioRing. * * * @return Number of ticks spent servicing the MMIO requests in * the MMIO ring buffer */ Tick flushCoalescedMMIO(); /** * Setup a signal handler to catch the timer signal used to * switch back to the monitor. */ void setupSignalHandler(); /** Setup hardware performance counters */ void setupCounters(); /** KVM vCPU file descriptor */ int vcpuFD; /** Size of MMAPed kvm_run area */ int vcpuMMapSize; /** * Pointer to the kvm_run structure used to communicate parameters * with KVM. * * @note This is the base pointer of the MMAPed KVM region. The * first page contains the kvm_run structure. Subsequent pages may * contain other data such as the MMIO ring buffer. */ struct kvm_run *_kvmRun; /** * Coalesced MMIO ring buffer. NULL if coalesced MMIO is not * supported. */ struct kvm_coalesced_mmio_ring *mmioRing; /** Cached page size of the host */ const long pageSize; TickEvent tickEvent; /** @{ */ /** Guest performance counters */ PerfKvmCounter hwCycles; PerfKvmCounter hwInstructions; /** @} */ /** * Does the runTimer control the performance counters? * * The run timer will automatically enable and disable performance * counters if a PerfEvent-based timer is used to control KVM * exits. */ bool perfControlledByTimer; /** * Timer used to force execution into the monitor after a * specified number of simulation tick equivalents have executed * in the guest. This counter generates the signal specified by * KVM_TIMER_SIGNAL. */ std::unique_ptr<BaseKvmTimer> runTimer; float hostFactor; public: /* @{ */ Stats::Scalar numInsts; Stats::Scalar numVMExits; Stats::Scalar numMMIO; Stats::Scalar numCoalescedMMIO; Stats::Scalar numIO; Stats::Scalar numHalt; Stats::Scalar numInterrupts; Stats::Scalar numHypercalls; /* @} */ }; #endif
31.234286
78
0.664715
joerocklin
f467177ede885e9e945e308fb4afbee637655127
1,392
hpp
C++
include/lol/op/PostRecofrienderV1RegistrationsByNetwork.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/op/PostRecofrienderV1RegistrationsByNetwork.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/op/PostRecofrienderV1RegistrationsByNetwork.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_op.hpp" #include <functional> #include "../def/RecofrienderUrlResource.hpp" namespace lol { template<typename T> inline Result<RecofrienderUrlResource> PostRecofrienderV1RegistrationsByNetwork(T& _client, const std::string& network) { try { return ToResult<RecofrienderUrlResource>(_client.https.request("post", "/recofriender/v1/registrations/"+to_string(network)+"?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }))); } catch(const SimpleWeb::system_error &e) { return ToResult<RecofrienderUrlResource>(e.code()); } } template<typename T> inline void PostRecofrienderV1RegistrationsByNetwork(T& _client, const std::string& network, std::function<void(T&, const Result<RecofrienderUrlResource>&)> cb) { _client.httpsa.request("post", "/recofriender/v1/registrations/"+to_string(network)+"?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }),[cb,&_client](std::shared_ptr<HttpsClient::Response> response, const SimpleWeb::error_code &e) { if(e) cb(_client, ToResult<RecofrienderUrlResource>(e)); else cb(_client, ToResult<RecofrienderUrlResource>(response)); }); } }
42.181818
162
0.66523
Maufeat
f46a5569ab2301e6db3b620e226c0c5659f43ce8
694
cpp
C++
fp_core/src/main/src/Python/PyUtils.cpp
submain/fruitpunch
31773128238830d3d335c1915877dc0db56836cd
[ "MIT" ]
null
null
null
fp_core/src/main/src/Python/PyUtils.cpp
submain/fruitpunch
31773128238830d3d335c1915877dc0db56836cd
[ "MIT" ]
null
null
null
fp_core/src/main/src/Python/PyUtils.cpp
submain/fruitpunch
31773128238830d3d335c1915877dc0db56836cd
[ "MIT" ]
1
2020-08-14T02:51:47.000Z
2020-08-14T02:51:47.000Z
/* * PyUtils.cpp * * Created on: 2012-05-26 * Author: leo */ #include <fruitpunch/Python/PyUtils.h> #include <boost/python/call_method.hpp> namespace fp_core { PyUtils::PyUtils() { // TODO Auto-generated constructor stub } bool PyUtils::hasMethod(PyObject* obj, std::string methodName) { int hasIt = PyObject_HasAttrString(obj, methodName.c_str()); if (hasIt == 0) return false; PyObject * attr = PyObject_GetAttrString(obj, methodName.c_str()); return PyCallable_Check(attr) == 1; } void PyUtils::call(PyObject* obj, std::string method) { if (!hasMethod(obj, method)) return ; boost::python::call_method<void>(obj, method.c_str()); } }/* namespace fp_core */
21.030303
68
0.691643
submain
c2e30354aa67f3686d41f6cf9b9e23406598c634
1,487
cpp
C++
cpgf/test/scriptbind/luabind/test_lua_operator.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
187
2015-01-19T06:05:30.000Z
2022-03-27T14:28:21.000Z
cpgf/test/scriptbind/luabind/test_lua_operator.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
37
2015-01-16T04:15:11.000Z
2020-03-31T23:42:55.000Z
cpgf/test/scriptbind/luabind/test_lua_operator.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
50
2015-01-13T13:50:10.000Z
2022-01-25T17:16:51.000Z
#include "../testscriptbind.h" namespace { void TestLuaOperator(TestScriptContext * context) { QDO(a = TestOperator(99)) QDO(b = a + 5) QASSERT(b.value == 99 + 5) QDO(b = a + TestOperator(8)) QASSERT(b.value == 99 + 8) QDO(b = a + TestObject(15)) QASSERT(b.value == 99 + 15) QDO(a = TestOperator(98)) QDO(b = a - 5) QASSERT(b.value == 98 - 5) QDO(b = a - TestOperator(8)) QASSERT(b.value == 98 - 8) QDO(b = a - TestObject(15)) QASSERT(b.value == 98 - 15) QDO(a = TestOperator(97)) QDO(b = a * 5) QASSERT(b.value == 97 * 5) QDO(b = a * TestOperator(8)) QASSERT(b.value == 97 * 8) QDO(b = a * TestObject(15)) QASSERT(b.value == 97 * 15) QDO(a = TestOperator(99)) QDO(b = a / 5) QASSERT(b.value == math.floor(99 / 5)) QDO(b = a / TestOperator(8)) QASSERT(b.value == math.floor(99 / 8)) QDO(b = a / TestObject(15)) QASSERT(b.value == math.floor(99 / 15)) QDO(a = TestOperator(88)) QDO(b = a % 5) QASSERT(b.value == 88 % 5) QDO(b = a % TestOperator(8)) QASSERT(b.value == 88 % 8) QDO(b = a % TestObject(15)) QASSERT(b.value == 88 % 15) QDO(a = TestOperator(99)) QDO(b = -a) QASSERT(b.value == -99) QDO(c = TestOperator(9)) QDO(a = c) QDO(b = -a) QASSERT(b.value == -9) QDO(d = TestOperator(3)) QDO(b = d(5, 7, 9, 1, 2, 6, 8)) QASSERT(b == 3 + 5 + 7 + 9 + 1 + 2 + 6 + 8) } #define CASE TestLuaOperator #include "../testcase_lua.h" }
17.494118
50
0.544721
mousepawmedia
c2e551d860206d075ffe8d70b56002208d5c2a5f
13,781
cpp
C++
Sourcecode/mx/core/elements/ArticulationsChoice.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mx/core/elements/ArticulationsChoice.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mx/core/elements/ArticulationsChoice.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "mx/core/elements/ArticulationsChoice.h" #include "mx/core/FromXElement.h" #include "mx/core/elements/Accent.h" #include "mx/core/elements/BreathMark.h" #include "mx/core/elements/Caesura.h" #include "mx/core/elements/DetachedLegato.h" #include "mx/core/elements/Doit.h" #include "mx/core/elements/Falloff.h" #include "mx/core/elements/OtherArticulation.h" #include "mx/core/elements/Plop.h" #include "mx/core/elements/Scoop.h" #include "mx/core/elements/Spiccato.h" #include "mx/core/elements/Staccatissimo.h" #include "mx/core/elements/Staccato.h" #include "mx/core/elements/Stress.h" #include "mx/core/elements/StrongAccent.h" #include "mx/core/elements/Tenuto.h" #include "mx/core/elements/Unstress.h" #include <iostream> namespace mx { namespace core { ArticulationsChoice::ArticulationsChoice() :myChoice( Choice::accent ) ,myAccent( makeAccent() ) ,myStrongAccent( makeStrongAccent() ) ,myStaccato( makeStaccato() ) ,myTenuto( makeTenuto() ) ,myDetachedLegato( makeDetachedLegato() ) ,myStaccatissimo( makeStaccatissimo() ) ,mySpiccato( makeSpiccato() ) ,myScoop( makeScoop() ) ,myPlop( makePlop() ) ,myDoit( makeDoit() ) ,myFalloff( makeFalloff() ) ,myBreathMark( makeBreathMark() ) ,myCaesura( makeCaesura() ) ,myStress( makeStress() ) ,myUnstress( makeUnstress() ) ,myOtherArticulation( makeOtherArticulation() ) {} bool ArticulationsChoice::hasAttributes() const { return false; } std::ostream& ArticulationsChoice::streamAttributes( std::ostream& os ) const { return os; } std::ostream& ArticulationsChoice::streamName( std::ostream& os ) const { os << "articulations"; return os; } bool ArticulationsChoice::hasContents() const { return true; } std::ostream& ArticulationsChoice::streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const { MX_UNUSED( isOneLineOnly ); switch ( myChoice ) { case Choice::accent: { myAccent->toStream( os, indentLevel ); } break; case Choice::strongAccent: { myStrongAccent->toStream( os, indentLevel ); } break; case Choice::staccato: { myStaccato->toStream( os, indentLevel ); } break; case Choice::tenuto: { myTenuto->toStream( os, indentLevel ); } break; case Choice::detachedLegato: { myDetachedLegato->toStream( os, indentLevel ); } break; case Choice::staccatissimo: { myStaccatissimo->toStream( os, indentLevel ); } break; case Choice::spiccato: { mySpiccato->toStream( os, indentLevel ); } break; case Choice::scoop: { myScoop->toStream( os, indentLevel ); } break; case Choice::plop: { myPlop->toStream( os, indentLevel ); } break; case Choice::doit: { myDoit->toStream( os, indentLevel ); } break; case Choice::falloff: { myFalloff->toStream( os, indentLevel ); } break; case Choice::breathMark: { myBreathMark->toStream( os, indentLevel ); } break; case Choice::caesura: { myCaesura->toStream( os, indentLevel ); } break; case Choice::stress: { myStress->toStream( os, indentLevel ); } break; case Choice::unstress: { myUnstress->toStream( os, indentLevel ); } break; case Choice::otherArticulation: { myOtherArticulation->toStream( os, indentLevel ); } break; default: break; } return os; } ArticulationsChoice::Choice ArticulationsChoice::getChoice() const { return myChoice; } void ArticulationsChoice::setChoice( const ArticulationsChoice::Choice value ) { myChoice = value; } AccentPtr ArticulationsChoice::getAccent() const { return myAccent; } void ArticulationsChoice::setAccent( const AccentPtr& value ) { if( value ) { myAccent = value; } } StrongAccentPtr ArticulationsChoice::getStrongAccent() const { return myStrongAccent; } void ArticulationsChoice::setStrongAccent( const StrongAccentPtr& value ) { if( value ) { myStrongAccent = value; } } StaccatoPtr ArticulationsChoice::getStaccato() const { return myStaccato; } void ArticulationsChoice::setStaccato( const StaccatoPtr& value ) { if( value ) { myStaccato = value; } } TenutoPtr ArticulationsChoice::getTenuto() const { return myTenuto; } void ArticulationsChoice::setTenuto( const TenutoPtr& value ) { if( value ) { myTenuto = value; } } DetachedLegatoPtr ArticulationsChoice::getDetachedLegato() const { return myDetachedLegato; } void ArticulationsChoice::setDetachedLegato( const DetachedLegatoPtr& value ) { if( value ) { myDetachedLegato = value; } } StaccatissimoPtr ArticulationsChoice::getStaccatissimo() const { return myStaccatissimo; } void ArticulationsChoice::setStaccatissimo( const StaccatissimoPtr& value ) { if( value ) { myStaccatissimo = value; } } SpiccatoPtr ArticulationsChoice::getSpiccato() const { return mySpiccato; } void ArticulationsChoice::setSpiccato( const SpiccatoPtr& value ) { if( value ) { mySpiccato = value; } } ScoopPtr ArticulationsChoice::getScoop() const { return myScoop; } void ArticulationsChoice::setScoop( const ScoopPtr& value ) { if( value ) { myScoop = value; } } PlopPtr ArticulationsChoice::getPlop() const { return myPlop; } void ArticulationsChoice::setPlop( const PlopPtr& value ) { if( value ) { myPlop = value; } } DoitPtr ArticulationsChoice::getDoit() const { return myDoit; } void ArticulationsChoice::setDoit( const DoitPtr& value ) { if( value ) { myDoit = value; } } FalloffPtr ArticulationsChoice::getFalloff() const { return myFalloff; } void ArticulationsChoice::setFalloff( const FalloffPtr& value ) { if( value ) { myFalloff = value; } } BreathMarkPtr ArticulationsChoice::getBreathMark() const { return myBreathMark; } void ArticulationsChoice::setBreathMark( const BreathMarkPtr& value ) { if( value ) { myBreathMark = value; } } CaesuraPtr ArticulationsChoice::getCaesura() const { return myCaesura; } void ArticulationsChoice::setCaesura( const CaesuraPtr& value ) { if( value ) { myCaesura = value; } } StressPtr ArticulationsChoice::getStress() const { return myStress; } void ArticulationsChoice::setStress( const StressPtr& value ) { if( value ) { myStress = value; } } UnstressPtr ArticulationsChoice::getUnstress() const { return myUnstress; } void ArticulationsChoice::setUnstress( const UnstressPtr& value ) { if( value ) { myUnstress = value; } } OtherArticulationPtr ArticulationsChoice::getOtherArticulation() const { return myOtherArticulation; } void ArticulationsChoice::setOtherArticulation( const OtherArticulationPtr& value ) { if( value ) { myOtherArticulation = value; } } bool ArticulationsChoice::fromXElementImpl( std::ostream& message, xml::XElement& xelement ) { if( xelement.getName() == "accent" ) { myChoice = Choice::accent; return getAccent()->fromXElement( message, xelement ); } if( xelement.getName() == "strong-accent" ) { myChoice = Choice::strongAccent; return getStrongAccent()->fromXElement( message, xelement ); } if( xelement.getName() == "staccato" ) { myChoice = Choice::staccato; return getStaccato()->fromXElement( message, xelement ); } if( xelement.getName() == "tenuto" ) { myChoice = Choice::tenuto; return getTenuto()->fromXElement( message, xelement ); } if( xelement.getName() == "detached-legato" ) { myChoice = Choice::detachedLegato; return getDetachedLegato()->fromXElement( message, xelement ); } if( xelement.getName() == "staccatissimo" ) { myChoice = Choice::staccatissimo; return getStaccatissimo()->fromXElement( message, xelement ); } if( xelement.getName() == "spiccato" ) { myChoice = Choice::spiccato; return getSpiccato()->fromXElement( message, xelement ); } if( xelement.getName() == "scoop" ) { myChoice = Choice::scoop; return getScoop()->fromXElement( message, xelement ); } if( xelement.getName() == "plop" ) { myChoice = Choice::plop; return getPlop()->fromXElement( message, xelement ); } if( xelement.getName() == "doit" ) { myChoice = Choice::doit; return getDoit()->fromXElement( message, xelement ); } if( xelement.getName() == "falloff" ) { myChoice = Choice::falloff; return getFalloff()->fromXElement( message, xelement ); } if( xelement.getName() == "breath-mark" ) { myChoice = Choice::breathMark; return getBreathMark()->fromXElement( message, xelement ); } if( xelement.getName() == "caesura" ) { myChoice = Choice::caesura; return getCaesura()->fromXElement( message, xelement ); } if( xelement.getName() == "stress" ) { myChoice = Choice::stress; return getStress()->fromXElement( message, xelement ); } if( xelement.getName() == "unstress" ) { myChoice = Choice::unstress; return getUnstress()->fromXElement( message, xelement ); } if( xelement.getName() == "other-articulation" ) { myChoice = Choice::otherArticulation; return getOtherArticulation()->fromXElement( message, xelement ); } message << "ArticulationsChoice: '" << xelement.getName() << "' is not allowed" << std::endl; return false; } } }
26.299618
127
0.465641
diskzero
c2e6174a44630e91dd32c8319bd19c32d7fff6fd
3,750
cpp
C++
src/PA02/MedianFiltering.cpp
pateldeev/cs474
4aeb7c6a5317256e9e1f517d614a83b5b52f9f52
[ "Xnet", "X11" ]
null
null
null
src/PA02/MedianFiltering.cpp
pateldeev/cs474
4aeb7c6a5317256e9e1f517d614a83b5b52f9f52
[ "Xnet", "X11" ]
null
null
null
src/PA02/MedianFiltering.cpp
pateldeev/cs474
4aeb7c6a5317256e9e1f517d614a83b5b52f9f52
[ "Xnet", "X11" ]
null
null
null
#include "PA02/HelperFunctions.h" #include "ReadWrite.h" #include <iostream> #include <ctime> #include <string> #include <algorithm> #include <sstream> // Corrupt the image with salt and pepper void saltPepperCorruption(const ImageType &, ImageType &, int); // Median filtering function void medianMask(const ImageType &, ImageType &, int); int main(int argc, char * argv[]){ if (argc != 3) { std::cout << "Incorrect number of arguments provided" << std::endl << "Please provide the image file and mask size in that order" << std::endl; return 0; } // Check to make sure argument is valid number std::istringstream ss(argv[2]); int medianFilterSize; if(!(ss >> medianFilterSize)){ std::cerr << "Invalid number\n"; return 0; } else if(!(ss.eof())){ std::cerr << "Trailing characters after number\n"; return 0; } //---------------------------------------------------------------------------- // Start reading image in int M, N, Q; // M = Columns, N = Rows, Q = Levels bool type; // P5 or P6 // Read header for image information readImageHeader(argv[1], N, M, Q, type); // Allocate memory for image ImageType image(N, M, Q); // Read in image information readImage(argv[1], image); //---------------------------------------------------------------------------- // Corrupt the image first ImageType corrupted_30(N, M, Q), corrupted_50(N, M, Q); saltPepperCorruption(image, corrupted_30, 30); std::string imageOutputName = "images/PA02/median/corrupted_30.pgm"; writeImage(imageOutputName.c_str(), corrupted_30); saltPepperCorruption(image, corrupted_50, 50); imageOutputName = "images/PA02/median/corrupted_50.pgm"; writeImage(imageOutputName.c_str(), corrupted_50); // Applying median filter to corrupted images ImageType medianFix_30(N, M, Q), medianFix_50(N, M, Q); medianMask(corrupted_30, medianFix_30, medianFilterSize); imageOutputName = "images/PA02/median/medianFix_30.pgm"; writeImage(imageOutputName.c_str(), medianFix_30); medianMask(corrupted_50, medianFix_50, medianFilterSize); imageOutputName = "images/PA02/median/medianFix_50.pgm"; writeImage(imageOutputName.c_str(), medianFix_50); return 0; } void saltPepperCorruption(const ImageType &og_image, ImageType &new_image, int percentage){ int numRows, numCols, numLevels, roll, tmpVal; og_image.getImageInfo(numRows, numCols, numLevels); srand(time(NULL)); for(int i = 0; i < numRows; ++i){ for(int j = 0; j < numCols; ++j){ roll = rand() % 100; if(roll < (percentage / 2)){ // Make it white new_image.setPixelVal(i, j, 255); } else if(roll > (percentage / 2) && roll < percentage){ // Make it black new_image.setPixelVal(i, j, 0); } else{ og_image.getPixelVal(i, j, tmpVal); new_image.setPixelVal(i, j, tmpVal); } } } } void medianMask(const ImageType &og_image, ImageType &new_image, int maskSize){ int values[maskSize * maskSize]; int imgRows, imgCols, imgLevels, valuesCounter = 0; int rowOffset, colOffset, rowLoc, colLoc, sortedMedianValue; og_image.getImageInfo(imgRows, imgCols, imgLevels); for(int i = 0; i < imgRows; ++i){ for(int j = 0; j < imgCols; ++j){ for(int k = 0; k < maskSize; ++k){ for(int l = 0; l < maskSize; ++l){ rowOffset = l - (maskSize / 2); colOffset = k - (maskSize / 2); rowLoc = i + rowOffset; colLoc = j + colOffset; if(rowLoc >= 0 && rowLoc < imgRows && colLoc >= 0 && colLoc < imgCols){ og_image.getPixelVal(rowLoc, colLoc, values[valuesCounter]); } valuesCounter++; } } std::sort(values, values + (maskSize * maskSize)); sortedMedianValue = values[(maskSize * maskSize) / 2]; new_image.setPixelVal(i, j, sortedMedianValue); valuesCounter = 0; } } }
29.296875
91
0.652
pateldeev
c2e80a0a4dd13a5aabb43f1b3dfc06f9b7c51670
5,233
cpp
C++
utils/wikistat-loader/main.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
3
2016-12-30T14:19:47.000Z
2021-11-13T06:58:32.000Z
utils/wikistat-loader/main.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
1
2017-01-13T21:29:36.000Z
2017-01-16T18:29:08.000Z
utils/wikistat-loader/main.cpp
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
1
2021-02-07T16:00:54.000Z
2021-02-07T16:00:54.000Z
#include <boost/program_options.hpp> #include <DB/IO/ReadBuffer.h> #include <DB/IO/WriteBuffer.h> #include <DB/IO/ReadHelpers.h> #include <DB/IO/WriteHelpers.h> #include <DB/IO/ReadBufferFromFileDescriptor.h> #include <DB/IO/WriteBufferFromFileDescriptor.h> /** Reads uncompressed wikistat data from stdin, * and writes transformed data in tsv format, * ready to be loaded into ClickHouse. * * Input data has format: * * aa Wikipedia 1 17224 * aa.b Main_Page 2 21163 * * project, optional subproject, path, hits, total size in bytes. */ template <bool break_at_dot> static void readString(std::string & s, DB::ReadBuffer & buf) { s.clear(); while (!buf.eof()) { const char * next_pos; if (break_at_dot) next_pos = find_first_symbols<' ', '\n', '.'>(buf.position(), buf.buffer().end()); else next_pos = find_first_symbols<' ', '\n'>(buf.position(), buf.buffer().end()); s.append(buf.position(), next_pos - buf.position()); buf.position() += next_pos - buf.position(); if (!buf.hasPendingData()) continue; if (*buf.position() == ' ' || *buf.position() == '\n' || (break_at_dot && *buf.position() == '.')) return; } } /** Reads path before whitespace and decodes %xx sequences (to more compact and handy representation), * except %2F '/', %26 '&', %3D '=', %3F '?', %23 '#' (to not break structure of URL). */ static void readPath(std::string & s, DB::ReadBuffer & buf) { s.clear(); while (!buf.eof()) { const char * next_pos = find_first_symbols<' ', '\n', '%'>(buf.position(), buf.buffer().end()); s.append(buf.position(), next_pos - buf.position()); buf.position() += next_pos - buf.position(); if (!buf.hasPendingData()) continue; if (*buf.position() == ' ' || *buf.position() == '\n') return; if (*buf.position() == '%') { ++buf.position(); char c1; char c2; if (buf.eof() || *buf.position() == ' ') break; DB::readChar(c1, buf); if (buf.eof() || *buf.position() == ' ') break; DB::readChar(c2, buf); if ((c1 == '2' && (c2 == 'f' || c2 == '6' || c2 == '3' || c2 == 'F')) || (c1 == '3' && (c2 == 'd' || c2 == 'f' || c2 == 'D' || c2 == 'F'))) { s += '%'; s += c1; s += c2; } else s += static_cast<char>(static_cast<UInt8>(DB::unhex(c1)) * 16 + static_cast<UInt8>(DB::unhex(c2))); } } } static void skipUntilNewline(DB::ReadBuffer & buf) { while (!buf.eof()) { const char * next_pos = find_first_symbols<'\n'>(buf.position(), buf.buffer().end()); buf.position() += next_pos - buf.position(); if (!buf.hasPendingData()) continue; if (*buf.position() == '\n') { ++buf.position(); return; } } } namespace DB { namespace ErrorCodes { extern const int CANNOT_PARSE_INPUT_ASSERTION_FAILED; } } int main(int argc, char ** argv) try { boost::program_options::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("time", boost::program_options::value<std::string>()->required(), "time of data in YYYY-MM-DD hh:mm:ss form") ; boost::program_options::variables_map options; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), options); if (options.count("help")) { std::cout << "Reads uncompressed wikistat data from stdin and writes transformed data in tsv format." << std::endl; std::cout << "Usage: " << argv[0] << " --time='YYYY-MM-DD hh:00:00' < in > out" << std::endl; std::cout << desc << std::endl; return 1; } std::string time_str = options.at("time").as<std::string>(); LocalDateTime time(time_str); LocalDate date(time); DB::ReadBufferFromFileDescriptor in(STDIN_FILENO); DB::WriteBufferFromFileDescriptor out(STDOUT_FILENO); std::string project; std::string subproject; std::string path; UInt64 hits = 0; UInt64 size = 0; size_t row_num = 0; while (!in.eof()) { try { ++row_num; readString<true>(project, in); if (in.eof()) break; if (*in.position() == '.') readString<false>(subproject, in); else subproject.clear(); DB::assertChar(' ', in); readPath(path, in); DB::assertChar(' ', in); DB::readIntText(hits, in); DB::assertChar(' ', in); DB::readIntText(size, in); DB::assertChar('\n', in); } catch (const DB::Exception & e) { /// Sometimes, input data has errors. For example, look at first lines in pagecounts-20130210-130000.gz /// To save rest of data, just skip lines with errors. if (e.code() == DB::ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED) { std::cerr << "At row " << row_num << ": " << DB::getCurrentExceptionMessage(false) << '\n'; skipUntilNewline(in); continue; } else throw; } DB::writeText(date, out); DB::writeChar('\t', out); DB::writeText(time, out); DB::writeChar('\t', out); DB::writeText(project, out); DB::writeChar('\t', out); DB::writeText(subproject, out); DB::writeChar('\t', out); DB::writeText(path, out); DB::writeChar('\t', out); DB::writeText(hits, out); DB::writeChar('\t', out); DB::writeText(size, out); DB::writeChar('\n', out); } return 0; } catch (...) { std::cerr << DB::getCurrentExceptionMessage(true) << '\n'; throw; }
23.257778
117
0.611504
rudneff
c2ea6e86714e98c2dd15582c5eaf0de13f51164c
782
cpp
C++
libraries/physics/src/ContactInfo.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
7
2015-08-24T17:01:00.000Z
2021-03-30T09:30:40.000Z
libraries/physics/src/ContactInfo.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
1
2016-01-17T17:49:05.000Z
2016-01-17T17:49:05.000Z
libraries/physics/src/ContactInfo.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
1
2021-12-07T23:16:45.000Z
2021-12-07T23:16:45.000Z
// // ContactEvent.cpp // libraries/physcis/src // // Created by Andrew Meadows 2015.01.20 // Copyright 2015 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ContactInfo.h" void ContactInfo::update(uint32_t currentStep, const btManifoldPoint& p) { _lastStep = currentStep; ++_numSteps; positionWorldOnB = p.m_positionWorldOnB; normalWorldOnB = p.m_normalWorldOnB; distance = p.m_distance1; } ContactEventType ContactInfo::computeType(uint32_t thisStep) { if (_lastStep != thisStep) { return CONTACT_EVENT_TYPE_END; } return (_numSteps == 1) ? CONTACT_EVENT_TYPE_START : CONTACT_EVENT_TYPE_CONTINUE; }
27.928571
88
0.721228
stojce
c2eacebb56e52cde22eef90af868baf2404fa613
66
cpp
C++
src/array/destructor.cpp
violador/catalyst
40d5c1dd04269a0764a9804711354a474bc43c15
[ "Unlicense" ]
null
null
null
src/array/destructor.cpp
violador/catalyst
40d5c1dd04269a0764a9804711354a474bc43c15
[ "Unlicense" ]
null
null
null
src/array/destructor.cpp
violador/catalyst
40d5c1dd04269a0764a9804711354a474bc43c15
[ "Unlicense" ]
null
null
null
// // // inline ~array() { #pragma omp master delete[] data; };
7.333333
19
0.545455
violador
c2eda66913ce0805dfc4de582df933966e0a15e4
5,524
cpp
C++
Source/Core/Pipeline.cpp
milkru/foton
cf16abf02db80677ae22ff527aff5ef1c3702140
[ "MIT" ]
null
null
null
Source/Core/Pipeline.cpp
milkru/foton
cf16abf02db80677ae22ff527aff5ef1c3702140
[ "MIT" ]
null
null
null
Source/Core/Pipeline.cpp
milkru/foton
cf16abf02db80677ae22ff527aff5ef1c3702140
[ "MIT" ]
null
null
null
#include "Pipeline.h" #include "Device.h" #include "Swapchain.h" #include "DescriptorSet.h" #include "Shader.h" FT_BEGIN_NAMESPACE static void CreatePipelineLayout(const VkDevice inDevice, const VkDescriptorSetLayout inDescriptorSetLayout, VkPipelineLayout& outPipelineLayout) { VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{}; pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = &inDescriptorSetLayout; FT_VK_CALL(vkCreatePipelineLayout(inDevice, &pipelineLayoutCreateInfo, nullptr, &outPipelineLayout)); } static void CreateGraphicsPipeline(const VkDevice inDevice, const Swapchain* inSwapchain, const Shader* inVertexShader, const Shader* inFragmentShader, const VkPipelineLayout inPipelineLayout, VkPipeline& outPraphicsPipeline) { VkPipelineShaderStageCreateInfo shaderStageCreateInfos[] = { inVertexShader->GetVkPipelineStageInfo(), inFragmentShader->GetVkPipelineStageInfo() }; VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo{}; vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo{}; inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(inSwapchain->GetExtent().width); viewport.height = static_cast<float>(inSwapchain->GetExtent().height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = inSwapchain->GetExtent(); VkPipelineViewportStateCreateInfo viewportStateCreateInfo{}; viewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportStateCreateInfo.viewportCount = 1; viewportStateCreateInfo.pViewports = &viewport; viewportStateCreateInfo.scissorCount = 1; viewportStateCreateInfo.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizationStateCreateInfo{}; rasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizationStateCreateInfo.depthClampEnable = VK_FALSE; rasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE; rasterizationStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL; rasterizationStateCreateInfo.lineWidth = 1.0f; rasterizationStateCreateInfo.cullMode = VK_CULL_MODE_FRONT_BIT; rasterizationStateCreateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationStateCreateInfo.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampleStateCreateInfo{}; multisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampleStateCreateInfo.sampleShadingEnable = VK_FALSE; multisampleStateCreateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlendStateCreateInfo{}; colorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlendStateCreateInfo.logicOpEnable = VK_FALSE; colorBlendStateCreateInfo.logicOp = VK_LOGIC_OP_COPY; colorBlendStateCreateInfo.attachmentCount = 1; colorBlendStateCreateInfo.pAttachments = &colorBlendAttachment; colorBlendStateCreateInfo.blendConstants[0] = 0.0f; colorBlendStateCreateInfo.blendConstants[1] = 0.0f; colorBlendStateCreateInfo.blendConstants[2] = 0.0f; colorBlendStateCreateInfo.blendConstants[3] = 0.0f; VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = 2; pipelineCreateInfo.pStages = shaderStageCreateInfos; pipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo; pipelineCreateInfo.pViewportState = &viewportStateCreateInfo; pipelineCreateInfo.pRasterizationState = &rasterizationStateCreateInfo; pipelineCreateInfo.pMultisampleState = &multisampleStateCreateInfo; pipelineCreateInfo.pColorBlendState = &colorBlendStateCreateInfo; pipelineCreateInfo.layout = inPipelineLayout; pipelineCreateInfo.renderPass = inSwapchain->GetRenderPass(); pipelineCreateInfo.subpass = 0; pipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE; FT_VK_CALL(vkCreateGraphicsPipelines(inDevice, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &outPraphicsPipeline)); } Pipeline::Pipeline(const Device* inDevice, const Swapchain* inSwapchain, const DescriptorSet* inDescriptorSet, const Shader* inVertexShader, const Shader* inFragmentShader) : m_Device(inDevice) { CreatePipelineLayout(m_Device->GetDevice(), inDescriptorSet->GetDescriptorSetLayout(), m_PipelineLayout); CreateGraphicsPipeline(m_Device->GetDevice(), inSwapchain, inVertexShader, inFragmentShader, m_PipelineLayout, m_GraphicsPipeline); } Pipeline::~Pipeline() { vkDestroyPipeline(m_Device->GetDevice(), m_GraphicsPipeline, nullptr); vkDestroyPipelineLayout(m_Device->GetDevice(), m_PipelineLayout, nullptr); } FT_END_NAMESPACE
49.321429
225
0.857169
milkru