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
92b1c6a7b55446d4f208d00f303bc7b15d0b4182
296
cpp
C++
Testing/C++/_TDDExtras.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
61
2015-04-21T20:40:37.000Z
2022-03-25T03:35:03.000Z
Testing/C++/_TDDExtras.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
17
2015-06-23T20:51:57.000Z
2020-08-17T17:08:57.000Z
Testing/C++/_TDDExtras.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
56
2015-05-11T11:04:35.000Z
2022-01-15T20:37:04.000Z
#include "_TDDConfigure.h" #include "EigenFilterTest.h" #include "EigenFiltFiltTest.h" #include "EigenIIRFilterDesignTest.h" #include "GammalnTest.h" #include "CombTest.h" #include "CumtrapzTest.h" #include "Interp1Test.h" #include "MedianTest.h" #include "StdTest.h" #include "PercentileTest.h"
24.666667
37
0.777027
mitkof6
92b24e1febd4e548b6c726b55d2d7e972f5f219b
8,994
cpp
C++
libpvguiqt/src/PVLayerStackModel.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvguiqt/src/PVLayerStackModel.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvguiqt/src/PVLayerStackModel.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
// // MIT License // // © ESI Group, 2015 // // 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 <inendi/PVLayerStack.h> #include <inendi/PVView.h> #include <pvguiqt/PVCustomQtRoles.h> #include <pvguiqt/PVLayerStackModel.h> /****************************************************************************** * * PVGuiQt::PVLayerStackModel::PVLayerStackModel * *****************************************************************************/ PVGuiQt::PVLayerStackModel::PVLayerStackModel(Inendi::PVView& lib_view, QObject* parent) : QAbstractTableModel(parent) , _lib_view(lib_view) , select_brush(QColor(255, 240, 200)) , unselect_brush(QColor(180, 180, 180)) { PVLOG_DEBUG("PVGuiQt::PVLayerStackModel::%s : Creating object\n", __FUNCTION__); select_font.setBold(true); lib_view._layer_stack_about_to_refresh.connect( sigc::mem_fun(this, &PVGuiQt::PVLayerStackModel::layer_stack_about_to_be_refreshed)); lib_view._layer_stack_refreshed.connect( sigc::mem_fun(this, &PVGuiQt::PVLayerStackModel::layer_stack_refreshed)); } /****************************************************************************** * * PVGuiQt::PVLayerStackModel::columnCount * *****************************************************************************/ int PVGuiQt::PVLayerStackModel::columnCount(const QModelIndex& /*index*/) const { return 3; } /****************************************************************************** * * PVGuiQt::PVLayerStackModel::data * *****************************************************************************/ QVariant PVGuiQt::PVLayerStackModel::data(const QModelIndex& index, int role) const { // AG: the two following lines are kept for the sake of history... /* We prepare a direct acces to the total number of layers */ // int layer_count = lib_layer_stack().get_layer_count(); // AG: this comment is also kept for history :) /* We create and store the true index of the layer in the lib */ int lib_index = lib_index_from_model_index(index.row()); switch (role) { case Qt::DecorationRole: switch (index.column()) { case 0: if (lib_layer_stack().get_layer_n(lib_index).get_visible()) { return QPixmap(":/layer-active.png"); } else { return QPixmap(":/layer-inactive.png"); } break; } break; case (Qt::BackgroundRole): if (lib_layer_stack().get_selected_layer_index() == lib_index) { return QBrush(QColor(205, 139, 204)); } break; case (Qt::DisplayRole): switch (index.column()) { case 1: return lib_layer_stack().get_layer_n(lib_index).get_name(); case 2: return QString("%L3").arg( lib_layer_stack().get_layer_n(lib_index).get_selectable_count()); } break; case (Qt::EditRole): switch (index.column()) { case 1: return lib_layer_stack().get_layer_n(lib_index).get_name(); } break; case (Qt::TextAlignmentRole): switch (index.column()) { case 0: return (Qt::AlignCenter + Qt::AlignVCenter); case 2: return (Qt::AlignRight + Qt::AlignVCenter); default: return (Qt::AlignLeft + Qt::AlignVCenter); } break; case (Qt::ToolTipRole): switch (index.column()) { case 1: return lib_layer_stack().get_layer_n(lib_index).get_name(); break; } break; case (PVCustomQtRoles::UnderlyingObject): { QVariant ret; ret.setValue<void*>((void*)&lib_layer_stack().get_layer_n(lib_index)); return ret; } } return QVariant(); } /****************************************************************************** * * PVGuiQt::PVLayerStackModel::flags * *****************************************************************************/ Qt::ItemFlags PVGuiQt::PVLayerStackModel::flags(const QModelIndex& index) const { switch (index.column()) { case 0: // return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; return Qt::ItemIsEditable | Qt::ItemIsEnabled; default: return (Qt::ItemIsEditable | Qt::ItemIsEnabled); } } /****************************************************************************** * * PVGuiQt::PVLayerStackModel::headerData * *****************************************************************************/ QVariant PVGuiQt::PVLayerStackModel::headerData(int /*section*/, Qt::Orientation /*orientation*/, int role) const { // FIXME : this should not be used : delegate... switch (role) { case (Qt::SizeHintRole): return QSize(37, 37); break; } return QVariant(); } /****************************************************************************** * * PVGuiQt::PVLayerStackModel::rowCount * *****************************************************************************/ int PVGuiQt::PVLayerStackModel::rowCount(const QModelIndex& /*index*/) const { return lib_layer_stack().get_layer_count(); } /****************************************************************************** * * PVGuiQt::PVLayerStackModel::setData * *****************************************************************************/ bool PVGuiQt::PVLayerStackModel::setData(const QModelIndex& index, const QVariant& value, int role) { int layer_count = lib_layer_stack().get_layer_count(); /* We create and store the true index of the layer in the lib */ int lib_index = layer_count - 1 - index.row(); switch (role) { case (Qt::EditRole): switch (index.column()) { case 0: lib_view().toggle_layer_stack_layer_n_visible_state(lib_index); lib_view().process_layer_stack(); return true; case 1: lib_view().set_layer_stack_layer_n_name(lib_index, value.toString()); return true; default: return QAbstractTableModel::setData(index, value, role); } default: return QAbstractTableModel::setData(index, value, role); } return false; } void PVGuiQt::PVLayerStackModel::layer_stack_about_to_be_refreshed() { beginResetModel(); } void PVGuiQt::PVLayerStackModel::reset_layer_colors(const int idx) { Inendi::PVLayerStack& layerstack = lib_layer_stack(); Inendi::PVLayer& layer = layerstack.get_layer_n(lib_index_from_model_index(idx)); layer.reset_to_default_color(); lib_view().process_layer_stack(); } void PVGuiQt::PVLayerStackModel::show_this_layer_only(const int idx) { Inendi::PVLayerStack& layerstack = lib_layer_stack(); int layer_idx = lib_index_from_model_index(idx); Inendi::PVLayer& layer = layerstack.get_layer_n(layer_idx); layer.set_visible(true); // in case, it isn't visible for (int i = 0; i < layerstack.get_layer_count(); i++) { if (i != layer_idx) { Inendi::PVLayer& layer = layerstack.get_layer_n(i); layer.set_visible(false); } } lib_view().process_layer_stack(); } void PVGuiQt::PVLayerStackModel::layer_stack_refreshed() { endResetModel(); } void PVGuiQt::PVLayerStackModel::add_new_layer(QString name) { _lib_view.add_new_layer(name); Inendi::PVLayer& layer = lib_layer_stack().get_layer_n(rowCount() - 1); layer.reset_to_full_and_default_color(); lib_view().process_layer_stack(); } void PVGuiQt::PVLayerStackModel::move_selected_layer_up() { beginResetModel(); lib_view().move_selected_layer_up(); lib_view().process_layer_stack(); endResetModel(); } void PVGuiQt::PVLayerStackModel::move_selected_layer_down() { beginResetModel(); lib_view().move_selected_layer_down(); lib_view().process_layer_stack(); endResetModel(); } void PVGuiQt::PVLayerStackModel::delete_selected_layer() { if (lib_layer_stack().get_selected_layer().is_locked()) { return; } _lib_view.delete_selected_layer(); lib_view().process_layer_stack(); } void PVGuiQt::PVLayerStackModel::duplicate_selected_layer(const QString& name) { beginResetModel(); lib_view().duplicate_selected_layer(name); lib_view().process_layer_stack(); endResetModel(); } void PVGuiQt::PVLayerStackModel::delete_layer_n(const int idx) { assert(idx < rowCount()); if (lib_layer_stack().get_layer_n(idx).is_locked()) { return; } _lib_view.delete_layer_n(idx); lib_view().process_layer_stack(); }
28.919614
99
0.632199
inendi-inspector
92b39e8022390f7662723c15701eda42b756749c
552
hpp
C++
mspp/mspp/Utils/IterableUtils.hpp
shailist/ms-
4f40dd670bdd442c26abcc1642f748775381bb3c
[ "Unlicense" ]
null
null
null
mspp/mspp/Utils/IterableUtils.hpp
shailist/ms-
4f40dd670bdd442c26abcc1642f748775381bb3c
[ "Unlicense" ]
null
null
null
mspp/mspp/Utils/IterableUtils.hpp
shailist/ms-
4f40dd670bdd442c26abcc1642f748775381bb3c
[ "Unlicense" ]
null
null
null
#pragma once namespace IterableUtils { template <typename TIterable> inline constexpr bool starts_with(const TIterable& iterable, const TIterable& sub_iterable) { auto iterable_iter = iterable.cbegin(); auto sub_iterable_iter = sub_iterable.cbegin(); for (;; ++iterable_iter, ++sub_iterable_iter) { if ((iterable.cend() == iterable_iter) || (sub_iterable.cend() == sub_iterable_iter)) { break; } if(*iterable_iter != *sub_iterable_iter) { return false; } } return sub_iterable.cend() == sub_iterable_iter; } }
24
92
0.697464
shailist
92b791d0a438f2e5837ccd1f36103314f392b407
109
cpp
C++
examples/libsimdpp/main.cpp
PhoebeWangintw/hunter
67fadbe7388254c8626b2130c0afb0a5f1817e47
[ "BSD-2-Clause" ]
2
2019-05-28T06:24:08.000Z
2021-08-10T17:10:35.000Z
examples/libsimdpp/main.cpp
PhoebeWangintw/hunter
67fadbe7388254c8626b2130c0afb0a5f1817e47
[ "BSD-2-Clause" ]
null
null
null
examples/libsimdpp/main.cpp
PhoebeWangintw/hunter
67fadbe7388254c8626b2130c0afb0a5f1817e47
[ "BSD-2-Clause" ]
1
2020-03-02T16:07:55.000Z
2020-03-02T16:07:55.000Z
#include <simdpp/simd.h> int main() { simdpp::uint8<32> a; simdpp::uint8<32> b; auto c = a + b; }
18.166667
24
0.550459
PhoebeWangintw
92b91c3a630d2dae339e0020e080401f953971b4
129
hpp
C++
Blob_Lib/Include/glm/gtc/matrix_access.hpp
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/Include/glm/gtc/matrix_access.hpp
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/Include/glm/gtc/matrix_access.hpp
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:1c7028cb87b23548dc8559943cc413e2ba2fededcfaca6d619d999ced1f117bf size 1468
32.25
75
0.883721
antholuo
92b96f0e0dd0547baa0f1c902788a8c9bd5e3b3e
22,855
cpp
C++
third-party/casadi/external_packages/qpOASES/src/OQPinterface.cpp
dbdxnuliba/mit-biomimetics_Cheetah
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
8
2020-02-18T09:07:48.000Z
2021-12-25T05:40:02.000Z
third-party/casadi/external_packages/qpOASES/src/OQPinterface.cpp
geekfeiw/Cheetah-Software
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
null
null
null
third-party/casadi/external_packages/qpOASES/src/OQPinterface.cpp
geekfeiw/Cheetah-Software
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
13
2019-08-25T12:32:06.000Z
2022-03-31T02:38:12.000Z
/* * This file is part of qpOASES. * * qpOASES -- An Implementation of the Online Active Set Strategy. * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, * Christian Kirches et al. All rights reserved. * * qpOASES 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. * * qpOASES 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 qpOASES; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ /** * \file src/OQPinterface.cpp * \author Hans Joachim Ferreau * \version 3.2 * \date 2008-2015 * * Implementation of an interface comprising several utility functions * for solving test problems from the Online QP Benchmark Collection * (This collection is no longer maintained, see * http://www.qpOASES.org/onlineQP for a backup). * */ #include <qpOASES/extras/OQPinterface.hpp> #include <qpOASES/QProblem.hpp> BEGIN_NAMESPACE_QPOASES /* * r e a d O q p D i m e n s i o n s */ returnValue readOqpDimensions( const char* path, int_t& nQP, int_t& nV, int_t& nC, int_t& nEC ) { /* 1) Setup file name where dimensions are stored. */ char filename[MAX_STRING_LENGTH]; snprintf( filename,MAX_STRING_LENGTH,"%sdims.oqp",path ); /* 2) Load dimensions from file. */ int_t dims[4]; if ( readFromFile( dims,4,filename ) != SUCCESSFUL_RETURN ) return THROWERROR( RET_UNABLE_TO_READ_FILE ); nQP = dims[0]; nV = dims[1]; nC = dims[2]; nEC = dims[3]; /* consistency check */ if ( ( nQP <= 0 ) || ( nV <= 0 ) || ( nC < 0 ) || ( nEC < 0 ) ) return THROWERROR( RET_FILEDATA_INCONSISTENT ); return SUCCESSFUL_RETURN; } /* * r e a d O q p D a t a */ returnValue readOqpData( const char* path, int_t& nQP, int_t& nV, int_t& nC, int_t& nEC, real_t** H, real_t** g, real_t** A, real_t** lb, real_t** ub, real_t** lbA, real_t** ubA, real_t** xOpt, real_t** yOpt, real_t** objOpt ) { char filename[MAX_STRING_LENGTH]; /* consistency check */ if ( ( H == 0 ) || ( g == 0 ) || ( lb == 0 ) || ( ub == 0 ) ) return THROWERROR( RET_INVALID_ARGUMENTS ); /* 1) Obtain OQP dimensions. */ if ( readOqpDimensions( path, nQP,nV,nC,nEC ) != SUCCESSFUL_RETURN ) return THROWERROR( RET_UNABLE_TO_READ_FILE ); /* another consistency check */ if ( ( nC > 0 ) && ( ( A == 0 ) || ( lbA == 0 ) || ( ubA == 0 ) ) ) return THROWERROR( RET_FILEDATA_INCONSISTENT ); /* 2) Allocate memory and load OQP data: */ /* Hessian matrix */ *H = new real_t[nV*nV]; snprintf( filename,MAX_STRING_LENGTH,"%sH.oqp",path ); if ( readFromFile( *H,nV,nV,filename ) != SUCCESSFUL_RETURN ) { delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } /* gradient vector sequence */ *g = new real_t[nQP*nV]; snprintf( filename,MAX_STRING_LENGTH,"%sg.oqp",path ); if ( readFromFile( *g,nQP,nV,filename ) != SUCCESSFUL_RETURN ) { delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } /* lower bound vector sequence */ *lb = new real_t[nQP*nV]; snprintf( filename,MAX_STRING_LENGTH,"%slb.oqp",path ); if ( readFromFile( *lb,nQP,nV,filename ) != SUCCESSFUL_RETURN ) { delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } /* upper bound vector sequence */ *ub = new real_t[nQP*nV]; snprintf( filename,MAX_STRING_LENGTH,"%sub.oqp",path ); if ( readFromFile( *ub,nQP,nV,filename ) != SUCCESSFUL_RETURN ) { delete[] *ub; delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } if ( nC > 0 ) { /* Constraint matrix */ *A = new real_t[nC*nV]; snprintf( filename,MAX_STRING_LENGTH,"%sA.oqp",path ); if ( readFromFile( *A,nC,nV,filename ) != SUCCESSFUL_RETURN ) { delete[] *A; delete[] *ub; delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } /* lower constraints' bound vector sequence */ *lbA = new real_t[nQP*nC]; snprintf( filename,MAX_STRING_LENGTH,"%slbA.oqp",path ); if ( readFromFile( *lbA,nQP,nC,filename ) != SUCCESSFUL_RETURN ) { delete[] *lbA; delete[] *A; delete[] *ub; delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } /* upper constraints' bound vector sequence */ *ubA = new real_t[nQP*nC]; snprintf( filename,MAX_STRING_LENGTH,"%subA.oqp",path ); if ( readFromFile( *ubA,nQP,nC,filename ) != SUCCESSFUL_RETURN ) { delete[] *ubA; delete[] *lbA; delete[] *A; delete[] *ub; delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } } else { *A = 0; *lbA = 0; *ubA = 0; } if ( xOpt != 0 ) { /* primal solution vector sequence */ *xOpt = new real_t[nQP*nV]; snprintf( filename,MAX_STRING_LENGTH,"%sx_opt.oqp",path ); if ( readFromFile( *xOpt,nQP,nV,filename ) != SUCCESSFUL_RETURN ) { delete[] xOpt; if ( nC > 0 ) { delete[] *ubA; delete[] *lbA; delete[] *A; }; delete[] *ub; delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } } if ( yOpt != 0 ) { /* dual solution vector sequence */ *yOpt = new real_t[nQP*(nV+nC)]; snprintf( filename,MAX_STRING_LENGTH,"%sy_opt.oqp",path ); if ( readFromFile( *yOpt,nQP,nV+nC,filename ) != SUCCESSFUL_RETURN ) { delete[] yOpt; if ( xOpt != 0 ) { delete[] xOpt; }; if ( nC > 0 ) { delete[] *ubA; delete[] *lbA; delete[] *A; }; delete[] *ub; delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } } if ( objOpt != 0 ) { /* dual solution vector sequence */ *objOpt = new real_t[nQP]; snprintf( filename,MAX_STRING_LENGTH,"%sobj_opt.oqp",path ); if ( readFromFile( *objOpt,nQP,1,filename ) != SUCCESSFUL_RETURN ) { delete[] objOpt; if ( yOpt != 0 ) { delete[] yOpt; }; if ( xOpt != 0 ) { delete[] xOpt; }; if ( nC > 0 ) { delete[] *ubA; delete[] *lbA; delete[] *A; }; delete[] *ub; delete[] *lb; delete[] *g; delete[] *H; return THROWERROR( RET_UNABLE_TO_READ_FILE ); } } return SUCCESSFUL_RETURN; } /* * s o l v e O q p B e n c h m a r k */ returnValue solveOqpBenchmark( int_t nQP, int_t nV, int_t nC, int_t nEC, const real_t* const _H, const real_t* const g, const real_t* const _A, const real_t* const lb, const real_t* const ub, const real_t* const lbA, const real_t* const ubA, BooleanType isSparse, const Options& options, int_t& nWSR, real_t& maxCPUtime, real_t& maxStationarity, real_t& maxFeasibility, real_t& maxComplementarity ) { real_t maxNWSR = 0.0; real_t avgNWSR = 0.0; real_t avgCPUtime = 0.0; returnValue returnvalue = solveOqpBenchmark( nQP,nV,nC,nEC, _H,g,_A,lb,ub,lbA,ubA, isSparse,BT_TRUE, options,nWSR, maxNWSR,avgNWSR,maxCPUtime,avgCPUtime, maxStationarity,maxFeasibility,maxComplementarity ); nWSR = (int_t)maxNWSR; return returnvalue; } /* * s o l v e O q p B e n c h m a r k */ returnValue solveOqpBenchmark( int_t nQP, int_t nV, int_t nC, int_t nEC, const real_t* const _H, const real_t* const g, const real_t* const _A, const real_t* const lb, const real_t* const ub, const real_t* const lbA, const real_t* const ubA, BooleanType isSparse, BooleanType useHotstarts, const Options& options, int_t maxAllowedNWSR, real_t& maxNWSR, real_t& avgNWSR, real_t& maxCPUtime, real_t& avgCPUtime, real_t& maxStationarity, real_t& maxFeasibility, real_t& maxComplementarity ) { int_t k; /* I) SETUP AUXILIARY VARIABLES: */ /* 1) Keep nWSR and store current and maximum number of * working set recalculations in temporary variables */ int_t nWSRcur; real_t CPUtimeLimit = maxCPUtime; real_t CPUtimeCur = CPUtimeLimit; maxNWSR = 0.0; avgNWSR = 0.0; maxCPUtime = 0.0; avgCPUtime = 0.0; maxStationarity = 0.0; maxFeasibility = 0.0; maxComplementarity = 0.0; real_t stat, feas, cmpl; /* 2) Pointers to data of current QP ... */ const real_t* gCur; const real_t* lbCur; const real_t* ubCur; const real_t* lbACur; const real_t* ubACur; /* 3) Vectors for solution obtained by qpOASES. */ real_t* x = new real_t[nV]; real_t* y = new real_t[nV+nC]; //real_t obj; /* 4) Prepare matrix objects */ SymmetricMatrix *H; Matrix *A; real_t* H_cpy = new real_t[nV*nV]; memcpy( H_cpy,_H, ((uint_t)(nV*nV))*sizeof(real_t) ); real_t* A_cpy = new real_t[nC*nV]; memcpy( A_cpy,_A, ((uint_t)(nC*nV))*sizeof(real_t) ); if ( isSparse == BT_TRUE ) { SymSparseMat *Hs; H = Hs = new SymSparseMat(nV, nV, nV, H_cpy); A = new SparseMatrixRow(nC, nV, nV, A_cpy); Hs->createDiagInfo(); delete[] A_cpy; delete[] H_cpy; } else { H = new SymDenseMat(nV, nV, nV, const_cast<real_t *>(H_cpy)); A = new DenseMatrix(nC, nV, nV, const_cast<real_t *>(A_cpy)); } H->doFreeMemory( ); A->doFreeMemory( ); /* II) SETUP QPROBLEM OBJECT */ QProblem qp( nV,nC ); qp.setOptions( options ); //qp.setPrintLevel( PL_LOW ); //qp.printOptions(); /* III) RUN BENCHMARK SEQUENCE: */ returnValue returnvalue; for( k=0; k<nQP; ++k ) { //if ( k%50 == 0 ) // printf( "%d\n",k ); /* 1) Update pointers to current QP data. */ gCur = &( g[k*nV] ); lbCur = &( lb[k*nV] ); ubCur = &( ub[k*nV] ); lbACur = &( lbA[k*nC] ); ubACur = &( ubA[k*nC] ); /* 2) Set nWSR and maximum CPU time. */ nWSRcur = maxAllowedNWSR; CPUtimeCur = CPUtimeLimit; /* 3) Solve current QP. */ if ( ( k == 0 ) || ( useHotstarts == BT_FALSE ) ) { /* initialise */ returnvalue = qp.init( H,gCur,A,lbCur,ubCur,lbACur,ubACur, nWSRcur,&CPUtimeCur ); if ( ( returnvalue != SUCCESSFUL_RETURN ) && ( returnvalue != RET_MAX_NWSR_REACHED ) ) { delete A; delete H; delete[] y; delete[] x; return THROWERROR( returnvalue ); } } else { /* hotstart */ returnvalue = qp.hotstart( gCur,lbCur,ubCur,lbACur,ubACur, nWSRcur,&CPUtimeCur ); if ( ( returnvalue != SUCCESSFUL_RETURN ) && ( returnvalue != RET_MAX_NWSR_REACHED ) ) { delete A; delete H; delete[] y; delete[] x; return THROWERROR( returnvalue ); } } /* 4) Obtain solution vectors and objective function value */ qp.getPrimalSolution( x ); qp.getDualSolution( y ); //obj = qp.getObjVal( ); /* 5) Compute KKT residuals */ getKktViolation( nV,nC, _H,gCur,_A,lbCur,ubCur,lbACur,ubACur, x,y, stat,feas,cmpl ); /* 6) Update maximum and average values. */ if ( ((double)nWSRcur) > maxNWSR ) maxNWSR = ((double)nWSRcur); if (stat > maxStationarity) maxStationarity = stat; if (feas > maxFeasibility) maxFeasibility = feas; if (cmpl > maxComplementarity) maxComplementarity = cmpl; if ( CPUtimeCur > maxCPUtime ) maxCPUtime = CPUtimeCur; avgNWSR += ((double)nWSRcur); avgCPUtime += CPUtimeCur; } avgNWSR /= ((double)nQP); avgCPUtime /= ((double)nQP); delete A; delete H; delete[] y; delete[] x; return SUCCESSFUL_RETURN; } /* * s o l v e O q p B e n c h m a r k */ returnValue solveOqpBenchmark( int_t nQP, int_t nV, const real_t* const _H, const real_t* const g, const real_t* const lb, const real_t* const ub, BooleanType isSparse, const Options& options, int_t& nWSR, real_t& maxCPUtime, real_t& maxStationarity, real_t& maxFeasibility, real_t& maxComplementarity ) { real_t maxNWSR = 0.0; real_t avgNWSR = 0.0; real_t avgCPUtime = 0.0; returnValue returnvalue = solveOqpBenchmark( nQP,nV, _H,g,lb,ub, isSparse,BT_TRUE, options,nWSR, maxNWSR,avgNWSR,maxCPUtime,avgCPUtime, maxStationarity,maxFeasibility,maxComplementarity ); nWSR = (int_t)maxNWSR; return returnvalue; } /* * s o l v e O q p B e n c h m a r k */ returnValue solveOqpBenchmark( int_t nQP, int_t nV, const real_t* const _H, const real_t* const g, const real_t* const lb, const real_t* const ub, BooleanType isSparse, BooleanType useHotstarts, const Options& options, int_t maxAllowedNWSR, real_t& maxNWSR, real_t& avgNWSR, real_t& maxCPUtime, real_t& avgCPUtime, real_t& maxStationarity, real_t& maxFeasibility, real_t& maxComplementarity ) { int_t k; /* I) SETUP AUXILIARY VARIABLES: */ /* 1) Keep nWSR and store current and maximum number of * working set recalculations in temporary variables */ int_t nWSRcur; real_t CPUtimeLimit = maxCPUtime; real_t CPUtimeCur = CPUtimeLimit; real_t stat, feas, cmpl; maxNWSR = 0; avgNWSR = 0; maxCPUtime = 0.0; avgCPUtime = 0.0; maxStationarity = 0.0; maxFeasibility = 0.0; maxComplementarity = 0.0; /* 2) Pointers to data of current QP ... */ const real_t* gCur; const real_t* lbCur; const real_t* ubCur; /* 3) Vectors for solution obtained by qpOASES. */ real_t* x = new real_t[nV]; real_t* y = new real_t[nV]; //real_t obj; /* 4) Prepare matrix objects */ SymmetricMatrix *H; real_t* H_cpy = new real_t[nV*nV]; memcpy( H_cpy,_H, ((uint_t)(nV*nV))*sizeof(real_t) ); if ( isSparse == BT_TRUE ) { SymSparseMat *Hs; H = Hs = new SymSparseMat(nV, nV, nV, H_cpy); Hs->createDiagInfo(); delete[] H_cpy; } else { H = new SymDenseMat(nV, nV, nV, const_cast<real_t *>(H_cpy)); } H->doFreeMemory( ); /* II) SETUP QPROBLEM OBJECT */ QProblemB qp( nV ); qp.setOptions( options ); //qp.setPrintLevel( PL_LOW ); /* III) RUN BENCHMARK SEQUENCE: */ returnValue returnvalue; for( k=0; k<nQP; ++k ) { //if ( k%50 == 0 ) // printf( "%d\n",k ); /* 1) Update pointers to current QP data. */ gCur = &( g[k*nV] ); lbCur = &( lb[k*nV] ); ubCur = &( ub[k*nV] ); /* 2) Set nWSR and maximum CPU time. */ nWSRcur = maxAllowedNWSR; CPUtimeCur = CPUtimeLimit; /* 3) Solve current QP. */ if ( ( k == 0 ) || ( useHotstarts == BT_FALSE ) ) { /* initialise */ returnvalue = qp.init( H,gCur,lbCur,ubCur, nWSRcur,&CPUtimeCur ); if ( ( returnvalue != SUCCESSFUL_RETURN ) && ( returnvalue != RET_MAX_NWSR_REACHED ) ) { delete H; delete[] y; delete[] x; return THROWERROR( returnvalue ); } } else { /* hotstart */ returnvalue = qp.hotstart( gCur,lbCur,ubCur, nWSRcur,&CPUtimeCur ); if ( ( returnvalue != SUCCESSFUL_RETURN ) && ( returnvalue != RET_MAX_NWSR_REACHED ) ) { delete H; delete[] y; delete[] x; return THROWERROR( returnvalue ); } } /* 4) Obtain solution vectors and objective function value ... */ qp.getPrimalSolution( x ); qp.getDualSolution( y ); //obj = qp.getObjVal( ); /* 5) Compute KKT residuals */ getKktViolation( nV, _H,gCur,lbCur,ubCur, x,y, stat,feas,cmpl ); /* 6) update maximum values. */ if ( nWSRcur > maxNWSR ) maxNWSR = nWSRcur; if (stat > maxStationarity) maxStationarity = stat; if (feas > maxFeasibility) maxFeasibility = feas; if (cmpl > maxComplementarity) maxComplementarity = cmpl; if ( CPUtimeCur > maxCPUtime ) maxCPUtime = CPUtimeCur; avgNWSR += nWSRcur; avgCPUtime += CPUtimeCur; } avgNWSR /= nQP; avgCPUtime /= ((double)nQP); delete H; delete[] y; delete[] x; return SUCCESSFUL_RETURN; } /* * r u n O q p B e n c h m a r k */ returnValue runOqpBenchmark( const char* path, BooleanType isSparse, const Options& options, int_t& nWSR, real_t& maxCPUtime, real_t& maxStationarity, real_t& maxFeasibility, real_t& maxComplementarity ) { real_t maxNWSR = 0.0; real_t avgNWSR = 0.0; real_t avgCPUtime = 0.0; returnValue returnvalue = runOqpBenchmark( path,isSparse,BT_TRUE, options,nWSR, maxNWSR,avgNWSR,maxCPUtime,avgCPUtime, maxStationarity,maxFeasibility,maxComplementarity ); nWSR = (int_t)maxNWSR; return returnvalue; } /* * r u n O q p B e n c h m a r k */ returnValue runOqpBenchmark( const char* path, BooleanType isSparse, BooleanType useHotstarts, const Options& options, int_t maxAllowedNWSR, real_t& maxNWSR, real_t& avgNWSR, real_t& maxCPUtime, real_t& avgCPUtime, real_t& maxStationarity, real_t& maxFeasibility, real_t& maxComplementarity ) { int_t nQP=0, nV=0, nC=0, nEC=0; real_t *H=0, *g=0, *A=0, *lb=0, *ub=0, *lbA=0, *ubA=0; returnValue returnvalue; /* I) SETUP BENCHMARK: */ /* 1) Obtain QP sequence dimensions. */ if ( readOqpDimensions( path, nQP,nV,nC,nEC ) != SUCCESSFUL_RETURN ) return THROWERROR( RET_BENCHMARK_ABORTED ); /* 2) Read OQP benchmark data. */ if ( readOqpData( path, nQP,nV,nC,nEC, &H,&g,&A,&lb,&ub,&lbA,&ubA, 0,0,0 ) != SUCCESSFUL_RETURN ) { return THROWERROR( RET_UNABLE_TO_READ_BENCHMARK ); } // normaliseConstraints( nV,nC,A,lbA,ubA ); //only works when nP==1 /* II) SOLVE BENCHMARK */ if ( nC > 0 ) { returnvalue = solveOqpBenchmark( nQP,nV,nC,nEC, H,g,A,lb,ub,lbA,ubA, isSparse,useHotstarts, options,maxAllowedNWSR, maxNWSR,avgNWSR,maxCPUtime,avgCPUtime, maxStationarity,maxFeasibility,maxComplementarity ); if ( returnvalue != SUCCESSFUL_RETURN ) { if ( H != 0 ) delete[] H; if ( g != 0 ) delete[] g; if ( A != 0 ) delete[] A; if ( lb != 0 ) delete[] lb; if ( ub != 0 ) delete[] ub; if ( lbA != 0 ) delete[] lbA; if ( ubA != 0 ) delete[] ubA; return THROWERROR( returnvalue ); } } else { returnvalue = solveOqpBenchmark( nQP,nV, H,g,lb,ub, isSparse,useHotstarts, options,maxAllowedNWSR, maxNWSR,avgNWSR,maxCPUtime,avgCPUtime, maxStationarity,maxFeasibility,maxComplementarity ); if ( returnvalue != SUCCESSFUL_RETURN ) { if ( H != 0 ) delete[] H; if ( g != 0 ) delete[] g; if ( A != 0 ) delete[] A; if ( lb != 0 ) delete[] lb; if ( ub != 0 ) delete[] ub; return THROWERROR( returnvalue ); } } if ( H != 0 ) delete[] H; if ( g != 0 ) delete[] g; if ( A != 0 ) delete[] A; if ( lb != 0 ) delete[] lb; if ( ub != 0 ) delete[] ub; if ( lbA != 0 ) delete[] lbA; if ( ubA != 0 ) delete[] ubA; return SUCCESSFUL_RETURN; } END_NAMESPACE_QPOASES /* * end of file */
33.413743
117
0.517611
dbdxnuliba
92ba9bf7560ef6f03ae869dc01267e613f30ae6f
801
cpp
C++
cpp/memory_ranges_uninitialized_fill_n_1.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/memory_ranges_uninitialized_fill_n_1.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/memory_ranges_uninitialized_fill_n_1.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/memory_ranges_uninitialized_fill_n_1.exe ./cpp/memory_ranges_uninitialized_fill_n_1.cpp && (cd ../_build/cpp/;./memory_ranges_uninitialized_fill_n_1.exe) https://en.cppreference.com/w/cpp/memory/ranges/uninitialized_fill_n */ #include <iostream> #include <memory> #include <string> int main() { constexpr int n {3}; alignas(alignof(std::string)) char out[n * sizeof(std::string)]; try { auto first {reinterpret_cast<std::string*>(out)}; auto last = std::ranges::uninitialized_fill_n(first, n, "cppreference"); for (auto it {first}; it != last; ++it) { std::cout << *it << '\n'; } std::ranges::destroy(first, last); } catch(...) { std::cout << "Exception!\n"; } }
29.666667
195
0.617978
rpuntaie
92bc0e770e74ab566c2ad501f1c0cc77c0caf138
6,443
cpp
C++
test/system-level/dca/dca_sp_DCA+_mpi_test.cpp
gonidelis/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
null
null
null
test/system-level/dca/dca_sp_DCA+_mpi_test.cpp
gonidelis/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
11
2020-04-22T14:50:27.000Z
2021-09-10T05:43:51.000Z
test/system-level/dca/dca_sp_DCA+_mpi_test.cpp
weilewei/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
1
2019-09-22T16:33:19.000Z
2019-09-22T16:33:19.000Z
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Urs R. Haehner (haehneru@itp.phys.ethz.ch) // Giovanni Balduzzi (gbalduzz@itp.phys.ethz.ch) // // No-change test for a concurrent (using MPI) DCA+ calculation using the CT-AUX cluster solver. // It runs a simulation of a tight-binding model on 2D square lattice. This also tests the // checkpointing between DCA iterations. #include <iostream> #include <string> #include "gtest/gtest.h" #include "dca/config/cmake_options.hpp" #include "dca/function/domains.hpp" #include "dca/function/function.hpp" #include "dca/function/util/difference.hpp" #include "dca/io/filesystem.hpp" #include "dca/io/hdf5/hdf5_reader.hpp" #include "dca/io/json/json_reader.hpp" #include "dca/function/util/difference.hpp" #include "dca/math/random/std_random_wrapper.hpp" #include "dca/parallel/no_threading/no_threading.hpp" #include "dca/phys/dca_data/dca_data.hpp" #include "dca/phys/dca_loop/dca_loop.hpp" #include "dca/phys/dca_step/cluster_solver/ctaux/ctaux_cluster_solver.hpp" #include "dca/phys/domains/cluster/cluster_domain.hpp" #include "dca/phys/domains/cluster/symmetries/point_groups/2d/2d_square.hpp" #include "dca/phys/models/analytic_hamiltonians/square_lattice.hpp" #include "dca/phys/models/tight_binding_model.hpp" #include "dca/phys/parameters/parameters.hpp" #include "dca/profiling/null_profiler.hpp" #include "dca/testing/dca_mpi_test_environment.hpp" #include "dca/testing/minimalist_printer.hpp" #include "dca/util/git_version.hpp" #include "dca/util/modules.hpp" constexpr bool update_baseline = false; dca::testing::DcaMpiTestEnvironment* dca_test_env; TEST(dca_sp_DCAplus_mpi, Self_energy) { using RngType = dca::math::random::StdRandomWrapper<std::mt19937_64>; using DcaPointGroupType = dca::phys::domains::D4; using LatticeType = dca::phys::models::square_lattice<DcaPointGroupType>; using ModelType = dca::phys::models::TightBindingModel<LatticeType>; using Threading = dca::parallel::NoThreading; using ParametersType = dca::phys::params::Parameters<dca::testing::DcaMpiTestEnvironment::ConcurrencyType, Threading, dca::profiling::NullProfiler, ModelType, RngType, dca::phys::solver::CT_AUX>; using DcaDataType = dca::phys::DcaData<ParametersType>; using ClusterSolverType = dca::phys::solver::CtauxClusterSolver<dca::linalg::CPU, ParametersType, DcaDataType>; // The DistType parameter should be covered by the default in dca_loop.hpp // but it doesn't work for gcc 8.3.0 on cray. using DcaLoopType = dca::phys::DcaLoop<ParametersType, DcaDataType, ClusterSolverType, dca::DistType::NONE>; auto& concurrency = dca_test_env->concurrency; dca::util::SignalHandler::init(concurrency.id() == concurrency.first()); if (concurrency.id() == concurrency.first()) { // Copy initial state from an aborted run. filesystem::copy_file( DCA_SOURCE_DIR "/test/system-level/dca/data.dca_sp_DCA+_mpi_test.hdf5.tmp", "./data.dca_sp_DCA+_mpi_test.hdf5.tmp", filesystem::copy_options::overwrite_existing); dca::util::GitVersion::print(); dca::util::Modules::print(); dca::config::CMakeOptions::print(); std::cout << "\n" << "********************************************************************************\n" << "********** DCA(+) Calculation **********\n" << "********************************************************************************\n" << "\n" << "Start time : " << dca::util::print_time() << "\n" << "\n" << "MPI-world set up: " << dca_test_env->concurrency.number_of_processors() << " processes." << "\n" << std::endl; } ParametersType parameters(dca::util::GitVersion::string(), dca_test_env->concurrency); parameters.read_input_and_broadcast<dca::io::JSONReader>(dca_test_env->input_file_name); parameters.update_model(); parameters.update_domains(); DcaDataType dca_data(parameters); dca_data.initialize(); DcaLoopType dca_loop(parameters, dca_data, dca_test_env->concurrency); dca_loop.initialize(); dca_loop.execute(); dca_loop.finalize(); if (!update_baseline) { if (dca_test_env->concurrency.id() == dca_test_env->concurrency.first()) { std::cout << "\nProcessor " << dca_test_env->concurrency.id() << " is checking data " << std::endl; // Read self-energy from check_data file. DcaDataType::SpGreensFunction Sigma_check("Self_Energy"); dca::io::HDF5Reader reader; reader.open_file(DCA_SOURCE_DIR "/test/system-level/dca/check_data.dca_sp_DCA+_mpi_test.hdf5"); reader.open_group("functions"); reader.execute(Sigma_check); reader.close_file(); // Compare the computed self-energy with the expected result. auto diff = dca::func::util::difference(Sigma_check, dca_data.Sigma); EXPECT_NEAR(0, diff.l2, 1.e-9); std::cout << "\nProcessor " << dca_test_env->concurrency.id() << " is writing data." << std::endl; dca_loop.write(); std::cout << "\nFinish time: " << dca::util::print_time() << "\n" << std::endl; } } else { if (concurrency.id() == concurrency.first()) { dca::io::HDF5Writer writer; writer.open_file(DCA_SOURCE_DIR "/test/system-level/dca/check_data.dca_sp_DCA+_mpi_test.hdf5"); writer.open_group("functions"); writer.execute(dca_data.Sigma); writer.close_file(); } } } int main(int argc, char** argv) { int result = 0; ::testing::InitGoogleTest(&argc, argv); dca::parallel::MPIConcurrency concurrency(argc, argv); dca_test_env = new dca::testing::DcaMpiTestEnvironment( concurrency, DCA_SOURCE_DIR "/test/system-level/dca/input.dca_sp_DCA+_mpi_test.json"); ::testing::AddGlobalTestEnvironment(dca_test_env); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); if (dca_test_env->concurrency.id() != 0) { delete listeners.Release(listeners.default_result_printer()); listeners.Append(new dca::testing::MinimalistPrinter); } result = RUN_ALL_TESTS(); return result; }
39.771605
100
0.670185
gonidelis
92bd737b215e7eddb8116b6c482a19b1e9c4f3b5
6,902
cpp
C++
engine/src/communication/messages/GPUComponentMessage.cpp
Ethyling/blazingsql
973e868e5f0a80189b69e56090ef2dc26ac90aa1
[ "Apache-2.0" ]
1,059
2019-08-05T13:14:42.000Z
2019-11-28T21:03:23.000Z
engine/src/communication/messages/GPUComponentMessage.cpp
ciusji/blazingsql
a35643d4c983334757eee96d5b9005b8b9fbd21b
[ "Apache-2.0" ]
1,140
2019-11-30T00:36:17.000Z
2022-03-31T22:51:51.000Z
engine/src/communication/messages/GPUComponentMessage.cpp
ciusji/blazingsql
a35643d4c983334757eee96d5b9005b8b9fbd21b
[ "Apache-2.0" ]
109
2019-12-13T08:31:43.000Z
2022-03-31T06:01:26.000Z
#include "GPUComponentMessage.h" using namespace fmt::literals; namespace ral { namespace communication { namespace messages { gpu_raw_buffer_container serialize_gpu_message_to_gpu_containers(ral::frame::BlazingTableView table_view){ std::vector<std::size_t> buffer_sizes; std::vector<const char *> raw_buffers; std::vector<ColumnTransport> column_offset; std::vector<std::unique_ptr<rmm::device_buffer>> temp_scope_holder; for(int i = 0; i < table_view.num_columns(); ++i) { const cudf::column_view&column = table_view.column(i); ColumnTransport col_transport = ColumnTransport{ColumnTransport::MetaData{ .dtype = (int32_t)column.type().id(), .size = column.size(), .null_count = column.null_count(), .col_name = {}, }, .data = -1, .valid = -1, .strings_data = -1, .strings_offsets = -1, .strings_nullmask = -1, .strings_data_size = 0, .strings_offsets_size = 0, .size_in_bytes = 0}; strcpy(col_transport.metadata.col_name, table_view.names().at(i).c_str()); if (column.size() == 0) { // do nothing } else if(column.type().id() == cudf::type_id::STRING) { cudf::strings_column_view str_col_view{column}; auto offsets_column = str_col_view.offsets(); auto chars_column = str_col_view.chars(); if (str_col_view.size() + 1 == offsets_column.size()){ // this column does not come from a buffer than had been zero-copy partitioned col_transport.strings_data = raw_buffers.size(); buffer_sizes.push_back(chars_column.size()); col_transport.size_in_bytes += chars_column.size(); raw_buffers.push_back(chars_column.head<char>()); col_transport.strings_data_size = chars_column.size(); col_transport.strings_offsets = raw_buffers.size(); col_transport.strings_offsets_size = offsets_column.size() * sizeof(int32_t); buffer_sizes.push_back(col_transport.strings_offsets_size); col_transport.size_in_bytes += col_transport.strings_offsets_size; raw_buffers.push_back(offsets_column.head<char>()); if(str_col_view.has_nulls()) { col_transport.strings_nullmask = raw_buffers.size(); buffer_sizes.push_back(cudf::bitmask_allocation_size_bytes(str_col_view.size())); col_transport.size_in_bytes += cudf::bitmask_allocation_size_bytes(str_col_view.size()); raw_buffers.push_back((const char *)str_col_view.null_mask()); } } else { // this column comes from a column that was zero-copy partitioned std::pair<int32_t, int32_t> char_col_start_end = getCharsColumnStartAndEnd(str_col_view); std::unique_ptr<CudfColumn> new_offsets = getRebasedStringOffsets(str_col_view, char_col_start_end.first); col_transport.strings_data = raw_buffers.size(); col_transport.strings_data_size = char_col_start_end.second - char_col_start_end.first; buffer_sizes.push_back(col_transport.strings_data_size); col_transport.size_in_bytes += col_transport.strings_data_size; raw_buffers.push_back(chars_column.head<char>() + char_col_start_end.first); col_transport.strings_offsets = raw_buffers.size(); col_transport.strings_offsets_size = new_offsets->size() * sizeof(int32_t); buffer_sizes.push_back(col_transport.strings_offsets_size); col_transport.size_in_bytes += col_transport.strings_offsets_size; raw_buffers.push_back(new_offsets->view().head<char>()); cudf::column::contents new_offsets_contents = new_offsets->release(); temp_scope_holder.emplace_back(std::move(new_offsets_contents.data)); if(str_col_view.has_nulls()) { col_transport.strings_nullmask = raw_buffers.size(); buffer_sizes.push_back(cudf::bitmask_allocation_size_bytes(str_col_view.size())); col_transport.size_in_bytes += cudf::bitmask_allocation_size_bytes(str_col_view.size()); temp_scope_holder.emplace_back(std::make_unique<rmm::device_buffer>( cudf::copy_bitmask(str_col_view.null_mask(), str_col_view.offset(), str_col_view.offset() + str_col_view.size()))); raw_buffers.push_back((const char *)temp_scope_holder.back()->data()); } } } else { col_transport.data = raw_buffers.size(); buffer_sizes.push_back((std::size_t) column.size() * cudf::size_of(column.type())); col_transport.size_in_bytes += (std::size_t) column.size() * cudf::size_of(column.type()); raw_buffers.push_back(column.head<char>() + column.offset() * cudf::size_of(column.type())); // here we are getting the beginning of the buffer and manually calculating the offset. if(column.has_nulls()) { col_transport.valid = raw_buffers.size(); buffer_sizes.push_back(cudf::bitmask_allocation_size_bytes(column.size())); col_transport.size_in_bytes += cudf::bitmask_allocation_size_bytes(column.size()); if (column.offset() == 0){ raw_buffers.push_back((const char *)column.null_mask()); } else { temp_scope_holder.emplace_back(std::make_unique<rmm::device_buffer>( cudf::copy_bitmask(column))); raw_buffers.push_back((const char *)temp_scope_holder.back()->data()); } } } column_offset.push_back(col_transport); } return std::make_tuple(buffer_sizes, raw_buffers, column_offset, std::move(temp_scope_holder)); } std::unique_ptr<ral::frame::BlazingHostTable> serialize_gpu_message_to_host_table(ral::frame::BlazingTableView table_view, bool use_pinned) { std::vector<std::size_t> buffer_sizes; std::vector<const char *> raw_buffers; std::vector<ColumnTransport> column_offset; std::vector<std::unique_ptr<rmm::device_buffer>> temp_scope_holder; std::tie(buffer_sizes, raw_buffers, column_offset, temp_scope_holder) = serialize_gpu_message_to_gpu_containers(table_view); typedef std::pair< std::vector<ral::memory::blazing_chunked_column_info>, std::vector<std::unique_ptr<ral::memory::blazing_allocation_chunk> >> buffer_alloc_type; buffer_alloc_type buffers_and_allocations = ral::memory::convert_gpu_buffers_to_chunks(buffer_sizes,use_pinned); auto & allocations = buffers_and_allocations.second; size_t buffer_index = 0; for(auto & chunked_column_info : buffers_and_allocations.first){ size_t position = 0; for(size_t i = 0; i < chunked_column_info.chunk_index.size(); i++){ size_t chunk_index = chunked_column_info.chunk_index[i]; size_t offset = chunked_column_info.offset[i]; size_t chunk_size = chunked_column_info.size[i]; cudaMemcpyAsync((void *) (allocations[chunk_index]->data + offset), raw_buffers[buffer_index] + position, chunk_size, cudaMemcpyDeviceToHost,0); position += chunk_size; } buffer_index++; } cudaStreamSynchronize(0); auto table = std::make_unique<ral::frame::BlazingHostTable>(column_offset, std::move(buffers_and_allocations.first),std::move(buffers_and_allocations.second)); return table; } } // namespace messages } // namespace communication } // namespace ral
44.529032
183
0.738626
Ethyling
92c2922b87aa91169fd3c82c5fca5dd7f7e6cf95
17,799
cpp
C++
src/main/conversion/DLSFile.cpp
sykhro/vgmtrans-qt
6d0780bdaaac29ffe118b9be2e2ad87401b426fe
[ "Zlib" ]
18
2018-01-04T17:42:15.000Z
2021-05-26T02:52:22.000Z
src/main/conversion/DLSFile.cpp
sykhro/vgmtrans-qt
6d0780bdaaac29ffe118b9be2e2ad87401b426fe
[ "Zlib" ]
6
2017-10-19T16:47:19.000Z
2021-09-10T15:26:24.000Z
src/main/conversion/DLSFile.cpp
sykhro/vgmtrans-qt
6d0780bdaaac29ffe118b9be2e2ad87401b426fe
[ "Zlib" ]
1
2017-10-19T16:40:12.000Z
2017-10-19T16:40:12.000Z
/* * VGMTrans (c) 2002-2019 * Licensed under the zlib license, * refer to the included LICENSE.txt file */ #include "VGMInstrSet.h" #include "VGMSamp.h" #include "Root.h" using namespace std; // void WriteLIST(vector<uint8_t> & buf, uint32_t listName, uint32_t listSize) //{ // PushTypeOnVectBE<uint32_t>(buf, 0x4C495354); //write "LIST" // PushTypeOnVect<uint32_t>(buf, listSize); // PushTypeOnVectBE<uint32_t>(buf, listName); //} // // ////Adds a null byte and ensures 16 bit alignment of a text string // void AlignName(string &name) //{ // name += (char)0x00; // if (name.size() % 2) //if the size of the name string is //odd name += (char)0x00; //add another null byte //} // ******* // DLSFile // ******* DLSFile::DLSFile(string dls_name) : RiffFile(dls_name, "DLS ") {} DLSFile::~DLSFile(void) { DeleteVect(aInstrs); DeleteVect(aWaves); } DLSInstr *DLSFile::AddInstr(unsigned long bank, unsigned long instrNum) { aInstrs.insert(aInstrs.end(), new DLSInstr(bank, instrNum, "Unnamed Instrument")); return aInstrs.back(); } DLSInstr *DLSFile::AddInstr(unsigned long bank, unsigned long instrNum, string name) { aInstrs.insert(aInstrs.end(), new DLSInstr(bank, instrNum, name)); return aInstrs.back(); } void DLSFile::DeleteInstr(unsigned long bank, unsigned long instrNum) {} DLSWave *DLSFile::AddWave(uint16_t formatTag, uint16_t channels, int samplesPerSec, int aveBytesPerSec, uint16_t blockAlign, uint16_t bitsPerSample, uint32_t waveDataSize, unsigned char *waveData, string name) { aWaves.insert(aWaves.end(), new DLSWave(formatTag, channels, samplesPerSec, aveBytesPerSec, blockAlign, bitsPerSample, waveDataSize, waveData, name)); return aWaves.back(); } // GetSize returns total DLS size, including the "RIFF" header size uint32_t DLSFile::GetSize(void) { uint32_t size = 0; size += 12; // "RIFF" + size + "DLS " size += COLH_SIZE; // COLH chunk (collection chunk - tells how many instruments) size += LIST_HDR_SIZE; //"lins" list (list of instruments - contains all the "ins " lists) for (uint32_t i = 0; i < aInstrs.size(); i++) size += aInstrs[i]->GetSize(); // each "ins " list size += 16; // "ptb" + size + cbSize + cCues size += (uint32_t)aWaves.size() * sizeof(uint32_t); // each wave gets a poolcue size += LIST_HDR_SIZE; //"wvp" list (wave pool - contains all the "wave" lists) for (uint32_t i = 0; i < aWaves.size(); i++) size += aWaves[i]->GetSize(); // each "wave" list size += LIST_HDR_SIZE; //"INFO" list size += 8; //"INAM" + size size += (uint32_t)name.size(); // size of name string return size; } int DLSFile::WriteDLSToBuffer(vector<uint8_t> &buf) { uint32_t theDWORD; PushTypeOnVectBE<uint32_t>(buf, 0x52494646); //"RIFF" PushTypeOnVect<uint32_t>(buf, GetSize() - 8); // size PushTypeOnVectBE<uint32_t>(buf, 0x444C5320); //"DLS " PushTypeOnVectBE<uint32_t>(buf, 0x636F6C68); //"colh " PushTypeOnVect<uint32_t>(buf, 4); // size PushTypeOnVect<uint32_t>(buf, (uint32_t)aInstrs.size()); // cInstruments - number of // instruments theDWORD = 4; // account for 4 "lins" bytes for (uint32_t i = 0; i < aInstrs.size(); i++) theDWORD += aInstrs[i]->GetSize(); // each "ins " list WriteLIST(buf, 0x6C696E73, theDWORD); // Write the "lins" LIST for (uint32_t i = 0; i < aInstrs.size(); i++) aInstrs[i]->Write(buf); // Write each "ins " list PushTypeOnVectBE<uint32_t>(buf, 0x7074626C); //"ptb" theDWORD = 8; theDWORD += (uint32_t)aWaves.size() * sizeof(uint32_t); // each wave gets a poolcue PushTypeOnVect<uint32_t>(buf, theDWORD); // size PushTypeOnVect<uint32_t>(buf, 8); // cbSize PushTypeOnVect<uint32_t>(buf, (uint32_t)aWaves.size()); // cCues theDWORD = 0; for (uint32_t i = 0; i < (uint32_t)aWaves.size(); i++) { PushTypeOnVect<uint32_t>(buf, theDWORD); // write the poolcue for each sample // hFile->Write(&theDWORD, sizeof(uint32_t)); //write the poolcue for each // sample theDWORD += aWaves[i]->GetSize(); // increment the offset to the next wave } theDWORD = 4; for (uint32_t i = 0; i < aWaves.size(); i++) theDWORD += aWaves[i]->GetSize(); // each "wave" list WriteLIST(buf, 0x7776706C, theDWORD); // Write the "wvp" LIST for (uint32_t i = 0; i < aWaves.size(); i++) aWaves[i]->Write(buf); // Write each "wave" list theDWORD = 12 + (uint32_t)name.size(); //"INFO" + "INAM" + size + the string size WriteLIST(buf, 0x494E464F, theDWORD); // write the "INFO" list PushTypeOnVectBE<uint32_t>(buf, 0x494E414D); //"INAM" PushTypeOnVect<uint32_t>(buf, (uint32_t)name.size()); // size PushBackStringOnVector(buf, name); // The Instrument Name string return true; } // I should probably make this function part of a parent class for both Midi and DLS file bool DLSFile::SaveDLSFile(const std::string &filepath) { vector<uint8_t> dlsBuf; WriteDLSToBuffer(dlsBuf); return pRoot->UI_WriteBufferToFile(filepath, &dlsBuf[0], (uint32_t)dlsBuf.size()); } // ******* // DLSInstr // ******** DLSInstr::DLSInstr(uint32_t bank, uint32_t instrument) : ulBank(bank), ulInstrument(instrument), name("Unnamed Instrument") { RiffFile::AlignName(name); } DLSInstr::DLSInstr(uint32_t bank, uint32_t instrument, string instrName) : ulBank(bank), ulInstrument(instrument), name(instrName) { RiffFile::AlignName(name); } DLSInstr::DLSInstr(uint32_t bank, uint32_t instrument, string instrName, vector<DLSRgn *> listRgns) : ulBank(bank), ulInstrument(instrument), name(instrName) { RiffFile::AlignName(name); aRgns = listRgns; } DLSInstr::~DLSInstr() { DeleteVect(aRgns); } uint32_t DLSInstr::GetSize(void) { uint32_t size = 0; size += LIST_HDR_SIZE; //"ins " list size += INSH_SIZE; // insh chunk size += LIST_HDR_SIZE; //"lrgn" list for (uint32_t i = 0; i < aRgns.size(); i++) size += aRgns[i]->GetSize(); // each "rgn2" list size += LIST_HDR_SIZE; //"INFO" list size += 8; //"INAM" + size size += (uint32_t)name.size(); // size of name string return size; } void DLSInstr::Write(vector<uint8_t> &buf) { uint32_t theDWORD; theDWORD = GetSize() - 8; RiffFile::WriteLIST(buf, 0x696E7320, theDWORD); // write "ins " list PushTypeOnVectBE<uint32_t>(buf, 0x696E7368); //"insh" PushTypeOnVect<uint32_t>(buf, INSH_SIZE - 8); // size PushTypeOnVect<uint32_t>(buf, (uint32_t)aRgns.size()); // cRegions PushTypeOnVect<uint32_t>(buf, ulBank); // ulBank PushTypeOnVect<uint32_t>(buf, ulInstrument); // ulInstrument theDWORD = 4; for (uint32_t i = 0; i < aRgns.size(); i++) theDWORD += aRgns[i]->GetSize(); // get the size of each "rgn2" list RiffFile::WriteLIST(buf, 0x6C72676E, theDWORD); // write the "lrgn" list for (uint32_t i = 0; i < aRgns.size(); i++) aRgns[i]->Write(buf); // write each "rgn2" list theDWORD = 12 + (uint32_t)name.size(); //"INFO" + "INAM" + size + the string size RiffFile::WriteLIST(buf, 0x494E464F, theDWORD); // write the "INFO" list PushTypeOnVectBE<uint32_t>(buf, 0x494E414D); //"INAM" theDWORD = (uint32_t)name.size(); PushTypeOnVect<uint32_t>(buf, theDWORD); // size PushBackStringOnVector(buf, name); // The Instrument Name string } DLSRgn *DLSInstr::AddRgn(void) { aRgns.insert(aRgns.end(), new DLSRgn()); return aRgns.back(); } DLSRgn *DLSInstr::AddRgn(DLSRgn rgn) { DLSRgn *newRgn = new DLSRgn(); *newRgn = rgn; aRgns.insert(aRgns.end(), newRgn); return aRgns.back(); } // ****** // DLSRgn // ****** DLSRgn::~DLSRgn(void) { if (Wsmp) delete Wsmp; if (Art) delete Art; } uint32_t DLSRgn::GetSize(void) { uint32_t size = 0; size += LIST_HDR_SIZE; //"rgn2" list size += RGNH_SIZE; // rgnh chunk if (Wsmp) size += Wsmp->GetSize(); size += WLNK_SIZE; if (Art) size += Art->GetSize(); return size; } void DLSRgn::Write(vector<uint8_t> &buf) { RiffFile::WriteLIST(buf, 0x72676E32, (uint32_t)(GetSize() - 8)); // write "rgn2" list PushTypeOnVectBE<uint32_t>(buf, 0x72676E68); //"rgnh" PushTypeOnVect<uint32_t>(buf, (uint32_t)(RGNH_SIZE - 8)); // size PushTypeOnVect<uint16_t>(buf, usKeyLow); // usLow (key) PushTypeOnVect<uint16_t>(buf, usKeyHigh); // usHigh (key) PushTypeOnVect<uint16_t>(buf, usVelLow); // usLow (vel) PushTypeOnVect<uint16_t>(buf, usVelHigh); // usHigh (vel) PushTypeOnVect<uint16_t>(buf, 1); // fusOptions PushTypeOnVect<uint16_t>(buf, 0); // usKeyGroup // new for dls2 PushTypeOnVect<uint16_t>(buf, 1); // NO CLUE if (Wsmp) Wsmp->Write(buf); // write the "wsmp" chunk PushTypeOnVectBE<uint32_t>(buf, 0x776C6E6B); //"wlnk" PushTypeOnVect<uint32_t>(buf, WLNK_SIZE - 8); // size PushTypeOnVect<uint16_t>(buf, fusOptions); // fusOptions PushTypeOnVect<uint16_t>(buf, usPhaseGroup); // usPhaseGroup PushTypeOnVect<uint32_t>(buf, channel); // ulChannel PushTypeOnVect<uint32_t>(buf, tableIndex); // ulTableIndex if (Art) Art->Write(buf); } DLSArt *DLSRgn::AddArt(void) { Art = new DLSArt(); return Art; } DLSWsmp *DLSRgn::AddWsmp(void) { Wsmp = new DLSWsmp(); return Wsmp; } void DLSRgn::SetRanges(uint16_t keyLow, uint16_t keyHigh, uint16_t velLow, uint16_t velHigh) { usKeyLow = keyLow; usKeyHigh = keyHigh; usVelLow = velLow; usVelHigh = velHigh; } void DLSRgn::SetWaveLinkInfo(uint16_t options, uint16_t phaseGroup, uint32_t theChannel, uint32_t theTableIndex) { fusOptions = options; usPhaseGroup = phaseGroup; channel = theChannel; tableIndex = theTableIndex; } // ****** // DLSArt // ****** DLSArt::~DLSArt() { DeleteVect(aConnBlocks); } uint32_t DLSArt::GetSize(void) { uint32_t size = 0; size += LIST_HDR_SIZE; //"lar2" list size += 16; //"art2" chunk + size + cbSize + cConnectionBlocks for (uint32_t i = 0; i < aConnBlocks.size(); i++) size += aConnBlocks[i]->GetSize(); // each connection block return size; } void DLSArt::Write(vector<uint8_t> &buf) { RiffFile::WriteLIST(buf, 0x6C617232, GetSize() - 8); // write "lar2" list PushTypeOnVectBE<uint32_t>(buf, 0x61727432); //"art2" PushTypeOnVect<uint32_t>(buf, GetSize() - LIST_HDR_SIZE - 8); // size PushTypeOnVect<uint32_t>(buf, 8); // cbSize PushTypeOnVect<uint32_t>(buf, (uint32_t)aConnBlocks.size()); // cConnectionBlocks for (uint32_t i = 0; i < aConnBlocks.size(); i++) aConnBlocks[i]->Write(buf); // each connection block } void DLSArt::AddADSR(long attack_time, uint16_t atk_transform, long decay_time, long sustain_lev, long release_time, uint16_t rls_transform) { aConnBlocks.insert(aConnBlocks.end(), new ConnectionBlock(CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_ATTACKTIME, atk_transform, attack_time)); aConnBlocks.insert(aConnBlocks.end(), new ConnectionBlock(CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_DECAYTIME, CONN_TRN_NONE, decay_time)); aConnBlocks.insert(aConnBlocks.end(), new ConnectionBlock(CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_SUSTAINLEVEL, CONN_TRN_NONE, sustain_lev)); aConnBlocks.insert(aConnBlocks.end(), new ConnectionBlock(CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_RELEASETIME, rls_transform, release_time)); } void DLSArt::AddPan(long pan) { aConnBlocks.insert(aConnBlocks.end(), new ConnectionBlock(CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_PAN, CONN_TRN_NONE, pan)); } // *************** // ConnectionBlock // *************** void ConnectionBlock::Write(vector<uint8_t> &buf) { PushTypeOnVect<uint16_t>(buf, usSource); // usSource PushTypeOnVect<uint16_t>(buf, usControl); // usControl PushTypeOnVect<uint16_t>(buf, usDestination); // usDestination PushTypeOnVect<uint16_t>(buf, usTransform); // usTransform PushTypeOnVect<int32_t>(buf, lScale); // lScale } // ******* // DLSWsmp // ******* uint32_t DLSWsmp::GetSize(void) { uint32_t size = 0; size += 28; // all the variables minus the loop info if (cSampleLoops) size += 16; // plus the loop info return size; } void DLSWsmp::Write(vector<uint8_t> &buf) { PushTypeOnVectBE<uint32_t>(buf, 0x77736D70); //"wsmp" PushTypeOnVect<uint32_t>(buf, GetSize() - 8); // size PushTypeOnVect<uint32_t>(buf, 20); // cbSize (size of structure without loop record) PushTypeOnVect<uint16_t>(buf, usUnityNote); // usUnityNote PushTypeOnVect<int16_t>(buf, sFineTune); // sFineTune PushTypeOnVect<int32_t>(buf, lAttenuation); // lAttenuation PushTypeOnVect<uint32_t>(buf, 1); // fulOptions PushTypeOnVect<uint32_t>(buf, cSampleLoops); // cSampleLoops if (cSampleLoops) // if it loops, write the loop structure { PushTypeOnVect<uint32_t>(buf, 16); PushTypeOnVect<uint32_t>(buf, ulLoopType); // ulLoopType PushTypeOnVect<uint32_t>(buf, ulLoopStart); PushTypeOnVect<uint32_t>(buf, ulLoopLength); } } void DLSWsmp::SetLoopInfo(Loop &loop, VGMSamp *samp) { const int origFormatBytesPerSamp = samp->bps / 8; double compressionRatio = samp->GetCompressionRatio(); // If the sample loops, but the loop length is 0, then assume the length should // extend to the end of the sample. if (loop.loopStatus && loop.loopLength == 0) loop.loopLength = samp->dataLength - loop.loopStart; cSampleLoops = loop.loopStatus; ulLoopType = loop.loopType; // In DLS, the value is in number of samples // if the val is a raw offset of the original format, multiply it by the compression ratio ulLoopStart = (loop.loopStartMeasure == LM_BYTES) ? (uint32_t)((loop.loopStart * compressionRatio) / origFormatBytesPerSamp) : loop.loopStart; ulLoopLength = (loop.loopLengthMeasure == LM_BYTES) ? (uint32_t)((loop.loopLength * compressionRatio) / origFormatBytesPerSamp) : loop.loopLength; } void DLSWsmp::SetPitchInfo(uint16_t unityNote, short fineTune, long attenuation) { usUnityNote = unityNote; sFineTune = fineTune; lAttenuation = attenuation; } // ******* // DLSWave // ******* DLSWave::~DLSWave() { if (Wsmp) delete Wsmp; if (data) delete data; } uint32_t DLSWave::GetSize() { uint32_t size = 0; size += LIST_HDR_SIZE; //"wave" list size += 8; //"fmt " chunk + size size += 18; // fmt chunk data if (Wsmp) size += Wsmp->GetSize(); size += 8; //"data" chunk + size size += this->GetSampleSize(); // dataSize; //size of sample data size += LIST_HDR_SIZE; //"INFO" list size += 8; //"INAM" + size size += (uint32_t)name.size(); // size of name string return size; } void DLSWave::Write(vector<uint8_t> &buf) { uint32_t theDWORD; RiffFile::WriteLIST(buf, 0x77617665, GetSize() - 8); // write "wave" list PushTypeOnVectBE<uint32_t>(buf, 0x666D7420); //"fmt " PushTypeOnVect<uint32_t>(buf, 18); // size PushTypeOnVect<uint16_t>(buf, wFormatTag); // wFormatTag PushTypeOnVect<uint16_t>(buf, wChannels); // wChannels PushTypeOnVect<uint32_t>(buf, dwSamplesPerSec); // dwSamplesPerSec PushTypeOnVect<uint32_t>(buf, dwAveBytesPerSec); // dwAveBytesPerSec PushTypeOnVect<uint16_t>(buf, wBlockAlign); // wBlockAlign PushTypeOnVect<uint16_t>(buf, wBitsPerSample); // wBitsPerSample PushTypeOnVect<uint16_t>(buf, 0); // cbSize DLS2 specific. I don't know anything else if (Wsmp) Wsmp->Write(buf); // write the "wsmp" chunk PushTypeOnVectBE<uint32_t>(buf, 0x64617461); //"data" PushTypeOnVect<uint32_t>(buf, dataSize); // size: this is the ACTUAL size, not the even-aligned size buf.insert(buf.end(), data, data + dataSize); // Write the sample if (dataSize % 2) buf.push_back(0); theDWORD = 12 + (uint32_t)name.size(); //"INFO" + "INAM" + size + the string size RiffFile::WriteLIST(buf, 0x494E464F, theDWORD); // write the "INFO" list PushTypeOnVectBE<uint32_t>(buf, 0x494E414D); //"INAM" PushTypeOnVect<uint32_t>(buf, (uint32_t)name.size()); // size PushBackStringOnVector(buf, name); }
38.442765
100
0.604135
sykhro
92c7a5881925e2a1cb5a91536bb28fa71b7a20d9
691
hpp
C++
test-suite/generated-src/cpp/constant_enum.hpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/cpp/constant_enum.hpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/cpp/constant_enum.hpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file was generated by Djinni from constant_enum.djinni #pragma once #include <functional> namespace testsuite { enum class constant_enum : int { SOME_VALUE = 0, SOME_OTHER_VALUE = 1, }; constexpr const char* to_string(constant_enum e) noexcept { constexpr const char* names[] = { "some_value", "some_other_value", }; return names[static_cast<int>(e)]; } } // namespace testsuite namespace std { template <> struct hash<::testsuite::constant_enum> { size_t operator()(::testsuite::constant_enum type) const { return std::hash<int>()(static_cast<int>(type)); } }; } // namespace std
19.742857
62
0.668596
ggilles
92c93878627c2ba2b15cc26e32da6a70d2587e27
442
cc
C++
CondFormats/DataRecord/src/CastorGainsRcd.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CondFormats/DataRecord/src/CastorGainsRcd.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CondFormats/DataRecord/src/CastorGainsRcd.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// -*- C++ -*- // // Package: DataRecord // Class : CastorGainsRcd // // Implementation: // <Notes on implementation> // // Author: // Created: Mon Feb 11 12:16:54 CET 2008 // $Id: CastorGainsRcd.cc,v 1.1 2008/02/15 15:53:55 mccauley Exp $ #include "CondFormats/DataRecord/interface/CastorGainsRcd.h" #include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h" EVENTSETUP_RECORD_REG(CastorGainsRcd);
26
75
0.692308
nistefan
92c9d75b665ccc72165d44f9e3120a4264fcaf40
1,065
cpp
C++
C++/airplane-seat-assignment-probability.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/airplane-seat-assignment-probability.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/airplane-seat-assignment-probability.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(1) // Space: O(1) class Solution { public: double nthPersonGetsNthSeat(int n) { // p(k) = 1 * (prob that 1th passenger takes his own seat) + // 0 * (prob that 1th passenger takes kth one's seat) + // 1 * (prob that 1th passenger takes the others' seat) * // (prob that the first k-1 passengers get a seat // which is not kth one's seat) // = 1/k + p(k-1)*(k-2)/k // // p(1) = 1 // p(2) = 1/2 + p(1) * (2-2)/2 = 1/2 // p(3) = 1/3 + p(2) * (3-2)/3 = 1/3 + 1/2 * (3-2)/3 = 1/2 // ... // p(n) = 1/n + 1/2 * (n-2)/n = (2+n-2)/(2n) = 1/2 return n != 1 ? 0.5 : 1.0; } }; // Time: O(n) // Space: O(1) class Solution2 { public: double nthPersonGetsNthSeat(int n) { vector<double> dp(2); dp[0] = 1.0; // zero-indexed for (int i = 2; i <= n; ++i) { dp[(i - 1) % 2] = 1.0 / i + dp[(i - 2) % 2] * (i - 2) / i; } return dp[(n - 1) % 2]; } };
29.583333
73
0.406573
jaiskid
92ca7f67c200f4df3b2e92048d8ee211b1619c7a
1,181
cc
C++
mist/usb_interface.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
mist/usb_interface.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
mist/usb_interface.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium OS 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 "mist/usb_interface.h" #include <libusb.h> #include <base/check.h> #include <base/logging.h> #include <base/strings/stringprintf.h> #include "mist/usb_device.h" #include "mist/usb_interface_descriptor.h" namespace mist { UsbInterface::UsbInterface(const base::WeakPtr<UsbDevice>& device, const libusb_interface* interface) : device_(device), interface_(interface) { CHECK(interface_); } int UsbInterface::GetNumAlternateSettings() const { return interface_->num_altsetting; } std::unique_ptr<UsbInterfaceDescriptor> UsbInterface::GetAlternateSetting( int index) const { if (index < 0 || index >= GetNumAlternateSettings()) { LOG(ERROR) << base::StringPrintf( "Invalid alternate setting index %d. " "Must be non-negative and less than %d.", index, GetNumAlternateSettings()); return nullptr; } return std::make_unique<UsbInterfaceDescriptor>( device_, &interface_->altsetting[index]); } } // namespace mist
27.465116
74
0.707028
Toromino
92cc1db93cd9c60aece39e8e1854b738cd8f87b6
3,280
cpp
C++
efigy/src/efigytable.cpp
trailofbits/osquery-extensions
8a1a24a1142757579e001e4fa710e144169ab257
[ "Apache-2.0" ]
194
2017-12-14T14:00:34.000Z
2022-03-21T23:56:06.000Z
efigy/src/efigytable.cpp
trailofbits/osquery-extensions
8a1a24a1142757579e001e4fa710e144169ab257
[ "Apache-2.0" ]
49
2017-12-09T16:32:37.000Z
2021-12-14T22:15:06.000Z
efigy/src/efigytable.cpp
trailofbits/osquery-extensions
8a1a24a1142757579e001e4fa710e144169ab257
[ "Apache-2.0" ]
27
2017-12-14T23:48:39.000Z
2022-02-25T01:54:45.000Z
/* * Copyright (c) 2018 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "efigytable.h" #include <osquery/sql/dynamic_table_row.h> #include "Extension.h" #include "efigy.h" #include "utils.h" #include <curl/curl.h> namespace trailofbits { osquery::TableColumns EFIgyTablePlugin::columns() const { // clang-format off return { std::make_tuple("latest_efi_version", osquery::TEXT_TYPE, osquery::ColumnOptions::DEFAULT), std::make_tuple("efi_version", osquery::TEXT_TYPE, osquery::ColumnOptions::DEFAULT), std::make_tuple("efi_version_status", osquery::TEXT_TYPE, osquery::ColumnOptions::DEFAULT), std::make_tuple("latest_os_version", osquery::TEXT_TYPE, osquery::ColumnOptions::DEFAULT), std::make_tuple("os_version", osquery::TEXT_TYPE, osquery::ColumnOptions::DEFAULT), std::make_tuple("build_number_status", osquery::TEXT_TYPE, osquery::ColumnOptions::DEFAULT) }; // clang-format on } osquery::TableRows EFIgyTablePlugin::generate(osquery::QueryContext& request) { SystemInformation system_info; ServerResponse response; osquery::TableRows result; osquery::DynamicTableRowHolder r; try { getSystemInformation(system_info); queryEFIgy(response, system_info); } catch (const std::exception& e) { VLOG(1) << e.what(); r["efi_version_status"] = r["os_version_status"] = r["build_number_status"] = "error"; osquery::TableRows result; result.emplace_back(r); return result; } r["latest_efi_version"] = response.latest_efi_version; r["efi_version"] = system_info.rom_ver; if (system_info.rom_ver == response.latest_efi_version) { r["efi_version_status"] = "success"; } else { r["efi_version_status"] = "failure"; } r["latest_os_version"] = response.latest_os_version; r["os_version"] = system_info.os_ver; if (system_info.os_ver == response.latest_os_version) { r["os_version_status"] = "success"; } else { r["os_version_status"] = "failure"; } r["latest_build_number"] = response.latest_build_number; r["build_number"] = system_info.build_num; if (system_info.build_num == response.latest_build_number) { r["build_number_status"] = "success"; } else { r["build_number_status"] = "failure"; } result.emplace_back(r); return result; } EFIgyTablePlugin::EFIgyTablePlugin() { curl_global_init(CURL_GLOBAL_ALL); } EFIgyTablePlugin::~EFIgyTablePlugin() { curl_global_cleanup(); } } // namespace trailofbits
28.521739
79
0.658841
trailofbits
92d06cf5b5a0e7ad61f2bd93304a20844b9c8024
1,595
cc
C++
EventFilter/L1TRawToDigi/plugins/implementations_stage1/CaloTokens.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
EventFilter/L1TRawToDigi/plugins/implementations_stage1/CaloTokens.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
EventFilter/L1TRawToDigi/plugins/implementations_stage1/CaloTokens.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/InputTag.h" #include "CaloTokens.h" namespace l1t { namespace stage1 { CaloTokens::CaloTokens(const edm::ParameterSet& cfg, edm::ConsumesCollector& cc) { auto tag = cfg.getParameter<edm::InputTag>("InputLabel"); auto tautag = cfg.getParameter<edm::InputTag>("TauInputLabel"); auto isotautag = cfg.getParameter<edm::InputTag>("IsoTauInputLabel"); auto tagHFBitCounts = cfg.getParameter<edm::InputTag>("HFBitCountsInputLabel"); auto tagHFRingSums = cfg.getParameter<edm::InputTag>("HFRingSumsInputLabel"); auto tagRegion = cfg.getParameter<edm::InputTag>("RegionInputLabel"); auto tagEmCand = cfg.getParameter<edm::InputTag>("EmCandInputLabel"); towerToken_ = cc.consumes<CaloTowerBxCollection>(tag); egammaToken_ = cc.consumes<EGammaBxCollection>(tag); etSumToken_ = cc.consumes<EtSumBxCollection>(tag); jetToken_ = cc.consumes<JetBxCollection>(tag); tauToken_ = cc.consumes<TauBxCollection>(tautag); isotauToken_ = cc.consumes<TauBxCollection>(isotautag); calospareHFBitCountsToken_ = cc.consumes<CaloSpareBxCollection>(tagHFBitCounts); calospareHFRingSumsToken_ = cc.consumes<CaloSpareBxCollection>(tagHFRingSums); caloregionToken_ = cc.consumes<L1CaloRegionCollection>(tagRegion); caloemCandToken_ = cc.consumes<L1CaloEmCollection>(tagEmCand); } } }
46.911765
89
0.710345
nistefan
92d34bdc75e8f726ba72e0f207e4bbd8dadb960e
5,907
cpp
C++
arduino/stepper_servo_i2c/src/stepper_servo_controller.cpp
naturetwo/plantnotplant
be9e941e517080e175e292c782fefef9c8b17ce5
[ "Apache-2.0" ]
1
2019-03-30T12:36:34.000Z
2019-03-30T12:36:34.000Z
arduino/stepper_servo_i2c/src/stepper_servo_controller.cpp
naturetwo/plantnotplant
be9e941e517080e175e292c782fefef9c8b17ce5
[ "Apache-2.0" ]
null
null
null
arduino/stepper_servo_i2c/src/stepper_servo_controller.cpp
naturetwo/plantnotplant
be9e941e517080e175e292c782fefef9c8b17ce5
[ "Apache-2.0" ]
null
null
null
// Arduino Motor Controller // Marcus Jones 24FEB2019 // // Commands // f: Stepper forward 1 rotation // b: Stepper backward 1 rotation // 1: Servo posion 1 // 2: Servo posion 2 // 3: Servo posion 3 // // Serial API: #include <Arduino.h> #include <Servo.h> #include <Wire.h> #include <Adafruit_NeoPixel.h> // I2C settings int i2c_address = 0x09; // LED Settings const int PIN_LED = 12; void blink(int cnt, int delay); int BLINK_WAIT = 500; // NEO Pixel settings const int PIN_NEOPIXEL = 10; const int NUMPIXELS = 16; // Parameter 3 = pixel type flags, add together as needed: // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) Adafruit_NeoPixel neoRing = Adafruit_NeoPixel(NUMPIXELS, PIN_NEOPIXEL, NEO_GRB + NEO_KHZ800); void colorWipe(uint32_t c, uint8_t wait); // Servo settings // Servo accepts write(int), where int is 0 - 360 [degrees] Servo servo1; const int PIN_SERVO = 13; int position = 0; // Variable to store position const int DELAY_SERVO = 10; // Delay in ms // Stepper settings // Stepper accepts const int PIN_STEP = 4; const int PIN_DIRECTION = 3; const int PIN_EN = 2; const int STEPS_ROTATE = 200; const int STEP_SPEED = 500; // Delay in [ms] void stepper_rotate(float rotations); // Serial I2C settings void receiveEvent(int howMany); char str[50]; // For sprintf void setup() { // LED pinMode(PIN_LED, OUTPUT); digitalWrite(PIN_LED, LOW); // NEOpixel neoRing.begin(); neoRing.setBrightness(60); // Lower brightness and save eyeballs! neoRing.show(); // Initialize all pixels to 'off // Stepper pins setup pinMode(PIN_STEP, OUTPUT); pinMode(PIN_DIRECTION, OUTPUT); pinMode(PIN_EN, OUTPUT); digitalWrite(PIN_EN, LOW); // Servo pins setup servo1.attach(PIN_SERVO); servo1.write(180); // Serial setup Serial.begin(9600); // I2C setup Wire.begin(i2c_address); // join i2c bus with address #8 Wire.onReceive(receiveEvent); // register event } void loop() { delay(100); } void blink(int cnt, int wait){ for (int i=0; i<=cnt; i++){ digitalWrite(PIN_LED, HIGH); // turn the LED on (HIGH is the voltage level) delay(wait); // wait for a second digitalWrite(PIN_LED, LOW); // turn the LED off by making the voltage LOW delay(wait); // wait for a second; } } // function that executes whenever data is received from master // this function is registered as an event, see setup() // Execute a motor command AND print to serial for debugging void receiveEvent(int howMany) { while (Wire.available()) { // loop through all but the last char c = Wire.read(); // receive byte as a character // Handle the recieved bytes switch (c) { // LED Control case 'X': sprintf(str, "%c : LED ON\n", char(c)); Serial.print(str); digitalWrite(PIN_LED, HIGH); break; case 'x': sprintf(str, "%c : LED OFF\n", char(c)); Serial.print(str); digitalWrite(PIN_LED, LOW); break; // Stepper control case 'f': sprintf(str, "%c : Stepper forward\n", char(c)); Serial.print(str); stepper_rotate(1); blink(3,BLINK_WAIT); break; case 'b': sprintf(str, "%c : Stepper backward\n", char(c)); Serial.print(str); stepper_rotate(-1); blink(3,BLINK_WAIT); break; // Servo control case '1': sprintf(str, "%c : Servo position 1\n", char(c)); Serial.print(str); servo1.write(2); // Just above 0 to prevent motor chatter blink(3,BLINK_WAIT); break; case '2': sprintf(str, "%c : Servo position 2\n", char(c)); Serial.print(str); servo1.write(90); blink(3,BLINK_WAIT); break; case '3': sprintf(str, "%c : Servo position 3\n", char(c)); Serial.print(str); servo1.write(180); blink(3,BLINK_WAIT); break; // Neopixel Control case 'P': sprintf(str, "%c : NEOPIXEL ON\n", char(c)); Serial.print(str); colorWipe(neoRing.Color(255, 155, 50), 25); // Orange blink(3,BLINK_WAIT); break; case 'p': sprintf(str, "%c : NEOPIXEL ON\n", char(c)); Serial.print(str); colorWipe(neoRing.Color(0, 0, 0), 25); // Black blink(3,BLINK_WAIT); break; // case 'w': // sprintf(str, "%c : wait 500 ms!", char(c)); // Serial.print(str); // delay(500); // break; // case 'W': // sprintf(str, "%c : wait 1000 ms!", char(c)); // Serial.print(str); // delay(1000); // break; default: sprintf(str, "%c : Unrecognized byte!\n", char(c)); Serial.print(str); blink(10,BLINK_WAIT); break; } // End case-switch } } void stepper_rotate(float rotations) { // Smoothly rotate specified rotations // Accepts a signed floating point number // Fractional rotations possible // Get the direction from the sign if (rotations < 0) { // Backwards digitalWrite(PIN_DIRECTION, LOW); } else { // Forwards digitalWrite(PIN_DIRECTION, HIGH); } // Get the required steps int steps = abs(rotations) * STEPS_ROTATE; // Rotate for (int x = 0; x < steps; x++) { digitalWrite(PIN_STEP, HIGH); delayMicroseconds(STEP_SPEED); digitalWrite(PIN_STEP, LOW); delayMicroseconds(STEP_SPEED); } } // Fill the dots one after the other with a color void colorWipe(uint32_t c, uint8_t wait) { // Iterate over each pixel for (uint16_t i = 0; i < neoRing.numPixels(); i++) { neoRing.setPixelColor(i, c); neoRing.show(); delay(wait); } }
24.510373
93
0.619096
naturetwo
92d4d92a67fa67b0f562791ff39593ec02bb289d
1,239
hpp
C++
engine/runtime/rendering/generator/cylinder_mesh.hpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
791
2016-11-04T14:13:41.000Z
2022-03-20T20:47:31.000Z
engine/runtime/rendering/generator/cylinder_mesh.hpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
28
2016-12-01T05:59:30.000Z
2021-03-20T09:49:26.000Z
engine/runtime/rendering/generator/cylinder_mesh.hpp
ValtoForks/EtherealEngine
ab769803dcd71a61c2805afd259959b62fcdc1ff
[ "BSD-2-Clause" ]
151
2016-12-21T09:44:43.000Z
2022-03-31T13:42:18.000Z
#ifndef GENERATOR_CYLINDERMESH_HPP #define GENERATOR_CYLINDERMESH_HPP #include "axis_swap_mesh.hpp" #include "lathe_mesh.hpp" #include "line_shape.hpp" #include "uv_flip_mesh.hpp" namespace generator { /// Cylinder centered at origin aligned along the z-axis. /// @image html CylinderMesh.svg class cylinder_mesh_t { private: using impl_t = axis_swap_mesh_t<lathe_mesh_t<line_shape_t>>; impl_t axis_swap_mesh_; public: /// @param radius Radius of the cylinder along the xy-plane. /// @param size Half of the length of the cylinder along the z-axis. /// @param slices Subdivisions around the z-axis. /// @param segments Subdivisions along the z-axis. /// @param start Counterclockwise angle around the z-axis relative to the x-axis. /// @param sweep Counterclockwise angle around the z-axis. cylinder_mesh_t(double radius = 1.0, double size = 1.0, int slices = 32, int segments = 8, double start = 0.0, double sweep = gml::radians(360.0)); using triangles_t = typename impl_t::triangles_t; triangles_t triangles() const noexcept { return axis_swap_mesh_.triangles(); } using vertices_t = typename impl_t::vertices_t; vertices_t vertices() const noexcept { return axis_swap_mesh_.vertices(); } }; } #endif
26.361702
91
0.749798
ValtoForks
92d4e6ce166e1977f3f73e0beadf211dcbbba7d0
1,892
cpp
C++
framework/common/broker_interface.cpp
marcos-mxl/prplMesh
de16b3f74cf90d5d269e4b6f43723a34bc065917
[ "BSD-2-Clause-Patent" ]
1
2019-05-01T14:45:06.000Z
2019-05-01T14:45:06.000Z
framework/common/broker_interface.cpp
marcos-mxl/prplMesh
de16b3f74cf90d5d269e4b6f43723a34bc065917
[ "BSD-2-Clause-Patent" ]
8
2019-05-26T08:19:32.000Z
2019-06-03T14:41:05.000Z
framework/common/broker_interface.cpp
marcos-mxl/prplMesh
de16b3f74cf90d5d269e4b6f43723a34bc065917
[ "BSD-2-Clause-Patent" ]
2
2019-05-01T14:46:58.000Z
2019-05-02T15:23:56.000Z
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * Copyright (c) 2016-2019 Intel Corporation * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include <mapf/broker/broker_interface.h> namespace mapf { int BrokerInterface::syncCount = 0; void BrokerInterface::Init() { int rc = config_.Parse(); mapf_assert(rc == 0); for (auto &backend : config_.backend) { MAPF_INFO("connect " << config_.name << "@" << backend); rc = sub_.Connect(backend); mapf_assert(rc == 0); } for (auto &frontend : config_.frontend) { MAPF_INFO("connect " << config_.name << "@" << frontend); pub_.Connect(frontend); mapf_assert(rc == 0); } } void BrokerInterface::PrintConfig() { MAPF_DBG("BrokerInterface configuration"); config_.Print(); } void BrokerInterface::Sync() { if (!Socket::SyncRequired()) { return; } syncCount++; const std::string &msg_topic = sync_topic(); Message tx_msg(msg_topic); int rc, attempts = 0, max_attempts = 1000; Poller poller; rc = sub_.Subscribe(msg_topic); mapf_assert(rc == 0); rc = poller.Add(sub_); mapf_assert(rc == 0); while (attempts++ < max_attempts) { SyncSend(tx_msg); rc = poller.Poll(1); if (rc > 0) { mapf_assert(poller.CheckEvent(sub_) == MAPF_POLLIN); if (SyncRecv(msg_topic)) break; } } mapf_assert(attempts < max_attempts); rc = sub_.Unsubscribe(msg_topic); mapf_assert(rc == 0); } void BrokerInterface::SyncSend(Message &msg) { bool rc = pub_.Send(msg); mapf_assert(rc == true); } bool BrokerInterface::SyncRecv(const std::string &msg_topic) { Message msg; bool rc = sub_.Receive(msg); return rc && (msg_topic == msg.topic()); } } /* namespace mapf */
23.358025
65
0.609408
marcos-mxl
92d6b42a0a5f924cedd60817659ac6fe420ca030
1,318
cpp
C++
sxaccelerate/src/graph/SxGProps.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
sxaccelerate/src/graph/SxGProps.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
sxaccelerate/src/graph/SxGProps.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The general purpose cross platform C/C++ framework // // S x A c c e l e r a t e // // Home: https://www.sxlib.de // License: Apache 2 // Authors: see src/AUTHORS // // --------------------------------------------------------------------------- #include <SxGProps.h> size_t sxHash (const SxGProps &in) { return SxHashFunction::hash (in.getId ()); } SxGProps::SxGProps () : id(-1) { } SxGProps::SxGProps (ssize_t id_) : id(id_) {} ssize_t SxGProps::getId () const { return id; } SxVariant &SxGProps::getProperty (const SxString &key) { if(props.containsKey (key)) return props(key); else SX_CHECK (false, key); } const SxVariant &SxGProps::getProperty (const SxString &key) const { if(props.containsKey (key)) return props(key); else SX_CHECK (false, key); } const SxMap<SxString,SxVariant> & SxGProps::getProperties () const { return props; } bool SxGProps::operator== (const SxGProps &n1) const { return id == n1.id; } bool SxGProps::hasProperty (const SxString &key) const { return this->props.containsKey (key); } SxGProps::operator ssize_t() const { return id; }
22.338983
78
0.528073
ashtonmv
92d7507a777de4cbc7b66ae86ec2ac23ffd7d06f
3,013
cpp
C++
src/gui/tb/tb_str.cpp
sstanfield/hexGame
99edad55703846992d3f64ad4cf9d146d57ca625
[ "Zlib" ]
null
null
null
src/gui/tb/tb_str.cpp
sstanfield/hexGame
99edad55703846992d3f64ad4cf9d146d57ca625
[ "Zlib" ]
null
null
null
src/gui/tb/tb_str.cpp
sstanfield/hexGame
99edad55703846992d3f64ad4cf9d146d57ca625
[ "Zlib" ]
null
null
null
// ================================================================================ // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås == // == See tb_core.h for more information. == // ================================================================================ #include "tb_str.h" #include <stdlib.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <assert.h> namespace tb { static const char *empty = ""; inline void safe_delete(char *&str) { if (str != empty && str) free(str); str = const_cast<char*>(empty); } const char *stristr(const char *arg1, const char *arg2) { const char *a, *b; for(;*arg1;arg1++) { a = arg1; b = arg2; while (toupper(*a++) == toupper(*b++)) if (!*b) return arg1; } return nullptr; } // == TBStr ========================================================== TBStr::TBStr() : TBStrC(empty) { } TBStr::TBStr(const char* str) : TBStrC(str == empty ? empty : strdup(str)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const TBStr &str) : TBStrC(str.s == empty ? empty : strdup(str.s)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const char* str, int len) : TBStrC(empty) { Set(str, len); } TBStr::~TBStr() { safe_delete(s); } bool TBStr::Set(const char* str, int len) { safe_delete(s); if (len == TB_ALL_TO_TERMINATION) len = strlen(str); if (char *new_s = (char *) malloc(len + 1)) { s = new_s; memcpy(s, str, len); s[len] = 0; return true; } return false; } bool TBStr::SetFormatted(const char* format, ...) { safe_delete(s); if (!format) return true; va_list ap; int max_len = 64; char *new_s = nullptr; while (true) { if (char *tris_try_new_s = (char *) realloc(new_s, max_len)) { new_s = tris_try_new_s; va_start(ap, format); int ret = vsnprintf(new_s, max_len, format, ap); va_end(ap); if (ret > max_len) // Needed size is known (+2 for termination and avoid ambiguity) max_len = ret + 2; else if (ret == -1 || ret >= max_len - 1) // Handle some buggy vsnprintf implementations. max_len *= 2; else // Everything fit for sure { s = new_s; return true; } } else { // Out of memory free(new_s); break; } } return false; } void TBStr::Clear() { safe_delete(s); } void TBStr::Remove(int ofs, int len) { assert(ofs >= 0 && (ofs + len <= (int)strlen(s))); if (!len) return; char *dst = s + ofs; char *src = s + ofs + len; while (*src != 0) *(dst++) = *(src++); *dst = *src; } bool TBStr::Insert(int ofs, const char *ins, int ins_len) { int len1 = strlen(s); if (ins_len == TB_ALL_TO_TERMINATION) ins_len = strlen(ins); int newlen = len1 + ins_len; if (char *news = (char *) malloc(newlen + 1)) { memcpy(&news[0], s, ofs); memcpy(&news[ofs], ins, ins_len); memcpy(&news[ofs + ins_len], &s[ofs], len1 - ofs); news[newlen] = 0; safe_delete(s); s = news; return true; } return false; } } // namespace tb
18.83125
92
0.545636
sstanfield
92df5776c2237871b6299ff2eb1599fa24b05845
695
cpp
C++
Coding/CodeChef/Other/MANRECT.cpp
dhvanilp/Data-Structures-and-Algorithms
d9c04e424ef2d2a73dc8afda7ace4cc294c05420
[ "MIT" ]
null
null
null
Coding/CodeChef/Other/MANRECT.cpp
dhvanilp/Data-Structures-and-Algorithms
d9c04e424ef2d2a73dc8afda7ace4cc294c05420
[ "MIT" ]
null
null
null
Coding/CodeChef/Other/MANRECT.cpp
dhvanilp/Data-Structures-and-Algorithms
d9c04e424ef2d2a73dc8afda7ace4cc294c05420
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define alpha 1000000000 int main(){ int t; cin>>t; while(t--){ long long int k1,k2,k3,k4; cout<<"Q 0 0\n"<<flush; cin>>k1; cout<<"Q 1000000000 1000000000\n"<<flush; cin>>k2; cout<<"Q 1000000000 0\n"<<flush; cin>>k3; cout<<"Q 0 1000000000\n"<<flush; cin>>k4; long long int a,b,c,d; cout<<"Q 0 "<<(k1-k4+alpha)/2<<"\n"<<flush; cin>>a; b=k1-a; d=alpha*1LL+a-k4; c=2*alpha*1LL-d-k2; cout<<"A "<<a<<" "<<b<<" "<<c<<" "<<d<<"\n"<<flush; int temp; cin>>temp; } return 0; }
21.71875
59
0.443165
dhvanilp
92df58be4ba43f7498c6a5f73940bc99d8ac1b5a
975
cpp
C++
cpp1st/week05/byongmin/03.atomic.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
2
2022-03-10T10:18:23.000Z
2022-03-16T15:37:22.000Z
cpp1st/week05/byongmin/03.atomic.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
8
2022-03-09T16:14:47.000Z
2022-03-28T15:35:17.000Z
cpp1st/week05/byongmin/03.atomic.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
4
2022-03-08T00:22:29.000Z
2022-03-12T13:22:43.000Z
#include <iostream> #include <thread> #include <vector> #include <atomic> using namespace std; void increment(int& counter) { for (int i=0; i<10000; ++i) { ++counter; this_thread::sleep_for(chrono::microseconds(1)); } } void incrementAtomic(atomic<int>& counter) { for (int i=0; i<10000; ++i) { ++counter; this_thread::sleep_for(chrono::microseconds(1)); } } int main() { int counter{0}; atomic<int> counterAtomic{0}; vector<thread> threads; vector<thread> threadsAtomic; for (int i=0; i<10; ++i) { threads.emplace_back(thread{increment, ref(counter)}); threadsAtomic.emplace_back(thread{incrementAtomic, ref(counterAtomic)}); } for (auto& t : threads) { t.join(); } for (auto& t : threadsAtomic) { t.join(); } cout << "conter : " << counter << endl; cout << "conterAtomic : " << counterAtomic << endl; return 0; }
18.396226
80
0.575385
th4inquiry
92df73a360e783c4042fe13074567eaff71b5cf6
700
cpp
C++
src/system/kernel/arch/x86/paging/x86_physical_page_mapper_mapped.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/system/kernel/arch/x86/paging/x86_physical_page_mapper_mapped.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/system/kernel/arch/x86/paging/x86_physical_page_mapper_mapped.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2012, Alex Smith, alex@alex-smith.me.uk. * Distributed under the terms of the MIT License. */ #include <new> #include "paging/x86_physical_page_mapper.h" // #pragma mark - static X86PhysicalPageMapper sPhysicalPageMapper; static TranslationMapPhysicalPageMapper sKernelPageMapper; // #pragma mark - Initialization status_t mapped_physical_page_ops_init(kernel_args* args, X86PhysicalPageMapper*& _pageMapper, TranslationMapPhysicalPageMapper*& _kernelPageMapper) { new(&sPhysicalPageMapper) X86PhysicalPageMapper; new(&sKernelPageMapper) TranslationMapPhysicalPageMapper; _pageMapper = &sPhysicalPageMapper; _kernelPageMapper = &sKernelPageMapper; return B_OK; }
20.588235
58
0.804286
Kirishikesan
92df942efd3ad032c526291da16c335a7a6567a0
20,069
cc
C++
crash-reporter/util.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
crash-reporter/util.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
crash-reporter/util.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium OS 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 "crash-reporter/util.h" #include <poll.h> #include <signal.h> #include <stdlib.h> #include <algorithm> #include <map> #include <memory> #include <base/check_op.h> #include <base/logging.h> #if USE_DIRENCRYPTION #include <keyutils.h> #endif // USE_DIRENCRYPTION #include <base/command_line.h> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <base/strings/string_split.h> #include <base/strings/string_util.h> #include <brillo/cryptohome.h> #include <brillo/key_value_store.h> #include <brillo/userdb_utils.h> #include <re2/re2.h> #include <zlib.h> #include "crash-reporter/crossystem.h" #include "crash-reporter/paths.h" #include "crash-reporter/vm_support.h" namespace util { namespace { constexpr size_t kBufferSize = 4096; // Path to hardware class description. constexpr char kHwClassPath[] = "/sys/devices/platform/chromeos_acpi/HWID"; constexpr char kDevSwBoot[] = "devsw_boot"; constexpr char kDevMode[] = "dev"; // If the OS version is older than this we do not upload crash reports. constexpr base::TimeDelta kAgeForNoUploads = base::Days(180); #if USE_DIRENCRYPTION // Name of the session keyring. const char kDircrypt[] = "dircrypt"; #endif // USE_DIRENCRYPTION } // namespace const int kDefaultMaxUploadBytes = 1024 * 1024; bool IsCrashTestInProgress() { return base::PathExists(paths::GetAt(paths::kSystemRunStateDirectory, paths::kCrashTestInProgress)); } bool IsDeviceCoredumpUploadAllowed() { return base::PathExists(paths::GetAt(paths::kCrashReporterStateDirectory, paths::kDeviceCoredumpUploadAllowed)); } bool IsDeveloperImage() { // If we're testing crash reporter itself, we don't want to special-case // for developer images. if (IsCrashTestInProgress()) return false; return base::PathExists(paths::Get(paths::kLeaveCoreFile)); } // Determines if this is a test image, IGNORING IsCrashTestInProgress. // Use sparingly, and only if you're really sure you want to have different // behavior during crash tests than on real devices. bool IsReallyTestImage() { std::string channel; if (!GetCachedKeyValueDefault(base::FilePath(paths::kLsbRelease), "CHROMEOS_RELEASE_TRACK", &channel)) { return false; } return base::StartsWith(channel, "test", base::CompareCase::SENSITIVE); } bool IsTestImage() { // If we're testing crash reporter itself, we don't want to special-case // for test images. if (IsCrashTestInProgress()) return false; return IsReallyTestImage(); } bool IsOfficialImage() { std::string description; if (!GetCachedKeyValueDefault(base::FilePath(paths::kLsbRelease), "CHROMEOS_RELEASE_DESCRIPTION", &description)) { return false; } return description.find("Official") != std::string::npos; } bool HasMockConsent() { // Don't bypass user consent on real Chromebooks; this is for testing. // We can't use IsTestImage because that's always false if a crash test is in // progress. if (!IsReallyTestImage()) { return false; } return base::PathExists( paths::GetAt(paths::kSystemRunStateDirectory, paths::kMockConsent)); } bool IsFeedbackAllowed(MetricsLibraryInterface* metrics_lib) { if (HasMockConsent()) { LOG(INFO) << "mock-consent file present; assuming consent"; return true; } // For developer builds, we always want to keep the crash reports unless // we're testing the crash facilities themselves. This overrides // feedback. Crash sending still obeys consent. if (IsDeveloperImage()) { LOG(INFO) << "developer build - not testing - always dumping"; return true; } VmSupport* vm_support = VmSupport::Get(); bool ret = false; if (vm_support) { ret = vm_support->GetMetricsConsent(); } else { ret = metrics_lib->AreMetricsEnabled(); } if (!ret) { LOG(WARNING) << "No consent. Not handling invocation: " << base::CommandLine::ForCurrentProcess()->GetCommandLineString(); } return ret; } // Determine if the filter-in file tells us to skip static bool SkipForFilterIn(std::string command_line) { base::FilePath file = paths::GetAt(paths::kSystemRunStateDirectory, paths::kFilterInFile); if (!base::PathExists(file)) { return false; } std::string contents; if (!base::ReadFileToString(file, &contents)) { LOG(WARNING) << "Failed to read " << file; return false; } if (contents == "none" || command_line.find(contents) == std::string::npos) { // Doesn't match, so skip this crash. LOG(WARNING) << "Ignoring crash invocation '" << command_line << "' due to " << "filter_in=" << contents << "."; return true; } return false; } // Determine if the filter-out file tells us to skip static bool SkipForFilterOut(std::string command_line) { base::FilePath file = paths::GetAt(paths::kSystemRunStateDirectory, paths::kFilterOutFile); if (!base::PathExists(file)) { return false; } std::string contents; if (!base::ReadFileToString(file, &contents)) { LOG(WARNING) << "Failed to read " << file; return false; } if (command_line.find(contents) != std::string::npos) { // Matches, so skip this crash. LOG(WARNING) << "Ignoring crash invocation '" << command_line << "' due to " << "filter_out=" << contents << "."; return true; } return false; } bool SkipCrashCollection(int argc, const char* const argv[]) { // Don't skip crashes on real Chromebooks; this is for testing. // We can't use IsTestImage because that's always false if a crash test is in // progress. if (!IsReallyTestImage()) { return false; } std::vector<std::string> args(argv + 1, argv + argc); std::string command_line = base::JoinString(args, " "); // If the command line consists solely of these flags, it's always allowed // (regardless of filter-in state). // These flags are always accepted because they do not create crash files. // Tests may wish to verify or depend on their effects while also blocking all // crashes (using a filter-in of "none"). const std::vector<std::string> allowlist = { "--init", "--clean_shutdown", "--log_to_stderr", }; bool all_args_allowed = true; for (auto it = args.begin(); it != args.end() && all_args_allowed; ++it) { if (std::find(allowlist.begin(), allowlist.end(), *it) == allowlist.end()) { all_args_allowed = false; } } if (all_args_allowed) { return false; } return SkipForFilterIn(command_line) || SkipForFilterOut(command_line); } bool SetGroupAndPermissions(const base::FilePath& file, const char* group, bool execute) { gid_t gid; if (!brillo::userdb::GetGroupInfo(group, &gid)) { LOG(ERROR) << "Couldn't look up group " << group; return false; } if (lchown(file.value().c_str(), -1, gid) != 0) { PLOG(ERROR) << "Couldn't chown " << file.value(); return false; } int mode; if (!base::GetPosixFilePermissions(file, &mode)) { PLOG(ERROR) << "Couldn't get file permissions for " << file.value(); return false; } mode_t group_mode = S_IRGRP | S_IWGRP; if (execute) { group_mode |= S_IXGRP; } if (!base::SetPosixFilePermissions(file, mode | group_mode)) { PLOG(ERROR) << "Couldn't chmod " << file.value(); return false; } return true; } base::Time GetOsTimestamp() { base::FilePath lsb_release_path = paths::Get(paths::kEtcDirectory).Append(paths::kLsbRelease); base::File::Info info; if (!base::GetFileInfo(lsb_release_path, &info)) { LOG(ERROR) << "Failed reading info for /etc/lsb-release"; return base::Time(); } return info.last_modified; } bool IsBuildTimestampTooOldForUploads(int64_t build_time_millis, base::Clock* clock) { if (build_time_millis == 0) { return true; } else if (build_time_millis < 0) { LOG(ERROR) << "build timestamp is negative: " << build_time_millis; return false; } base::Time timestamp(base::Time::UnixEpoch() + base::Milliseconds(build_time_millis)); if (timestamp.is_null()) { return false; } base::Time now = clock->Now(); // In case of invalid timestamps, always upload a crash -- something strange // is happening. if (timestamp > now) { LOG(ERROR) << "OS timestamp is in the future: " << timestamp; return false; } else if (timestamp < base::Time::UnixEpoch()) { LOG(ERROR) << "OS timestamp is negative: " << timestamp; return false; } return (now - timestamp) > kAgeForNoUploads; } std::string GetHardwareClass() { std::string hw_class; if (base::ReadFileToString(paths::Get(kHwClassPath), &hw_class)) return hw_class; auto vb_value = crossystem::GetInstance()->VbGetSystemPropertyString("hwid"); return vb_value ? vb_value.value() : "undefined"; } std::string GetBootModeString() { // If we're testing crash reporter itself, we don't want to special-case // for developer mode. if (IsCrashTestInProgress()) return ""; auto vb_value = crossystem::GetInstance()->VbGetSystemPropertyInt(kDevSwBoot); if (!vb_value) { LOG(ERROR) << "Error trying to determine boot mode"; return "missing-crossystem"; } if (vb_value.value() == 1) return kDevMode; return ""; } bool GetCachedKeyValue(const base::FilePath& base_name, const std::string& key, const std::vector<base::FilePath>& directories, std::string* value) { std::vector<std::string> error_reasons; for (const auto& directory : directories) { const base::FilePath file_name = directory.Append(base_name); if (!base::PathExists(file_name)) { error_reasons.push_back(file_name.value() + " not found"); continue; } brillo::KeyValueStore store; if (!store.Load(file_name)) { LOG(WARNING) << "Problem parsing " << file_name.value(); // Even though there was some failure, take as much as we could read. } if (!store.GetString(key, value)) { error_reasons.push_back("Key not found in " + file_name.value()); continue; } return true; } LOG(WARNING) << "Unable to find " << key << ": " << base::JoinString(error_reasons, ", "); return false; } bool GetCachedKeyValueDefault(const base::FilePath& base_name, const std::string& key, std::string* value) { const std::vector<base::FilePath> kDirectories = { paths::Get(paths::kCrashReporterStateDirectory), paths::Get(paths::kEtcDirectory), }; return GetCachedKeyValue(base_name, key, kDirectories, value); } bool GetUserHomeDirectories( org::chromium::SessionManagerInterfaceProxyInterface* session_manager_proxy, std::vector<base::FilePath>* directories) { brillo::ErrorPtr error; std::map<std::string, std::string> sessions; session_manager_proxy->RetrieveActiveSessions(&sessions, &error); if (error) { LOG(ERROR) << "Error calling D-Bus proxy call to interface " << "'" << session_manager_proxy->GetObjectPath().value() << "': " << error->GetMessage(); return false; } for (const auto& iter : sessions) { directories->push_back(paths::Get( brillo::cryptohome::home::GetHashedUserPath(iter.second).value())); } return true; } bool GetUserCrashDirectories( org::chromium::SessionManagerInterfaceProxyInterface* session_manager_proxy, std::vector<base::FilePath>* directories) { std::vector<base::FilePath> home_directories; if (!GetUserHomeDirectories(session_manager_proxy, &home_directories)) { return false; } for (const auto& iter : home_directories) { directories->push_back(iter.Append("crash")); } return true; } bool GetDaemonStoreCrashDirectories( org::chromium::SessionManagerInterfaceProxyInterface* session_manager_proxy, std::vector<base::FilePath>* directories) { if (!session_manager_proxy) { LOG(ERROR) << "Can't get active sessions - no session manager proxy"; return false; } brillo::ErrorPtr error; std::map<std::string, std::string> sessions; session_manager_proxy->RetrieveActiveSessions(&sessions, &error); if (error) { LOG(ERROR) << "Error calling D-Bus proxy call to interface " << "'" << session_manager_proxy->GetObjectPath().value() << "': " << error->GetMessage(); return false; } for (const auto& iter : sessions) { directories->push_back( paths::Get(base::FilePath(paths::kCryptohomeCrashDirectory) .Append(iter.second) .value())); } return true; } std::vector<unsigned char> GzipStream(brillo::StreamPtr data) { // Adapted from https://zlib.net/zlib_how.html z_stream deflate_stream; memset(&deflate_stream, 0, sizeof(deflate_stream)); deflate_stream.zalloc = Z_NULL; deflate_stream.zfree = Z_NULL; // Using a window size of 31 sets us to gzip mode (16) + default window size // (15). const int kDefaultWindowSize = 15; const int kWindowSizeGzipAdd = 16; const int kDefaultMemLevel = 8; int result = deflateInit2(&deflate_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, kDefaultWindowSize + kWindowSizeGzipAdd, kDefaultMemLevel, Z_DEFAULT_STRATEGY); if (result != Z_OK) { LOG(ERROR) << "Error initializing zlib: error code " << result << ", error msg: " << (deflate_stream.msg == nullptr ? "None" : deflate_stream.msg); return std::vector<unsigned char>(); } std::vector<unsigned char> deflated; int flush = Z_NO_FLUSH; /* compress until end of stream */ do { size_t read_size = 0; unsigned char in[kBufferSize]; if (!data->ReadBlocking(in, kBufferSize, &read_size, nullptr)) { // We are reading from a memory stream, so this really shouldn't happen. LOG(ERROR) << "Error reading from input stream"; deflateEnd(&deflate_stream); return std::vector<unsigned char>(); } if (data->GetRemainingSize() <= 0) { // We must request a flush on the last chunk of data, else deflateEnd // may just discard some compressed data. flush = Z_FINISH; } deflate_stream.next_in = in; deflate_stream.avail_in = read_size; do { unsigned char out[kBufferSize]; deflate_stream.avail_out = kBufferSize; deflate_stream.next_out = out; result = deflate(&deflate_stream, flush); // Note that most return values are acceptable; don't error out if result // is not Z_OK. See discussion at https://zlib.net/zlib_how.html DCHECK_NE(result, Z_STREAM_ERROR); DCHECK_LE(deflate_stream.avail_out, kBufferSize); int amount_in_output_buffer = kBufferSize - deflate_stream.avail_out; deflated.insert(deflated.end(), out, out + amount_in_output_buffer); } while (deflate_stream.avail_out == 0); DCHECK_EQ(deflate_stream.avail_in, 0) << "deflate did not consume all data"; } while (flush != Z_FINISH); DCHECK_EQ(result, Z_STREAM_END) << "Stream did not complete properly"; deflateEnd(&deflate_stream); return deflated; } int RunAndCaptureOutput(brillo::ProcessImpl* process, int fd, std::string* output) { process->RedirectUsingPipe(fd, false); if (process->Start()) { const int out = process->GetPipe(fd); char buffer[kBufferSize]; output->clear(); while (true) { const ssize_t count = HANDLE_EINTR(read(out, buffer, kBufferSize)); if (count < 0) { process->Wait(); break; } if (count == 0) return process->Wait(); output->append(buffer, count); } } return -1; } void LogMultilineError(const std::string& error) { std::vector<base::StringPiece> lines = base::SplitStringPiece( error, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); for (auto line : lines) LOG(ERROR) << line; } bool ReadMemfdToString(int mem_fd, std::string* contents) { if (contents) contents->clear(); base::ScopedFILE file(fdopen(mem_fd, "r")); if (!file) { PLOG(ERROR) << "Failed to fdopen(" << mem_fd << ")"; return false; } if (fseeko(file.get(), 0, SEEK_END) != 0) { PLOG(ERROR) << "fseeko() error"; return false; } off_t file_size = ftello(file.get()); if (file_size < 0) { PLOG(ERROR) << "ftello() error"; return false; } else if (file_size == 0) { LOG(ERROR) << "Minidump memfd has size of 0"; return false; } if (fseeko(file.get(), 0, SEEK_SET) != 0) { PLOG(ERROR) << "fseeko() error"; return false; } std::unique_ptr<char[]> buf(new char[file_size]); if (fread(buf.get(), 1, file_size, file.get()) != file_size) { PLOG(ERROR) << "fread() error"; return false; } if (contents) contents->assign(buf.get(), file_size); return true; } int GetSelinuxWeight() { return 1000; } int GetServiceFailureWeight() { return 1000; } int GetSuspendFailureWeight() { return 50; } int GetKernelWarningWeight(const std::string& flag) { // Sample kernel wifi warnings at a higher weight, since they're heavily // environmentally influenced. // Sample iwlwifi errors and ath10k errors using a higher weight since they're // not as useful and are only actionable for WiFi vendors. if (flag == "--kernel_wifi_warning" || flag == "--kernel_ath10k_error" || flag == "--kernel_iwlwifi_error") { return 50; } else if (flag == "--kernel_warning" || flag == "--kernel_suspend_warning") { return 10; } else { return 1; // e.g. kernel_smmu_fault } } int GetUmountStatefulFailureWeight() { return 10; } bool ReadFdToStream(unsigned int fd, std::stringstream* stream) { base::File src(fd); char buffer[kBufferSize]; while (true) { const int count = src.ReadAtCurrentPosNoBestEffort(buffer, kBufferSize); if (count < 0) return false; if (count == 0) return stream->tellp() > 0; // Crash log should not be empty. stream->write(buffer, count); } } #if USE_DIRENCRYPTION void JoinSessionKeyring() { key_serial_t session_keyring = keyctl_join_session_keyring(kDircrypt); if (session_keyring == -1) { // The session keyring may not exist if ext4 encryption isn't enabled so // just log an info message instead of an error. PLOG(INFO) << "Unable to join session keying"; } } #endif // USE_DIRENCRYPTION // Hash a string to a number. We define our own hash function to not // be dependent on a C++ library that might change. This function // uses basically the same approach as tr1/functional_hash.h but with // a larger prime number (16127 vs 131). unsigned HashString(base::StringPiece input) { unsigned hash = 0; for (auto c : input) hash = hash * 16127 + c; return hash; } base::FilePath GetPathToThisBinary(const char* const argv[]) { // To support usage with lddtree, allow overriding argv[0] with the LD_ARGV0 // environment variable set by lddtree wrappers. Without this, core_pattern // will include a .elf suffix, bypassing the lddtree wrapper, leaving // crash_reporter unable to start in response to crashes. // // TODO(crbug.com/1003841): Remove LD_ARGV0 once ld.so supports forwarding // the binary name. const char* arg0 = getenv("LD_ARGV0"); if (arg0 == nullptr || arg0[0] == '\0') { arg0 = argv[0]; } return base::MakeAbsoluteFilePath(base::FilePath(arg0)); } bool RedactDigests(std::string* to_filter) { static constexpr const LazyRE2 digest_re = { R"((^|[^0-9a-fA-F])(?:[0-9a-fA-F]{32,})([^0-9a-fA-F]|$))"}; return re2::RE2::Replace(to_filter, *digest_re, R"(\1<Redacted Digest>\2)"); } } // namespace util
31.066563
80
0.659724
Toromino
92e0f90428a0a6b4eeec4d42b63b8feabd42c22e
2,202
hpp
C++
src/sdl/error.hpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/sdl/error.hpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/sdl/error.hpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
#pragma once #include "lubee/src/error_chk.hpp" namespace rev { namespace detail { struct SDLErrorI { static const char* Get(); static void Reset(); static const char *const c_apiName; }; struct IMGErrorI { static const char* Get(); static void Reset(); static const char *const c_apiName; }; } template <class I> struct ErrorT { std::string _errMsg; const char* errorDesc() { const char* err = I::Get(); if(*err != '\0') { _errMsg = err; I::Reset(); return _errMsg.c_str(); } return nullptr; } void reset() const { I::Reset(); } const char* getAPIName() const { return I::c_apiName; } }; using SDLError = ErrorT<detail::SDLErrorI>; using IMGError = ErrorT<detail::IMGErrorI>; } #define SDLEC_Base(flag, act, ...) EChk_polling##flag<::lubee::err::act>(::rev::SDLError(), SOURCEPOS, __VA_ARGS__) #define SDLEC_Base0(flag, act) EChk_polling##flag<::lubee::err::act>(::rev::SDLError(), SOURCEPOS) #define SDLAssert(...) SDLEC_Base(_a, Trap, __VA_ARGS__) #define SDLWarn(...) SDLEC_Base(_a, Warn, __VA_ARGS__) #define SDLAssert0() SDLEC_Base0(_a, Trap) #define SDLWarn0() SDLEC_Base0(_a, Warn) #define D_SDLAssert(...) SDLEC_Base(_d, Trap, __VA_ARGS__) #define D_SDLWarn(...) SDLEC_Base(_d, Warn, __VA_ARGS__) #define D_SDLAssert0() SDLEC_Base0(_d, Trap) #define D_SDLWarn0() SDLEC_Base0(_d, Warn) #define SDLThrow(typ, ...) SDLEC_Base(_a, Throw<typ>, __VA_ARGS__) #define IMGEC_Base(flag, act, ...) EChk_polling##flag<::lubee::err::act>(::rev::IMGError(), SOURCEPOS, __VA_ARGS__) #define IMGEC_Base0(flag, act) EChk_polling##flag<::lubee::err::act>(::rev::IMGError(), SOURCEPOS) #define IMGAssert(...) IMGEC_Base(_a, Trap, __VA_ARGS__) #define IMGWarn(...) IMGEC_Base(_a, Warn, __VA_ARGS__) #define IMGAssert0() IMGEC_Base0(_a, Trap) #define IMGWarn0() IMGEC_Base0(_a, Warn) #define D_IMGAssert(...) IMGEC_Base(_d, Trap, __VA_ARGS__) #define D_IMGWarn(...) IMGEC_Base(_d, Warn, __VA_ARGS__) #define D_IMGAssert0() IMGEC_Base0(_d, Trap) #define D_IMGWarn0() IMGEC_Base0(_d, Warn) #define IMGThrow(typ, ...) IMGEC_Base(_a, Throw<typ>, __VA_ARGS__)
33.876923
116
0.669846
degarashi
2bb18eb9a832d5aa49f473e5b4b0752a3cc1e525
6,135
cpp
C++
base/win32/fusion/sxsservice/server/main.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/win32/fusion/sxsservice/server/main.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/win32/fusion/sxsservice/server/main.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "stdinc.h" #pragma hdrstop #include <svcs.h> #include "sxsserviceserver.h" EXTERN_C RPC_IF_HANDLE SxsStoreManager_ServerIfHandle; BOOL CServiceStatus::Initialize( PCWSTR pcwszServiceName, LPHANDLER_FUNCTION pHandler, DWORD dwServiceType, DWORD dwControlsAccepted, DWORD dwInitialState ) { NTSTATUS status = STATUS_SUCCESS; BOOL fSuccess = FALSE; // // Double-initialization isn't a bad thing, but it's frowned on. // ASSERT(m_StatusHandle == NULL); if (m_StatusHandle != NULL) return TRUE; InitializeCriticalSection(&m_CSection); // // Register this service as owning the service status // m_StatusHandle = RegisterServiceCtrlHandler(pcwszServiceName, pHandler); if (m_StatusHandle == NULL) { goto Failure; } // // Set the initial state of the world // ZeroMemory(static_cast<SERVICE_STATUS*>(this), sizeof(SERVICE_STATUS)); this->dwServiceType = dwServiceType; this->dwCurrentState = dwInitialState; this->dwControlsAccepted = dwControlsAccepted; if (!SetServiceStatus(m_StatusHandle, this)) { goto Failure; } return TRUE; Failure: { const DWORD dwLastError = ::GetLastError(); DeleteCriticalSection(&m_CSection); m_StatusHandle = NULL; SetLastError(dwLastError); } return FALSE; } BOOL CServiceStatus::SetServiceState( DWORD dwStatus, DWORD dwCheckpoint ) { BOOL fSuccess = FALSE; EnterCriticalSection(&m_CSection); __try { if (m_StatusHandle != NULL) { this->dwCurrentState = dwStatus; if (dwCheckpoint != 0xFFFFFFFF) { this->dwCheckPoint = dwCheckpoint; } fSuccess = SetServiceStatus(m_StatusHandle, this); } } __finally { LeaveCriticalSection(&m_CSection); } return fSuccess; } // // In-place construction // bool CServiceStatus::Construct( CServiceStatus *&pServiceStatusTarget ) { ASSERT(pServiceStatusTarget == NULL); return (pServiceStatusTarget = new CServiceStatus) != NULL; } EXTERN_C HANDLE g_hFakeServiceControllerThread = INVALID_HANDLE_VALUE; EXTERN_C DWORD g_dwFakeServiceControllerThreadId = 0; EXTERN_C PSVCHOST_GLOBAL_DATA g_pGlobalServiceData = NULL; BYTE g_rgbServiceStatusStorage[sizeof(CServiceStatus)]; EXTERN_C CServiceStatus *g_pServiceStatus = NULL; // // The service host will call this to send in API callbacks // VOID SvchostPushServiceGlobals( PSVCHOST_GLOBAL_DATA pGlobals ) { ASSERT(g_pGlobalServiceData == NULL); g_pGlobalServiceData = pGlobals; } PVOID operator new(size_t cb, PVOID pv) { return pv; } // // Control handler for service notifications // VOID ServiceHandler( DWORD dwControlCode ) { return; } #define CHECKPOINT_ZERO (0) #define CHECKPOINT_RPC_STARTED (1) // // Stop the service with an error code, ERROR_SUCCESS for a successful stoppage // VOID ShutdownService( DWORD dwLastError ) { return; } // // Where the fun starts // VOID WINAPI ServiceMain( DWORD dwServiceArgs, LPWSTR lpServiceArgList[] ) { NTSTATUS status = STATUS_SUCCESS; // // svchost must have given us some global data before we got to this point. // ASSERT(g_pGlobalServiceData != NULL); ASSERT(g_pServiceStatus == NULL); g_pServiceStatus = new (g_rgbServiceStatusStorage) CServiceStatus; if (!g_pServiceStatus->Initialize( SXS_STORE_SERVICE_NAME, ServiceHandler, SERVICE_WIN32, SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE, SERVICE_START_PENDING)) { DebugPrint(DBGPRINT_LVL_ERROR, "Can't start service status handler, error 0x%08lx\n", ::GetLastError()); } // // Go initialize RPC, and register our interface. If this fails, we shut down. // status = g_pGlobalServiceData->StartRpcServer( SXS_STORE_SERVICE_NAME, SxsStoreManager_ServerIfHandle); if (!NT_SUCCESS(status)) { ShutdownService(status); return; } // // Tell the world that we're off and running // g_pServiceStatus->SetServiceState(SERVICE_RUNNING); return; } DWORD WINAPI FakeServiceController(PVOID pvCookie); // // This stub will start a dispatch thread, and then call into the // service main function // BOOL FakeRunningAsService() { // // Create a thread running the service dispatch function, and then call // the service main function to get things rolling // g_hFakeServiceControllerThread = CreateThread( NULL, 0, FakeServiceController, 0, 0, &g_dwFakeServiceControllerThreadId); if (g_hFakeServiceControllerThread == NULL) { return FALSE; } ServiceMain(0, NULL); return TRUE; } VOID __cdecl wmain(INT argc, WCHAR** argv) { SERVICE_TABLE_ENTRYW SxsGacServiceEntries[] = { { SXS_STORE_SERVICE_NAME, ServiceMain }, { NULL, NULL } }; BOOL RunningAsService = TRUE; BOOL fSuccess = FALSE; if (argc > 1 && (lstrcmpiW(argv[1], L"notservice") == 0)) { RunningAsService = FALSE; } if (RunningAsService) { fSuccess = StartServiceCtrlDispatcherW(SxsGacServiceEntries); if (!fSuccess) { const DWORD dwError = ::GetLastError(); DebugPrint(DBGPRINT_LVL_ERROR, "Failed starting service dispatch, error %ld\n", dwError); } } else { fSuccess = FakeRunningAsService(); if (!fSuccess) { const DWORD dwError = ::GetLastError(); DebugPrint(DBGPRINT_LVL_ERROR, "Failed faking service startup, error %ld\n", dwError); } } return; }
22.472527
113
0.623961
npocmaka
2bb450124612e631b02f7d839b2f37920171d2fc
6,043
cpp
C++
Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/m1EasingSplines.cpp
polarpathgames/Polar-Path
cf0eed03bbd6478c4fdd1eb074f48a2ceb78e0d6
[ "MIT" ]
9
2019-03-05T07:26:04.000Z
2019-10-09T15:57:45.000Z
Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/m1EasingSplines.cpp
polarpathgames/Polar-Path
cf0eed03bbd6478c4fdd1eb074f48a2ceb78e0d6
[ "MIT" ]
114
2019-03-10T09:35:12.000Z
2019-06-10T21:39:12.000Z
Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/m1EasingSplines.cpp
polarpathgames/Polar-Path
cf0eed03bbd6478c4fdd1eb074f48a2ceb78e0d6
[ "MIT" ]
3
2019-02-25T16:12:40.000Z
2019-11-19T20:48:06.000Z
#include "p2Defs.h" #include "p2Log.h" #include "App.h" #include "m1Input.h" #include "m1Textures.h" #include "m1Render.h" #include "m1MenuManager.h" #include "m1Window.h" #include "m1Map.h" #include "m1EasingSplines.h" #include <string> #include "p2Log.h" #include "Brofiler/Brofiler.h" m1EasingSplines::m1EasingSplines() : m1Module() { name.assign("easingsplines"); } // Destructor m1EasingSplines::~m1EasingSplines() { } // Called each loop iteration bool m1EasingSplines::Update(float dt) { BROFILER_CATEGORY("UpdateEasingSplines", Profiler::Color::Purple); std::list<EaseSplineInfo*>::iterator item = easing_splines.begin(); for (; item != easing_splines.end(); ++item) { if (*item != nullptr) { if (!(*item)->Update(dt)) { delete(*item); (*item) = nullptr; } } } easing_splines.remove(nullptr); return true; } // Called before quitting bool m1EasingSplines::CleanUp() { LOG("Freeing scene"); std::list<EaseSplineInfo*>::iterator item = easing_splines.begin(); for (; item != easing_splines.end(); ++item) { if (*item != nullptr) { delete(*item); (*item) = nullptr; } } easing_splines.clear(); return true; } EaseSplineInfo* m1EasingSplines::CreateSpline(int * position, const int target_position, const float time_to_travel, TypeSpline type, std::function<void()> fn) { std::list <EaseSplineInfo*>::iterator item = easing_splines.begin(); for (; item != easing_splines.end(); ++item) { if ((*item) != nullptr && (*item)->position == position) { (*item)->to_delete = true; break; } } EaseSplineInfo* info = DBG_NEW EaseSplineInfo(position, target_position, time_to_travel, type, fn); if (info != nullptr) easing_splines.push_back(info); else LOG("Could not create the Spline..."); return info; } bool EaseSplineInfo::Update(float dt) { bool ret = true; float time_passed = SDL_GetTicks() - time_started; if (time_passed < time_to_travel && !to_delete) { switch (type) { case EASE: { *position = ease_function.Ease(time_passed, initial_position, distance_to_travel, time_to_travel); } break; case EASE_OUT_QUINT: { *position = ease_function.EaseOutQuint(time_passed, initial_position, distance_to_travel, time_to_travel); } break; case EASE_IN_OUT_BACK: { *position = ease_function.EaseInOutBack(time_passed, initial_position, distance_to_travel, time_to_travel); } break; case EASE_IN_BACK: { *position = ease_function.EaseInBack(time_passed, initial_position, distance_to_travel, time_to_travel); } break; case EASE_OUT_BACK: { *position = ease_function.EaseOutBack(time_passed, initial_position, distance_to_travel, time_to_travel); } break; case EASE_IN_CUBIC: { *position = ease_function.EaseInCubic(time_passed, initial_position, distance_to_travel, time_to_travel); } break; case EASE_OUT_CUBIC: { *position = ease_function.EaseOutCubic(time_passed, initial_position, distance_to_travel, time_to_travel); } break; case EASE_OUT_BOUNCE: { *position = ease_function.EaseOutBounce(time_passed, initial_position, distance_to_travel, time_to_travel); } break; default: break; } } else { if (fn != nullptr) this->fn(); to_delete = true; ret = false; } return ret; } int EaseFunctions::EaseOutQuint(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { return distance_to_travel * ((time_passed = time_passed / time_to_travel - 1)*time_passed*time_passed*time_passed*time_passed + 1) + initial_position; } int EaseFunctions::Ease(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { return distance_to_travel * (time_passed / time_to_travel) + initial_position; } int EaseFunctions::EaseInOutBack(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { float s = 1.70158f; if ((time_passed /= time_to_travel / 2) < 1) { return distance_to_travel / 2 * (time_passed*time_passed*(((s *= (1.525f)) + 1)*time_passed - s)) + initial_position; } else { float postFix = time_passed -= 2; return distance_to_travel / 2 * ((postFix)*time_passed*(((s *= (1.525f)) + 1)*time_passed + s) + 2) + initial_position; } } int EaseFunctions::EaseInBack(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { float s = 2.70158f; float postFix = time_passed /= time_to_travel; return distance_to_travel * (postFix)*time_passed*((s + 1)*time_passed - s) + initial_position; } int EaseFunctions::EaseOutBack(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { float s = 1.10158f; return distance_to_travel * ((time_passed = time_passed / time_to_travel - 1)*time_passed*((s + 1)*time_passed + s) + 1) + initial_position; } int EaseFunctions::EaseInCubic(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { return distance_to_travel * (time_passed /= time_to_travel)*time_passed*time_passed + initial_position; } int EaseFunctions::EaseOutCubic(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { return distance_to_travel * ((time_passed = time_passed / time_to_travel - 1)*time_passed*time_passed + 1) + initial_position; } int EaseFunctions::EaseOutBounce(float time_passed, int initial_position, int distance_to_travel, float time_to_travel) { if ((time_passed /= time_to_travel) < (1 / 2.75f)) { return distance_to_travel * (7.5625f*time_passed*time_passed) + initial_position; } else if (time_passed < (2 / 2.75f)) { float postFix = time_passed -= (1.5f / 2.75f); return distance_to_travel * (7.5625f*(postFix)*time_passed + .75f) + initial_position; } else if (time_passed < (2.5 / 2.75)) { float postFix = time_passed -= (2.25f / 2.75f); return distance_to_travel * (7.5625f*(postFix)*time_passed + .9375f) + initial_position; } else { float postFix = time_passed -= (2.625f / 2.75f); return distance_to_travel * (7.5625f*(postFix)*time_passed + .984375f) + initial_position; } }
29.915842
159
0.730101
polarpathgames
2bb5086b377f9557b71a737d06db2a6d5f33517b
71
cpp
C++
Src/App.cpp
Kataglyphis/GraphicsEngineVulkan
5c66d5761419a6a1b1a6a0628d391d29f03fb0ad
[ "BSD-3-Clause" ]
null
null
null
Src/App.cpp
Kataglyphis/GraphicsEngineVulkan
5c66d5761419a6a1b1a6a0628d391d29f03fb0ad
[ "BSD-3-Clause" ]
null
null
null
Src/App.cpp
Kataglyphis/GraphicsEngineVulkan
5c66d5761419a6a1b1a6a0628d391d29f03fb0ad
[ "BSD-3-Clause" ]
null
null
null
#include "App.h" App::App() { } void App::run() { } App::~App() { }
5.071429
16
0.464789
Kataglyphis
2bb62a640cf30baf34c8397376008da560128338
1,209
cpp
C++
src/test.weapon.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.weapon.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.weapon.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
/** * @file test.weapon.cpp * @author Team Rogue++ * @date December 08, 2016 * * @brief Member definitions for the WeaponTest class */ #include <exception> #include <iostream> #include <string> #include <vector> #include "include/playerchar.h" #include "include/weapon.h" #include "test.testable.h" /** * @brief Tests the Weapon class. */ class WeaponTest : public Testable { public: WeaponTest(){} void test(){ comment("Commencing Weapon tests..."); try { Weapon weaponCon = Weapon(Coord(0,0)); assert(true, "Created Weapon (1)"); Weapon weaponCon2 = Weapon(Coord(0,0), Item::FLOOR, 0); assert(true, "Created Weapon (2)"); } catch (const std::exception& e) { assert(false, "Failure creating Potion"); } Weapon weapon = Weapon(Coord(0,0), Item::FLOOR, 5); weapon.setEnchantments(-1, -2); assert (weapon.isIdentified(), "Weapon Identification Test"); assert (weapon.hasEffect(Item::CURSED), "Weapon Curse Test"); assert (weapon.getName().find("/") != std::string::npos, "Get Weapon Name"); assert (weapon.getEnchantments() == std::make_pair<int, int>(-1, -2), "Get Weapon Enchantments"); comment("Finished Weapon tests."); } };
25.1875
100
0.652605
prinsij
2bbfffebeab6997db4591b2bad5db24d4f641254
5,814
cpp
C++
cpp/sec.cpp
Ypig/vergil
1fedad4a6afbd108530959275e959c4bf5ed0990
[ "MIT" ]
74
2019-10-03T07:22:47.000Z
2022-03-15T11:54:45.000Z
cpp/sec.cpp
Ypig/vergil
1fedad4a6afbd108530959275e959c4bf5ed0990
[ "MIT" ]
null
null
null
cpp/sec.cpp
Ypig/vergil
1fedad4a6afbd108530959275e959c4bf5ed0990
[ "MIT" ]
34
2019-10-05T05:08:26.000Z
2022-02-14T03:36:01.000Z
#include "sec.h" namespace tokza{ SEC_ELE::SEC_ELE() { this->head = 0; this->end = 0; this->file_hash = 0; this->mem_hash = 0; return; } SEC_ELE::~SEC_ELE() { this->head = 0; this->end = 0; this->file_hash = 0; this->mem_hash = 0; return; } SEC::SEC(CONFHANDLE& confhandle__, MDBASE& mdbase__):confhandle(confhandle__),mdbase(mdbase__) { this->flag = false; this->is_hook = 0; this->dec_conf = confhandle.get_dec_conf(); if(nullptr==dec_conf){ LOGD("FUNC::FUNC(),fail.\n"); FAIL_EXIT; } return; } SEC::~SEC() { flag = false; is_hook = 0; dec_conf = nullptr; return; } bool SEC::init() { vector<u32> vec; bool ret = this->confhandle.get_type_vec(CONF_TYPE::TYPE_SEC_ELE,vec); if(!ret){ LOGD("SEC::init(),fail.\n"); return false; } // 举例 @@type##@@head##@@end##@@filehash##(段信息) STR_UTILS su; for(auto& idx:vec){ char* dec = su.get_decconf_by_idx(this->dec_conf,idx); char* p1 = su.getpart(dec,1); char* p2 = su.getpart(dec,2); char* p3 = su.getpart(dec,3); char* p4 = su.getpart(dec,4); if (NULL == p1 || NULL == p2 || NULL == p3 || NULL == p4) { LOGD("SEC::init(),fail.\n"); return false; } SEC_TYPE sec_type = (SEC_TYPE)(su.str2num(p1)); u32 head = (u32)(su.str2num(p2)); u32 end = (u32)(su.str2num(p3)); u32 filehash = (u32)(su.str2num(p4)); if(SEC_TYPE::TYPE_DYNSYM ==sec_type){ sub_init(this->LOAD1.dynsym,head,end,filehash); } else if(SEC_TYPE::TYPE_DYNSTR ==sec_type){ sub_init(this->LOAD1.dynstr,head,end,filehash); } else if(SEC_TYPE::TYPE_HASH ==sec_type){ sub_init(this->LOAD1.hash,head,end,filehash); } else if(SEC_TYPE::TYPE_RELDYN ==sec_type){ sub_init(this->LOAD1.reldyn,head,end,filehash); } else if(SEC_TYPE::TYPE_RELPLT ==sec_type){ sub_init(this->LOAD1.relplt,head,end,filehash); } else if(SEC_TYPE::TYPE_PLT ==sec_type){ sub_init(this->LOAD1.plt,head,end,filehash); } else if(SEC_TYPE::TYPE_ARMEXTAB ==sec_type){ sub_init(this->LOAD1.arm_extab,head,end,filehash); } else if(SEC_TYPE::TYPE_ARMEXIDX ==sec_type){ sub_init(this->LOAD1.arm_exidx,head,end,filehash); } else if(SEC_TYPE::TYPE_RODATA ==sec_type){ sub_init(this->LOAD1.rodata,head,end,filehash); } else if(SEC_TYPE::TYPE_FINIARRAY ==sec_type){ sub_init(this->LOAD2.fini_array,head,end,filehash); } else if(SEC_TYPE::TYPE_INITARRAY ==sec_type){ sub_init(this->LOAD2.init_array,head,end,filehash); } else if(SEC_TYPE::TYPE_DYNAMIC ==sec_type){ sub_init(this->LOAD2.dynamic,head,end,filehash); }else{ LOGD("SEC::init(),fail.\n"); return false; }//ifelse }//for return true; } void SEC::sub_init(SEC_ELE& ele, u32 head, u32 end, u32 file_hash) { ele.head = head; ele.end = end; ele.file_hash =file_hash; return; } void SEC::get_memhash() { u32 base = this->mdbase.get_self(); sub_getmemhash(this->LOAD1.dynsym,base); sub_getmemhash(this->LOAD1.dynstr,base); sub_getmemhash(this->LOAD1.hash,base); sub_getmemhash(this->LOAD1.reldyn,base); sub_getmemhash(this->LOAD1.relplt,base); sub_getmemhash(this->LOAD1.plt,base); sub_getmemhash(this->LOAD1.arm_extab,base); sub_getmemhash(this->LOAD1.arm_exidx,base); sub_getmemhash(this->LOAD1.rodata,base); sub_getmemhashload2(this->LOAD2.fini_array,base); sub_getmemhashload2(this->LOAD2.init_array,base); sub_getmemhash(this->LOAD2.dynamic,base); return; } void SEC::sub_getmemhash(SEC_ELE& ele,u32 base) { ele.mem_hash = str_utils.membkdrhash_half(base,ele.head,ele.end); if(ele.mem_hash != ele.file_hash){ this->is_hook += IS_HOOK; LOGD("SEC::sub_getmemhash(),find sec hook.\n"); } return; } void SEC::sub_getmemhashload2(SEC_ELE& ele, u32 base) { if(ele.end <= ele.head){ ele.mem_hash = 0; return; } MEM mem; u8* addr = (u8*)(ele.head + base); u32 size = (ele.end - ele.head); u32* buf = (u32*)(mem.get(size)); u32 count = size / 4; memcpy(buf, addr, size); for (u32 k = 0; k < count; k++) { if (0 == buf[k]) continue; else buf[k] = buf[k] - base; }//for ele.mem_hash = str_utils.membkdrhash_half( 0, (u32)buf,(u32)buf + size ); if(ele.mem_hash != ele.file_hash){ this->is_hook += IS_HOOK; LOGD("SEC::sub_getmemhashload2(),find sec hook.\n"); } return; } bool SEC::check() { // 初始化 if(!this->flag){ if(!init()){ FAIL_EXIT; } this->flag = true; } // 实时计算内存hash,与预设对比后返回结果 this->is_hook = 0; get_memhash(); if( 0!=this->is_hook ){ return true; }else{ return false; } } }
31.597826
100
0.5086
Ypig
2bc2a35da628b06dec5d795ffe1a5575b375f772
3,052
cpp
C++
src/Picasso_InputParser.cpp
streeve/picasso
8e546ede7729dbb0462f5a856d06530f7cbf912c
[ "BSD-3-Clause" ]
3
2021-02-17T14:59:09.000Z
2021-09-29T23:29:52.000Z
src/Picasso_InputParser.cpp
streeve/picasso
8e546ede7729dbb0462f5a856d06530f7cbf912c
[ "BSD-3-Clause" ]
48
2021-02-17T17:24:12.000Z
2022-03-18T14:12:02.000Z
src/Picasso_InputParser.cpp
streeve/picasso
8e546ede7729dbb0462f5a856d06530f7cbf912c
[ "BSD-3-Clause" ]
5
2021-02-17T14:39:58.000Z
2021-10-05T18:42:21.000Z
/**************************************************************************** * Copyright (c) 2021 by the Picasso authors * * All rights reserved. * * * * This file is part of the Picasso library. Picasso is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <Picasso_InputParser.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/xml_parser.hpp> namespace Picasso { //---------------------------------------------------------------------------// //! Input argument constructor. InputParser::InputParser( int argc, char* argv[] ) { // Get the filename from the input. bool found_arg = false; std::string filename; for ( int n = 0; n < argc - 1; ++n ) { if ( 0 == std::strcmp( argv[n], "--picasso-input-json" ) ) { filename = std::string( argv[n + 1] ); found_arg = true; parse( filename, "json" ); break; } else if ( 0 == std::strcmp( argv[n], "--picasso-input-xml" ) ) { filename = std::string( argv[n + 1] ); found_arg = true; parse( filename, "xml" ); break; } } // Check that we found the filename. if ( !found_arg ) throw std::runtime_error( "No Picasso input file specified: --picasso-input-*type* [file name] is required.\ Where *type* can be json or xml" ); } //---------------------------------------------------------------------------// //! Filename constructor. InputParser::InputParser( const std::string& filename, const std::string& type ) { parse( filename, type ); } //---------------------------------------------------------------------------// //! Get the ptree. const boost::property_tree::ptree& InputParser::propertyTree() const { return _ptree; } //---------------------------------------------------------------------------// // Parse the field. void InputParser::parse( const std::string& filename, const std::string& type ) { // Get the filename from the input. if ( 0 == type.compare( "json" ) ) { boost::property_tree::read_json( filename, _ptree ); } else if ( 0 == type.compare( "xml" ) ) { boost::property_tree::read_xml( filename, _ptree ); } else // Check that we found the filename. { throw std::runtime_error( "Only json or xml inputs supported" ); } } //---------------------------------------------------------------------------// } // end namespace Picasso
34.681818
94
0.424967
streeve
2bc3612efa6deba48d73001ac47174f596347899
5,617
hpp
C++
lib/generated/definitions/mask/mask_neon.hpp
db-tu-dresden/TVL
051261d49f993ce5c70629526038a6f7717055ef
[ "Apache-2.0" ]
2
2022-03-21T23:17:32.000Z
2022-03-22T19:56:17.000Z
lib/generated/definitions/mask/mask_neon.hpp
db-tu-dresden/TVL
051261d49f993ce5c70629526038a6f7717055ef
[ "Apache-2.0" ]
1
2022-03-31T11:56:21.000Z
2022-03-31T11:56:21.000Z
lib/generated/definitions/mask/mask_neon.hpp
db-tu-dresden/TVL
051261d49f993ce5c70629526038a6f7717055ef
[ "Apache-2.0" ]
1
2022-03-23T08:38:49.000Z
2022-03-23T08:38:49.000Z
/*==========================================================================* * This file is part of the TVL - a template SIMD library. * * * * Copyright 2022 TVL-Team, Database Research Group TU Dresden * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *==========================================================================*/ /* * @file lib/generated/definitions/mask/mask_neon.hpp * @date 30.03.2022 * @brief Mask related primitives. Implementation for neon */ #ifndef TUD_D2RG_TVL_LIB_GENERATED_DEFINITIONS_MASK_MASK_NEON_HPP #define TUD_D2RG_TVL_LIB_GENERATED_DEFINITIONS_MASK_MASK_NEON_HPP #include "../../declarations/mask.hpp" namespace tvl { namespace details { /** * @brief: Template specialization of implementation for "to_integral". * @details: * Target Extension: neon. * Data Type: int64_t * Extension Flags: ['neon'] */ template<ImplementationDegreeOfFreedom Idof> struct to_integral_impl<simd<int64_t, neon>, Idof> { using Vec = simd< int64_t, neon >; static constexpr bool native_supported() { return false; } [[nodiscard]] TVL_NO_NATIVE_SUPPORT_WARNING TVL_FORCE_INLINE static typename Vec::base_type apply( typename Vec::mask_type vec_mask ) { static_assert( !std::is_same_v< Idof, native >, "The primitive to_integral is not supported by your hardware natively while it is forced by using native" ); return ( ( vec_mask[ 1 ] >> 62 ) & 0b10 ) | ( vec_mask[ 0 ] >> 63 ); } }; } // end of namespace details for template specialization of to_integral_impl for neon using int64_t. namespace details { /** * @brief: Template specialization of implementation for "get_msb". * @details: * Target Extension: neon. * Data Type: int64_t * Extension Flags: ['neon'] */ template<ImplementationDegreeOfFreedom Idof> struct get_msb_impl<simd<int64_t, neon>, Idof> { using Vec = simd< int64_t, neon >; static constexpr bool native_supported() { return false; } [[nodiscard]] TVL_NO_NATIVE_SUPPORT_WARNING TVL_FORCE_INLINE static typename Vec::base_type apply( typename Vec::register_type vec ) { static_assert( !std::is_same_v< Idof, native >, "The primitive get_msb is not supported by your hardware natively while it is forced by using native" ); return ( ( vec[ 1 ] >> 62 ) & 0b10 ) | ( vec[ 0 ] >> 63 ); } }; } // end of namespace details for template specialization of get_msb_impl for neon using int64_t. namespace details { /** * @brief: Template specialization of implementation for "to_vector". * @details: * Target Extension: neon. * Data Type: int64_t * Extension Flags: ['neon'] */ template<ImplementationDegreeOfFreedom Idof> struct to_vector_impl<simd<int64_t, neon>, Idof> { using Vec = simd< int64_t, neon >; static constexpr bool native_supported() { return true; } [[nodiscard]] TVL_FORCE_INLINE static typename Vec::register_type apply( typename Vec::mask_type mask ) { return vreinterpretq_s64_u64( mask ); //mask is a vector already. } }; } // end of namespace details for template specialization of to_vector_impl for neon using int64_t. namespace details { /** * @brief: Template specialization of implementation for "mask_reduce". * @details: * Target Extension: neon. * Data Type: int64_t * Extension Flags: ['neon'] */ template<ImplementationDegreeOfFreedom Idof> struct mask_reduce_impl<simd<int64_t, neon>, Idof> { using Vec = simd< int64_t, neon >; static constexpr bool native_supported() { return true; } [[nodiscard]] TVL_FORCE_INLINE static typename Vec::base_type apply( typename Vec::base_type mask ) { return mask & 0x3; } }; } // end of namespace details for template specialization of mask_reduce_impl for neon using int64_t. } // end of namespace tvl #endif //TUD_D2RG_TVL_LIB_GENERATED_DEFINITIONS_MASK_MASK_NEON_HPP
45.666667
171
0.541926
db-tu-dresden
2bc61916cabd98ca28e8a5e61c37a6f44c5753e7
223
hpp
C++
examples/glfw_opengl_es_renderer/parameters_persistency.hpp
vladimir-voinea/vr
0af18898ee512a0f94be7609e19753b92da03775
[ "MIT" ]
null
null
null
examples/glfw_opengl_es_renderer/parameters_persistency.hpp
vladimir-voinea/vr
0af18898ee512a0f94be7609e19753b92da03775
[ "MIT" ]
null
null
null
examples/glfw_opengl_es_renderer/parameters_persistency.hpp
vladimir-voinea/vr
0af18898ee512a0f94be7609e19753b92da03775
[ "MIT" ]
null
null
null
#pragma once #include <parameters.hpp> bool have_parameters_file(const std::string& path); parameters load_parameters(const std::string& path); void save_parameters(const std::string& path, const parameters& parameters);
27.875
76
0.793722
vladimir-voinea
2bc813b8772e1619ff3e931dcb0e15fe35b54154
1,051
hpp
C++
nd-coursework/books/cpp/C++Templates/traits/ifthenelse.hpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/C++Templates/traits/ifthenelse.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/C++Templates/traits/ifthenelse.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved. // See the LICENSE file in the project root for more information. // // Name: ifthenelse.hpp // Author: crdrisko // Date: 08/31/2020-20:09:37 // Description: Selecting between two type parameters based on the value of a Boolean value, based on std::conditional<> #ifndef IFTHENELSE_HPP #define IFTHENELSE_HPP // primary template: yield the second argument by default and rely on // a partial specialization to yield the third argument // if COND is false template<bool COND, typename TrueType, typename FalseType> struct IfThenElseT { using Type = TrueType; }; // partial specialization: false yields third argument template<typename TrueType, typename FalseType> struct IfThenElseT<false, TrueType, FalseType> { using Type = FalseType; }; template<bool COND, typename TrueType, typename FalseType> using IfThenElse = typename IfThenElseT<COND, TrueType, FalseType>::Type; #endif
32.84375
121
0.743102
crdrisko
2bc9ec327d7cfd0dfd9eeed6bd82811f3b4a6b20
692
cpp
C++
HDU-Code/2009 Multi-University Training Contest 1/H.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
HDU-Code/2009 Multi-University Training Contest 1/H.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
HDU-Code/2009 Multi-University Training Contest 1/H.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> #ifdef WIN32 #define LL "%I64d" #else #define LL "%lld" #endif const int MAXN = 3000001; const int Maxdata = 3000000; int g, p[MAXN]; long long phi[MAXN]; bool vis[MAXN]; int main() { phi[1] = 1; for (int i = 2; i <= Maxdata; i++) { if (!vis[i]) phi[p[++g] = i] = i - 1; for (int j = 1; i * p[j] <= Maxdata && j <= g; j++) { vis[i * p[j]] = true; if (i % p[j] == 0) { phi[i * p[j]] = phi[i] * p[j]; break; } else phi[i * p[j]] = phi[i] * phi[p[j]]; } } for (int i = 2; i <= Maxdata; i++) phi[i] += phi[i - 1]; int l, r; while (scanf("%d%d", &l, &r) == 2) { printf(LL "\n", phi[r] - phi[l - 1]); } return 0; }
18.210526
55
0.482659
PrayStarJirachi
2bca3bb76da31998ae094bb5e148962887c7bb02
523
cpp
C++
Code/Engine/Math/Vector3.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/Math/Vector3.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/Math/Vector3.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#include "Engine/Math/Vector3.hpp" #define STATIC //Do-nothing to indicate static STATIC const Vector3 Vector3::ZERO(0.f, 0.f, 0.f); STATIC const Vector3 Vector3::ONE(1.f, 1.f, 1.f); STATIC const Vector3 Vector3::UNIT_VECTOR_X(1.f, 0.f, 0.f); STATIC const Vector3 Vector3::UNIT_VECTOR_Y(0.f, 1.f, 0.f); STATIC const Vector3 Vector3::UNIT_VECTOR_Z(0.f, 0.f, 1.f); STATIC const Vector3 Vector3::RIGHT( 1.f, 0.f, 0.f); STATIC const Vector3 Vector3::UP( 0.f, 1.f, 0.f); STATIC const Vector3 Vector3::FORWARD( 0.f, 0.f, 1.f);
43.583333
59
0.711281
ntaylorbishop
2bcec88dace2a7a2c87a113d27636a436387ef60
619
cc
C++
public/test/cc/test_main.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
3
2015-05-18T14:52:47.000Z
2018-11-12T07:51:00.000Z
public/test/cc/test_main.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
null
null
null
public/test/cc/test_main.cc
room77/77up
736806fbf52a5e722e8e57ef5c248823b067175d
[ "MIT" ]
3
2015-08-04T05:58:18.000Z
2018-11-12T07:51:01.000Z
// Copyright 2012 Room77 Inc. All Rights Reserved. // Author: pramodg@room77.com (Pramod Gupta) // // The default main file that can be used to run unit tests. #include "util/init/main.h" #include "test/cc/test_main.h" extern string gFlag_init_include; int main(int argc, char** argv) { // Init the google mock framework. // This in turn inits the google test framework. testing::InitGoogleMock(&argc, argv); // Only include test inits. gFlag_init_include = "test"; // Init R77. r77::R77Init(argc, argv); int status = RUN_ALL_TESTS(); // Shutdown R77. r77::R77Shutdown(); return status; }
21.344828
60
0.694669
room77
2bcf80363a8770c67fcdb4a0143ead4f672fdaad
8,810
cc
C++
c_src/sst_file_manager.cc
k32/erlang-rocksdb
54657d3a44a09bd4357f07ecfa54b327c1033a17
[ "Apache-2.0" ]
2
2022-03-10T08:21:57.000Z
2022-03-10T14:09:33.000Z
c_src/sst_file_manager.cc
tsutsu/erlang-rocksdb
5b1b66d06539dcb5891c12e5d5ff7a16a3ef3824
[ "Apache-2.0" ]
null
null
null
c_src/sst_file_manager.cc
tsutsu/erlang-rocksdb
5b1b66d06539dcb5891c12e5d5ff7a16a3ef3824
[ "Apache-2.0" ]
1
2021-12-31T06:13:02.000Z
2021-12-31T06:13:02.000Z
// Copyright (c) 2018-2020 Benoit Chesneau // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #include <array> #include <string> #include "rocksdb/sst_file_manager.h" #include "atoms.h" #include "env.h" #include "sst_file_manager.h" #include "util.h" namespace erocksdb { ErlNifResourceType * SstFileManager::m_SstFileManager_RESOURCE(NULL); void SstFileManager::CreateSstFileManagerType( ErlNifEnv * env) { ErlNifResourceFlags flags = (ErlNifResourceFlags)(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER); m_SstFileManager_RESOURCE = enif_open_resource_type(env, NULL, "erocksdb_SstFileManager", &SstFileManager::SstFileManagerResourceCleanup, flags, NULL); return; } // SstFileManager::CreateSstFileManagerType void SstFileManager::SstFileManagerResourceCleanup(ErlNifEnv * /*env*/, void * arg) { SstFileManager* mgr_ptr = (SstFileManager *)arg; mgr_ptr->~SstFileManager(); mgr_ptr = nullptr; return; } // SstFileManager::SstFileManagerResourceCleanup SstFileManager * SstFileManager::CreateSstFileManagerResource(std::shared_ptr<rocksdb::SstFileManager> mgr) { SstFileManager * ret_ptr; void * alloc_ptr; alloc_ptr=enif_alloc_resource(m_SstFileManager_RESOURCE, sizeof(SstFileManager)); ret_ptr=new (alloc_ptr) SstFileManager(mgr); return(ret_ptr); } SstFileManager * SstFileManager::RetrieveSstFileManagerResource(ErlNifEnv * Env, const ERL_NIF_TERM & term) { SstFileManager * ret_ptr; if (!enif_get_resource(Env, term, m_SstFileManager_RESOURCE, (void **)&ret_ptr)) return NULL; return ret_ptr; } SstFileManager::SstFileManager(std::shared_ptr<rocksdb::SstFileManager> Mgr) : mgr_(Mgr) {} SstFileManager::~SstFileManager() { if(mgr_) { mgr_ = nullptr; } return; } std::shared_ptr<rocksdb::SstFileManager> SstFileManager::sst_file_manager() { auto m = mgr_; return m; } ERL_NIF_TERM NewSstFileManager( ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM argv[]) { erocksdb::ManagedEnv* env_ptr = erocksdb::ManagedEnv::RetrieveEnvResource(env,argv[0]); if(NULL==env_ptr) return enif_make_badarg(env); ErlNifUInt64 rate_bytes_per_sec = 0; double max_trash_db_ratio = 0.25; ErlNifUInt64 bytes_max_delete_chunk = 64 * 1024 * 1024; ERL_NIF_TERM head, tail; const ERL_NIF_TERM* option; int arity; tail = argv[1]; while(enif_get_list_cell(env, tail, &head, &tail)) { if (enif_get_tuple(env, head, &arity, &option) && 2 == arity) { if(option[0] == erocksdb::ATOM_DELETE_RATE_BYTES_PER_SEC) { if(!enif_get_uint64(env, option[1], &rate_bytes_per_sec)) return enif_make_badarg(env); } else if(option[0] == erocksdb::ATOM_MAX_TRASH_DB_RATIO) { if(!enif_get_double(env, option[1], &max_trash_db_ratio)) return enif_make_badarg(env); } else if(option[0] == erocksdb::ATOM_BYTES_MAX_DELETE_CHUNK) { if(!enif_get_uint64(env, option[1], &bytes_max_delete_chunk)) return enif_make_badarg(env); } else { return enif_make_badarg(env); } } else { return enif_make_badarg(env); } } rocksdb::Status status; rocksdb::SstFileManager* mgr = rocksdb::NewSstFileManager( (rocksdb::Env*)env_ptr->env(), nullptr, "", /* trash_dir, deprecated */ rate_bytes_per_sec, true, /* delete_existing_trash, deprecate */ &status, max_trash_db_ratio, bytes_max_delete_chunk ); if(!status.ok()) return error_tuple(env, ATOM_ERROR, status); std::shared_ptr<rocksdb::SstFileManager> sptr_sst_file_manager(mgr); auto mgr_ptr = SstFileManager::CreateSstFileManagerResource(sptr_sst_file_manager); // create a resource reference to send erlang ERL_NIF_TERM result = enif_make_resource(env, mgr_ptr); // clear the automatic reference from enif_alloc_resource in EnvObject enif_release_resource(mgr_ptr); sptr_sst_file_manager.reset(); sptr_sst_file_manager = nullptr; return enif_make_tuple2(env, ATOM_OK, result); } ERL_NIF_TERM ReleaseSstFileManager(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM argv[]) { SstFileManager* mgr_ptr; std::shared_ptr<rocksdb::SstFileManager> mgr; mgr_ptr = erocksdb::SstFileManager::RetrieveSstFileManagerResource(env, argv[0]); if(nullptr==mgr_ptr) return ATOM_OK; mgr = mgr_ptr->sst_file_manager(); mgr.reset(); mgr = nullptr; mgr_ptr = nullptr; return ATOM_OK; } ERL_NIF_TERM SstFileManagerFlag(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM argv[]) { SstFileManager* mgr_ptr; mgr_ptr = erocksdb::SstFileManager::RetrieveSstFileManagerResource(env, argv[0]); if(nullptr==mgr_ptr) return enif_make_badarg(env); ErlNifUInt64 ival; double dval; if(argv[1] == erocksdb::ATOM_MAX_ALLOWED_SPACE_USAGE) { if(!enif_get_uint64(env, argv[2], &ival)) return enif_make_badarg(env); mgr_ptr->sst_file_manager()->SetMaxAllowedSpaceUsage(ival); } else if (argv[1] == erocksdb::ATOM_COMPACTION_BUFFER_SIZE) { if(!enif_get_uint64(env, argv[2], &ival)) return enif_make_badarg(env); mgr_ptr->sst_file_manager()->SetCompactionBufferSize(ival); } else if (argv[1] == erocksdb::ATOM_DELETE_RATE_BYTES_PER_SEC) { if(!enif_get_uint64(env, argv[2], &ival)) return enif_make_badarg(env); mgr_ptr->sst_file_manager()->SetDeleteRateBytesPerSecond(ival); } else if (argv[1] == erocksdb::ATOM_MAX_TRASH_DB_RATIO) { if(!enif_get_double(env, argv[2], &dval)) return enif_make_badarg(env); mgr_ptr->sst_file_manager()->SetMaxTrashDBRatio(dval); } else { return enif_make_badarg(env); } return ATOM_OK; } ERL_NIF_TERM sst_file_manager_info_1( ErlNifEnv *env, SstFileManager* mgr_ptr, ERL_NIF_TERM item) { if (item == erocksdb::ATOM_TOTAL_SIZE) { return enif_make_uint64(env, mgr_ptr->sst_file_manager()->GetTotalSize()); } else if (item == erocksdb::ATOM_DELETE_RATE_BYTES_PER_SEC) { return enif_make_uint64(env, mgr_ptr->sst_file_manager()->GetDeleteRateBytesPerSecond()); } else if (item == erocksdb::ATOM_MAX_TRASH_DB_RATIO) { return enif_make_double(env, mgr_ptr->sst_file_manager()->GetMaxTrashDBRatio()); } else if (item == erocksdb::ATOM_TOTAL_TRASH_SIZE) { return enif_make_uint64(env, mgr_ptr->sst_file_manager()->GetTotalTrashSize()); } else if (item == erocksdb::ATOM_IS_MAX_ALLOWED_SPACE_REACHED) { if(mgr_ptr->sst_file_manager()->IsMaxAllowedSpaceReached()) return ATOM_TRUE; return ATOM_FALSE; } else if (item == erocksdb::ATOM_MAX_ALLOWED_SPACE_REACHED_INCLUDING_COMPACTIONS) { if(mgr_ptr->sst_file_manager()->IsMaxAllowedSpaceReachedIncludingCompactions()) return ATOM_TRUE; return ATOM_FALSE; } else { return enif_make_badarg(env); } } ERL_NIF_TERM SstFileManagerInfo(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { SstFileManager* mgr_ptr; mgr_ptr = erocksdb::SstFileManager::RetrieveSstFileManagerResource(env, argv[0]); if(nullptr==mgr_ptr) return enif_make_badarg(env); if(argc > 1) return sst_file_manager_info_1(env, mgr_ptr, argv[1]); std::array<ERL_NIF_TERM, 6> items = { erocksdb::ATOM_MAX_ALLOWED_SPACE_REACHED_INCLUDING_COMPACTIONS, erocksdb::ATOM_IS_MAX_ALLOWED_SPACE_REACHED, erocksdb::ATOM_TOTAL_TRASH_SIZE, erocksdb::ATOM_MAX_TRASH_DB_RATIO, erocksdb::ATOM_DELETE_RATE_BYTES_PER_SEC, erocksdb::ATOM_TOTAL_SIZE }; ERL_NIF_TERM info = enif_make_list(env, 0); for(const auto& item : items) { info = enif_make_list_cell( env, enif_make_tuple2(env, item, sst_file_manager_info_1(env, mgr_ptr, item)), info); } return info; } }
32.996255
97
0.673099
k32
2bd45a878db370a93f30d836942761e67ae10d86
2,563
cc
C++
content/shell/renderer/layout_test/gc_controller.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
content/shell/renderer/layout_test/gc_controller.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/shell/renderer/layout_test/gc_controller.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/renderer/layout_test/gc_controller.h" #include "gin/arguments.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebKit.h" #include "v8/include/v8.h" namespace content { gin::WrapperInfo GCController::kWrapperInfo = {gin::kEmbedderNativeGin}; // static void GCController::Install(blink::WebFrame* frame) { v8::Isolate* isolate = blink::mainThreadIsolate(); v8::HandleScope handle_scope(isolate); v8::Handle<v8::Context> context = frame->mainWorldScriptContext(); if (context.IsEmpty()) return; v8::Context::Scope context_scope(context); gin::Handle<GCController> controller = gin::CreateHandle(isolate, new GCController()); if (controller.IsEmpty()) return; v8::Handle<v8::Object> global = context->Global(); global->Set(gin::StringToV8(isolate, "GCController"), controller.ToV8()); } GCController::GCController() {} GCController::~GCController() {} gin::ObjectTemplateBuilder GCController::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<GCController>::GetObjectTemplateBuilder(isolate) .SetMethod("collect", &GCController::Collect) .SetMethod("collectAll", &GCController::CollectAll) .SetMethod("minorCollect", &GCController::MinorCollect); } void GCController::Collect(const gin::Arguments& args) { args.isolate()->RequestGarbageCollectionForTesting( v8::Isolate::kFullGarbageCollection); } void GCController::CollectAll(const gin::Arguments& args) { // In order to collect a DOM wrapper, two GC cycles are needed. // In the first GC cycle, a weak callback of the DOM wrapper is called back // and the weak callback disposes a persistent handle to the DOM wrapper. // In the second GC cycle, the DOM wrapper is reclaimed. // Given that two GC cycles are needed to collect one DOM wrapper, // more than two GC cycles are needed to collect all DOM wrappers // that are chained. Seven GC cycles look enough in most tests. for (int i = 0; i < 7; i++) { args.isolate()->RequestGarbageCollectionForTesting( v8::Isolate::kFullGarbageCollection); } } void GCController::MinorCollect(const gin::Arguments& args) { args.isolate()->RequestGarbageCollectionForTesting( v8::Isolate::kMinorGarbageCollection); } } // namespace content
35.109589
77
0.736247
kjthegod
2bd8f489ebafa3e13a9524915624eafd0bfa30b6
6,544
cpp
C++
scrabble.cpp
siweiwang24/scrabble
f8fd9e0d8738757ff0b1502cf3093e4cf2b3496e
[ "MIT" ]
null
null
null
scrabble.cpp
siweiwang24/scrabble
f8fd9e0d8738757ff0b1502cf3093e4cf2b3496e
[ "MIT" ]
null
null
null
scrabble.cpp
siweiwang24/scrabble
f8fd9e0d8738757ff0b1502cf3093e4cf2b3496e
[ "MIT" ]
null
null
null
/* Copyright 2019. Siwei Wang. Scrabble solver. */ #include <algorithm> #include <fstream> #include <iostream> #include <map> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> using std::cin; using std::cout; using std::ifstream; using std::ios_base; using std::map; using std::string; using std::unordered_map; using std::unordered_set; using std::vector; using std::is_integral; using std::runtime_error; using std::sort; using std::transform; /** * A power function for integers. * Avoids floating point ambiguity. * @param base The base of the power. * @param exponent The power to raise to. * @returns base^exponent. */ template <typename T> T power(T base, T exponent); /** * Applies mask to string. * @param original The full string. * @param bits The values to take. * @returns The masked original string. */ string subset(const string &original, uint64_t bits); /** * Generates the in-order power set of the line string. * Complexity O(2^n). * @param line The full set to generate a power set of. * @returns The power set of line. */ unordered_set<string> generate_power_set(const string &line); /** * Ensures command line arguments are valid. Retrieves input from * the list of all words and returns a sorted dictionary. * @param argc The number of arguments. * @param argv The argument list. * @returns Validated command line arguments. */ unordered_map<string, vector<string>> get_input(int argc, char **argv); /** * Removes non alphanumeric characters and sets everything to lower case. * @param line The original input line. * @returns A cleaned up line. */ string process_line(string line); /** * Finds the possible words in the dictionary that matches pset. * @param pset A set of words. * @param dict The reference dictionary. * @returns The subset of pset containing the possible words in the dictionary. */ vector<string> possible_words( const unordered_set<string> &pset, const unordered_map<string, vector<string>> &dict); /** * Buckets strings by their length. * @param possible A list of words. * @returns A mapping of lengths to word lists. */ map<size_t, vector<string>> categorize_lengths(const vector<string> &possible); /** * Returns the longest possible words. */ vector<string> longest(const vector<string> &possible); int main(int argc, char **argv) { ios_base::sync_with_stdio(false); auto dict = get_input(argc, argv); // Read line by line from standard input. for (string line; getline(cin, line);) { cout << "\nORIGINAL INPUT: " << line << '\n'; const auto processed = process_line(line); // There are 64 bits in a uint64_t type. if (processed.length() > 64) { throw runtime_error("Lines can have at most 64 characters."); } // Generate the power set of line. unordered_set<string> pset = generate_power_set(processed); // Keep track of possible words and the longest/shortest lengths. const auto possible = possible_words(pset, dict); if (possible.empty()) { cout << "\nNO WORDS CAN BE FORMED USING THESE LETTERS.\n"; continue; } const auto cat_len = categorize_lengths(possible); // Print possible words. cout << "\nTHERE ARE " << possible.size() << " POSSIBLE WORD(S) USING THESE LETTERS.\n"; for (const auto &len_vec : cat_len) { cout << '\t' << len_vec.second.size() << " OF LENGTH " << len_vec.first << ": "; for (const auto &word : len_vec.second) { cout << word << ' '; } cout << '\n'; } cout << '\n'; } } template <typename T> T power(T base, T exponent) { static_assert(is_integral<T>::value); if (exponent == 0) return 1; if (exponent == 1) return base; auto tmp = power(base, exponent / 2); auto tmp_sq = tmp * tmp; return exponent % 2 == 0 ? tmp_sq : base * tmp_sq; } string subset(const string &original, uint64_t bits) { string substring; // Check up to n bits. for (uint64_t j = 0; j < original.length(); ++j) { // If bit j is 1, we include the j th letter if (bits & (1 << j)) substring.push_back(original[j]); } return substring; } unordered_set<string> generate_power_set(const string &line) { // To get the power set, we iterate over the binary numbers from 0 to 2^n - 1. const uint64_t n = line.size(); const uint64_t two_pow_n = power(static_cast<uint64_t>(2), n); unordered_set<string> pset; pset.reserve(two_pow_n); for (uint64_t i = 0; i < two_pow_n; ++i) { pset.emplace(subset(line, i)); } return pset; } unordered_map<string, vector<string>> get_input(int argc, char **argv) { if (argc != 2) { throw runtime_error( "Error: usage ./scrabble words_file < strings_file > output_file"); } // Open up the words file. ifstream fin(argv[1]); // Initialize the word dictionary and insert strings. unordered_map<string, vector<string>> dict; for (string word; fin >> word;) { // Use sorted word as key. string key = word; sort(key.begin(), key.end()); dict[key].emplace_back(word); } return dict; } string process_line(string line) { // Get rid of anything that is not a letter. line.erase( remove_if(line.begin(), line.end(), [](char c) { return !isalpha(c); }), line.end()); transform(line.begin(), line.end(), line.begin(), ::tolower); // Sort line in alphabetical format. sort(line.begin(), line.end()); return line; } vector<string> possible_words( const unordered_set<string> &pset, const unordered_map<string, vector<string>> &dict) { vector<string> possible; /** * Loop over possible subsets and see which * are contained in the dictionary. */ for (const auto &str : pset) { if (dict.find(str) == dict.end()) continue; const auto &words = dict.at(str); // Otherwise, the dictionary contains this substring. possible.insert(possible.end(), words.begin(), words.end()); } return possible; } map<size_t, vector<string>> categorize_lengths(const vector<string> &possible) { map<size_t, vector<string>> cat_len; for (const auto &word : possible) { cat_len[word.size()].emplace_back(word); } for (auto &len_vec : cat_len) { sort(len_vec.second.begin(), len_vec.second.end()); } return cat_len; }
28.576419
81
0.646699
siweiwang24
2bde43f65ef5fa046d20c5ad721e68d5144cad57
707
cpp
C++
biblioteka/src/model/Service.cpp
aantczakpiotr/OOP-final-project
9559e797f4b98e88a6a97ef39ea6a8a4b67808b2
[ "MIT" ]
null
null
null
biblioteka/src/model/Service.cpp
aantczakpiotr/OOP-final-project
9559e797f4b98e88a6a97ef39ea6a8a4b67808b2
[ "MIT" ]
null
null
null
biblioteka/src/model/Service.cpp
aantczakpiotr/OOP-final-project
9559e797f4b98e88a6a97ef39ea6a8a4b67808b2
[ "MIT" ]
null
null
null
#include <sstream> #include "Service.hpp" #include "ItemException.hpp" Service::Service(double price, int durationInDays) : Item(price), durationInDays(durationInDays) { if (durationInDays < 0) { throw ItemException("Duration cannot be set to 0 or negative, provided: " + std::to_string(durationInDays)); } } int Service::getDurationInDays() const { return durationInDays; } std::string Service::itemInfo() { std::ostringstream stringStream; stringStream << ", duration: " << durationInDays << " days"; return Item::itemInfo() + stringStream.str(); } double Service::getPrice() const { return Item::getPrice() * durationInDays; } Service::~Service() = default;
25.25
116
0.69024
aantczakpiotr
2bde4f01591cbba2ad10e2ae236f67e3c7091b19
7,407
cpp
C++
sample/src/DX12/PSDownsampler.cpp
ColleenKeegan/FidelityFX-SPD
7c796c6d9fa6a9439e3610478148cfd742d97daf
[ "MIT" ]
92
2020-05-11T18:33:09.000Z
2022-03-28T14:17:36.000Z
sample/src/DX12/PSDownsampler.cpp
adv-sw/FidelityFX-SPD
254099a5111dbcbd9b02f629a55991789ec5a9d0
[ "MIT" ]
4
2020-06-03T19:05:47.000Z
2021-03-23T17:38:42.000Z
sample/src/DX12/PSDownsampler.cpp
adv-sw/FidelityFX-SPD
254099a5111dbcbd9b02f629a55991789ec5a9d0
[ "MIT" ]
17
2020-08-18T04:12:37.000Z
2022-03-29T23:27:20.000Z
// SPDSample // // Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved. // 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 "stdafx.h" #include "base/Device.h" #include "base/DynamicBufferRing.h" #include "base/StaticBufferPool.h" #include "base/UploadHeap.h" #include "base/Texture.h" #include "base/Imgui.h" #include "base/Helper.h" #include "PSDownsampler.h" namespace CAULDRON_DX12 { void PSDownsampler::OnCreate( Device *pDevice, UploadHeap *pUploadHeap, ResourceViewHeaps *pResourceViewHeaps, DynamicBufferRing *pConstantBufferRing, StaticBufferPool *pStaticBufferPool ) { m_pDevice = pDevice; m_pStaticBufferPool = pStaticBufferPool; m_pResourceViewHeaps = pResourceViewHeaps; m_pConstantBufferRing = pConstantBufferRing; // Use helper class to create the fullscreen pass // D3D12_STATIC_SAMPLER_DESC SamplerDesc = {}; SamplerDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; SamplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; SamplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; SamplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; SamplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; SamplerDesc.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; SamplerDesc.MinLOD = 0.0f; SamplerDesc.MaxLOD = D3D12_FLOAT32_MAX; SamplerDesc.MipLODBias = 0; SamplerDesc.MaxAnisotropy = 1; SamplerDesc.ShaderRegister = 0; SamplerDesc.RegisterSpace = 0; SamplerDesc.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; m_cubeTexture.InitFromFile(pDevice, pUploadHeap, "..\\media\\envmaps\\papermill\\specular.dds", true, 1.0f, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); pUploadHeap->FlushAndFinish(); m_downsample.OnCreate(pDevice, "PSDownsampler.hlsl", m_pResourceViewHeaps, m_pStaticBufferPool, 1, 1, &SamplerDesc, m_cubeTexture.GetFormat()); // Allocate descriptors for the mip chain // for (uint32_t slice = 0; slice < m_cubeTexture.GetArraySize(); slice++) { for (uint32_t i = 0; i < m_cubeTexture.GetMipCount() - 1; i++) { m_pResourceViewHeaps->AllocCBV_SRV_UAVDescriptor(1, &m_mip[slice * (m_cubeTexture.GetMipCount() - 1) + i].m_SRV); m_pResourceViewHeaps->AllocRTVDescriptor(1, &m_mip[slice * (m_cubeTexture.GetMipCount() - 1) + i].m_RTV); m_cubeTexture.CreateSRV(0, &m_mip[slice * (m_cubeTexture.GetMipCount() - 1) + i].m_SRV, i, 1, slice); m_cubeTexture.CreateRTV(0, &m_mip[slice * (m_cubeTexture.GetMipCount() - 1) + i].m_RTV, i + 1, 1, slice); } } for (uint32_t slice = 0; slice < m_cubeTexture.GetArraySize(); slice++) { for (uint32_t mip = 0; mip < m_cubeTexture.GetMipCount(); mip++) { m_pResourceViewHeaps->AllocCBV_SRV_UAVDescriptor(1, &m_imGUISRV[slice * m_cubeTexture.GetMipCount() + mip]); m_cubeTexture.CreateSRV(0, &m_imGUISRV[slice * m_cubeTexture.GetMipCount() + mip], mip, 1, slice); } } } void PSDownsampler::OnDestroy() { m_cubeTexture.OnDestroy(); m_downsample.OnDestroy(); } void PSDownsampler::Draw(ID3D12GraphicsCommandList *pCommandList) { UserMarker marker(pCommandList, "PSDownsampler"); // downsample // for (uint32_t slice = 0; slice < m_cubeTexture.GetArraySize(); slice++) { for (uint32_t i = 0; i < m_cubeTexture.GetMipCount() - 1; i++) { pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_cubeTexture.GetResource(), D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET, slice * m_cubeTexture.GetMipCount() + i + 1)); pCommandList->OMSetRenderTargets(1, &m_mip[slice * (m_cubeTexture.GetMipCount() - 1) + i].m_RTV.GetCPU(), true, NULL); SetViewportAndScissor(pCommandList, 0, 0, m_cubeTexture.GetWidth() >> (i + 1), m_cubeTexture.GetHeight() >> (i + 1)); cbDownsample* data; D3D12_GPU_VIRTUAL_ADDRESS constantBuffer; m_pConstantBufferRing->AllocConstantBuffer(sizeof(cbDownsample), (void**)&data, &constantBuffer); data->outWidth = (float)(m_cubeTexture.GetWidth() >> (i + 1)); data->outHeight = (float)(m_cubeTexture.GetHeight() >> (i + 1)); data->invWidth = 1.0f / (float)(m_cubeTexture.GetWidth() >> i); data->invHeight = 1.0f / (float)(m_cubeTexture.GetHeight() >> i); data->slice = slice; m_downsample.Draw(pCommandList, 1, &m_mip[slice * (m_cubeTexture.GetMipCount() - 1) + i].m_SRV, constantBuffer); pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_cubeTexture.GetResource(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, slice * m_cubeTexture.GetMipCount() + i + 1)); } } } void PSDownsampler::GUI(int *pSlice) { bool opened = true; std::string header = "Downsample"; ImGui::Begin(header.c_str(), &opened); if (ImGui::CollapsingHeader("PS", ImGuiTreeNodeFlags_DefaultOpen)) { const char* sliceItemNames[] = { "Slice 0", "Slice 1", "Slice 2", "Slice 3", "Slice 4", "Slice 5" }; ImGui::Combo("Slice of Cube Texture", pSlice, sliceItemNames, _countof(sliceItemNames)); for (uint32_t i = 0; i < m_cubeTexture.GetMipCount(); i++) { ImGui::Image((ImTextureID)&m_imGUISRV[*pSlice * m_cubeTexture.GetMipCount() + i], ImVec2(static_cast<float>(512 >> i), static_cast<float>(512 >> i))); } } ImGui::End(); } }
44.620482
166
0.63575
ColleenKeegan
2be5512eed93e3ee439ebb3537d8988fd766027e
1,451
cpp
C++
test cases/frameworks/9 wxwidgets/wxprog.cpp
kira78/meson
0ae840656c5b87f30872072aa8694667c63c96d2
[ "Apache-2.0" ]
4,047
2015-06-18T10:36:48.000Z
2022-03-31T09:47:02.000Z
test cases/frameworks/9 wxwidgets/wxprog.cpp
kira78/meson
0ae840656c5b87f30872072aa8694667c63c96d2
[ "Apache-2.0" ]
8,206
2015-06-14T12:20:48.000Z
2022-03-31T22:50:37.000Z
test cases/frameworks/9 wxwidgets/wxprog.cpp
kira78/meson
0ae840656c5b87f30872072aa8694667c63c96d2
[ "Apache-2.0" ]
1,489
2015-06-27T04:06:38.000Z
2022-03-29T10:14:48.000Z
#include"mainwin.h" wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(ID_Hello, MyFrame::OnHello) EVT_MENU(wxID_EXIT, MyFrame::OnExit) EVT_MENU(wxID_ABOUT, MyFrame::OnAbout) wxEND_EVENT_TABLE() bool MyApp::OnInit() { MyFrame *frame = new MyFrame("Hello World", wxPoint(50, 50), wxSize(450, 340)); frame->Show( true ); return true; } MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, pos, size) { wxMenu *menuFile = new wxMenu; menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item"); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxMenu *menuHelp = new wxMenu; menuHelp->Append(wxID_ABOUT); wxMenuBar *menuBar = new wxMenuBar; menuBar->Append(menuFile, "&File"); menuBar->Append(menuHelp, "&Help"); SetMenuBar(menuBar); CreateStatusBar(); SetStatusText("This is status." ); } void MyFrame::OnExit(wxCommandEvent& event) { Close( true ); } void MyFrame::OnAbout(wxCommandEvent& event) { //wxMessageBox("Some text", wxOK | wxICON_INFORMATION); } void MyFrame::OnHello(wxCommandEvent& event) { wxLogMessage("Some more text."); } #if 0 wxIMPLEMENT_APP(MyApp); #else // Don't open a window because this is an unit test and needs to // run headless. int main(int, char **) { wxString name("Some app"); wxPoint p(0, 0); wxSize s(100, 100); return 0; } #endif
25.45614
81
0.694004
kira78
2be7a2698e1649e99974b65d08258edd176c0c86
13,006
cpp
C++
src/films/transientfilm.cpp
klein-j/transient_pbrt
71d1e3223521a985c93afc5a2e21833afe9f24d7
[ "BSD-2-Clause" ]
null
null
null
src/films/transientfilm.cpp
klein-j/transient_pbrt
71d1e3223521a985c93afc5a2e21833afe9f24d7
[ "BSD-2-Clause" ]
null
null
null
src/films/transientfilm.cpp
klein-j/transient_pbrt
71d1e3223521a985c93afc5a2e21833afe9f24d7
[ "BSD-2-Clause" ]
null
null
null
#include "transientfilm.h" #include "paramset.h" #include "imageio.h" #include "stats.h" #include "TransientImage.hpp" #include "util.h" #include <array> #include <fstream> #include <sstream> namespace pbrt { TransientFileMetaData g_TFMD; STAT_MEMORY_COUNTER("Memory/Film pixels", filmPixelMemory); TransientSampleCache::TransientSample* begin(TransientSampleCache& c) { return &c.cache[0]; } TransientSampleCache::TransientSample* end(TransientSampleCache& c) { return &c.cache[0]+c.size(); } // Film Method Definitions TransientFilm::TransientFilm(const Point3i &resolution, Float tmin, Float tmax, const Bounds2f &cropWindow, std::unique_ptr<Filter> filt, Float diagonal, const std::string &filename, Float maxSampleLuminance) : fullResolution(resolution), tmin(tmin), tmax(tmax), diagonal(diagonal * .001), filter(std::move(filt)), filename(filename), maxSampleLuminance(maxSampleLuminance) { // Compute film image bounds croppedPixelBounds = Bounds2i(Point2i(std::ceil(fullResolution.x * cropWindow.pMin.x), std::ceil(fullResolution.y * cropWindow.pMin.y)), Point2i(std::ceil(fullResolution.x * cropWindow.pMax.x), std::ceil(fullResolution.y * cropWindow.pMax.y))); LOG(INFO) << "Created film with full resolution " << resolution << ". Crop window of " << cropWindow << " -> croppedPixelBounds " << croppedPixelBounds; // Allocate film image storage pixelIntensities.resize(croppedPixelBounds.Area() * fullResolution.z); pixelWeights.resize(croppedPixelBounds.Area()); filmPixelMemory += croppedPixelBounds.Area() * fullResolution.z * sizeof(Float); // the intensities filmPixelMemory += croppedPixelBounds.Area() * sizeof(Float); // the weights // Precompute filter weight table int offset = 0; for(int y = 0; y < filterTableWidth; ++y) { for(int x = 0; x < filterTableWidth; ++x, ++offset) { Point2f p; p.x = (x + 0.5f) * filter->radius.x / filterTableWidth; p.y = (y + 0.5f) * filter->radius.y / filterTableWidth; filterTable[offset] = filter->Evaluate(p); } } } Bounds2i TransientFilm::GetSampleBounds() const { Bounds2f floatBounds(Floor(Point2f(croppedPixelBounds.pMin) + Vector2f(0.5f, 0.5f) - filter->radius), Ceil(Point2f(croppedPixelBounds.pMax) - Vector2f(0.5f, 0.5f) + filter->radius)); return (Bounds2i)floatBounds; } Bounds2f TransientFilm::GetPhysicalExtent() const { Float aspect = (Float)fullResolution.y / (Float)fullResolution.x; Float x = std::sqrt(diagonal * diagonal / (1 + aspect * aspect)); Float y = aspect * x; return Bounds2f(Point2f(-x / 2, -y / 2), Point2f(x / 2, y / 2)); } std::unique_ptr<TransientFilmTile> TransientFilm::GetFilmTile(const Bounds2i &sampleBounds) { // Bound image pixels that samples in _sampleBounds_ contribute to Vector2f halfPixel = Vector2f(0.5f, 0.5f); Bounds2f floatBounds = (Bounds2f)sampleBounds; Point2i p0 = (Point2i)Ceil(floatBounds.pMin - halfPixel - filter->radius); Point2i p1 = (Point2i)Floor(floatBounds.pMax - halfPixel + filter->radius) + Point2i(1, 1); Bounds2i tilePixelBounds = Intersect(Bounds2i(p0, p1), croppedPixelBounds); return std::unique_ptr<TransientFilmTile>(new TransientFilmTile( tilePixelBounds, fullResolution.z, tmin, tmax, filter->radius, filterTable, filterTableWidth, maxSampleLuminance)); } void TransientFilm::MergeFilmTile(std::unique_ptr<TransientFilmTile> tile) { ProfilePhase p(Prof::MergeFilmTile); VLOG(1) << "Merging film tile " << tile->pixelBounds; std::lock_guard<std::mutex> lock(mutex); for(Point2i pixel : tile->GetPixelBounds()) { // iterate over temporal dimension of pixels for(auto t=0; t<fullResolution.z; ++t) { // Merge _pixel_ into _Film::pixels_ const auto& tilePixel = tile->GetPixel({pixel.x, pixel.y, t}); auto mergePixel = GetPixel({pixel.x, pixel.y, t}); *mergePixel.intensity += *tilePixel.intensity; *mergePixel.filterWeightSum += *tilePixel.filterWeightSum; } } } void TransientFilm::WriteImage() { g_TFMD.RenderEndTime = std::chrono::system_clock::now(); // Convert image to RGB and compute final pixel values LOG(INFO) << "Converting image to RGB and computing final weighted pixel values"; // Write RGB image LOG(INFO) << "Writing image " << filename << " with bounds " << croppedPixelBounds; LibTransientImage::T01 outputImage; outputImage.header.numBins = fullResolution.z; outputImage.header.uResolution = (croppedPixelBounds.pMax-croppedPixelBounds.pMin).x; outputImage.header.vResolution = (croppedPixelBounds.pMax-croppedPixelBounds.pMin).y; outputImage.header.tmin = tmin; outputImage.header.tmax = tmax; outputImage.data.resize(croppedPixelBounds.Area() * fullResolution.z); int offset = 0; for(Point2i p : croppedPixelBounds) { for(auto t=0; t<fullResolution.z; ++t) { auto pp = Point3i(p.x, p.y, t); // this is not quite right: if different samples fall in different times bins, the total amount is higher than if they fall into the same one // we have to add weights of all time bins and divide each bin by the total amount. // but how would this be changed, if we wanted also temporal sampling? outputImage.data[offset] = *GetPixel(pp).intensity / *GetPixel(pp).filterWeightSum; ++offset; } } // add meta information: std::stringstream imageProperties; imageProperties << "\n\n\n" << "{\n" << " \"File\": {\n" << " \"MetadataVersion\": \"TransientRenderer\"\n" << " },\n" << " \n" << " \"RenderParameters\": {\n" << " \"Renderer\": \"TransientRenderer\",\n" << " \"InputFile\": \"" << g_TFMD.RenderInputFile << "\",\n" << " \"BlenderExport\": {\n" << " \"Filename\": \"" << g_TFMD.BlenderFilename << "\",\n" << " \"CurrentFrame\": " << g_TFMD.BlenderCurrentFrame << ",\n" << " \"ExportTime\": \"" << g_TFMD.ExportTime << "\"\n" << " },\n" << " \"StartTime\": \"" << FormatTime(g_TFMD.RenderStartTime) << "\",\n" << " \"EndTime\": \"" << FormatTime(g_TFMD.RenderEndTime) << "\",\n" << " \"TotalSeconds\": \"" << std::chrono::duration_cast<std::chrono::seconds>(g_TFMD.RenderEndTime-g_TFMD.RenderStartTime).count() << "\",\n" << " \"Samples\": \"" << g_TFMD.RenderSamples <<"\",\n" << " \"Cores\": \"" << g_TFMD.RenderCores <<"\"\n" << " }\n" << "}" << std::endl; outputImage.imageProperties = imageProperties.str(); outputImage.WriteFile(filename); } TransientPixelRef TransientFilm::GetPixel(const Point3i &p) { CHECK(InsideExclusive(Point2i(p.x, p.y), croppedPixelBounds)); int width = croppedPixelBounds.pMax.x - croppedPixelBounds.pMin.x; int pixelOffset = (p.x - croppedPixelBounds.pMin.x) + (p.y - croppedPixelBounds.pMin.y) * width; return {&pixelIntensities[pixelOffset*fullResolution.z + p.z], &pixelWeights[pixelOffset]}; } std::unique_ptr<TransientFilm> CreateTransientFilm(const ParamSet &params, std::unique_ptr<Filter> filter) { // Intentionally use FindOneString() rather than FindOneFilename() here // so that the rendered image is left in the working directory, rather // than the directory the scene file lives in. std::string filename = params.FindOneString("filename", ""); if(PbrtOptions.imageFile != "") { if(filename != "") { Warning( "Output filename supplied in scene description file, \"%s\", ignored " "due to filename provided on command line, \"%s\".", filename.c_str(), PbrtOptions.imageFile.c_str()); } filename = PbrtOptions.imageFile; } if(filename == "") filename = "pbrt.exr"; int xres = params.FindOneInt("xresolution", 256); int yres = params.FindOneInt("yresolution", 256); int tres = params.FindOneInt("tresolution", 32); if(PbrtOptions.quickRender) xres = std::max(1, xres / 4); if(PbrtOptions.quickRender) yres = std::max(1, yres / 4); if(PbrtOptions.quickRender) tres = std::max(1, tres / 4); Bounds2f crop(Point2f(0, 0), Point2f(1, 1)); int cwi; const Float *cr = params.FindFloat("cropwindow", &cwi); if(cr && cwi == 4) { crop.pMin.x = Clamp(std::min(cr[0], cr[1]), 0.f, 1.f); crop.pMax.x = Clamp(std::max(cr[0], cr[1]), 0.f, 1.f); crop.pMin.y = Clamp(std::min(cr[2], cr[3]), 0.f, 1.f); crop.pMax.y = Clamp(std::max(cr[2], cr[3]), 0.f, 1.f); } else if(cr) Error("%d values supplied for \"cropwindow\". Expected 4.", cwi); Float tmin = params.FindOneFloat("t_min", 0); Float tmax = params.FindOneFloat("t_max", 100); Float diagonal = params.FindOneFloat("diagonal", 35.); Float maxSampleLuminance = params.FindOneFloat("maxsampleluminance", Infinity); return std::make_unique<TransientFilm>(Point3i(xres, yres, tres), tmin, tmax, crop, std::move(filter), diagonal, filename, maxSampleLuminance); } // ------------------ Transient Film Tile ------------------------------ TransientFilmTile::TransientFilmTile(const Bounds2i &pixelBounds, unsigned int tresolution, Float tmin, Float tmax, const Vector2f &filterRadius, const Float *filterTable, int filterTableSize, Float maxSampleLuminance) : pixelBounds(pixelBounds), tresolution(tresolution), tmin(tmin), tmax(tmax), invBinSize(static_cast<Float>(tresolution)/(tmax-tmin)), filterRadius(filterRadius), invFilterRadius(1 / filterRadius.x, 1 / filterRadius.y), filterTable(filterTable), filterTableSize(filterTableSize), maxSampleLuminance(maxSampleLuminance) { pixelIntensities = std::vector<Float>(std::max(0, pixelBounds.Area()) * tresolution); pixelWeights = std::vector<Float>(std::max(0, pixelBounds.Area())); } void TransientFilmTile::AddSample(const Point2f &pFilm, TransientSampleCache& sample, Float sampleWeight) { ProfilePhase _(Prof::AddFilmSample); //if(L > maxSampleLuminance) // L = maxSampleLuminance; // Compute sample's raster bounds Point2f pFilmDiscrete = pFilm - Vector2f(0.5f, 0.5f); Point2i p0 = (Point2i)Ceil(pFilmDiscrete - filterRadius); Point2i p1 = (Point2i)Floor(pFilmDiscrete + filterRadius) + Point2i(1, 1); p0 = Max(p0, pixelBounds.pMin); p1 = Min(p1, pixelBounds.pMax); // Precompute $x$ and $y$ filter table offsets int *ifx = ALLOCA(int, p1.x - p0.x); for(int x = p0.x; x < p1.x; ++x) { Float fx = std::abs((x - pFilmDiscrete.x) * invFilterRadius.x * filterTableSize); ifx[x - p0.x] = std::min((int)std::floor(fx), filterTableSize - 1); } int *ify = ALLOCA(int, p1.y - p0.y); for(int y = p0.y; y < p1.y; ++y) { Float fy = std::abs((y - pFilmDiscrete.y) * invFilterRadius.y * filterTableSize); ify[y - p0.y] = std::min((int)std::floor(fy), filterTableSize - 1); } /* normally the weight is stored for each pixel separately and at the end, the sample sum is divided by the sum of the weights. As we have importance sampling in the temporal dimension, we store the pixel weight only for the spatial dimensions. Thus the weights of filtering the temporal dimension is immediately applied and no denominator must be stored. */ for(int y = p0.y; y < p1.y; ++y) { for(int x = p0.x; x < p1.x; ++x) { // Evaluate filter value at $(x,y)$ pixel int offset = ify[y - p0.y] * filterTableSize + ifx[x - p0.x]; Float filterWeight = filterTable[offset]; // now loop over all the sub samples for(auto& s : sample) { auto T = s.second; auto L = s.first; // same for temporal dimension auto timeBin = (T-tmin) * invBinSize; if(timeBin >= tresolution || timeBin < 0) continue; //skip these samples auto tDiscrete = timeBin - 0.5; auto t0 = static_cast<int>( ceil(tDiscrete-filterRadius.x)); auto t1 = static_cast<int>(floor(tDiscrete+filterRadius.x) + 1); t0 = std::max<int>(t0, 0); t1 = std::min<int>(t1, tresolution); // precompute temporal filter table offsets int *ift = ALLOCA(int, t1-t0); Float temporalFilterTotalWeight = 0; for(int t=t0; t<t1; ++t) { Float ft = std::abs((t - tDiscrete) * invFilterRadius.x * filterTableSize); auto offset = filterTableSize*static_cast<int>(filterTableSize/2); // to get the middle row of the filter ift[t - t0] = std::min((int)std::floor(ft), filterTableSize - 1) + offset; temporalFilterTotalWeight += filterTable[ift[t - t0]]; } auto temporalFilterTotalWeightInv = 1.0 / temporalFilterTotalWeight; for(int t=t0; t<t1; ++t) { // Update pixel values with filtered sample contribution auto pixel = GetPixel({x, y, t}); *pixel.intensity += L.y() * sampleWeight * filterWeight * filterTable[ift[t-t0]] * temporalFilterTotalWeightInv * invBinSize; } } auto pixel = GetPixel({x, y, 0}); // filter weight sum is the same for all pixels with the same x,y *pixel.filterWeightSum += filterWeight; } } } TransientPixelRef TransientFilmTile::GetPixel(const Point3i &p) { CHECK(InsideExclusive(Point2i(p.x, p.y), pixelBounds)); int width = pixelBounds.pMax.x - pixelBounds.pMin.x; int pixelOffset = (p.x - pixelBounds.pMin.x) + (p.y - pixelBounds.pMin.y) * width; return {&pixelIntensities[pixelOffset*tresolution + p.z], &pixelWeights[pixelOffset]}; } Bounds2i TransientFilmTile::GetPixelBounds() const{ return pixelBounds; } } // namespace pbrt
35.438692
145
0.687913
klein-j
2be8412cad95ef11e957aae696128ee2d30153b3
1,902
hpp
C++
aplibs/include/anumlst.hpp
pgul/fastlst
ce07baa06b0063f4c9e1374f24e67e1316ee5af4
[ "BSD-3-Clause" ]
2
2018-01-14T02:49:46.000Z
2021-04-11T11:29:11.000Z
aplibs/include/anumlst.hpp
pgul/fastlst
ce07baa06b0063f4c9e1374f24e67e1316ee5af4
[ "BSD-3-Clause" ]
null
null
null
aplibs/include/anumlst.hpp
pgul/fastlst
ce07baa06b0063f4c9e1374f24e67e1316ee5af4
[ "BSD-3-Clause" ]
1
2018-01-10T19:44:14.000Z
2018-01-10T19:44:14.000Z
/*****************************************************************************/ /* */ /* (C) Copyright 1995-1997 Alberto Pasquale */ /* */ /* A L L R I G H T S R E S E R V E D */ /* */ /*****************************************************************************/ /* */ /* This source code is NOT in the public domain and it CANNOT be used or */ /* distributed without written permission from the author. */ /* */ /*****************************************************************************/ /* */ /* How to contact the author: Alberto Pasquale of 2:332/504@fidonet */ /* Viale Verdi 106 */ /* 41100 Modena */ /* Italy */ /* */ /*****************************************************************************/ // AnumLst.hpp #include <limits.h> struct _anumlist; typedef unsigned int uint; typedef unsigned short word; class ANumLst { private: uint narea; _anumlist *anlhead, *anlcur; _anumlist **anlnext; public: ANumLst (); ~ANumLst (); void Add (word anum); word Get (int first = 0); // USHRT_MAX for no more areas };
46.390244
79
0.241325
pgul
2be86c24de1ed945b238c56ad33487081ad16110
1,722
cpp
C++
test/matrix.cpp
NiklasDallmann/math
e0610b20911923c35660a1c566008cb823e17da8
[ "Apache-2.0" ]
null
null
null
test/matrix.cpp
NiklasDallmann/math
e0610b20911923c35660a1c566008cb823e17da8
[ "Apache-2.0" ]
null
null
null
test/matrix.cpp
NiklasDallmann/math
e0610b20911923c35660a1c566008cb823e17da8
[ "Apache-2.0" ]
null
null
null
#include <chrono> #include <cmath> #include <cstdlib> #include <iostream> #include <memory> #include <matrix.hpp> #include "test.hpp" using namespace nd::math; constexpr std::size_t matrixOrder = 512u; using MatrixType = Matrix<float, matrixOrder, matrixOrder>; int main(int, char **) { { constexpr std::size_t iterations = 5u; const std::unique_ptr<MatrixType> matrix0 = std::make_unique<MatrixType>(traits::initialization::zero); const std::unique_ptr<MatrixType> matrix1 = std::make_unique<MatrixType>(traits::initialization::identity); std::unique_ptr<MatrixType> matrix2 = std::make_unique<MatrixType>(traits::initialization::zero); std::chrono::duration<double> actualDuration; benchmark(iterations, actualDuration, [&matrix0, &matrix1, &matrix2]() { mul(*matrix2, *matrix0, *matrix1); }); const double seconds = std::chrono::duration_cast<std::chrono::milliseconds>(actualDuration).count() / 1000.0; const double flop = std::pow(double(matrixOrder), 3.0); const double gflops = (double(iterations) / seconds * flop / 1.0E9); std::cout << iterations << " runs performed " << std::to_string(seconds) << " s " << std::to_string(gflops) << " GFLOPS\n"; } { const Matrix3x3_f matrix{traits::initialization::identity}; std::cout << static_cast<Matrix4x4_f>(matrix) << "\n"; } { const Vector3_f v{traits::initialization::zero}; const float s = 1.0f; std::cout << Vector4_f{s, v} << "\n"; std::cout << ColumnVector4_f{s, v.transposed()} << "\n"; } { const Matrix4x4_f m = {{1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f}}; std::cout << m << "\n"; } return EXIT_SUCCESS; }
27.774194
125
0.660859
NiklasDallmann
2be8d16505f271a9d0b742a1236714b95aa58b61
2,097
cpp
C++
ListProcessing/Polynomial.cpp
Mohitmauryagit/datastructures
df61f3f5b592dc4fe0b9d6a966b87f3348328e0a
[ "MIT" ]
8
2021-08-12T08:09:37.000Z
2021-12-30T10:45:54.000Z
ListProcessing/Polynomial.cpp
Mohitmauryagit/datastructures
df61f3f5b592dc4fe0b9d6a966b87f3348328e0a
[ "MIT" ]
7
2021-06-09T05:13:23.000Z
2022-01-24T04:47:59.000Z
ListProcessing/Polynomial.cpp
Mohitmauryagit/datastructures
df61f3f5b592dc4fe0b9d6a966b87f3348328e0a
[ "MIT" ]
4
2021-11-07T07:09:58.000Z
2022-02-08T11:43:56.000Z
#include<iostream> using namespace std; typedef struct mynode{ int coef; int pow; mynode* next; } node; void insert(node** head, int val,int pow) { if((*head)==NULL) { node* newnode=(node*)malloc(sizeof(node)); newnode->coef=val; newnode->pow=pow; newnode->next=NULL; (*head)=newnode; return; } insert(&((*head)->next),val,pow); } void showPol(node* temp) //shows polynomial { while(temp!=NULL) { cout<<temp->coef<<"x^"<<temp->pow; temp= temp->next; if(temp!=NULL) { cout<<" + "; } } cout<<endl; } void addPol(node**hd3,node* hd2, node* hd1)//add two polynomial { node* temp= (*hd3); while(hd2!=NULL) { insert(hd3,hd1->coef + hd2 ->coef, hd2->pow); hd1 = hd1->next; hd2 = hd2->next; } } void mult(int *c, int *p, int c1, int p1, int c2, int p2) { *c=c1*c2; *p= p1+p2; } void multPol(node** hd3, node* hd2, node* hd1) { node* temp= (*hd3); int a[4]={0}; while(hd2!=NULL) { node* temp=hd1; int c,p; while (temp!=NULL) { mult(&c,&p,temp->coef,temp->pow, hd2->coef, hd2->pow); cout<<c<<" "<<p<<" "; a[p]=a[p]+c; cout<<a[p]<<endl; temp=temp->next; } hd2=hd2->next; } for(int i=0; i<=4-1; i++) { insert(hd3,a[i],i); } } int main() { node* hd1=NULL; node* hd2=NULL; int c1[]={1,2,3}; int size= sizeof(c1)/sizeof(int); int c2[]={25,7,5}; int count1=0; for(int i=0; i<=size-1; i++) { insert(&hd1,c1[i],i); insert(&hd2,c2[i],i); } cout<<"*********************************ADDITION*****************"<<endl; showPol(hd1); cout<<"+"<<endl; showPol(hd2); cout<<"_______________________"<<endl; node* hd3=NULL; addPol(&hd3,hd1,hd2); showPol(hd3); node* hd4=NULL; multPol(&hd4,hd1,hd2); // node* a = mult(25,0,hd1); // showPol(a); showPol(hd4); return 0; }
18.723214
76
0.469242
Mohitmauryagit
2bea8f091bcefe22842b48d839502ee2d4f5d1f0
2,098
cpp
C++
gpu/src/GrGLIndexBuffer.cpp
blackberry/Skia
a55319dfb35814b1d7be4540646891332eac9727
[ "Apache-2.0" ]
10
2015-02-16T03:19:55.000Z
2021-06-16T04:33:37.000Z
gpu/src/GrGLIndexBuffer.cpp
blackberry/Skia
a55319dfb35814b1d7be4540646891332eac9727
[ "Apache-2.0" ]
null
null
null
gpu/src/GrGLIndexBuffer.cpp
blackberry/Skia
a55319dfb35814b1d7be4540646891332eac9727
[ "Apache-2.0" ]
13
2015-02-10T15:02:31.000Z
2021-05-25T09:29:03.000Z
/* Copyright 2011 Google Inc. Copyright (C) 2011 Research In Motion Limited. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "GrGLIndexBuffer.h" #include "GrGpuGL.h" #define GPUGL static_cast<GrGpuGL*>(getGpu()) GrGLIndexBuffer::GrGLIndexBuffer(GrGpuGL* gpu, void* ptr, size_t sizeInBytes, bool dynamic) : INHERITED(gpu, sizeInBytes, dynamic) , fPtr(ptr) , fLocked(false) { } void GrGLIndexBuffer::onRelease() { // make sure we've not been abandoned if (fPtr) { free(fPtr); GPUGL->notifyIndexBufferDelete(this); fPtr = 0; fLocked = false; } } void GrGLIndexBuffer::onAbandon() { fPtr = 0; fLocked = false; } void* GrGLIndexBuffer::lock() { fLocked = true; return fPtr; } void* GrGLIndexBuffer::lockPtr() const { return fPtr; } void GrGLIndexBuffer::unlock() { fLocked = false; } bool GrGLIndexBuffer::isLocked() const { return fLocked; } bool GrGLIndexBuffer::updateData(const void* src, size_t srcSizeInBytes) { if (srcSizeInBytes > size()) { return false; } memcpy(fPtr, src, srcSizeInBytes); return true; } bool GrGLIndexBuffer::updateSubData(const void* src, size_t srcSizeInBytes, size_t offset) { if (srcSizeInBytes + offset > size()) { return false; } memcpy((char*)fPtr + offset, src, srcSizeInBytes); return true; }
24.97619
76
0.623928
blackberry
2bf39d78e830470d56455008ab83f5ef908b0e73
412
cpp
C++
149.cpp
jonathanxqs/lintcode
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
[ "MIT" ]
1
2016-06-21T16:29:37.000Z
2016-06-21T16:29:37.000Z
149.cpp
jonathanxqs/lintcode
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
[ "MIT" ]
null
null
null
149.cpp
jonathanxqs/lintcode
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
[ "MIT" ]
null
null
null
class Solution { public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here int min=INT_MAX,rt_profit=0; for (auto const s:prices){ if (s-min>rt_profit) rt_profit=s-min; if (s<min) min=s; } return rt_profit; } }; // Total Runtime: 36 ms
17.913043
46
0.541262
jonathanxqs
2bf450f408f7ba571d335ad220b2e4a2a03550e4
885
cpp
C++
C++/Language/A Tour Of C++/StringAndRegex/Strings.cpp
prynix/learning-programming
85aea40a61fb824a2b4e142331d9ac7971fef263
[ "MIT" ]
2
2017-03-14T16:02:08.000Z
2017-05-02T13:48:18.000Z
C++/Language/A Tour Of C++/StringAndRegex/Strings.cpp
CajetanP/learning-programming
85aea40a61fb824a2b4e142331d9ac7971fef263
[ "MIT" ]
4
2021-05-20T21:10:13.000Z
2022-02-26T09:50:19.000Z
C++/Language/A Tour Of C++/StringAndRegex/Strings.cpp
CajetanP/learning-programming
85aea40a61fb824a2b4e142331d9ac7971fef263
[ "MIT" ]
1
2021-06-18T01:31:24.000Z
2021-06-18T01:31:24.000Z
#include <iostream> using std::string; using std::cout; using std::endl; string compose (const string& name, const string& domain) { return name + '@' + domain; } string name = "Cajetan Puchalski"; void m3 () { string s = name.substr (8, 9); cout << name << endl; name.replace (0, 7, "hello"); std::cout << name << std::endl; name[0] = toupper (name[0]); std::cout << name << std::endl; cout << endl; } void respond (const string& answer) { string hoho = "hoho"; if (answer == hoho) cout << "Hoho it is !" << endl; else if (answer == "yes") cout << "Yes indeed." << endl; } int main () { auto addr = compose ("cajetan.puchalski", "gmail.com"); std::cout << addr << std::endl; addr += " !"; std::cout << addr << std::endl; cout << endl; m3 (); respond ("hoho"); respond ("yes"); for (auto& c : addr) cout << c << " "; cout << endl; return 0; }
16.698113
59
0.572881
prynix
2bf96316c92cde0e864eb0da637d87e42a5c709e
14,150
cpp
C++
implementations/ugene/src/plugins/GUITestBase/src/GTUtilsDashboard.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/GUITestBase/src/GTUtilsDashboard.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/GUITestBase/src/GTUtilsDashboard.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <GTUtilsMdi.h> #include <primitives/GTTabWidget.h> #include <primitives/GTWebView.h> #include <primitives/GTWidget.h> #include <QRegularExpression> #include <QTabWidget> #include <U2Designer/Dashboard.h> #include "GTUtilsDashboard.h" namespace U2 { using namespace HI; #define GT_CLASS_NAME "GTUtilsDashboard" QString GTUtilsDashboard::getNodeSpanId(const QString &nodeId) { // It is defined in ExternalToolsWidget.js. return nodeId + "_span"; } HIWebElement GTUtilsDashboard::getCopyButton(GUITestOpStatus &os, const QString &toolRunNodeId) { const QString selector = QString("SPAN#%1 > BUTTON").arg(getNodeSpanId(toolRunNodeId)); GTGlobals::FindOptions options; options.searchInHidden = true; return GTWebView::findElementBySelector(os, getDashboardWebView(os), selector, options); } HIWebElement GTUtilsDashboard::getNodeSpan(GUITestOpStatus &os, const QString &nodeId) { const QString selector = QString("SPAN#%1").arg(getNodeSpanId(nodeId)); GTGlobals::FindOptions options; options.searchInHidden = true; return GTWebView::findElementBySelector(os, getDashboardWebView(os), selector, options); } #define GT_METHOD_NAME "clickOutputFile" QString GTUtilsDashboard::getLogUrlFromElement(GUITestOpStatus &os, const HIWebElement &element) { Q_UNUSED(os); const QString onclickFunction = element.attribute(ON_CLICK); QRegularExpression urlFetcher("openLog\\(\\\'(.*)\\\'\\)"); const QRegularExpressionMatch match = urlFetcher.match(onclickFunction); GT_CHECK_RESULT(match.hasMatch(), QString("Can't get URL with a regexp from an element: regexp is '%1', element ID is '%2', element class is '%3'") .arg(urlFetcher.pattern()) .arg(element.id()) .arg(element.attribute("class")), QString()); return match.captured(1); } #undef GT_METHOD_NAME const QString GTUtilsDashboard::TREE_ROOT_ID = "treeRoot"; const QString GTUtilsDashboard::PARENT_LI = "parent_li"; const QString GTUtilsDashboard::TITLE = "title"; const QString GTUtilsDashboard::COLLAPSED_NODE_TITLE = "Expand this branch"; const QString GTUtilsDashboard::ON_CLICK = "onclick"; WebView *GTUtilsDashboard::getDashboardWebView(HI::GUITestOpStatus &os) { Dashboard *dashboard = findDashboard(os); return dashboard == nullptr ? nullptr : dashboard->getWebView(); } QTabWidget *GTUtilsDashboard::getTabWidget(HI::GUITestOpStatus &os) { return GTWidget::findExactWidget<QTabWidget *>(os, "WorkflowTabView", GTUtilsMdi::activeWindow(os)); } QToolButton *GTUtilsDashboard::findLoadSchemaButton(HI::GUITestOpStatus &os) { Dashboard *dashboard = findDashboard(os); return dashboard == nullptr ? nullptr : dashboard->findChild<QToolButton *>("loadSchemaButton"); } const QString GTUtilsDashboard::getDashboardName(GUITestOpStatus &os, int dashboardNumber) { return GTTabWidget::getTabName(os, getTabWidget(os), dashboardNumber); } QStringList GTUtilsDashboard::getOutputFiles(HI::GUITestOpStatus &os) { QString selector = "div#outputWidget button.btn.full-width.long-text"; QList<HIWebElement> outputFilesButtons = GTWebView::findElementsBySelector(os, getDashboardWebView(os), selector, GTGlobals::FindOptions(false)); QStringList outputFilesNames; foreach (const HIWebElement &outputFilesButton, outputFilesButtons) { const QString outputFileName = outputFilesButton.toPlainText(); if (!outputFileName.isEmpty()) { outputFilesNames << outputFileName; } } return outputFilesNames; } #define GT_METHOD_NAME "clickOutputFile" void GTUtilsDashboard::clickOutputFile(GUITestOpStatus &os, const QString &outputFileName) { const QString selector = "div#outputWidget button.btn.full-width.long-text"; const QList<HIWebElement> outputFilesButtons = GTWebView::findElementsBySelector(os, getDashboardWebView(os), selector); foreach (const HIWebElement &outputFilesButton, outputFilesButtons) { QString buttonText = outputFilesButton.toPlainText(); if (buttonText == outputFileName) { click(os, outputFilesButton); return; } if (buttonText.endsWith("...")) { buttonText.chop(QString("...").length()); if (!buttonText.isEmpty() && outputFileName.startsWith(buttonText)) { click(os, outputFilesButton); return; } } } GT_CHECK(false, QString("The output file with name '%1' not found").arg(outputFileName)); } #undef GT_METHOD_NAME HIWebElement GTUtilsDashboard::findElement(HI::GUITestOpStatus &os, QString text, QString tag, bool exactMatch) { return GTWebView::findElement(os, getDashboardWebView(os), text, tag, exactMatch); } HIWebElement GTUtilsDashboard::findTreeElement(HI::GUITestOpStatus &os, QString text) { return GTWebView::findTreeElement(os, getDashboardWebView(os), text); } HIWebElement GTUtilsDashboard::findContextMenuElement(HI::GUITestOpStatus &os, QString text) { return GTWebView::findContextMenuElement(os, getDashboardWebView(os), text); } void GTUtilsDashboard::click(HI::GUITestOpStatus &os, HIWebElement el, Qt::MouseButton button) { GTWebView::click(os, getDashboardWebView(os), el, button); } bool GTUtilsDashboard::areThereNotifications(HI::GUITestOpStatus &os) { openTab(os, Overview); return GTWebView::doesElementExist(os, getDashboardWebView(os), "Notifications", "DIV", true); } QString GTUtilsDashboard::getTabObjectName(Tabs tab) { switch (tab) { case Overview: return "overviewTabButton"; case Input: return "inputTabButton"; case ExternalTools: return "externalToolsTabButton"; } return "unknown tab"; } Dashboard *GTUtilsDashboard::findDashboard(HI::GUITestOpStatus &os) { QTabWidget *tabWidget = getTabWidget(os); return tabWidget == nullptr ? nullptr : qobject_cast<Dashboard *>(tabWidget->currentWidget()); } #define GT_METHOD_NAME "openTab" void GTUtilsDashboard::openTab(HI::GUITestOpStatus &os, Tabs tab) { QWidget *dashboard = findDashboard(os); GT_CHECK(dashboard != nullptr, "Dashboard widget not found"); QString tabButtonObjectName = getTabObjectName(tab); QToolButton *tabButton = GTWidget::findExactWidget<QToolButton *>(os, tabButtonObjectName, dashboard); GT_CHECK(tabButton != nullptr, "Tab button not found: " + tabButtonObjectName); GTWidget::click(os, tabButton); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "doesTabExist" bool GTUtilsDashboard::doesTabExist(HI::GUITestOpStatus &os, Tabs tab) { QWidget *dashboard = findDashboard(os); GT_CHECK_RESULT(dashboard != nullptr, "Dashboard is not found", false); QString tabButtonObjectName = getTabObjectName(tab); QWidget *button = dashboard->findChild<QWidget *>(tabButtonObjectName); return button != nullptr && button->isVisible(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getNodeText" QString GTUtilsDashboard::getNodeText(GUITestOpStatus &os, const QString &nodeId) { return getNodeSpan(os, nodeId).toPlainText(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getChildrenNodesCount" int GTUtilsDashboard::getChildrenNodesCount(GUITestOpStatus &os, const QString &nodeId) { const QString selector = QString("UL#%1 > LI.%2 > UL").arg(nodeId).arg(PARENT_LI); GTGlobals::FindOptions options; options.failIfNotFound = false; options.searchInHidden = true; return GTWebView::findElementsBySelector(os, getDashboardWebView(os), selector, options).size(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getChildNodeId" QString GTUtilsDashboard::getChildNodeId(GUITestOpStatus &os, const QString &nodeId, int childNum) { return getDescendantNodeId(os, nodeId, {childNum}); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getDescendantNodeId" QString GTUtilsDashboard::getDescendantNodeId(GUITestOpStatus &os, const QString &nodeId, const QList<int> &childNums) { QString selector = QString("UL#%1").arg(nodeId); foreach (const int childNum, childNums) { selector += QString(" > LI:nth-of-type(%1) > UL").arg(childNum + 1); } GTGlobals::FindOptions options; options.searchInHidden = true; return GTWebView::findElementBySelector(os, getDashboardWebView(os), selector, options).id(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getChildWithTextId" QString GTUtilsDashboard::getChildWithTextId(GUITestOpStatus &os, const QString &nodeId, const QString &text) { const int childrenCount = getChildrenNodesCount(os, nodeId); QString resultChildId; QStringList quotedChildrenTexts; for (int i = 0; i < childrenCount; i++) { const QString currentChildId = getChildNodeId(os, nodeId, i); const QString childText = getNodeText(os, currentChildId); quotedChildrenTexts << "\'" + childText + "\'"; if (text == childText) { GT_CHECK_RESULT(resultChildId.isEmpty(), QString("Expected text '%1' is not unique among the node with ID '%2' children") .arg(text) .arg(nodeId), ""); resultChildId = currentChildId; } } GT_CHECK_RESULT(!resultChildId.isEmpty(), QString("Child with text '%1' not found among the node with ID '%2' children; there are children with the following texts: %3") .arg(text) .arg(nodeId) .arg(quotedChildrenTexts.join(", ")), ""); return resultChildId; } #undef GT_METHOD_NAME #define GT_METHOD_NAME "doesNodeHaveLimitationMessageNode" bool GTUtilsDashboard::doesNodeHaveLimitationMessageNode(GUITestOpStatus &os, const QString &nodeId) { const QString selector = QString("UL#%1 > LI.%2 > SPAN.limitation-message").arg(nodeId).arg(PARENT_LI); GTGlobals::FindOptions options; options.failIfNotFound = false; return !GTWebView::findElementsBySelector(os, getDashboardWebView(os), selector, options).isEmpty(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getLimitationMessageNodeText" QString GTUtilsDashboard::getLimitationMessageNodeText(GUITestOpStatus &os, const QString &nodeId) { const QString selector = QString("UL#%1 > LI.%2 > SPAN.limitation-message").arg(nodeId).arg(PARENT_LI); return GTWebView::findElementBySelector(os, getDashboardWebView(os), selector).toPlainText(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getLimitationMessageLogUrl" QString GTUtilsDashboard::getLimitationMessageLogUrl(GUITestOpStatus &os, const QString &nodeId) { const QString selector = QString("UL#%1 > LI.%2 > SPAN.limitation-message > A").arg(nodeId).arg(PARENT_LI); return getLogUrlFromElement(os, GTWebView::findElementBySelector(os, getDashboardWebView(os), selector)); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getCopyButtonSize" QSize GTUtilsDashboard::getCopyButtonSize(GUITestOpStatus &os, const QString &toolRunNodeId) { return getCopyButton(os, toolRunNodeId).geometry().size(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "clickCopyButton" void GTUtilsDashboard::clickCopyButton(GUITestOpStatus &os, const QString &toolRunNodeId) { click(os, getCopyButton(os, toolRunNodeId)); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "isNodeVisible" bool GTUtilsDashboard::isNodeVisible(GUITestOpStatus &os, const QString &nodeId) { return getNodeSpan(os, nodeId).isVisible(); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "isNodeCollapsed" bool GTUtilsDashboard::isNodeCollapsed(GUITestOpStatus &os, const QString &nodeId) { const HIWebElement nodeSpanElement = getNodeSpan(os, nodeId); return nodeSpanElement.attribute(TITLE, "") == COLLAPSED_NODE_TITLE; } #undef GT_METHOD_NAME #define GT_METHOD_NAME "collapseNode" void GTUtilsDashboard::collapseNode(GUITestOpStatus &os, const QString &nodeId) { GT_CHECK(isNodeVisible(os, nodeId), QString("SPAN of the node with ID '%1' is not visible. Some of the parent nodes are collapsed?").arg(nodeId)); GT_CHECK(!isNodeCollapsed(os, nodeId), QString("UL of the node with ID '%1' is not visible. It is already collapsed.").arg(nodeId)); click(os, getNodeSpan(os, nodeId)); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "expandNode" void GTUtilsDashboard::expandNode(GUITestOpStatus &os, const QString &nodeId) { GT_CHECK(isNodeVisible(os, nodeId), QString("SPAN of the node with ID '%1' is not visible. Some of the parent nodes are collapsed?").arg(nodeId)); GT_CHECK(isNodeCollapsed(os, nodeId), QString("UL of the node with ID '%1' is visible. It is already expanded.").arg(nodeId)); click(os, getNodeSpan(os, nodeId)); } #undef GT_METHOD_NAME #define GT_METHOD_NAME "getLogUrlFromNode" QString GTUtilsDashboard::getLogUrlFromNode(GUITestOpStatus &os, const QString &outputNodeId) { const QString logFileLinkSelector = QString("SPAN#%1 A").arg(getNodeSpanId(outputNodeId)); return getLogUrlFromElement(os, GTWebView::findElementBySelector(os, getDashboardWebView(os), logFileLinkSelector)); } #undef GT_METHOD_NAME #undef GT_CLASS_NAME } // namespace U2
40.084986
149
0.725442
r-barnes
2bff15a2f598a1e2effbb666032452d05defe259
1,657
cpp
C++
src/platform/aarch64_vm/os.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
4
2016-05-18T12:30:04.000Z
2019-07-19T20:49:23.000Z
src/platform/aarch64_vm/os.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
2
2016-02-22T14:49:18.000Z
2016-04-03T18:19:27.000Z
src/platform/aarch64_vm/os.cpp
AndreasAakesson/IncludeOS
891b960a0a7473c08cd0d93a2bba7569c6d88b48
[ "Apache-2.0" ]
1
2017-04-20T11:45:25.000Z
2017-04-20T11:45:25.000Z
#include <kernel.hpp> #include <timer.h> #include <service> #include <kernel/events.hpp> #include "platform.hpp" #define DEBUG #define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__) extern bool os_default_stdout; struct alignas(SMP_ALIGN) OS_CPU { uint64_t cycles_hlt = 0; }; static SMP::Array<OS_CPU> os_per_cpu; uint64_t os::cycles_asleep() noexcept { return PER_CPU(os_per_cpu).cycles_hlt; } uint64_t os::nanos_asleep() noexcept { return (PER_CPU(os_per_cpu).cycles_hlt * 1e6) / os::cpu_freq().count(); } extern kernel::ctor_t __stdout_ctors_start; extern kernel::ctor_t __stdout_ctors_end; void kernel::start(uint64_t fdt_addr) // boot_magic, uint32_t boot_addr) { kernel::state().cmdline = Service::binary_name(); // Initialize stdout handlers if(os_default_stdout) { os::add_stdout(&kernel::default_stdout); } kernel::run_ctors(&__stdout_ctors_start, &__stdout_ctors_end); // Print a fancy header CAPTION("#include<os> // Literally"); __platform_init(fdt_addr); } void os::block() noexcept { } __attribute__((noinline)) void os::halt() noexcept{ uint64_t cycles_before = os::Arch::cpu_cycles(); asm volatile("wfi" :::"memory"); //asm volatile("hlt #0xf000"); asm volatile( ".global _irq_cb_return_location;\n" "_irq_cb_return_location:" ); // Count sleep cycles PER_CPU(os_per_cpu).cycles_hlt += os::Arch::cpu_cycles() - cycles_before; } void os::event_loop() { Events::get(0).process_events(); do { os::halt(); Events::get(0).process_events(); } while (kernel::is_running()); MYINFO("Stopping service"); Service::stop(); MYINFO("Powering off"); __arch_poweroff(); }
21.24359
75
0.704285
jaeh
9200501f534949246d20a99262bc3ed797b432e4
40,160
cc
C++
src/Basics/Isotope.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
4
2021-03-15T10:02:13.000Z
2022-01-16T11:06:28.000Z
src/Basics/Isotope.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
1
2022-01-27T15:35:03.000Z
2022-01-27T15:35:03.000Z
src/Basics/Isotope.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
null
null
null
/* Isotope.cc ***************************************************-*-c++-*- ** ** ** G A M M A ** ** ** ** Isotope Implementation ** ** ** ** Copyright (c) 1990 ** ** Tilo Levante, Scott A. Smith ** ** Eidgenoessische Technische Hochschule ** ** Labor fur physikalische Chemie ** ** 8092 Zurich / Switzerland ** ** ** ** $Header: $ ** ** *************************************************************************/ /************************************************************************* ** ** ** Description ** ** ** ** Isotope maintains a list of isotopes. It is used as a reference ** ** for an Isotope. ** ** ** *************************************************************************/ // ---------------------------------------------------------------------------- // --------------------------- PRIVATE FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- #ifndef Isotope_cc_ // Is the file already included? # define Isotope_cc_ 1 // If no, then remember it # if defined(GAMPRAGMA) // Using the GNU compiler? # pragma implementation // Then this is the implementation # endif #include <GamGen.h> // Include OS specific stuff #include <Basics/Isotope.h> // Include the interface #include <Basics/IsotopeData.h> // Include list elements #include <Basics/StringCut.h> // Include string cutting #include <Basics/Gutils.h> // Include GAMMA errors #include <Basics/Gconstants.h> // Include GAMMA constants #include <Basics/ParamSet.h> // Include GAMMA parameter sets #include <string> // Include libstdc++ string class #include <vector> // Include libstdc++ STL vectors #include <fstream> // Include libstdc++ I/O streams #include <cmath> // Include max and min functions using std::string; // Using libstdc++ strings using std::vector; // Using libstdc++ vectors /* Note that although Isotopes is a construct of class Isotope, it must still be initialized because it is static. This helps out in library linking */ vector<IsotopeData> Isotope::Isotopes; // Set empty list double Isotope::RELFRQ1H = 400.13; // Set rel. Om(1H) // ---------------------------------------------------------------------------- // --------------------------- PRIVATE FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // i CLASS ISOTOPE ERROR HANDLING // ____________________________________________________________________________ /* Input I : Isotope (this) eidx : Error index noret : Flag for linefeed (0=linefeed) pname : Added error message for output Output none : Error message output Program execution stopped if fatal The following error messages use the defaults set in the Gutils package Case Error Message (0) Program Aborting..... (1) Problems With Input File Stream (2) Problems With Output File Stream default Unknown Error */ void Isotope::Isoerror(int eidx, int noret) const { string hdr("Isotope"); string msg; switch(eidx) { case 10: msg = string("Spin To Be Added Already Exists!"); // (10) GAMMAerror(hdr, msg, noret); break; case 33: msg = string("Not Specified From Given Parameters"); // (33) GAMMAerror(hdr,msg,noret); break; case 34: msg = string("Cannot Properly Glean From Param. Set"); // (34) GAMMAerror(hdr,msg,noret); break; case 41: msg = string("Can't Read Parameters From File"); // (41) GAMMAerror(hdr,msg,noret); break; case 42: msg = string("Can't Read Isotope From Parameter File"); // (42) GAMMAerror(hdr,msg,noret); break; default: GAMMAerror(hdr, eidx, noret); break; // Unknown Error (-1) } } void Isotope::Isoerror(int eidx, const string& pname, int noret) const { string hdr("Isotope"); string msg; switch(eidx) { case 2: msg=string("Attempted Access of Unknown Isotope ")+pname; // (2) break; case 3: msg=string("Cannot Find Parameter ") + pname; // (3) break; case 10: msg=string("Cannot Add Another Spin Of Type ") + pname + string(" Into GAMMA"); break; //(10) default: msg=string("Unknown Error - ") + pname; break; } GAMMAerror(hdr, msg, noret); } volatile void Isotope::Isofatal(int eidx) const { Isoerror(eidx, 1); // Output error message if(eidx) Isoerror(0); // State that its fatal GAMMAfatal(); // Clean exit from program } volatile void Isotope::Isofatal(int eidx, const string& pname) const { Isoerror(eidx, pname, eidx); // Output error message if(eidx) Isoerror(0); // State that its fatal GAMMAfatal(); // Clean exit from program } // ____________________________________________________________________________ // ii CLASS ISOTOPE DEALINGS WITH ISOTOPE LISTS // ____________________________________________________________________________ /* The code for this next function was generated from a program which parsed the original GAMMA file Isotopes.list. Users should keep in mind that since our Isotopes.list may be "incomplete" in that we don't have all values for all isotopes, we'll use a default value for anything that we don't know. Since most values in the list are positive, the default will be negative! In those rare cases where an isotope does have some negative values (15N for example) we'll just hope that they won't have the ISODEFVAL I've picked. If they do, just change the number for ISODEFVAL to any negative number not in the list and we'll be just fine and still know what an "undefined" value is...... Input I : A dummy isotope (this) Output void : Fills isotopes list with all spins Note : The value of RELFRQ1H is set in this routine. It assumes the first entry in the arrays (below) is the proton. Note : The value NIso is set herein too! */ // const double ISODEFVAL = -1.1e6; // Default value void Isotope::set_Isotope_list() { int NIso = 131; // Set # isotopes we know /* An array of known isotope spin Hilbert spaces (2*I+1) */ int Spins[131] = { 2, 3, 2, 2, 1, 1, 3, 4, 5, 4, 7, 4, 1, 2, 3, 2, 1, 6, 1, 2, 1, 4, 1, 4, 6, 6, 2, 2, 4, 4, 4, 4, 4, 8, 8, 6, 8, 13, 8, 4, 6, 2, 8, 4, 4, 4, 6, 4, 4, 10, 4, 2, 4, 4, 6, 4, 10, 2, 6, 10, 6, 6, 10, 6, 6, 2, 6, 2, 2, 2, 2, 10, 10, 2, 2, 6, 8, 2, 2, 6, 2, 4, 8, 4, 4, 11, 8, 6, 8, 8, 8, 8, 6, 6, 4, 4, 4, 6, 6, 8, 8, 2, 2, 6, 8, 15, 8, 10, 8, 2, 6, 6, 2, 4, 4, 4, 2, 4, 2, 4, 2, 2, 2, 10, 10, 4, 6, 4, 4, 8, 2 }; /* An array of known isotope atomic numbers (1=H, 6=C, ...) */ int Numbers[131] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 9, 10, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 19, 19, 20, 21, 22, 22, 23, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 31, 31, 32, 33, 34, 35, 37, 37, 38, 39, 40, 41, 42, 42, 43, 44, 44, 45, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 54, 54, 55, 56, 56, 57, 57, 59, 60, 60, 62, 62, 63, 63, 64, 64, 65, 66, 66, 67, 68, 69, 70, 70, 71, 71, 72, 72, 73, 74, 75, 75, 76, 76, 77, 77, 78, 79, 80, 80, 81, 81, 82, 83, 85, 89, 90, 91, 91, 92, 0 }; /* An array of known isotope atomic masses (1=1H, 2=2H, 13=13C, ...) */ int Masses[131] = { 1, 2, 3, 3, 4, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 50, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 85, 87, 87, 89, 91, 93, 95, 97, 99, 99, 101, 103, 105, 107, 109, 111, 113, 113, 115, 117, 119, 121, 123, 123, 125, 127, 129, 131, 133, 135, 137, 138, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 176, 177, 179, 181, 183, 185, 187, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 227, 229, 231, 233, 235, 0 }; /* An array of known isotope atomic weights (1H = 1.008665 g/mole, ...) */ double Weights[131] = { 1.008665, 2.0140, 3.01605, 3.01603, 4.00260, 6.01888, 6.01512, 7.01600, -1.1e6, 9.01218, 10.0129, 11.00931, 12.00000, 13.00335, 14.00307, 15.00011, 15.99491, -1.1e6, -1.1e6, 18.99840, 19.99244, 20.99395, 21.99138, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, 0.000001 }; /* An array of known isotope receptivities (based on 13C = 1) */ double Recepts[131] = { 5.68E+3, 8.21E-3, -1.1e6, 3.26E-3, -1.1e6, -1.1e6, 3.58, 1.54E+3, -1.1e6, 7.88E+1, 2.21E+1, 7.54E+2, -1.1e6, 1.00, 5.69, 2.19E-2, -1.1e6, 6.11E-2, -1.1e6, 4.73E+3, -1.1e6, 3.59E-2, -1.1e6, 5.25E+2, 1.54, 1.17E+3, 2.09, 3.77E+2, 9.73E-2, 2.02E+1, 3.77, 2.69, 3.28E-2, 5.27E-2, 1.71E+3, 8.64E-1, 1.18, 7.55E-1, 2.16E+3, 4.90E-1, 9.94E+2, 4.19E-3, 1.57E+3, 2.41E-1, 3.65E+2, 2.01E+2, 6.65E-1, 2.37E+2, 3.19E+2, 6.17E-1, 1.43E+2, 2.98, 2.26E+2, 2.77E+2, 4.34E+1, 2.77E+2, 1.07, 6.68E-1, 6.04, 2.74E+3, 2.88, 1.84, 2.13E+3, 8.30E-1, 1.56, 1.77E-1, 1.41, 1.95E-1, 2.76E-1, 6.93, 7.6, 8.38E+1, 1.89E+3, 1.95E+1, 2.52E+1, 5.20E+2, 1.11E+2, 8.90E-1, 1.25E+1, 5.30E+2, 3.18E+1, 3.31, 2.69E+2, 1.83, 4.41, 4.30E-1, 3.36E+2, 1.65E+3, 2.34, 3.70E-1, 1.26, 0.59, 4.83E+2, 4.53E+1, 2.33E-1, 4.84E-1, 3.31E+2, 4.47E-1, 1.58, 1.02E+3, 6.59E-1, 3.21, 4.44, 1.22, 1.72E+2, 5.47, 6.70E-1, 1.69E-1, 2.04E+2, 5.89E-2, 2.80E+2, 4.90E+2, 1.14E-3, 2.13, 5.36E-2, 1.16E-1, 1.91E+1, 1.43E-1, 5.42, 1.08, 2.89E+2, 7.69E+2, 1.18E+1, 7.77E+2, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, 4.95E-3, -1.1e6 }; /* An array of known isotope relative frequencies (from 1H @ 400.130 MHz) */ double RelFreqs[131] = { 400.130, 61.424, 426.791, 304.811, -1.1e6, -1.1e6, 58.883, 155.503, -1.1e6, 56.226, 42.990, 128.330, -1.1e6, 100.613, 28.913, -40.561, -1.1e6, 54.242, -1.1e6, 376.498, -1.1e6, 31.586, -1.1e6, 105.842, 24.496, 104.262, 79.494, 161.977, 30.714, 39.205, 32.635, 18.670, 10.247, 26.925, 97.200, 22.563, 22.557, 39.893, 105.246, 22.615, 99.012, 12.956, 94.939, 35.756, 106.146, 113.705, 25.036, 96.035, 122.028, 13.957, 68.514, 76.313, 100.249, 108.063, 38.633, 130.927, 17.342, 19.606, 37.196, 97.936, 26.076, 26.625, 90.061, 18.462, 20.691, 12.744, 18.310, 16.197, 18.622, 84.832, 88.741, 87.492, 87.680, 142.574, 149.212, 95.755, 51.853, 104.714, 126.241, 80.062, 110.668, 32.811, 52.481, 39.749, 44.466, 52.793, 56.522, 117.202, 21.755, 13.384, 16.517, 13.160, 99.236, 43.818, 15.281, 19.102, 90.741, 13.180, 18.338, 82.079, 11.564, 33.095, 70.475, 19.414, 45.643, 31.722, 12.484, 7.478, 47.976, 16.669, 90.129, 91.038, 9.131, 31.070, 6.874, 7.486, 85.876, 6.918, 71.667, 26.457, 228.970, 231.219, 83.459, 64.297, -1.1e6, -1.1e6, -1.1e6, -1.1e6, -1.1e6, 7.162, -263376.60322 }; /* An array of known isotope names */ string Names[87] = { "Hydrogen", "Deuterium", "Tritium", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon", "Sodium", "Magnesium", "Aluminum", "Silicon", "Phosphorus", "Sulfur", "Chlorine", "Potassium", "Calcium", "Scandium", "Titanium", "Vanadium", "Chromium", "Manganese", "Iron", "Cobalt", "Nickel", "Copper", "Zinc", "Gallium", "Germanium", "Arsenic", "Selenium", "Bromine", "Rubidium", "Strontium", "Yttrium", "Zirconium", "Niobium", "Molybdenum", "Technetium", "Ruthenium", "Rhodium", "Palladium", "Silver", "Cadmium", "Indium", "Tin", "Antimony", "Tellurium", "Iodine", "Xenon", "Cesium", "Barium", "Lanthanum", "Praseodymium", "Neodymium", "Samarium", "Europium", "Gadolinium", "Terbium", "Dysprosium", "Holmium", "Erbium", "Thulium", "Ytterbium", "Lutetium", "Hafnium", "Tantalum", "Tungsten", "Rhenium", "Osmium", "Iridium", "Platinum", "Gold", "Mercury", "Thallium", "Lead", "Bismuth", "Astatine", "Actinium", "Thorium", "Protactinium", "Uranium", "Electron" }; /* Known Isotope Indices For Previous Names Array */ int NamesIdx[131] = { 0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 10, 11, 11, 11, 12, 13, 14, 15, 16, 17, 18, 18, 19, 19, 20, 21, 22, 22, 23, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 35, 35, 36, 36, 37, 38, 39, 40, 41, 41, 42, 43, 43, 44, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 53, 53, 54, 55, 55, 56, 56, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 63, 63, 64, 65, 66, 67, 67, 68, 68, 69, 69, 70, 71, 72, 72, 73, 73, 74, 74, 75, 76, 77, 77, 78, 78, 79, 80, 81, 82, 83, 84, 84, 85, 86 }; string Elements[85] = { "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Pr", "Nd", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "At", "Ac", "Th", "Pa", "U", "e" }; int IElements[131] = { 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 8, 9, 9, 9, 10, 11, 12, 13, 14, 15, 16, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 23, 24, 25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 33, 33, 34, 34, 35, 36, 37, 38, 39, 39, 40, 41, 41, 42, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 51, 51, 52, 53, 53, 54, 54, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 61, 61, 62, 63, 64, 65, 65, 66, 66, 67, 67, 68, 69, 70, 70, 71, 71, 72, 72, 73, 74, 75, 75, 76, 76, 77, 78, 79, 80, 81, 82, 82, 83, 84 }; IsotopeData ID; // Working isotope data for(int i=0; i<NIso; i++) // Loop over all isotopes { ID._HS = Spins[i]; // Set spin Hilbert space ID._number = Numbers[i]; // Set the atomic number ID._mass = Masses[i]; // Set the atomic mass ID._weight = Weights[i]; // Set the atomic weights ID._receptivity = Recepts[i]; // Set the receptivities ID._relfreq = RelFreqs[i]; // Set the relative frequency ID._name = Names[NamesIdx[i]]; // Set the isotope name ID._element = Elements[IElements[i]]; // Set the isotope element ID._symbol = Gdec(ID._mass)+ID._element; ID._iselectron = false; // Set the type to nucleus if(ID._element == string("e")) // Exceptions occur for all { // electrons in this scheme ID._symbol = string("e-"); // Use symbol e- (NOT 0e) ID._iselectron = true; // Flag it is electron } Isotopes.push_back(ID); // Set isotope list entry } RELFRQ1H = RelFreqs[0]; // Setting Base 1H Frequency } // [not using SetRel1HF()] // Input I : A dummy isotope (this) // Output void : Sets the relative 1H frequency // Note : Must have filled isotopes list first! /* GAMMA's isotopes, rather than having a known gyromagnetic ratio, have a relative Larmor frequency from which gyromagnetic ratio may be calculated. The base relative Larmor frequency used in GAMMA is that of a proton, RELFRQ1H, and to date will be 400.13 (MHz) in GAMMA. The gyromagnetic ratio of isotope type i relates to its relative frequency RelFreq according to gamma = RelFreq*GAMMA1H/RELFRQ1H = Omega * gamma / Omega i i 1H 1H GAMMA has the DEFAULT value GAMMA1H = 2.67519e8 (1/T-sec) set in its constants module (Gutils). It sets the default proton relative frequency herein because that value (usually 400.13) is imported into GAMMA from a stardard isotopes list. Were that list to change, perhaps the listed base frequencys would change. But that is O.K. because it will be set here accordingly. Note however that this does NOT affect any GAMMA programs that wish to set alternate field strengths through spin systems. The relative frequencies in GAMMA's isotope list are Larmor frequencies but used ONLY to determine gamma values. Larmor frequencies in MR simulations are set independently by the user in typical GAMMA programs. */ void Isotope::SetRel1HF() { Isotope I("1H"); // Use proton for base RELFRQ1H = (Isotopes[I.Iso]).rel_freq(); // Here is rel.frq. (400.13) } // ____________________________________________________________________________ // iii Class Isotope Private Parameter Set Functions // ____________________________________________________________________________ /* This is used for reading an Isotope in from a GAMMA Parameter Set */ bool Isotope::SetIsotope(const ParameterSet& pset, int idx, bool warn) { string pname("Iso"); // Isotope parameter name if(idx != -1) // Add a suffix of (#) where pname += string("(")+Gdec(idx)+string(")"); // # = idx if idx is not -1 ParameterSet::const_iterator item; // A pix into parameter list item = pset.seek(pname); // Look in parameter set if(item != pset.end()) // If the parameter is found { string sval, pstate; // Parameter value & statement (*item).parse(pname,sval,pstate); // Parse out value as string *this = Isotope(sval); // Set out isotope type return true; // Return we were successful } if(warn) Isoerror(3, pname, 1); return false; // Return we failed our quest } // ---------------------------------------------------------------------------- // ---------------------------- PUBLIC FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // A ISOTOPE CONSTRUCTION, ASSIGNMENT // ____________________________________________________________________________ /* These construct single spin isotopes. Note that on the very first isotope made in a program a persistent list of spin isotopes is automatically generated. This remains in memory until the program ends. Also note that "construction" doesn't do a whole lot except set the isotope to point to a member in the isotope list. */ Isotope::Isotope() { IsotopeData Proton("1H"); // Set mock default isotope, if(!Isotopes.size()) set_Isotope_list(); // Fill Isotopes list if empty Iso = seek(Proton); // Get 1H index in Isotopes list if(Iso < 0) Isofatal(2, "1H"); // If no 1H FATAL ERROR! } Isotope::Isotope(const Isotope& I) :Iso(I.Iso) {} // Only copy index. Cannot have // any isotope without list set! Isotope::Isotope(const string& symbol) { IsotopeData i(symbol); // Form data for this isotope if(!Isotopes.size()) set_Isotope_list(); // Fill Isotopes list if empty Iso = seek(i); // Get index into Isotopes list if(Iso < 0) Isofatal(2, symbol); // Fatal error, unknown isotope } Isotope& Isotope::operator= (const Isotope& I) { if(this == &I) return *this; Iso = I.Iso; return *this; } Isotope::~Isotope() { } // ____________________________________________________________________________ // C ISOTOPE ACCESS FUNCTIONS // ____________________________________________________________________________ // Input I : An Isotope (this) // Note : All functions use IsotopesData // except gamma which must be calculated // based on relative frequencies /* Function Return Units Example(s) -------- ------------- ----- ------------------------------- qn mz (double) hbar 0.5, 1.0, 1.5, .... HS 2I+1 (int) none 2, 3, 4, ..... momentum mz (string) none 1/2, 1, 3/2, ..... symbol (string) none 1H, 2H, 13C, 19F, .... name (string) none Hydrogen, Lithium, Carbon, ... element (string) none H, Li, F, C, ...... number (int) none 1<-H, 3<-Li, 6<-C, ..... mass (int) amu 1<-1H, 2<-2H, 13<-13C, .... weight (double) g/m 1.00866<-1H, 7.016<-7Li, .... gamma (double) 1/T-s 2.67519*10^8 receptivity (double) none 400.13, 155.503, ... relative_frequency (double) MHz 400.13, 155.503, ... */ double Isotope::qn() const { return (Isotopes[Iso]).qn(); } int Isotope::HS() const { return (Isotopes[Iso]).HS(); } string Isotope::momentum() const { return (Isotopes[Iso]).momentum();} const string& Isotope::symbol() const { return (Isotopes[Iso]).symbol(); } const string& Isotope::name() const { return (Isotopes[Iso]).name(); } const string& Isotope::element() const { return (Isotopes[Iso]).element(); } int Isotope::number() const { return (Isotopes[Iso]).number(); } int Isotope::mass() const { return (Isotopes[Iso]).mass(); } double Isotope::weight() const { return (Isotopes[Iso]).weight(); } double Isotope::receptivity() const { return (Isotopes[Iso]).recept(); } bool Isotope::electron() const { return (Isotopes[Iso]).electron(); } double Isotope::relative_frequency() const {return (Isotopes[Iso]).rel_freq();} double Isotope::gamma() const { return ((Isotopes[Iso]).rel_freq()/RELFRQ1H)*GAMMA1H; } // ____________________________________________________________________________ // D ISOTOPE I/O FUNCTIONS // ____________________________________________________________________________ /* These read/write the isotope to from an ASCII file via Single Parameters */ bool Isotope::read(const string& filename, int idx, int warn) { ParameterSet pset; // Declare a parameter set if(!pset.read(filename, warn?1:0)) // Read in pset from file { Isoerror(1, filename,1); // Filename problems if(warn > 1) Isofatal(41); // Cant read from file, fatal else Isoerror(41); // or non-fatal warning return false; } if(!read(pset, idx, warn?1:0)) // User overloaded function { Isoerror(1, filename,1); // Filename problems if(warn > 1) Isofatal(42); // Cannot read isotope from file else Isoerror(42); // or non-fatal one return false; } return true; } bool Isotope::read(const ParameterSet& pset, int idx, int warn) { bool TF=SetIsotope(pset,idx,warn?true:false); // Try & set ourself up if(!TF) // If we didn't handle { // setting ourself properly if(warn) // then we'll issue some { // warnings if desired Isoerror(33, 1); // Cant read parameters if(warn > 1) Isofatal(34); // Can't set from parameters else Isoerror(34,1); // or a warning issued } return false; // Return that we failed } return TF; } vector<string> Isotope::printStrings(bool hdr) const { vector<string> PStrings; if(!hdr) hdr = true; // Why is hdr an argument? if(!hdr) return PStrings; // Use just to stop Borland warnings IsotopeData ID = Isotopes[Iso]; PStrings = ID.printStrings(true); string gs = string(" Gamma ") + Gform("%10.4f", gamma() * 1.e-8) + string(" 10^-8/T-s\n"); PStrings.push_back(gs); return PStrings; } std::ostream& Isotope::print(std::ostream& ostr) const { vector<string> PStrings = printStrings(true); unsigned ns = PStrings.size(); // No. of strings to print unsigned i; // Looping index unsigned ml = 0; // Maximum string length for(i=0; i<ns; i++) // Loop over strings and find ml = gmax(PStrings[i].length(), ml); // the longest one int cl = 40 - ml/2; string cstr; if(cl > 0) cstr = string(cl, ' '); for(i=0; i<ns; i++) ostr << cstr << PStrings[i] << std::endl; return ostr; } std::ostream& operator<< (std::ostream& ostr, const Isotope& I) { return I.print(ostr); } // ____________________________________________________________________________ // E ISOTOPE LIST FUNCTIONS // ____________________________________________________________________________ /* Allow users to search for a specific isotope in the list or find whether a particular isotope is contained in the list. Remember that each Isotope only contains a pointer to the Isotopes list with an index for which Isotope in the list it actually is. Input I : An isotope (this) ID : A single isotope symbol : A string designating an isotope Output i : Index of isotope in list if it exists. If id does NOT exist, returns is -1 TF : TRUE if isotope of type "symbol" known Note : Will return FALSE if symbol not found due to no isotope list */ int Isotope::seek(const IsotopeData& I) { if(!Isotopes.size()) return -1; // If Isotopes empty, fail int NISO = Isotopes.size(); // Get size of list, some for(int i=0; i<NISO; i++) // may have been added! if(I.symbol() == (Isotopes[i]).symbol()) return i; return -1; } bool Isotope::exists(const string& symbol) { IsotopeData i(symbol); // Form data for this isotope if(!Isotopes.size()) set_Isotope_list(); // Fill Isotopes list if empty return (seek(i)<0)?false:true; } bool Isotope::known(const string& symbol) { Isotope X; return X.exists(symbol); } int Isotope::size() { return int(Isotopes.size()); } vector<string> Isotope::PrintListStrings() { vector<string> PStrings; Isotope X("1H"); // A temp dummy isotope int NISO = X.size(); // Get size of list, some // Set Up Output Column Alignment int nl = (Gdec(NISO)).length(); // Length of printed index string nspc(nl+1, ' '); // Spacer for index column string csp(" "); // Space between each columns int cspl = csp.length(); // Length of space between cols string sy; // String for symbol int syl, syi, syf; // For symbol alignment string icol(" "); // Space between isotopes int nml = 0; // For Name column width int nmi, nmf; // For Name column spacing int i; // Dummy index for(i=0; i<NISO; i++) // Find longest name nml = gmax(nml, int(((Isotopes[i]).name()).length())); string nms("Name"); // For Name column header nmi = (nml-4)/2; nmf = nml - nmi - 4; if(nmi > 0) nms = string(nmi, ' ') + nms; if(nmf > 0) nms += string(nmf, ' '); int ncols = 2; // No. isotopes per row we print int next = 0; // For line end int cw = nl + 1 + cspl; cw += 6 + cspl; cw += nms.length() + cspl; cw *= ncols; cw += (ncols-1)*icol.length(); string cen(40-cw/2, ' '); // Set Up Column Headers string pline = cen; // Initial spacing (center) for(i=0; i<ncols; i++) { pline += "Indx" + csp; // Index pline += "Symbol" + csp; // Symbol pline += nms + csp; // Name pline += icol; // Next Isotope } PStrings.push_back(pline); pline = cen; // Initial spacing (center) for(i=0; i<ncols; i++) { pline += string(nl+1, '=') + string(cspl, ' '); pline += string(6, '=') + string(cspl, ' '); pline += string(nms.length(), '=') + string(cspl, ' '); pline += icol; } PStrings.push_back(pline); pline = string(""); for(i=0; i<NISO; i++) { sy = (Isotopes[i]).symbol(); // Set symbol string syl = sy.length(); syi = (6-syl)/2; syf = 6-syi-syl; if(syi>0) sy = string(syi, ' ') + sy; if(syf>0) sy += string(syf, ' '); nms = (Isotopes[i]).name(); nms += string(nml - nms.length(), ' '); if(!next) pline = cen; pline += Gdec(i+1, nl) + "." + csp; // Print index pline += sy + csp; // Print symbol pline += nms + csp; next++; if(next >= ncols) { next=0; PStrings.push_back(pline); } else pline += icol; } if(next) PStrings.push_back(pline); return PStrings; } void Isotope::PrintList(std::ostream& ostr, bool hdr) { if(hdr) { string H("Currently Available Isotopes"); ostr << string(40-H.length()/2, ' ') << H << "\n"; } Isotope X("1H"); int NISO = X.size(); // Get size of list, some // Set Up Output Column Alignment int nl = 1; // Length of printed index if(NISO >= 9) nl++; if(NISO >= 99) nl++; if(NISO >= 999) nl++; if(NISO >= 9999) nl++; string nspc(nl+1, ' '); // Spacer for index string sy; // String for symbol int syl, syi, syf; // For symbol alignment string csp(" "); // Space between each columns int cspl = csp.length(); // Length of space string icol(" "); // Space between isotopes int nml = 0; // For Name column width int nmi, nmf; // For Name column spacing int i; // Dummy index for(i=0; i<NISO; i++) // Find longest name nml = gmax(nml, int(((Isotopes[i]).name()).length())); string nms("Name"); // For Name column header nmi = (nml-4)/2; nmf = nml - nmi - 4; if(nmi > 0) nms = string(nmi, ' ') + nms; if(nmf > 0) nms += string(nmf, ' '); int ncols = 2; // Number of columns int next = 0; // For line end int cw = nl + 1 + cspl; cw += 6 + cspl; cw += nms.length() + cspl; cw *= ncols; cw += (ncols-1)*icol.length(); string cen(40-cw/2, ' '); // Write Column Headers ostr << "\n" << cen; for(i=0; i<ncols; i++) { ostr << "Indx" << csp; // Index ostr << "Symbol" << csp; // Symbol ostr << nms << csp; // Name ostr << icol; // Next Isotope } ostr << "\n" << cen; for(i=0; i<ncols; i++) { ostr << string(nl+1, '=') << string(cspl, ' '); ostr << string(6, '=') << string(cspl, ' '); ostr << string(nms.length(), '=') << string(cspl, ' '); ostr << icol; } for(i=0; i<NISO; i++) { sy = (Isotopes[i]).symbol(); // Set symbol string syl = sy.length(); syi = (6-syl)/2; syf = 6-syi-syl; if(syi>0) sy = string(syi, ' ') + sy; if(syf>0) sy += string(syf, ' '); nms = (Isotopes[i]).name(); nms += string(nml - nms.length(), ' '); if(!next) ostr << "\n" << cen; ostr << Gdec(i+1, nl) << "." << csp; // Print index ostr << sy << csp; // Print symbol ostr << nms << csp; next++; if(next >= ncols) next = 0; else ostr << icol; } } // ____________________________________________________________________________ // F Isotope List Expansion Functions // ____________________________________________________________________________ /* These functions allow users to add additional spins into the working GAMMA isotopes list. This will primarily be used in EPR/ESR/EMR simulations when electrons with I>1/2 are required. For example, this will occur when dealing with an electron about a metal center when the surroundings effecitvely cause it to be split. To add in an additional spin one simply constructs a new isotope type then adds/subtracts it with these functions. Note that one may NOT remove any "standard" isotopes in GAMMA nor may one add an isotope that already exists.. */ bool Isotope::AddIsotope(const IsotopeData& ID, int warn) { Isotope X; // A dummy isotope if(!Isotopes.size()) X.set_Isotope_list(); // Fill Isotopes list if empty if(X.seek(ID) >= 0) // If isotope already in list { // we cannot add it again! if(warn) // If warnings set we output { // error messages, maybe quit X.Isoerror(10, 1); // Spin already exists string pname = ID.symbol(); // Get isotope name if(warn>1) X.Isofatal(10,ID.symbol()); // We cannot add another else X.Isoerror(10, ID.symbol()); // Quit program if needed } return false; // Return we failed to add it } Isotopes.push_back(ID); // Add ID to Isotopes List return true; // Return added successfully } // ____________________________________________________________________________ // G Isotope Container Support Functions & (In)Equality // ____________________________________________________________________________ /* These functions allow for comparisons between spin isotopes. Such functions are required under some compilers if one desired to build containers of spin isotopes (STL lists, vectors, ....). Equal spin isotopes will simply point to the same entry in the isotopes list. For sorting purposes we go by the spin Hilbert space associated with the isotope. */ bool Isotope::operator== (const Isotope& i) const { return (Iso==i.Iso); } bool Isotope::operator!= (const Isotope& i) const { return (Iso!=i.Iso); } bool Isotope::operator< (const Isotope& I) const { return (HS() < I.HS()); } bool Isotope::operator> (const Isotope& I) const { return (HS() > I.HS()); } // ____________________________________________________________________________ // H Isotope Auxiliary Functions // ____________________________________________________________________________ /* These are just handy to have available for other parts of GAMMA */ bool Isotope::nepair(const Isotope& S) const { return enpair(S); } bool Isotope::enpair(const Isotope& S) const { if(electron()) return S.electron()?false:true; else return S.electron()?true:false; } bool Isotope::eepair(const Isotope& S) const { if(electron()) return S.electron()?true:false; return false; } bool Isotope::nnpair(const Isotope& S) const { if(!electron()) return S.electron()?false:true; return false; } #endif // Isotope.cc
46.055046
86
0.502291
pygamma-mrs
92009eca9ebe617f308bc971789fb3abb0dc8664
3,129
cc
C++
toolkit/gl_font.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
null
null
null
toolkit/gl_font.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
null
null
null
toolkit/gl_font.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
null
null
null
// Copyright (C) 2014-2020 Russell Smith. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. #define GL_FONT_IMPLEMENTATION #include "gl_font.h" #include "error.h" #include "gl_utils.h" #include "shaders.h" #include <vector> #include <stdint.h> struct StringToDraw { std::string s; const Font *font; double x, y; float red, green, blue; TextAlignment halign, valign; }; static std::vector<StringToDraw> strings; void DrawString(const char *s, double x, double y, const Font *font, float red, float green, float blue, TextAlignment halign, TextAlignment valign) { if (!s || !s[0]) { return; } strings.resize(strings.size() + 1); strings.back().s = s; strings.back().font = font; strings.back().x = x; strings.back().y = y; strings.back().red = red; strings.back().green = green; strings.back().blue = blue; strings.back().halign = halign; strings.back().valign = valign; } void DrawStringM(const char *s, double x, double y, double z, const Eigen::Matrix4d &T, const Font *font, float red, float green, float blue, TextAlignment halign, TextAlignment valign) { GLint viewport[4]; GL(GetIntegerv)(GL_VIEWPORT, viewport); Eigen::Vector3d win; gl::Project(x, y, z, T, viewport, &win); DrawString(s, win[0], win[1], font, red, green, blue, halign, valign); } //*************************************************************************** // Qt implementation #ifdef QT_CORE_LIB #include <QPainter> #include <QWidget> #include <QFont> void RenderDrawStrings(QWidget *win) { double scale = win->devicePixelRatio(); QPainter painter(win); for (int i = 0; i < strings.size(); i++) { StringToDraw &s = strings[i]; // Convert from opengl pixel coordinates to Qt window coordinates. double x = s.x / scale; double y = win->height() - s.y / scale; // Measure and align the text. double w = s.font->fm->size(0, s.s.c_str()).width(); double h = s.font->fm->height(); double ascent = s.font->fm->ascent(); double descent = s.font->fm->descent(); y = -y; // Since Y coordinates increase going up in AlignText AlignText(w, h, descent, s.halign, s.valign, false, &x, &y); y = -y; // Draw the text. painter.setPen(QColor(s.red, s.green, s.blue, 255)); painter.setFont(*s.font->font); painter.drawText(QPointF(x, y + ascent - 1), s.s.c_str()); } strings.clear(); } void DrawStringGetSize(const char *s, const Font *font, double *width, double *height) { *width = font->fm->size(0, s).width(); *height = font->fm->height(); } #endif // QT_CORE_LIB
30.086538
78
0.63311
teenylasers
9202045d76ad92acc2e3f6db2b7e3004145ed454
5,759
hpp
C++
src/libraries/turbulenceModels/compressible/LES/kOmegaSSTDES/compressiblekOmegaSSTDES.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/turbulenceModels/compressible/LES/kOmegaSSTDES/compressiblekOmegaSSTDES.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/turbulenceModels/compressible/LES/kOmegaSSTDES/compressiblekOmegaSSTDES.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2016 Applied CCM ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Description DES implementation of the k-omega-SST turbulence model for compressible flows (SST-2003). Author Aleksandar Jemcov \*---------------------------------------------------------------------------*/ #ifndef compressiblekOmegaSSTDES_HPP #define compressiblekOmegaSSTDES_HPP #include "compressibleLESModel.hpp" #include "wallDist.hpp" namespace CML { namespace compressible { namespace LESModels { class kOmegaSSTDES : public LESModel { protected: // Protected data //- Curvature correction on/off flag Switch curvatureCorrection_; Switch damped_; // Model coefficients dimensionedScalar alphaK1_; dimensionedScalar alphaK2_; dimensionedScalar alphaOmega1_; dimensionedScalar alphaOmega2_; dimensionedScalar Prt_; dimensionedScalar gamma1_; dimensionedScalar gamma2_; dimensionedScalar beta1_; dimensionedScalar beta2_; dimensionedScalar betaStar_; dimensionedScalar a1_; dimensionedScalar c1_; dimensionedScalar kappa_; dimensionedScalar CDES_; dimensionedScalar Cr1_; dimensionedScalar Cr2_; dimensionedScalar Cr3_; dimensionedScalar Cscale_; dimensionedScalar frMax_; //- Wall distance field wallDist y_; // Fields volScalarField k_; volScalarField omega_; volScalarField muSgs_; volScalarField yStar_; volScalarField alphaSgs_; volScalarField fr1_; volScalarField Fd_; tmp<volScalarField> F1(volScalarField const& CDkOmega) const; tmp<volScalarField> F2() const; tmp<volScalarField> Lt() const; virtual tmp<volScalarField> FDES() const; tmp<volScalarField> blend ( volScalarField const& F1, dimensionedScalar const& psi1, dimensionedScalar const& psi2 ) const { return F1*(psi1 - psi2) + psi2; } tmp<volScalarField> alphaK(volScalarField const& F1) const { return blend(F1, alphaK1_, alphaK2_); } tmp<volScalarField> alphaOmega(volScalarField const& F1) const { return blend(F1, alphaOmega1_, alphaOmega2_); } tmp<volScalarField> beta(volScalarField const& F1) const { return blend(F1, beta1_, beta2_); } tmp<volScalarField> gamma(volScalarField const& F1) const { return blend(F1, gamma1_, gamma2_); } public: //- Runtime type information TypeName("kOmegaSSTDES"); // Constructors //- Construct from components kOmegaSSTDES ( volScalarField const& rho, volVectorField const& U, surfaceScalarField const& phi, fluidThermo const& thermophysicalModel, word const& turbulenceModelName = turbulenceModel::typeName, word const& modelName = typeName ); //- Destructor virtual ~kOmegaSSTDES() {} // Member Functions //- Return the turbulence viscosity virtual tmp<volScalarField> muSgs() const { return muSgs_; } //- Return the turbulent thermal diffusivity virtual tmp<volScalarField> alphaSgs() const { return alphaSgs_; } //- Return the effective diffusivity for k tmp<volScalarField> DkEff(volScalarField const& F1) const { return tmp<volScalarField> ( new volScalarField("DkEff", alphaK(F1)*muSgs_ + mu()) ); } //- Return the effective diffusivity for omega tmp<volScalarField> DomegaEff(volScalarField const& F1) const { return tmp<volScalarField> ( new volScalarField("DomegaEff", alphaOmega(F1)*muSgs_ + mu()) ); } //- Return the turbulence kinetic energy virtual tmp<volScalarField> k() const { return k_; } //- Return the turbulence specific dissipation rate virtual tmp<volScalarField> omega() const { return omega_; } //- Return the turbulence kinetic energy dissipation rate virtual tmp<volScalarField> epsilon() const { return tmp<volScalarField> ( new volScalarField ( IOobject ( "epsilon", mesh_.time().timeName(), mesh_ ), betaStar_*k_*omega_, omega_.boundaryField().types() ) ); } //- Return the Reynolds stress tensor virtual tmp<volSymmTensorField> B() const; //- Return the effective stress tensor including the laminar stress virtual tmp<volSymmTensorField> devRhoBeff() const; //- Return the source term for the momentum equation virtual tmp<fvVectorMatrix> divDevRhoBeff(volVectorField& U) const; //- Solve the turbulence equations and correct the turbulence viscosity virtual void correct(); //- Read RASProperties dictionary virtual bool read(); }; } } } #endif
23.699588
79
0.631186
MrAwesomeRocks
92039f8f242ee91aadb4765a2252cee259355645
6,918
cpp
C++
lua_cpp_experiment/lua_cpp_experiment/main.cpp
baransrc/lua-cpp-experiment
d8d31d41e4399f19a6b04699baa7f604a3babecc
[ "MIT" ]
2
2022-02-14T19:21:05.000Z
2022-02-21T01:28:55.000Z
lua_cpp_experiment/lua_cpp_experiment/main.cpp
baransrc/lua-cpp-experiment
d8d31d41e4399f19a6b04699baa7f604a3babecc
[ "MIT" ]
null
null
null
lua_cpp_experiment/lua_cpp_experiment/main.cpp
baransrc/lua-cpp-experiment
d8d31d41e4399f19a6b04699baa7f604a3babecc
[ "MIT" ]
null
null
null
#include <iostream> #include "entity_component.h" #include "lua_helper.h" #include "script.h" //bool check_lua(lua_State* L, int result) //{ // if (result != 0) // { // std::string error_message = lua_tostring(L, -1); // std::cout << error_message << std::endl; // // return false; // } // // return true; //} // //void vanilla_lua_test() //{ // // Create lua state: // lua_State* L = luaL_newstate(); // // // Load all lua libraries: // luaL_openlibs(L); // // if (!check_lua(L, luaL_dofile(L, "experiment.lua"))) // { // // Close and free lua_State L: // lua_close(L); // // return; // } // // std::cout << "Hello World from CPP" << std::endl; // // // Try getting the "box" called print_test on the // // top of the stack: // lua_getglobal(L, "print_test"); // // // Check if top of the stack is a function: // // NOTE: In lua we have indexed stack, and the top // // of the stack is -1. // if (lua_isfunction(L, -1)) // { // // Run the function and if there is a problem // // log the error message given by lua: // if (check_lua(L, lua_pcall(L, 0, 0, 0))) // { // std::cout << "This works my dude" << std::endl; // } // } // // // Close and free lua_State L: // lua_close(L); //} int main() { sol::state lua(sol::c_call<decltype(&print_panic), &print_panic>); // Enable base libraries: lua.open_libraries ( sol::lib::base, sol::lib::package, sol::lib::debug, sol::lib::string, sol::lib::io, sol::lib::coroutine, sol::lib::os, sol::lib::table, sol::lib::math ); sol::load_result settings_load_result = lua.load_file("settings.lua"); // If the loaded script has errors, display it: if (!settings_load_result.valid()) { sol::error error = settings_load_result; std::cerr << "Failed to load settings: " << error.what() << std::endl; system("pause"); return 0; } // Run the settings script: settings_load_result(); // TODO: Get these runtime, and relative to working directory. std::string project_path = lua["project_path"]; std::string script_file_name = lua["script_file_name"]; std::string lua_path = lua["lua_path"]; std::string zbs_lib_path = lua["zbs_lib_path"]; std::string path = ""; path += "package.path = "; path += "\""; path += "./?.lua;"; path += zbs_lib_path + "/lualibs/?/?.lua;"; path += zbs_lib_path + "/lualibs/?.lua;"; path += project_path + "/lua-cpp-experiment/scripts/?.lua;"; path += "\""; path += "..package.path"; std::string c_path = ""; c_path += "package.cpath = "; c_path += "\""; // TODO: Get these runtime, and relative to working directory. c_path += lua_path + "/luaJIT/lib/?.dll;"; c_path += lua_path + "/lua_socket/bin/?.dll;"; c_path += lua_path + "/lua_socket/bin/clibs/?.dll;"; c_path += lua_path + "/lua_socket/bin/clibs/mime/?.dll;"; c_path += lua_path + "/lua_socket/bin/clibs/socket/?.dll;"; c_path += zbs_lib_path + "/bin/?.dll;"; c_path += zbs_lib_path + "/bin/clibs/?.dll"; c_path += "\""; c_path += "..package.cpath"; // Add lua file and dll file checkup paths to the script: // We don't need to check if these files are valid since // we statically run these from code instead of loading it // from file. lua.do_string(c_path); lua.do_string(path); Entity* entity = new Entity(); LuaScript script_1(script_file_name, entity); LuaScript script_2("experiment2.lua", entity); sol::safe_function execute_function = script_1.GetAsTable()["execute"]; //sol::load_result load_result = lua.load_file(script_file_name); //// If the loaded script has errors, display it: //if (!load_result.valid()) //{ // sol::error error = load_result; // std::cerr << "Failed to load " << script_file_name << " " << error.what() << std::endl; // system("pause"); // return 0; //} //// Run the script: //load_result(); //// Create Entity namespace: //sol::table this_namespace = lua["hachiko"].get_or_create<sol::table>(); //// Add entity and components to lua: //component_type_to_lua(this_namespace); //component_to_lua(this_namespace); //component_x_to_lua(this_namespace); //component_y_to_lua(this_namespace); //entity_to_lua(this_namespace); //// Create an entity: //Entity* entity = new Entity(); //// Add the api to interact with entity to namespace: //this_namespace.set("entity", entity); //// Run the execute method of the script: //sol::table experiment_table = lua["experiment"]; //sol::protected_function_result script_result = experiment_table["execute"](); //// If an error comes up, print to the screen and halt the //// execution: //if (!script_result.valid()) //{ // sol::error error = script_result; // std::cout << "[ERROR-LUA]: " << error.what() << std::endl; // std::cin.ignore(); // return 0; //} //// Test if script really changed entity: //std::cout << std::endl << "------------" << std::endl; //std::cout << "Result from CPP: " << entity->GetComponent<ComponentY>()->GetYValue() << std::endl; //// Create another lua state: //sol::state another_lua; // //// Enable libraries for that lua state: //another_lua.open_libraries //( // sol::lib::base, // sol::lib::package, // sol::lib::debug, // sol::lib::string, // sol::lib::io, // sol::lib::coroutine, // sol::lib::os, // sol::lib::table, // sol::lib::math //); //another_lua.do_string(c_path); //another_lua.do_string(path); //sol::table another_namespace = another_lua["hachiko"].get_or_create<sol::table>(); //// Add entity and components to lua: //component_type_to_lua(another_namespace); //component_to_lua(another_namespace); //component_x_to_lua(another_namespace); //component_y_to_lua(another_namespace); //entity_to_lua(another_namespace); //std::string table_name = "experiment"; //sol::table experiment_script_table = lua[table_name]; //sol::table other_script_table = another_lua["ExperimentScript"].get_or_create<sol::table>(); //std::cout << "Adding the experiment script table member functions to another script which runs the functions from experiment.lua" << std::endl; //for (const auto& entry : experiment_script_table) //{ // const sol::object& current_object = entry.second; // if (!current_object.is<sol::function>()) // { // continue; // } // const std::string& function_name = entry.first.as<std::string>(); // std::cout << "Adding: " << function_name << std::endl; // sol::function function = experiment_script_table[function_name]; // other_script_table.set_function(function_name, function); //} //// another_lua["ExperimentScript"].set(other_script_table); //sol::protected_function_result result = another_lua.do_string("ExperimentScript:call_from_another_script(888, \"please work\")"); //if (!result.valid()) //{ // sol::error error = result; // std::cout << "[ERROR-LUA]: " << error.what() << std::endl; // std::cin.ignore(); // return 0; //} //std::string name = lua["experiment"]["name"]; //std::cout << name << std::endl; std::cin.ignore(); return 0; }
26.918288
146
0.651923
baransrc
920604f22fdeefe4691f3ad2deef1ac4a64b5b9d
227
cpp
C++
1_DSAA_code/TestIntCell.cpp
amdfansheng/alogrithm
b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d
[ "MIT" ]
7
2018-07-22T14:29:58.000Z
2021-05-03T04:40:13.000Z
1_DSAA_code/TestIntCell.cpp
amdfansheng/alogrithm
b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d
[ "MIT" ]
null
null
null
1_DSAA_code/TestIntCell.cpp
amdfansheng/alogrithm
b2e1dd4094b766895dda8c8fc2cbb2e37e6aa22d
[ "MIT" ]
5
2019-02-13T14:50:51.000Z
2020-07-24T09:05:22.000Z
#include <iostream> #include "IntCell.h" using namespace std; int main( ) { IntCell m; // Or, IntCell m( 0 ); but not IntCell m( ); m.write( 5 ); cout << "Cell contents: " << m.read( ) << endl; return 0; }
16.214286
61
0.555066
amdfansheng
9207489418252ce1c6f3758c1f5ff70ed2503335
3,320
cpp
C++
groups/bdl/bdldfp/bdldfp_decimalimputil_inteldfp.t.cpp
silky/bde
c5d57392c022509e6346695b2c368f862afaefec
[ "Apache-2.0" ]
1
2019-06-27T11:32:37.000Z
2019-06-27T11:32:37.000Z
groups/bdl/bdldfp/bdldfp_decimalimputil_inteldfp.t.cpp
silky/bde
c5d57392c022509e6346695b2c368f862afaefec
[ "Apache-2.0" ]
null
null
null
groups/bdl/bdldfp/bdldfp_decimalimputil_inteldfp.t.cpp
silky/bde
c5d57392c022509e6346695b2c368f862afaefec
[ "Apache-2.0" ]
null
null
null
// bdldfp_decimalimputil_inteldfp.t.cpp -*-C++-*- #include <bdldfp_decimalimputil_inteldfp.h> #include <bsls_ident.h> BSLS_IDENT("$Id$") #include <bdls_testutil.h> #include <bsls_assert.h> #include <bsl_iostream.h> // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // The Intel DFP implementation provides a BID representation of DFP. The code // is written in C, but due to compiler-portability concerns, we have to // compile it with a C++ compiler. This test driver is not blank, to address // some C/C++ compatibility concerns. // // Global Concerns: // //: 1 The IntelDFP library defines some manifest constants that might cause //: linker failures. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- using namespace BloombergLP; using bsl::cout; using bsl::cerr; using bsl::flush; using bsl::endl; using bsl::atoi; //============================================================================= // STANDARD BDE ASSERT TEST MACRO //----------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool b, const char *s, int i) { if (b) { cout << "Error " << __FILE__ << "(" << i << "): " << s << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) ++testStatus; } } } // close unnamed namespace //============================================================================= // STANDARD BDE TEST DRIVER MACROS //----------------------------------------------------------------------------- #define ASSERT BDLS_TESTUTIL_ASSERT extern "C" { extern const unsigned long long int __four_over_pi[]; } #define DEFINES #include "library_float128_dpml_four_over_pi.cpp" typedef struct { float a, b; double c; } SQRT_COEF_STRUCT; extern "C" const SQRT_COEF_STRUCT __dpml_bid_sqrt_t_table[]; #undef DEFINES int main() { { const SQRT_COEF_STRUCT *p = &__dpml_bid_sqrt_t_table[0]; ASSERT(p); } { const DIGIT_TYPE *p = &FOUR_OVER_PI_TABLE_NAME[0]; ASSERT(p); } return -1; } // ---------------------------------------------------------------------------- // Copyright 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
32.871287
79
0.471386
silky
920c2f978460652ba6a709d9a9b4abb6ab32fcb5
13,682
hxx
C++
admin/activec/test/snapins/sample/samplesnap.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/activec/test/snapins/sample/samplesnap.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/activec/test/snapins/sample/samplesnap.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1994 - 1999 // // File: samplesnap.hxx // // Contents: Classes that implement sample snapin using the framework. // //-------------------------------------------------------------------- #ifndef _SAMPLESNAP_HXX_ #define _SAMPLESNAP_HXX_ // Forward declarations. class CSampleSnapinLVContainer; class CSampleSnapinLVLeafItem; //+------------------------------------------------------------------- // // Class: CSnapinRootItem // // Purpose: Implements the root item for a standalone snapin. // //-------------------------------------------------------------------- class CSnapinRootItem : public CBaseSnapinItem { typedef CBaseSnapinItem super; // Used by CBaseSnapinItem::ScCreateItem, connect this item with its children. typedef CComObject<CSnapinItem<CSnapinRootItem> > t_item; typedef CComObject<CSnapinItem<CSampleSnapinLVContainer> > t_itemChild; // Who is my child? public: CSnapinRootItem( void ) {} // Raw constructor - use only for static item. virtual ~CSnapinRootItem( void ) {} BEGIN_COM_MAP(CSnapinRootItem) COM_INTERFACE_ENTRY(IDataObject) // Cant have empty map so add IDataObject END_COM_MAP() protected: // Item tree related information // node type related information virtual const CNodeType* Pnodetype( void ) { return &nodetypeSampleRoot;} // the display name of the item virtual const tstring* PstrDisplayName( void ) { return &m_strDisplayName;} // Get ListView data (GetDisplayInfo calls this). virtual SC ScGetField(DAT dat, tstring& strField); // Image list information virtual LONG Iconid() { return m_uIconIndex; } virtual LONG OpenIconid() { return m_uIconIndex; } virtual BOOL FIsContainer( void ) { return TRUE; } public: virtual SC ScInit(CBaseSnapin *pSnapin, CColumnInfoEx *pcolinfoex = NULL, INT ccolinfoex = 0, BOOL fIsRoot = FALSE); public: // Creates children for the node virtual SC ScCreateChildren( void ); protected: tstring m_strDisplayName; UINT m_uIconIndex; }; //+------------------------------------------------------------------- // // Class: CSampleSnapinLVContainer // // Purpose: Implements a scope pane item. // //-------------------------------------------------------------------- class CSampleSnapinLVContainer : public CBaseSnapinItem { typedef CBaseSnapinItem super; // Used by CBaseSnapinItem::ScCreateItem, connect this item with its children. typedef CComObject<CSnapinItem<CSampleSnapinLVContainer> > t_item; typedef CComObject<CSnapinItem<CSampleSnapinLVLeafItem> > t_itemChild; public: CSampleSnapinLVContainer( void ) {} virtual ~CSampleSnapinLVContainer( void ) {} BEGIN_COM_MAP(CSampleSnapinLVContainer) COM_INTERFACE_ENTRY(IDataObject) // Cant have empty map so add IDataObject END_COM_MAP() protected: // Item tree related information // node type related information const CNodeType *Pnodetype( void ) { return &nodetypeSampleLVContainer;} // the display name of the item virtual const tstring* PstrDisplayName( void ) { return &m_strDisplayName;} // Get ListView data (GetDisplayInfo calls this). virtual SC ScGetField(DAT dat, tstring& strField); // Image list information virtual LONG Iconid() { return m_uIconIndex; } virtual LONG OpenIconid() { return m_uIconIndex; } // This item attributes. virtual BOOL FIsContainer( void ) { return TRUE; } virtual BOOL FAllowMultiSelectionForChildren() { return FALSE;} public: virtual SC ScInit(CBaseSnapin *pSnapin, CColumnInfoEx *pcolinfoex = NULL, INT ccolinfoex = 0, BOOL fIsRoot = FALSE); public: // Creates children for the node virtual SC ScCreateChildren( void ); static SC ScCreateLVContainer(CSnapinRootItem *pitemParent, t_item ** ppitem, BOOL fNew); protected: // virtual SC ScGetVerbs(DWORD * pdwVerbs); protected: tstring m_strDisplayName; UINT m_uIconIndex; }; //+------------------------------------------------------------------- // // Class: CSampleSnapinLVLeafItem // // Purpose: Implements a result pane item. // //-------------------------------------------------------------------- class CSampleSnapinLVLeafItem : public CBaseSnapinItem { typedef CBaseSnapinItem super; // Used by CBaseSnapinItem::ScCreateItem, connect this item with its children. // This is a leaf item so this item acts as its child. typedef CComObject<CSnapinItem<CSampleSnapinLVLeafItem> > t_item; typedef CComObject<CSnapinItem<CSampleSnapinLVLeafItem> > t_itemChild; public: CSampleSnapinLVLeafItem( void ) {} virtual ~CSampleSnapinLVLeafItem( void ) {} BEGIN_COM_MAP(CSampleSnapinLVLeafItem) COM_INTERFACE_ENTRY(IDataObject) // Cant have empty map so add IDataObject END_COM_MAP() protected: // Item tree related information // node type related information virtual const CNodeType *Pnodetype( void ) {return &nodetypeSampleLVLeafItem;} // the display name of the item virtual const tstring* PstrDisplayName( void ) { return &m_strDisplayName; } // Get ListView data (GetDisplayInfo calls this). virtual SC ScGetField(DAT dat, tstring& strField); // Image list information virtual LONG Iconid() { return m_uIconIndex; } virtual BOOL FIsContainer( void ) { return FALSE; } // Context menu support virtual SnapinMenuItem *Pmenuitem(void); virtual INT CMenuItem(void); virtual SC ScCommand(long nCommandID, CComponent *pComponent = NULL); public: virtual SC ScInit(CBaseSnapin *pSnapin, CColumnInfoEx *pcolinfoex = NULL, INT ccolinfoex = 0, BOOL fIsRoot = FALSE); public: static SC ScCreateLVLeafItem(CSampleSnapinLVContainer *pitemParent, t_itemChild * pitemPrevious, t_itemChild ** ppitem, BOOL fNew); protected: // virtual SC ScGetVerbs(DWORD * pdwVerbs); private: tstring m_strDisplayName; UINT m_uIconIndex; // For context menus static SnapinMenuItem s_rgmenuitemLVLeafItem[]; static INT s_cmenuitemLVLeafItem; }; //+------------------------------------------------------------------- // // Class: CSampleSnapin // // Purpose: Implements a snapin. // //-------------------------------------------------------------------- class CSampleSnapin : public CBaseSnapin { // Specify the root node of the snapin. typedef CComObject<CSnapinItem<CSnapinRootItem> > t_itemRoot; SNAPIN_DECLARE(CSampleSnapin); public: CSampleSnapin(); virtual ~CSampleSnapin(); // information about the snapin and root (ie initial) node virtual BOOL FStandalone() { return TRUE; } virtual BOOL FIsExtension() { return FALSE; } virtual LONG IdsDescription(void) {return IDS_SAMPLESNAPIN;} virtual LONG IdsName(void) {return IDS_SAMPLESNAPIN;} const CSnapinInfo* Psnapininfo() { return &snapininfoSample; } protected: // The column header info structures. static CColumnInfoEx s_colinfo[]; static INT s_colwidths[]; static INT s_ccolinfo; protected: virtual CColumnInfoEx* Pcolinfoex(INT icolinfo=0) { return s_colinfo + icolinfo; } virtual INT &ColumnWidth(INT icolwidth=0) { return s_colwidths[icolwidth]; } virtual INT Ccolinfoex() { return s_ccolinfo; } }; //----------------------Name Space Extension ---------------------- class CBaseProtSnapinItem; /* CSampleGhostRootSnapinItem * * PURPOSE: Implements the item class for the ghost root of container * */ class CSampleGhostRootSnapinItem : public CBaseSnapinItem { typedef CBaseSnapinItem super; typedef CComObject<CSnapinItem<CSampleGhostRootSnapinItem> > t_item; typedef CComObject<CSnapinItem<CBaseProtSnapinItem> > t_itemChild; friend CBaseProtSnapinItem; public: CSampleGhostRootSnapinItem( void ) {} virtual ~CSampleGhostRootSnapinItem( void ) {} BEGIN_COM_MAP(CSampleGhostRootSnapinItem) COM_INTERFACE_ENTRY(IDataObject) // Cant have empty map so add IDataObject END_COM_MAP() protected: // the name of the server (used to build up the DN of the object.) // Item tree related information virtual BOOL FIsContainer( void ) { return TRUE;} // Overiding pure virtual functions. Should never be called here!!! const CNodeType *Pnodetype(void) { ASSERT(FALSE); return NULL;} virtual const tstring *PstrDisplayName( void ) { ASSERT(FALSE); return &m_strDisplayName;} virtual SC ScGetField(DAT dat, tstring& strField) { ASSERT(FALSE); return E_FAIL;} // column header and image list information virtual LONG Iconid() { return m_uIconIndex;} public: virtual SC ScInitializeNamespaceExtension(LPDATAOBJECT lpDataObject, HSCOPEITEM item, CNodeType *pNodeType); virtual SC ScCreateChildren( void ); private: UINT m_uIconIndex; tstring m_strDisplayName; }; /* CBaseProtSnapinItem * * PURPOSE: Implements the sample namespace extension snapin items. * This class is instantiated from the CSampleGhostRootSnapinItem * by first creating a container and than filling it with the sample * item instances. * */ class CBaseProtSnapinItem : public CBaseSnapinItem { typedef CBaseSnapinItem super; typedef CComObject<CSnapinItem<CBaseProtSnapinItem> > t_item; typedef CComObject<CSnapinItem<CBaseProtSnapinItem> > t_itemChild; friend CSampleGhostRootSnapinItem; public: CBaseProtSnapinItem( void ); // Raw constructor - use only for static item. virtual ~CBaseProtSnapinItem( void ) {} BEGIN_COM_MAP(CBaseProtSnapinItem) COM_INTERFACE_ENTRY(IDataObject) // Cant have empty map so add IDataObject END_COM_MAP() protected: // Item tree related information // node type related information const CNodeType *Pnodetype( void ) { return &nodetypeSampleExtnNode;} // the display name of the item virtual const tstring* PstrDisplayName( void ) { return &m_strDisplayName;} virtual SC ScGetField(DAT dat, tstring& strField); // column header and image list information virtual LONG Iconid() { return PitemRoot()->Iconid(); } virtual BOOL FIsContainer( void ) { return m_fIsContainer;} void InitContainer(void) { m_fIsContainer = TRUE;} virtual CSampleGhostRootSnapinItem *PitemRoot(void) { return (dynamic_cast<CSampleGhostRootSnapinItem *>(CBaseSnapinItem::PitemRoot())); } public: // Creates children for the node virtual SC ScCreateChildren( void ); static SC ScCreateItem(CBaseSnapinItem *pitemParent, t_itemChild * pitemPrevious, t_itemChild ** ppitem, BOOL fNew); private: UINT m_uIconIndex; BOOL m_fInitialized : 1; BOOL m_fIsContainer : 1; tstring m_strDisplayName; }; /* CSampleSnapExtensionItem * * PURPOSE: Implements the NameSpace sample snapin item - must be a separate class to distinguish between different node types */ class CSampleSnapExtensionItem : public CSampleGhostRootSnapinItem { typedef CSampleGhostRootSnapinItem super; virtual SC ScInitializeNamespaceExtension(LPDATAOBJECT lpDataObject, HSCOPEITEM item, CNodeType *pnodetype) { return super::ScInitializeNamespaceExtension(lpDataObject, item, pnodetype); } }; /* CSampleExtnSnapin * * PURPOSE: Implements the Sample extension snapin */ class CSampleExtnSnapin : public CBaseSnapin { typedef CComObject<CSnapinItem<CSampleGhostRootSnapinItem> > t_itemRoot; SNAPIN_DECLARE(CSampleExtnSnapin); public: CSampleExtnSnapin(); virtual ~CSampleExtnSnapin(); // information about the snapin and root (ie initial) node virtual BOOL FStandalone() { return FALSE;} // only an extension snapin. virtual BOOL FIsExtension() { return TRUE;} const CSnapinInfo *Psnapininfo() { return &snapininfoSampleExtn;} virtual LONG IdsDescription() { return IDS_SampleExtnSnapinDescription;} virtual LONG IdsName() { return IDS_SampleExtnSnapinName;} protected: // The column header info structures. static CColumnInfoEx s_colinfo[]; static INT s_colwidths[]; static INT s_ccolinfo; protected: virtual CColumnInfoEx *Pcolinfoex(INT icolinfo=0) { return s_colinfo + icolinfo;} virtual INT &ColumnWidth(INT icolwidth=0) { return s_colwidths[icolwidth];} virtual INT Ccolinfoex() { return s_ccolinfo;} }; #endif //_BASEPROTSNAP_HXX
34.903061
143
0.625859
npocmaka
920c4481b54b5bd0acae7b8003cc8c11870f4970
843
cpp
C++
tests/cthread/test_cthread_wait_n_fail2.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
86
2020-10-23T15:59:47.000Z
2022-03-28T18:51:19.000Z
tests/cthread/test_cthread_wait_n_fail2.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
18
2020-12-14T13:11:26.000Z
2022-03-14T05:34:20.000Z
tests/cthread/test_cthread_wait_n_fail2.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
17
2020-10-29T16:19:43.000Z
2022-03-11T09:51:05.000Z
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ #include <systemc.h> // wait(N) where N is not constant, changed at next loop iteration, failed SC_MODULE(test_mod) { sc_signal<bool> clk{"clk"}; sc_signal<bool> rstn{"rstn"}; SC_CTOR(test_mod) { SC_CTHREAD(wait_n_inf, clk); async_reset_signal_is(rstn, false); } void wait_n_inf() { sc_uint<10> n = 1; wait(); while (1) { wait(n); n++; } } }; int sc_main(int argc, char **argv) { test_mod tmod{"tmod"}; sc_start(); return 0; }
21.615385
79
0.457888
hachetman
920dae05d475699885703980679dfb55d99c2d7c
13,990
cpp
C++
src/terminal/RenderBufferBuilder.cpp
herrhotzenplotz/contour
f6e58671fd94b44d88a76941bcf9c88a585a3550
[ "Apache-2.0" ]
null
null
null
src/terminal/RenderBufferBuilder.cpp
herrhotzenplotz/contour
f6e58671fd94b44d88a76941bcf9c88a585a3550
[ "Apache-2.0" ]
null
null
null
src/terminal/RenderBufferBuilder.cpp
herrhotzenplotz/contour
f6e58671fd94b44d88a76941bcf9c88a585a3550
[ "Apache-2.0" ]
null
null
null
#include <terminal/Color.h> #include <terminal/ColorPalette.h> #include <terminal/RenderBufferBuilder.h> #include <tuple> using namespace std; namespace terminal { namespace { constexpr RGBColor makeRGBColor(RGBColor fg, RGBColor bg, CellRGBColor cellColor) noexcept { if (holds_alternative<CellForegroundColor>(cellColor)) return fg; if (holds_alternative<CellBackgroundColor>(cellColor)) return bg; return get<RGBColor>(cellColor); } constexpr RGBColor average(RGBColor a, RGBColor b) noexcept { return RGBColor(static_cast<uint8_t>((a.red + b.red) / 2), static_cast<uint8_t>((a.green + b.green) / 2), static_cast<uint8_t>((a.blue + b.blue) / 2)); } tuple<RGBColor, RGBColor> makeColors(ColorPalette const& _colorPalette, CellFlags _cellFlags, bool _reverseVideo, Color foregroundColor, Color backgroundColor, bool _selected, bool _isCursor) { auto const [fg, bg] = makeColors(_colorPalette, _cellFlags, _reverseVideo, foregroundColor, backgroundColor); if (!_selected && !_isCursor) return tuple { fg, bg }; auto const [selectionFg, selectionBg] = [](auto fg, auto bg, bool selected, ColorPalette const& colors) -> tuple<RGBColor, RGBColor> { auto const a = colors.selectionForeground.value_or(bg); auto const b = colors.selectionBackground.value_or(fg); if (selected) return tuple { a, b }; else return tuple { b, a }; }(fg, bg, _selected, _colorPalette); if (!_isCursor) return tuple { selectionFg, selectionBg }; auto const cursorFg = makeRGBColor(selectionFg, selectionBg, _colorPalette.cursor.textOverrideColor); auto const cursorBg = makeRGBColor(selectionFg, selectionBg, _colorPalette.cursor.color); if (_selected) return tuple { average(selectionFg, cursorFg), average(selectionFg, cursorFg) }; return tuple { cursorFg, cursorBg }; } } // namespace template <typename Cell> RenderBufferBuilder<Cell>::RenderBufferBuilder(Terminal const& _terminal, RenderBuffer& _output): output { _output }, terminal { _terminal }, cursorPosition { _terminal.inputHandler().mode() == ViMode::Insert ? _terminal.realCursorPosition() : _terminal.state().viCommands.cursorPosition } { output.clear(); output.frameID = _terminal.lastFrameID(); output.cursor = renderCursor(); } template <typename Cell> optional<RenderCursor> RenderBufferBuilder<Cell>::renderCursor() const { if (!terminal.cursorCurrentlyVisible() || !terminal.viewport().isLineVisible(cursorPosition.line)) return nullopt; // TODO: check if CursorStyle has changed, and update render context accordingly. auto constexpr InactiveCursorShape = CursorShape::Rectangle; // TODO configurable auto const shape = terminal.state().focused ? terminal.cursorShape() : InactiveCursorShape; auto const cursorScreenPosition = CellLocation { cursorPosition.line + boxed_cast<LineOffset>(terminal.viewport().scrollOffset()), cursorPosition.column }; auto const cellWidth = terminal.currentScreen().cellWithAt(cursorPosition); return RenderCursor { cursorScreenPosition, shape, cellWidth }; } template <typename Cell> RenderCell RenderBufferBuilder<Cell>::makeRenderCellExplicit(ColorPalette const& _colorPalette, char32_t codepoint, CellFlags flags, RGBColor fg, RGBColor bg, Color ul, LineOffset _line, ColumnOffset _column) { RenderCell renderCell; renderCell.backgroundColor = bg; renderCell.foregroundColor = fg; renderCell.decorationColor = getUnderlineColor(_colorPalette, flags, fg, ul); renderCell.position.line = _line; renderCell.position.column = _column; renderCell.flags = flags; renderCell.width = 1; if (codepoint) renderCell.codepoints.push_back(codepoint); return renderCell; } template <typename Cell> RenderCell RenderBufferBuilder<Cell>::makeRenderCell(ColorPalette const& _colorPalette, HyperlinkStorage const& _hyperlinks, Cell const& screenCell, RGBColor fg, RGBColor bg, LineOffset _line, ColumnOffset _column) { RenderCell renderCell; renderCell.backgroundColor = bg; renderCell.foregroundColor = fg; renderCell.decorationColor = screenCell.getUnderlineColor(_colorPalette, fg); renderCell.position.line = _line; renderCell.position.column = _column; renderCell.flags = screenCell.styles(); renderCell.width = screenCell.width(); if (screenCell.codepointCount() != 0) { for (size_t i = 0; i < screenCell.codepointCount(); ++i) renderCell.codepoints.push_back(screenCell.codepoint(i)); } renderCell.image = screenCell.imageFragment(); if (auto href = _hyperlinks.hyperlinkById(screenCell.hyperlink())) { auto const& color = href->state == HyperlinkState::Hover ? _colorPalette.hyperlinkDecoration.hover : _colorPalette.hyperlinkDecoration.normal; // TODO(decoration): Move property into Terminal. auto const decoration = href->state == HyperlinkState::Hover ? CellFlags::Underline // TODO: decorationRenderer_.hyperlinkHover() : CellFlags::DottedUnderline; // TODO: decorationRenderer_.hyperlinkNormal(); renderCell.flags |= decoration; // toCellStyle(decoration); renderCell.decorationColor = color; } return renderCell; } template <typename Cell> std::tuple<RGBColor, RGBColor> RenderBufferBuilder<Cell>::makeColorsForCell(CellLocation gridPosition, CellFlags cellFlags, Color foregroundColor, Color backgroundColor) { auto const hasCursor = gridPosition == cursorPosition; // clang-format off bool const paintCursor = (hasCursor || (prevHasCursor && prevWidth == 2)) && output.cursor.has_value() && output.cursor->shape == CursorShape::Block; // clang-format on auto const selected = terminal.isSelected(CellLocation { gridPosition.line, gridPosition.column }); return makeColors(terminal.colorPalette(), cellFlags, reverseVideo, foregroundColor, backgroundColor, selected, paintCursor); } template <typename Cell> void RenderBufferBuilder<Cell>::renderTrivialLine(TriviallyStyledLineBuffer const& lineBuffer, LineOffset lineOffset) { // fmt::print("Rendering trivial line {:2} 0..{}/{}: \"{}\"\n", // lineOffset.value, // lineBuffer.text.size(), // lineBuffer.displayWidth, // lineBuffer.text.view()); auto const frontIndex = output.screen.size(); auto const textMargin = min(boxed_cast<ColumnOffset>(terminal.pageSize().columns), ColumnOffset::cast_from(lineBuffer.text.size())); auto const pageColumnsEnd = boxed_cast<ColumnOffset>(terminal.pageSize().columns); for (auto columnOffset = ColumnOffset(0); columnOffset < textMargin; ++columnOffset) { auto const pos = CellLocation { lineOffset, columnOffset }; auto const gridPosition = terminal.viewport().translateScreenToGridCoordinate(pos); auto const [fg, bg] = makeColorsForCell(gridPosition, lineBuffer.attributes.styles, lineBuffer.attributes.foregroundColor, lineBuffer.attributes.backgroundColor); auto const codepoint = static_cast<char32_t>(lineBuffer.text[unbox<size_t>(columnOffset)]); lineNr = lineOffset; prevWidth = 0; prevHasCursor = false; output.screen.emplace_back(makeRenderCellExplicit(terminal.colorPalette(), codepoint, lineBuffer.attributes.styles, fg, bg, lineBuffer.attributes.underlineColor, lineOffset, columnOffset)); } for (auto columnOffset = textMargin; columnOffset < pageColumnsEnd; ++columnOffset) { auto const pos = CellLocation { lineOffset, columnOffset }; auto const gridPosition = terminal.viewport().translateScreenToGridCoordinate(pos); auto const [fg, bg] = makeColorsForCell(gridPosition, lineBuffer.attributes.styles, lineBuffer.attributes.foregroundColor, lineBuffer.attributes.backgroundColor); output.screen.emplace_back(makeRenderCellExplicit(terminal.colorPalette(), char32_t { 0 }, lineBuffer.attributes.styles, fg, bg, lineBuffer.attributes.underlineColor, lineOffset, columnOffset)); } auto const backIndex = output.screen.size() - 1; output.screen[frontIndex].groupStart = true; output.screen[backIndex].groupEnd = true; } template <typename Cell> void RenderBufferBuilder<Cell>::startLine(LineOffset _line) noexcept { isNewLine = true; lineNr = _line; prevWidth = 0; prevHasCursor = false; } template <typename Cell> void RenderBufferBuilder<Cell>::endLine() noexcept { if (!output.screen.empty()) { output.screen.back().groupEnd = true; } } template <typename Cell> void RenderBufferBuilder<Cell>::renderCell(Cell const& screenCell, LineOffset _line, ColumnOffset _column) { auto const pos = CellLocation { _line, _column }; auto const gridPosition = terminal.viewport().translateScreenToGridCoordinate(pos); auto const [fg, bg] = makeColorsForCell( gridPosition, screenCell.styles(), screenCell.foregroundColor(), screenCell.backgroundColor()); prevWidth = screenCell.width(); prevHasCursor = gridPosition == cursorPosition; auto const cellEmpty = screenCell.empty(); auto const customBackground = bg != terminal.colorPalette().defaultBackground || !!screenCell.styles(); switch (state) { case State::Gap: if (!cellEmpty || customBackground) { state = State::Sequence; output.screen.emplace_back(makeRenderCell(terminal.colorPalette(), terminal.state().hyperlinks, screenCell, fg, bg, _line, _column)); output.screen.back().groupStart = true; } break; case State::Sequence: if (cellEmpty && !customBackground) { output.screen.back().groupEnd = true; state = State::Gap; } else { output.screen.emplace_back(makeRenderCell(terminal.colorPalette(), terminal.state().hyperlinks, screenCell, fg, bg, _line, _column)); if (isNewLine) output.screen.back().groupStart = true; } break; } isNewLine = false; } } // namespace terminal #include <terminal/Cell.h> template class terminal::RenderBufferBuilder<terminal::Cell>;
42.265861
109
0.523159
herrhotzenplotz
920de613c60f302b0952759e25aff4c25e77389e
5,575
cpp
C++
src/SimulationClient.cpp
IBM/dna-replication
2569f71c6eed0e6e9e201c1d531c2a93b69efcbe
[ "MIT" ]
null
null
null
src/SimulationClient.cpp
IBM/dna-replication
2569f71c6eed0e6e9e201c1d531c2a93b69efcbe
[ "MIT" ]
null
null
null
src/SimulationClient.cpp
IBM/dna-replication
2569f71c6eed0e6e9e201c1d531c2a93b69efcbe
[ "MIT" ]
3
2019-11-02T06:15:13.000Z
2022-03-09T08:51:08.000Z
#include <fstream> #include <vector> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include "Simulation.h" #include "misc/DataManager.h" #include "particle_behaviors/IsotropicParticleDiffusionBehavior.h" #include "particle_behaviors/ProbabilisticParticleActivationBehavior.h" #include "particle_behaviors/ProbabilisticParticleBindingBehavior.h" #define MY_SUCCESS 0 #define MY_ERROR 1 #define MYOPT_HELP "help" #define MYOPT_ORIFILE "orifile" #define MYOPT_ASSYFILE "assyfile" #define MYOPT_STRUCTFILE "structfile" #define MYOPT_RNUCL "rnucl" #define MYOPT_XNUCL "xnucl" #define MYOPT_RPERY "rpery" #define MYOPT_RSPB "rspb" #define MYOPT_NPART "npart" #define MYOPT_HGRID "hgrid" #define MYOPT_PACT "pact" #define MYOPT_DCOEF "dcoef" #define MYOPT_DBIND "dbind" #define MYOPT_PBIND "pbind" #define MYOPT_VFORK "vfork" using namespace DNAReplication; int main(int argc, char *argv[]) { // client options boost::program_options::options_description opts_client("Client options"); opts_client.add_options() (MYOPT_HELP ",h", "Display help message"); // input data boost::program_options::options_description opts_indata("Input data"); opts_indata.add_options() (MYOPT_ORIFILE ",o", boost::program_options::value<std::string>()->required(), "Path to origin positions file (required)") (MYOPT_ASSYFILE ",c", boost::program_options::value<std::string>()->required(), "Path to assembly information file (required)") (MYOPT_STRUCTFILE ",s", boost::program_options::value<std::string>()->required(), "Path genome structure file (required)"); // simulation parameters boost::program_options::options_description opts_simulation("Simulation parameters"); opts_simulation.add_options() (MYOPT_RNUCL ",r", boost::program_options::value<double>()->required(), "Nucleus radius (required, in um)") (MYOPT_XNUCL ",x", boost::program_options::value<double>()->required(), "Nucleolus displacement (required, in um)") (MYOPT_RPERY ",q", boost::program_options::value<double>(), "Periphery radius (set for peripheral particle inactivation, in um)") (MYOPT_RSPB ",z", boost::program_options::value<double>(), "Spindle pole body radius (enables SPB-mediated particle activation, in um)") (MYOPT_NPART ",n", boost::program_options::value<unsigned short int>()->required(), "Number of activation factors (required)") (MYOPT_HGRID ",g", boost::program_options::value<double>()->required(), "Step size of the diffusion grid (required, in um)") (MYOPT_PACT ",a", boost::program_options::value<double>()->required(), "Activation probability (for SPB-mediated particle activation)") (MYOPT_DCOEF ",d", boost::program_options::value<double>()->required(), "Effective diffusion coefficient (required, in um2/s)") (MYOPT_DBIND ",b", boost::program_options::value<double>()->required(), "Maximal binding distance (required, in um)") (MYOPT_PBIND ",p", boost::program_options::value<double>()->required(), "Binding probability (required)") (MYOPT_VFORK ",f", boost::program_options::value<double>()->required(), "Replication fork velocity (required, in b/s)"); // parse command line boost::program_options::variables_map vm; try { boost::program_options::options_description opts; opts.add(opts_client).add(opts_indata).add(opts_simulation); boost::program_options::store(boost::program_options::parse_command_line(argc, argv, opts), vm); if (vm.count(MYOPT_HELP) > 0) { std::cout << "Runs a single DNA replication simulation." << std::endl; std::cout << opts << std::endl; return MY_SUCCESS; } boost::program_options::notify(vm); } catch (boost::program_options::error &e) { std::cerr << "ERROR: " << e.what() << std::endl; std::cerr << "Specify option '--" MYOPT_HELP "' to display a help message." << std::endl; return MY_ERROR; } // determine parameters bool const spbActivationEnabled = vm.count(MYOPT_RSPB) > 0; bool const peripheryInactivationEnabled = vm.count(MYOPT_RPERY) > 0; double const rSPB = spbActivationEnabled ? vm[MYOPT_RSPB].as<double>() : 0; double const rPeriphery = peripheryInactivationEnabled ? vm[MYOPT_RPERY].as<double>() : 0; IsotropicParticleDiffusionBehavior diffusionBehavior(vm[MYOPT_HGRID].as<double>(), vm[MYOPT_DCOEF].as<double>(), vm[MYOPT_RNUCL].as<double>(), vm[MYOPT_XNUCL].as<double>(), rSPB, rPeriphery); ProbabilisticParticleActivationBehavior activationBehavior(vm[MYOPT_PACT].as<double>(), spbActivationEnabled, peripheryInactivationEnabled); ProbabilisticParticleBindingBehavior bindingBehavior(vm[MYOPT_DBIND].as<double>(), vm[MYOPT_PBIND].as<double>()); // load data std::vector<Origin::OriginData> originData = DataManager::loadOriginData(vm[MYOPT_ORIFILE].as<std::string>()); std::vector<Chromosome::ChromosomeData> chromosomeData = DataManager::loadChromosomeData(vm[MYOPT_ASSYFILE].as<std::string>()); DataManager::initializeChromosomeGranules(chromosomeData, vm[MYOPT_STRUCTFILE].as<std::string>()); // run simulation Simulation sim(vm[MYOPT_VFORK].as<double>(), originData, chromosomeData, diffusionBehavior, activationBehavior, bindingBehavior); sim.initializeParticles(vm[MYOPT_NPART].as<unsigned short int>()); sim.run(); return MY_SUCCESS; }
58.072917
148
0.700987
IBM
920fc095c54a05ab23695b82a48f91203952fa06
5,063
cpp
C++
src/lib/core/base/BasicKeyManager.cpp
eirTony/EIRC2
e8cb7239cff9c0ddce72e63d41b352ec1b4d1eb5
[ "BSD-3-Clause" ]
null
null
null
src/lib/core/base/BasicKeyManager.cpp
eirTony/EIRC2
e8cb7239cff9c0ddce72e63d41b352ec1b4d1eb5
[ "BSD-3-Clause" ]
6
2016-04-12T02:41:00.000Z
2016-06-01T09:28:02.000Z
src/lib/core/base/BasicKeyManager.cpp
eirTony/EIRC2
e8cb7239cff9c0ddce72e63d41b352ec1b4d1eb5
[ "BSD-3-Clause" ]
null
null
null
#include "BasicKeyManager.h" #include "Diagnostic.h" #ifdef BUILD_TEST ///////// TEST BasicKeyManagerTest::BasicKeyManagerTest(QObject * parent) : TestObject("BaseLib/BasicKeyManager", parent) { TRACE("in BasicKeyManagerTest ctor", ""); } #endif //\\\\\\\ test BasicKeyManager::BasicKeyManager(void) {;} void BasicKeyManager::clear(void) { mKeyIdDMap.clear(); } BasicKey BasicKeyManager::key(const BasicId & id) const { return mKeyIdDMap.at(id); } BasicId BasicKeyManager::id(const BasicKey key) const { return mKeyIdDMap.at(key); } bool BasicKeyManager::contains(const BasicId & id) const { return mKeyIdDMap.contains(id); } bool BasicKeyManager::contains(const BasicKey key) const { return mKeyIdDMap.contains(key); } BasicKey::List BasicKeyManager::keys(const BasicId & startsWith) const { BasicKey::List keys; if (startsWith.isNull()) { keys.append(mKeyIdDMap.all(BasicKey())); } else { MUSTDO("startsWith"); } return keys; } void BasicKeyManager::trace(void) const { foreach (BasicKey k, keys()) TRACE("%1 = %2", QString("0x%1").arg(k(),16,16,QChar('0')), id(k)()); } #ifdef BUILD_TEST ///////// TEST void BasicKeyManagerTest::add(void) { mKeys.clear(); BasicKey keyAddS = mKeys.add(idS, current); QCOMPARE(keyS(), keyAddS()); BasicKey keyAddS0 = mKeys.add(idS0, current); QCOMPARE(keyS0(), keyAddS0()); } #endif //\\\\\\\ test BasicKey BasicKeyManager::add(const BasicId & id, const BasicKey base) { #if 1 TRACE("BKM:add(%1(%3), 0x%2)", id(), QString::number(base(),16).toUpper(), id.size()); BasicKey basicKey; BasicKey key = base.isNull() ? BasicKey::newKey() : base; WARNNOT(basicKey.isZero()); WARNIF(id.isNull()); WARNIF(mKeyIdDMap.contains(id)); if (mKeyIdDMap.contains(id)) return mKeyIdDMap.at(id); //------------- BasicId parents = id.parents(); WARNNOT(mKeyIdDMap.contains(parents) && id.size() > 1); BasicKey parentKey = mKeyIdDMap.at(parents); TRACE("Parents: %1 0x%2", parents(), QString::number(parentKey(),16).toUpper()); if (id.name().isEmpty()) { basicKey = parentKey; } else if (id.size() > 1 && parentKey.isValid()) { basicKey |= parentKey; basicKey.set(BasicKey::part(id), key); } else if (1 == id.size()) { basicKey.set(BasicKey::Part::UpperGroup, key); } mKeyIdDMap.insertUnique(basicKey, id); TRACE("Result: %1 0x%2", id(), QString::number(basicKey(),16).toUpper()); trace(); return basicKey; #else BasicKey answer; WARNMSGNOT(answer.isZero(), "BasicKey() should be zero"); if ( ! mKeyValueDMap.contains(id)) switch(id.size()) { case 1: answer = addUpperGroup(id); break; case 2: answer = addUpperValue(id); break; case 3: answer = addLowerGroup(id); break; case 4: answer = addLowerValue(id); break; default: /* leave null */ break; } return answer; #endif } BasicKey BasicKeyManager::addUpperGroup(const BasicId & id) { return newKey(BasicId(), BasicKey::LowerGroup, id.at(0)); } BasicKey BasicKeyManager::addUpperValue(const BasicId & id) { return newKey(id.at(0), BasicKey::LowerGroup, id.at(1)); } BasicKey BasicKeyManager::addLowerGroup(const BasicId & id) { BasicId prefixId(id.at(0)); prefixId += BasicName("0"); return newKey(prefixId, BasicKey::LowerGroup, id.at(2)); } BasicKey BasicKeyManager::addLowerValue(const BasicId & id) { BasicId prefixId(id.at(0)); prefixId += id.at(1); prefixId += id.at(2); return newKey(prefixId, BasicKey::LowerGroup, id.at(3)); } BasicKey BasicKeyManager::newKey(const BasicId & prefixId, const BasicKey::Part part, const BasicName & newName) { BasicId completeId = prefixId; completeId += newName; if (mKeyIdDMap.contains(completeId)) return BasicKey(); BasicKey answer = mKeyIdDMap.at(prefixId); if (answer.isNull()) return BasicKey(); NEEDDO("Catch hard loop"); do answer.set(part, BasicKey::newKey()); while (mKeyIdDMap.contains(answer)); mKeyIdDMap.insertUnique(answer, completeId); return answer; } bool BasicKeyManager::load(const KeyIdPairList & list) { clear(); foreach (KeyIdPair pair, list) mKeyIdDMap.insertUnique(pair.first, pair.second); return true; } #ifdef BUILD_BASICKEYMANAGERINSTANCE DEFINE_BASICSINGLETON(BasicKeyManagerInstance) BasicKeyManagerInstance::BasicKeyManagerInstance(void) {;} BasicKeyManagerInstance * gpBasicKeyManagerInstance = BasicKeyManagerInstance::pointer(); #endif
26.647368
70
0.601422
eirTony
9212b19d35ae43515484bada4220f4aad4d45c41
1,654
cpp
C++
examples/uvmsc/simple/registers/models/aliasing/sc_main.cpp
kopinions/uvm-systemc
c8171a98bc75b3ff3ec207d369e1b724ae64632f
[ "ECL-2.0", "Apache-2.0" ]
3
2019-08-16T14:24:43.000Z
2022-03-14T13:02:33.000Z
examples/uvmsc/simple/registers/models/aliasing/sc_main.cpp
ezchi/uvm-systemc
3368d7a1756514d7edd3415282dea812f4a5512a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
examples/uvmsc/simple/registers/models/aliasing/sc_main.cpp
ezchi/uvm-systemc
3368d7a1756514d7edd3415282dea812f4a5512a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
//---------------------------------------------------------------------- // Copyright 2004-2011 Synopsys, Inc. // Copyright 2010 Mentor Graphics Corporation // Copyright 2010-2011 Cadence Design Systems, Inc. // Copyright 2013-2014 NXP B.V. // All Rights Reserved Worldwide // // 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 <systemc> #include <uvm> #include "tb_test.h" //---------------------------------------------------------------------- // This example demonstrates how to model aliased registers // i.e. registers that are present at two physical addresses, // possibily with different access policies. // // In this case, we have a register "R" which is known under two names // "Ra" and "Rb". When accessed as "Ra", field F2 is RO. //---------------------------------------------------------------------- int sc_main(int, char*[]) { uvm::uvm_root::get()->set_report_verbosity_level(uvm::UVM_FULL); uvm::uvm_report_server::get_server()->set_max_quit_count(10); uvm::run_test("tb_test"); return 0; }
35.956522
72
0.585852
kopinions
9214939be76289e7a928231da04d3982c68517ff
3,043
cpp
C++
src/a_datastruct_queue_link.cpp
jinfeng95/algorithms
2a663fe53b494fc6b9dd56cefd368375734de7b0
[ "MIT" ]
null
null
null
src/a_datastruct_queue_link.cpp
jinfeng95/algorithms
2a663fe53b494fc6b9dd56cefd368375734de7b0
[ "MIT" ]
null
null
null
src/a_datastruct_queue_link.cpp
jinfeng95/algorithms
2a663fe53b494fc6b9dd56cefd368375734de7b0
[ "MIT" ]
null
null
null
/* Project: single_linked_queue (链队列) Date: 2018/09/17 Author: Frank Yu InitQueue(LinkQueue &Q) 参数:链队Q 功能:初始化 时间复杂度O(1) EnQueue(LinkQueue &Q,QElemType e) 参数:链队Q,元素e 功能:将e入队 时间复杂度:O(1) DeQueue(LinkQueue &Q,QElemType &e) 参数:链队Q,元素e 功能:队头出队,e接收出队元素值 时间复杂度O(1) GetHead(LinkQueue &Q,QElemType &e) 参数:链队Q,元素e 功能:得到队顶元素 时间复杂度O(1) 注意:有头结点 */ #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> using namespace std; #define Status int #define QElemType int //链队结点数据结构 typedef struct QNode { QElemType data;//数据域 struct QNode *next;//指针域 }QNode,*QueuePtr; typedef struct { struct QNode *front,*rear;//rear指针指向队尾 用于入队 front指针指向队头 用于出队 }LinkQueue; //**************************基本操作函数***************************// //初始化函数 Status InitQueue(LinkQueue &Q) { Q.front=Q.rear=new QNode;//生成新节点作为头结点,队头队尾指针均指向它 Q.front->next=NULL; return 1; } //入队函数 Status EnQueue(LinkQueue &Q,QElemType e) { QNode *p; p=new QNode;//生成新节点 p->data=e; //赋值 p->next=NULL; Q.rear->next=p;//加入队尾 Q.rear=p; //尾指针后移 return 1; } //出队函数 队头出队用e返回 注意释放空间 bool DeQueue(LinkQueue &Q,QElemType &e) { QueuePtr p; if(Q.front==Q.rear)return false;//队空 e=Q.front->next->data; //e返回值 之前写的Q.front->data 炸了,头结点没数据的,一定要注意头结点 p=Q.front->next; //保留,一会儿释放空间 Q.front->next=p->next; //出队,注意Q.front->next 不是Q.front 还有头结点 if(Q.rear==p)Q.rear=Q.front; //最后一个元素出队,rear指向头结点 free(p); return true; } //取队顶函数 用e返回 bool GetHead(LinkQueue &Q,QElemType &e) { if(Q.front==Q.rear) return false;//队列为空 e=Q.front->next->data; return true; } //**************************功能实现函数***************************// //菜单 void menu() { printf("********1.入队 2.出队*********\n"); printf("********3.取队顶元素 4.退出*********\n"); } //入队功能函数 调用EnQueue函数 void EnterToQueue(LinkQueue &Q) { int n;QElemType e;int flag; printf("请输入入队元素个数(>=1):\n"); scanf("%d",&n); for(int i=0;i<n;i++) { printf("请输入第%d个元素的值:",i+1); scanf("%d",&e); flag=EnQueue(Q,e); if(flag)printf("%d已入队\n",e); } } //出队功能函数 调用DeQueue函数 void DeleteFromQueue(LinkQueue &Q) { int n;QElemType e;int flag; printf("请输入出队元素个数(>=1):\n"); scanf("%d",&n); for(int i=0;i<n;i++) { flag=DeQueue(Q,e); if(flag)printf("%d已出队\n",e); else {printf("队已空!!!\n");break;} } } //取队顶功能函数 调用GetHead函数 void GetHeadOfStack(LinkQueue Q) { QElemType e;bool flag; flag=GetHead(Q,e); if(flag)printf("队头元素为:%d\n",e); else printf("队已空!!!\n"); } //主函数 int main() { LinkQueue Q;int choice; InitQueue(Q); while(1) { menu(); printf("请输入菜单序号:\n"); scanf("%d",&choice); if(4==choice) break; switch(choice) { case 1:EnterToQueue(Q);break; case 2:DeleteFromQueue(Q);break; case 3:GetHeadOfStack(Q);break; default:printf("输入错误!!!\n"); } } return 0; }
23.05303
81
0.564246
jinfeng95
9214a2d9b73606dcd4d3482ce885b05148700b6a
4,480
cpp
C++
WhispEngine/WhispEngine/PanelCreate.cpp
Empty-Whisper/WhispEngine
f1f8412377db24569ea2e2db7118b0339a11e85d
[ "MIT" ]
10
2019-10-09T15:58:03.000Z
2022-01-24T07:09:16.000Z
WhispEngine/WhispEngine/PanelCreate.cpp
Empty-Whisper/WhispEngine
f1f8412377db24569ea2e2db7118b0339a11e85d
[ "MIT" ]
8
2019-10-21T16:48:49.000Z
2019-10-26T14:25:43.000Z
WhispEngine/WhispEngine/PanelCreate.cpp
Empty-Whisper/WhispEngine
f1f8412377db24569ea2e2db7118b0339a11e85d
[ "MIT" ]
5
2019-10-15T09:17:21.000Z
2020-05-17T21:43:03.000Z
#include "PanelCreate.h" #include "Imgui/imgui.h" #include "Imgui/imgui_internal.h" // for ImGui::PushFlag #include "Application.h" #include "Globals.h" #include "mmgr/mmgr.h" PanelCreate::PanelCreate(const bool &start_active, const SDL_Scancode &shortcut1, const SDL_Scancode &shortcut2, const SDL_Scancode &shortcut3) :Panel("Create", start_active, shortcut1, shortcut2, shortcut3) { items.resize((int)Primitives::MAX); for (int i = 0; i < (int)Primitives::MAX; ++i) { switch ((Primitives)i) { case Primitives::CUBE: items[i] = "Cube"; break; case Primitives::TETRAHEDRON: items[i] = "Tetrahedron"; break; case Primitives::OCTAHEDRON: items[i] = "Octahedron"; break; case Primitives::DODECAHEDRON: items[i] = "Dodecahedron"; break; case Primitives::ICOSAHEDRON: items[i] = "Icosahedron"; break; case Primitives::SPHERE: items[i] = "Sphere"; break; case Primitives::HEMISPHERE: items[i] = "Hemisphere"; break; case Primitives::TORUS: items[i] = "Torus"; break; case Primitives::CONE: items[i] = "Cone"; break; case Primitives::CYLINDER: items[i] = "Cylinder"; break; default: LOG("Added more primitives than expected, add the missing primitives to the for"); break; } } iterator = items.begin() + (int)Primitives::CUBE; active = false; } PanelCreate::~PanelCreate() { } void PanelCreate::Update() { if (ImGui::Begin("Create", &active)) { if (ImGui::BeginCombo("Primitive", (*iterator).data())) { for (int n = 0; n < items.size(); n++) { if (ImGui::Selectable(items[n].data(), iterator - items.begin() == n)) iterator = items.begin() + n; } ImGui::EndCombo(); } ImGui::NewLine(); ImGui::PushItemWidth(100); ImGui::PushID("pos"); ImGui::Text("Position"); ImGui::SliderFloat("X", &data.pos.x, -15.f, 15.f); ImGui::SameLine(); ImGui::SliderFloat("Y", &data.pos.y, -15.f, 15.f); ImGui::SameLine(); ImGui::SliderFloat("Z", &data.pos.z, -15.f, 15.f); ImGui::PopID(); ImGui::Separator(); ImGui::PushID("rot"); ImGui::Text("Rotation"); ImGui::SliderFloat("X", &data.rotate.axis[0], 0.f, 1.f); ImGui::SameLine(); ImGui::SliderFloat("Y", &data.rotate.axis[1], 0.f, 1.f); ImGui::SameLine(); ImGui::SliderFloat("Z", &data.rotate.axis[2], 0.f, 1.f); ImGui::SliderFloat("Angle (rad)", &data.rotate.angle, 0.f, 6.28); ImGui::PopID(); ImGui::Separator(); ImGui::PushID("scale"); ImGui::Text("Scale"); ImGui::SliderFloat("X", &data.scale.x, 0.f, 5.f); ImGui::SameLine(); ImGui::SliderFloat("Y", &data.scale.y, 0.f, 5.f); ImGui::SameLine(); ImGui::SliderFloat("Z", &data.scale.z, 0.f, 5.f); ImGui::PopItemWidth(); ImGui::PopID(); ImGui::Separator(); ImGui::NewLine(); switch (Primitives(iterator-items.begin())) { case Primitives::SPHERE: ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); ImGui::SliderFloat("Radius", &data.radius, 0.1f, 5.f); ImGui::SliderInt("Rings", &data.rings, 3, 50); ImGui::SliderInt("Sectors", &data.slices, 3, 50); ImGui::PopStyleVar(); ImGui::PopItemFlag(); ImGui::SameLine(); ImGui::TextDisabled("(?)"); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); ImGui::TextUnformatted("That items will replace items below"); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } break; case Primitives::HEMISPHERE: ImGui::SliderInt("Slices", &data.slices, 3, 20); ImGui::SliderInt("Rings", &data.rings, 3, 20); break; case Primitives::TORUS: ImGui::SliderInt("Slices", &data.slices, 3, 20); ImGui::SliderInt("Rings", &data.rings, 3, 20); ImGui::SliderFloat("Radius", &data.radius, 0.1f, 0.9999f); break; case Primitives::CONE: ImGui::SliderInt("Slices", &data.slices, 3, 20); ImGui::SliderInt("Rings", &data.rings, 3, 20); break; case Primitives::CYLINDER: ImGui::SliderInt("Slices", &data.slices, 3, 20); ImGui::SliderInt("Rings", &data.rings, 3, 20); break; default: break; } ImGui::ColorEdit3("Face color", data.face_color); ImGui::ColorEdit3("Wire color", data.wire_color); ImGui::NewLine(); if (ImGui::Button("Create")) { //App->object_manager->CreatePrimitive((Primitives)(iterator - items.begin()), data); } ImGui::SameLine(); if (ImGui::Button("Demo")) { //App->object_manager->Demo(); } } ImGui::End(); }
27.151515
143
0.642188
Empty-Whisper
9215cd4280a9b341ee18292b18834ad134f3ee16
6,783
cpp
C++
apps/viewer.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
null
null
null
apps/viewer.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
null
null
null
apps/viewer.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
null
null
null
#include <iostream> #include <OgreApplicationContext.h> #include <core/SceneAccessInterface.h> #include <core/OgreX3DPlugin.h> #include <OgreOverlaySystem.h> #include <OgreTrays.h> #include <OgreAdvancedRenderControls.h> #include <OgreCameraMan.h> #include <OgreSceneLoaderManager.h> #include <World/Viewpoint.h> #if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN #include <emscripten/bind.h> void emloop(void* target) { Ogre::WindowEventUtilities::messagePump(); try { static_cast<Ogre::Root*>(target)->renderOneFrame(); } catch (std::exception& e) { std::cout << e.what() << std::endl; emscripten_cancel_main_loop(); } } #endif namespace { void printSceneGraph(Ogre::SceneNode* node, const std::string& tabs = "") { std::cout << tabs << node->getName() << std::endl; Ogre::SceneNode::ObjectIterator mo = node->getAttachedObjectIterator(); while(mo.hasMoreElements()) { std::cout << tabs+"\t" << mo.getNext()->getName() << std::endl; } Ogre::SceneNode::ChildNodeIterator j = node->getChildIterator(); while(j.hasMoreElements()) { printSceneGraph(static_cast<Ogre::SceneNode*>(j.getNext()), tabs+"\t"); } } struct X3Ogre : public OgreBites::ApplicationContext, OgreBites::InputListener { std::unique_ptr<X3D::SceneAccessInterface> _sai; std::unique_ptr<OgreBites::TrayManager> _trays; std::unique_ptr<OgreBites::AdvancedRenderControls> _controls; std::unique_ptr<OgreBites::CameraMan> _camman; Ogre::SceneManager* _sceneManager = nullptr; X3Ogre() : OgreBites::ApplicationContext("x3ogre") { initApp(); } ~X3Ogre() { closeApp(); } // SAI like API bool nodeExists(const std::string& node) { return _sai->scene()->nodeExists(node); } void setNodeAttribute(const std::string& node, const std::string& field, const std::string& value) { _sai->setNodeAttribute(node, field, value); } std::string getNodeAttribute(const std::string& node, const std::string& field) { return _sai->getNodeAttribute(node, field); } void loadFile(const std::string& file) { // add X3D path to Ogre resources Ogre::String filename, basepath; Ogre::StringUtil::splitFilename(file, filename, basepath); if (!basepath.empty() && !Ogre::ResourceGroupManager::getSingleton().resourceLocationExists(basepath, "X3D")) { // Counts for android, since APK located files (crash if basepath is empty) Ogre::ResourceGroupManager::getSingleton().addResourceLocation(basepath, "FileSystem", "X3D", true); Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("X3D"); } if(_controls) { removeInputListener(_controls.get()); _controls.reset(); } if(_camman) { removeInputListener(_camman.get()); _camman.reset(); } if (_sceneManager) { mShaderGenerator->removeSceneManager(_sceneManager); mRoot->destroySceneManager(_sceneManager); mShaderGenerator->removeAllShaderBasedTechniques(); mShaderGenerator->flushShaderCache(); } // Remove old Viewport if present if (getRenderWindow()->hasViewportWithZOrder(0)) { getRenderWindow()->removeViewport(0); } _sceneManager = mRoot->createSceneManager(); mShaderGenerator->addSceneManager(_sceneManager); _sceneManager->addRenderQueueListener(getOverlaySystem()); Ogre::SceneLoaderManager::getSingleton().load(filename, "X3D", _sceneManager->getRootSceneNode()); // SAI init _sai.reset(new X3D::SceneAccessInterface(_sceneManager->getRootSceneNode())); _sai->addEssentialNodes(); // ensure we have a X3D::Viewpoint auto cam =_sai->scene()->bound<X3D::Viewpoint>()->getCamera(); _sai->scene()->setViewport(getRenderWindow()->addViewport(cam)); _controls.reset(new OgreBites::AdvancedRenderControls(_trays.get(), cam)); addInputListener(_controls.get()); _camman.reset(new OgreBites::CameraMan(cam->getParentSceneNode())); _camman->setStyle(OgreBites::CS_ORBIT); _camman->setYawPitchDist(Ogre::Radian(0), Ogre::Radian(0), _sai->getWorldSize()); addInputListener(_camman.get()); } // internal API void setup() override { // Ogre setup OgreBites::ApplicationContext::setup(); _trays.reset(new OgreBites::TrayManager("Interface", getRenderWindow())); addInputListener(_trays.get()); _trays->showFrameStats(OgreBites::TL_BOTTOMLEFT); _trays->hideCursor(); addInputListener(this); // register x3d file loader getRoot()->installPlugin(new X3D::OgreX3DPlugin); } void loop() { #if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN emscripten_set_main_loop_arg(emloop, getRoot(), 0, 0); #else getRoot()->startRendering(); #endif } void shutdown() override { getRoot()->removeFrameListener(_sai.get()); removeInputListener(this); removeInputListener(_trays.get()); removeInputListener(_controls.get()); _controls.reset(); _sai.reset(); _trays.reset(); } bool keyPressed(const OgreBites::KeyboardEvent& evt) override { using namespace OgreBites; switch(evt.keysym.sym) { case SDLK_ESCAPE: getRoot()->queueEndRendering(); break; case 'b': _sai->switchDebugDrawing(); break; case 'n': loadFile("../examples/flipper.x3d"); break; case 'w': _camman->setYawPitchDist(Ogre::Radian(0), Ogre::Radian(0), _sai->getWorldSize()); break; case 'x': auto comp = getNodeAttribute("vp", "compositors").empty() ? "Night Vision" : ""; setNodeAttribute("vp", "compositors", comp); break; } return true; } }; } #if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN EMSCRIPTEN_BINDINGS(my_module) { using namespace emscripten; class_<X3Ogre>("X3Ogre") .constructor() .function("loop", &X3Ogre::loop) .function("setNodeAttribute", &X3Ogre::setNodeAttribute) .function("getNodeAttribute", &X3Ogre::getNodeAttribute) .function("nodeExists", &X3Ogre::nodeExists) .function("loadFile", &X3Ogre::loadFile); } #else int main(int argc, char* argv[]) { if (argc < 2) return 1; // Ogre setup X3Ogre context; context.loadFile(argv[1]); context.loop(); return 0; } #endif
31.696262
117
0.626566
jess22664
921b87e4aff889a0d63cfe0ca6f0ba6c13f72dc7
945
cpp
C++
WTesterClient/widget_setting.cpp
RockRockWhite/WTester
50a9de8ba7c48738eb054680d6eae0a2fc0c06e3
[ "MIT" ]
null
null
null
WTesterClient/widget_setting.cpp
RockRockWhite/WTester
50a9de8ba7c48738eb054680d6eae0a2fc0c06e3
[ "MIT" ]
null
null
null
WTesterClient/widget_setting.cpp
RockRockWhite/WTester
50a9de8ba7c48738eb054680d6eae0a2fc0c06e3
[ "MIT" ]
null
null
null
#include "widget_setting.h" #include "ui_widget_setting.h" #include <QSettings> #include <QMessageBox> #include <QTextCodec> #pragma execution_character_set("utf-8") widget_setting::widget_setting(QWidget *parent) : QWidget(parent), ui(new Ui::widget_setting) { ui->setupUi(this); QSettings setting("\config.ini",QSettings::IniFormat); ui->lineEdit_server_ip->setText(setting.value("setting/IP").toString()); ui->lineEdit_server_port->setText(setting.value("setting/PORT").toString()); } widget_setting::~widget_setting() { delete ui; } void widget_setting::on_pushButton_2_clicked() { this->close(); } void widget_setting::on_pushButton_save_clicked() { QSettings setting("\config.ini",QSettings::IniFormat); setting.setValue("setting/IP",ui->lineEdit_server_ip->text()); setting.setValue("setting/PORT",ui->lineEdit_server_port->text()); QMessageBox::information(this,"提示","您的配置已保存!"); }
25.540541
80
0.725926
RockRockWhite
921cf50c31aca727db5aeb62877e8428ce7318bf
280
hpp
C++
include/RN_Generators.hpp
temken/DaMaSCUS
14be6907230e5ef1b93809a6fb5842330497a7a6
[ "MIT" ]
3
2018-09-13T13:36:50.000Z
2021-10-30T19:35:12.000Z
include/RN_Generators.hpp
temken/DaMaSCUS
14be6907230e5ef1b93809a6fb5842330497a7a6
[ "MIT" ]
2
2017-06-06T14:43:45.000Z
2022-03-16T13:01:56.000Z
include/RN_Generators.hpp
temken/DaMaSCUS
14be6907230e5ef1b93809a6fb5842330497a7a6
[ "MIT" ]
1
2017-06-09T09:48:10.000Z
2017-06-09T09:48:10.000Z
#ifndef __RN_Generators_hpp_ #define __RN_Generators_hpp_ #include <random> extern double ProbabilitySample(std::mt19937& PRNG); extern double MaxwellSample(std::mt19937& PRNG); extern double ThetaSample(std::mt19937& PRNG); extern double PhiSample(std::mt19937& PRNG); #endif
23.333333
52
0.8
temken
921d03f02be8e6d7bac76812068586898e5621c3
5,649
cpp
C++
unit_tests/gen8/image_tests_gen8.cpp
cmey/compute-runtime
118bad16dfe523724dfaf8016bfa6fbe6896348b
[ "MIT" ]
null
null
null
unit_tests/gen8/image_tests_gen8.cpp
cmey/compute-runtime
118bad16dfe523724dfaf8016bfa6fbe6896348b
[ "MIT" ]
null
null
null
unit_tests/gen8/image_tests_gen8.cpp
cmey/compute-runtime
118bad16dfe523724dfaf8016bfa6fbe6896348b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018, Intel Corporation * * 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 "unit_tests/fixtures/image_fixture.h" #include "unit_tests/mocks/mock_context.h" #include "test.h" using namespace OCLRT; typedef ::testing::Test gen8ImageTests; GEN8TEST_F(gen8ImageTests, appendSurfaceStateParamsDoesNothing) { typedef typename FamilyType::RENDER_SURFACE_STATE RENDER_SURFACE_STATE; MockContext context; auto image = std::unique_ptr<Image>(ImageHelper<Image1dDefaults>::create(&context)); auto surfaceStateBefore = RENDER_SURFACE_STATE::sInit(); auto surfaceStateAfter = RENDER_SURFACE_STATE::sInit(); auto imageHw = static_cast<ImageHw<FamilyType> *>(image.get()); EXPECT_EQ(0, memcmp(&surfaceStateBefore, &surfaceStateAfter, sizeof(RENDER_SURFACE_STATE))); imageHw->appendSurfaceStateParams(&surfaceStateAfter); EXPECT_EQ(0, memcmp(&surfaceStateBefore, &surfaceStateAfter, sizeof(RENDER_SURFACE_STATE))); } GEN8TEST_F(gen8ImageTests, WhenGetHostPtrRowOrSlicePitchForMapIsCalledOnMipMappedImageWithMipLevelZeroThenReturnWidthTimesBytesPerPixelAndRowPitchTimesHeight) { MockContext context; cl_image_desc imageDesc{}; imageDesc.image_type = CL_MEM_OBJECT_IMAGE3D; imageDesc.image_width = 5; imageDesc.image_height = 5; imageDesc.image_depth = 5; imageDesc.num_mip_levels = 2; std::unique_ptr<Image> image(ImageHelper<Image3dDefaults>::create(&context, &imageDesc)); auto rowPitch = image->getHostPtrRowPitchForMap(0u); auto slicePitch = image->getHostPtrSlicePitchForMap(0u); EXPECT_EQ(4 * imageDesc.image_width, rowPitch); EXPECT_EQ(imageDesc.image_height * rowPitch, slicePitch); } GEN8TEST_F(gen8ImageTests, WhenGetHostPtrRowOrSlicePitchForMapIsCalledOnMipMappedImageWithMipLevelNonZeroThenReturnScaledWidthTimesBytesPerPixelAndRowPitchTimesScaledHeight) { MockContext context; cl_image_desc imageDesc{}; imageDesc.image_type = CL_MEM_OBJECT_IMAGE3D; imageDesc.image_width = 5; imageDesc.image_height = 5; imageDesc.image_depth = 5; imageDesc.num_mip_levels = 2; std::unique_ptr<Image> image(ImageHelper<Image3dDefaults>::create(&context, &imageDesc)); auto rowPitch = image->getHostPtrRowPitchForMap(1u); auto slicePitch = image->getHostPtrSlicePitchForMap(1u); EXPECT_EQ(4 * (imageDesc.image_width >> 1), rowPitch); EXPECT_EQ((imageDesc.image_height >> 1) * rowPitch, slicePitch); } GEN8TEST_F(gen8ImageTests, WhenGetHostPtrRowOrSlicePitchForMapIsCalledOnMipMappedImageWithMipLevelNonZeroThenReturnScaledWidthTimesBytesPerPixelAndRowPitchTimesScaledHeightCannotBeZero) { MockContext context; cl_image_desc imageDesc{}; imageDesc.image_type = CL_MEM_OBJECT_IMAGE3D; imageDesc.image_width = 5; imageDesc.image_height = 5; imageDesc.image_depth = 5; imageDesc.num_mip_levels = 5; std::unique_ptr<Image> image(ImageHelper<Image3dDefaults>::create(&context, &imageDesc)); auto rowPitch = image->getHostPtrRowPitchForMap(4u); auto slicePitch = image->getHostPtrSlicePitchForMap(4u); EXPECT_EQ(4u, rowPitch); EXPECT_EQ(rowPitch, slicePitch); } GEN8TEST_F(gen8ImageTests, WhenGetHostPtrRowOrSlicePitchForMapIsCalledOnNonMipMappedImageThenReturnRowPitchAndSlicePitch) { MockContext context; cl_image_desc imageDesc{}; imageDesc.image_type = CL_MEM_OBJECT_IMAGE3D; imageDesc.image_width = 5; imageDesc.image_height = 5; imageDesc.image_depth = 5; imageDesc.num_mip_levels = 0; std::unique_ptr<Image> image(ImageHelper<Image3dDefaults>::create(&context, &imageDesc)); auto rowPitch = image->getHostPtrRowPitchForMap(0u); auto slicePitch = image->getHostPtrSlicePitchForMap(0u); EXPECT_EQ(image->getHostPtrRowPitch(), rowPitch); EXPECT_EQ(image->getHostPtrSlicePitch(), slicePitch); } GEN8TEST_F(gen8ImageTests, givenImageForGen8WhenClearColorParametersAreSetThenSurfaceStateIsNotModified) { typedef typename FamilyType::RENDER_SURFACE_STATE RENDER_SURFACE_STATE; MockContext context; auto image = std::unique_ptr<Image>(ImageHelper<Image1dDefaults>::create(&context)); auto surfaceStateBefore = RENDER_SURFACE_STATE::sInit(); auto surfaceStateAfter = RENDER_SURFACE_STATE::sInit(); auto imageHw = static_cast<ImageHw<FamilyType> *>(image.get()); EXPECT_EQ(0, memcmp(&surfaceStateBefore, &surfaceStateAfter, sizeof(RENDER_SURFACE_STATE))); imageHw->setClearColorParams(&surfaceStateAfter, imageHw->getGraphicsAllocation()->gmm); EXPECT_EQ(0, memcmp(&surfaceStateBefore, &surfaceStateAfter, sizeof(RENDER_SURFACE_STATE))); }
45.556452
187
0.779076
cmey
921dc15dceff6350cb59a41acd2a84a0fd2a8dc4
1,852
cpp
C++
phoenix/qt/widget/check-button.cpp
vgmtool/vgm2pre
f4f917df35d531512292541234a5c1722b8af96f
[ "MIT" ]
21
2015-04-13T03:07:12.000Z
2021-11-20T00:27:00.000Z
phoenix/qt/widget/check-button.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2015-10-06T14:59:48.000Z
2022-01-27T08:57:57.000Z
phoenix/qt/widget/check-button.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2021-11-19T08:36:57.000Z
2022-03-04T16:03:16.000Z
namespace phoenix { Size pCheckButton::minimumSize() { Size size = pFont::size(qtWidget->font(), checkButton.state.text); if(checkButton.state.orientation == Orientation::Horizontal) { size.width += checkButton.state.image.width; size.height = max(checkButton.state.image.height, size.height); } if(checkButton.state.orientation == Orientation::Vertical) { size.width = max(checkButton.state.image.width, size.width); size.height += checkButton.state.image.height; } return {size.width + 20, size.height + 12}; } void pCheckButton::setChecked(bool checked) { locked = true; qtCheckButton->setChecked(checked); locked = false; } void pCheckButton::setImage(const image& image, Orientation orientation) { qtCheckButton->setIconSize(QSize(image.width, image.height)); qtCheckButton->setIcon(CreateIcon(image)); qtCheckButton->setStyleSheet("text-align: top;"); switch(orientation) { case Orientation::Horizontal: qtCheckButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); break; case Orientation::Vertical: qtCheckButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); break; } } void pCheckButton::setText(string text) { qtCheckButton->setText(QString::fromUtf8(text)); } void pCheckButton::constructor() { qtWidget = qtCheckButton = new QToolButton; qtCheckButton->setCheckable(true); qtCheckButton->setToolButtonStyle(Qt::ToolButtonTextOnly); connect(qtCheckButton, SIGNAL(toggled(bool)), SLOT(onToggle(bool))); pWidget::synchronizeState(); setChecked(checkButton.state.checked); setText(checkButton.state.text); } void pCheckButton::destructor() { } void pCheckButton::orphan() { destructor(); constructor(); } void pCheckButton::onToggle(bool checked) { checkButton.state.checked = checked; if(!locked && checkButton.onToggle) checkButton.onToggle(); } }
28.9375
103
0.74406
vgmtool
921f0c2bc764b55cdb3c9d8ca033c1c1b9fe864c
7,654
cpp
C++
bin/setsketchscreener.cpp
dnbh/kpg
c9e79b8092434919e9ac90dc199f49845403c2ba
[ "MIT" ]
69
2018-01-08T19:56:55.000Z
2022-03-05T17:14:05.000Z
bin/setsketchscreener.cpp
dnbaker/emp
c9e79b8092434919e9ac90dc199f49845403c2ba
[ "MIT" ]
6
2018-04-14T21:09:51.000Z
2021-07-17T21:08:54.000Z
bin/setsketchscreener.cpp
dnbaker/emp
c9e79b8092434919e9ac90dc199f49845403c2ba
[ "MIT" ]
11
2018-03-21T19:28:35.000Z
2021-06-29T17:33:34.000Z
#include <getopt.h> #include <unistd.h> #include <sys/stat.h> #include <cstdio> #include <memory> #include <cstdint> #include <vector> #include <chrono> #include <string> #include <iostream> #include <fstream> #include <numeric> #include <cassert> #include <thread> #ifdef _OPENMP #include <omp.h> #endif #include <zlib.h> #include "bonsai/ssi.h" #include "bonsai/encoder.h" #if _OPENMP #define OMP_ELSE(x, y) x #define OMP_ONLY(...) __VA_ARGS__ #else # define OMP_ELSE(x, y) y #define OMP_ONLY(...) #endif using namespace bns::lsh; using namespace bns; //#include "flat_hash_map/flat_hash_map.hpp" using MapT = ska::flat_hash_map<uint64_t, uint32_t>; using std::uint64_t; using std::uint32_t; int usage() { std::fprintf(stderr, "Usage: setsketchscreener <opts> setsketch.db [input sequence files..]\n" "-c: cyclic hash\n" "-N: use cyclic hash\n" "-C: Do not canonicalize\n" "-P: Enable protein encoding (implies cylic)\n" ); return 1; } template<typename Func> void for_each_kmer(Encoder<> &enc, RollingHasher<uint64_t> &rolling_hasher, const std::string &path, const int htype, const Func &func, kseq_t *kseq=static_cast<kseq_t*>(nullptr)) { if(htype == 0) { enc.for_each(func, path.data(), kseq); } else if(htype == 1) { rolling_hasher.for_each_hash(func, path.data(), kseq); } else if(htype == 2) { enc.for_each_hash(func, path.data(), kseq); } else { std::fprintf(stderr, "Error: this should never happen. htype should be [0, 1, 2]\n"); std::exit(EXIT_FAILURE); } } // Step 1: load k-mer files // Step 2: invert matrix ska::flat_hash_map<uint64_t, std::vector<uint32_t>> read_file(gzFile fp) { auto timestart = std::chrono::high_resolution_clock::now(); uint64_t arr[2]; gzread(fp, arr, sizeof(arr)); std::unique_ptr<uint32_t[]> data(new uint32_t[arr[0]]); gzread(fp, data.get(), sizeof(uint32_t) * arr[0]); std::unique_ptr<uint64_t[]> keys(new uint64_t[arr[0]]); gzread(fp, data.get(), sizeof(uint64_t) * arr[0]); ska::flat_hash_map<uint64_t, std::vector<uint32_t>> map; std::vector<uint32_t> buffer; map.reserve(arr[0]); size_t total_ids_read = 0; for(size_t i = 0; i < arr[0]; ++i) { //if(i % 256 == 0) std::fprintf(stderr, "%zu/%zu, read %zu\n", i + 1, size_t(arr[1]), total_ids_read); const auto nids = data[i]; buffer.resize(nids); gzread(fp, buffer.data(), sizeof(uint32_t) * nids); total_ids_read += nids; map.emplace(keys[i], buffer); } std::fprintf(stderr, "Time to deserialize: %gms\n", std::chrono::duration<double, std::milli>(std::chrono::high_resolution_clock::now() - timestart).count()); return map; } MapT process(bns::Encoder<> *encoders, bns::RollingHasher<uint64_t> *rencoders, kseq_t *kseqs, std::vector<MapT> &matchcounts, int htype, const std::string &fn, int nthreads, std::vector<std::pair<char *, size_t>> &seqbuffers); int main(int argc, char **argv) { bool basename = false; int ret = 0; std::vector<std::string> names; std::FILE *ofp = stdout; std::string kmerparsetype = "bns"; bool enable_protein = false; bool canon = true; int k = -1, nthreads = 1; const size_t initsize = 2000000; for(int c;(c = getopt(argc, argv, "pPCcNk:o:F:bh")) >= 0;) switch(c) { case 'p': nthreads = std::atoi(optarg); break; case 'b': basename = true; break; case 'c': kmerparsetype = "cyclic"; break; case 'C': canon = true; break; case 'h': case '?': return usage(); case 'o': if(!(ofp = std::fopen(optarg, "w"))) {std::fprintf(stderr, "Could not open file at %s\n", optarg); std::abort();} break; case 'k': k = std::atoi(optarg); break; case 'P': enable_protein = true; kmerparsetype = "cyclic"; break; case 'N': kmerparsetype = "nthash"; break; case 'F': { std::ifstream ifs(optarg); for(std::string s; std::getline(ifs, s);) names.push_back(s); } } if(nthreads <= 0) nthreads = 1; const int htype = kmerparsetype == "bns" ? 0: kmerparsetype == "cyclic"? 1: 2; if(argc == optind) throw 1; else if(argc == optind + 1) { if(names.empty()) throw std::runtime_error("no query paths provided"); } else names.insert(names.end(), argv + optind + 1, argv + argc); auto mapk = read_database(argv[optind]); auto map = std::move(mapk.first); auto loaded_k = mapk.second; if(k < 0) { if(loaded_k <= 0) throw std::invalid_argument("k must be provided by command-line or at db construction."); } else k = loaded_k; MapT counter; counter.reserve(map.size()); for(const auto &pair: map) counter.emplace(pair.first, 0u); std::fprintf(stderr, "map size %zu and total number of ids %zu\n", map.size(), std::accumulate(map.begin(), map.end(), size_t(0), [](size_t x, auto &y) {return x + y.second.size();})); if(names.empty()) return usage(); const RollingHashingType alphabet = enable_protein ? RollingHashingType::PROTEIN: RollingHashingType::DNA; const size_t memtoalloc = (sizeof(bns::RollingHasher<uint64_t>) + sizeof(bns::Encoder<>)) * nthreads + 63; std::unique_ptr<uint8_t> mem(new uint8_t[memtoalloc]); uint8_t *memp = mem.get(), *ap = reinterpret_cast<uint8_t *>(reinterpret_cast<uint64_t>(memp) + (uint64_t)memp % 64 ? int(64 - (uint64_t)memp % 64): 0); bns::RollingHasher<uint64_t> *rencoders = (bns::RollingHasher<uint64_t> *)ap; bns::Encoder<> *encoders = (bns::Encoder<> *)(&rencoders[nthreads]); kseq_t *kseqs = static_cast<kseq_t *>(std::calloc(nthreads, sizeof(kseq_t))); std::vector<MapT> matchcounts(nthreads); std::vector<std::pair<char *, size_t>> seqbuffers; OMP_PFOR for(int idx = 0; idx < nthreads; ++idx) { auto &back = kseqs[idx]; back.seq.m = initsize; back.seq.s = static_cast<char *>(std::malloc(initsize)); new (encoders + idx) Encoder<>(k, canon); new (rencoders + idx) RollingHasher<uint64_t>(k, canon, alphabet); } std::vector<MapT> results; results.reserve(names.size()); for(const auto &fn: names) { results.push_back(process(encoders, rencoders, kseqs, matchcounts, htype, fn, nthreads, seqbuffers)); //for_each_kmer(encoder, renc, fn.data(), htype, } OMP_PFOR for(int i = 0; i < nthreads; ++i) { kseq_destroy_stack(kseqs[i]); encoders[i].~Encoder<>(); rencoders[i].~RollingHasher<uint64_t>(); } std::free(kseqs); return 0; } MapT process(bns::Encoder<> *encoders, bns::RollingHasher<uint64_t> *rencoders, kseq_t *kseqs, std::vector<MapT> &matchcounts, int htype, const std::string &fn, int nthreads, std::vector<std::pair<char *, size_t>> &seqbuffers) { #if 0 for(auto &m: matchcounts) m.clear(); for(auto &pair: seqbuffers) std::free(seqbuffers.first), seqbuffers.first = 0; gzFile ifp = gzopen(fn.data(), "rb"); kseq_assign(kseqs, ifp); for(;kseq_read(kseqs) >= 0;) { std::pair<char *, size_t> tup; tup.first = (char *)std::malloc(kseqs->seq.l + 1); std::memcpy(tup.first, kseqs->seq.s, kseqs->seq.l + 1); tup.second = kseqs->seq.l; } OMP_PFOR for(size_t i = 0; i < seqbuffers.size(); ++i) { } gzclose(ifp); par_reduce(matchcounts.data(), matchcounts.size()); return matchcounts.front(); // Copy is implied #endif return MapT(); }
38.462312
188
0.615103
dnbh
921f51a06063630f5746ec98482fd55037faaeeb
5,318
cc
C++
tools/hgdb-replay/hgdb-replay.cc
Kuree/hgdb
8a4771cff437979c1934efd1f07436aa5a36f2e9
[ "BSD-2-Clause" ]
34
2021-01-19T21:14:06.000Z
2022-03-31T18:42:58.000Z
tools/hgdb-replay/hgdb-replay.cc
Kuree/hgdb
8a4771cff437979c1934efd1f07436aa5a36f2e9
[ "BSD-2-Clause" ]
33
2021-01-12T18:50:16.000Z
2022-03-23T04:49:20.000Z
tools/hgdb-replay/hgdb-replay.cc
Kuree/hgdb
8a4771cff437979c1934efd1f07436aa5a36f2e9
[ "BSD-2-Clause" ]
2
2021-03-28T06:58:46.000Z
2022-03-31T02:55:53.000Z
#include <filesystem> #include <iostream> #include "argparse/argparse.hpp" #include "engine.hh" #include "log.hh" #include "sim.hh" #ifdef USE_FSDB #include "../fsdb/fsdb.hh" #endif #define STRINGIFY2(X) #X #define STRINGIFY(X) STRINGIFY2(X) #define VERSION_STR STRINGIFY(VERSION_NUMBER) std::optional<argparse::ArgumentParser> get_args(int argc, char **argv) { argparse::ArgumentParser program("HGDB Replay", VERSION_STR); std::string program_name; if (std::getenv("HGDB_PYTHON_PACKAGE")) { auto path = std::filesystem::path(program_name); program_name = path.filename(); } else { program_name = argv[0]; } // make the program name look nicer argv[0] = const_cast<char *>(program_name.c_str()); program.add_argument("filename").help("Waveform file in either VCD or FSDB format").required(); // optional argument for vcd program.add_argument("--db").implicit_value(true).default_value(false); // we can specify the port as well instead of changing it in the env by hand program.add_argument("--port", "-p") .help("Debug port") .default_value<uint16_t>(0) .scan<'d', uint16_t>(); program.add_argument("--debug").implicit_value(true).default_value(false); program.add_argument("--start-time", "-s").default_value<uint64_t>(0).help("When to start the replay").scan<'d', uint64_t>(); try { program.parse_args(argc, argv); return program; } catch (const std::runtime_error &err) { std::cerr << err.what() << std::endl; std::cerr << program; return std::nullopt; } } bool is_vcd(const std::string &filename) { // heuristics to detect if it's vcd std::ifstream stream(filename); std::array<char, 1> buffer = {0}; stream.read(buffer.data(), sizeof(buffer)); stream.close(); return buffer[0] == '$'; } void set_port(hgdb::replay::ReplayVPIProvider *vpi, uint16_t port) { // only try to override the env when the port is not 0 if (port > 0) { auto str = "+DEBUG_PORT=" + std::to_string(port); vpi->add_argv(str); } } void set_debug_log(hgdb::replay::ReplayVPIProvider *vpi, bool enable) { if (enable) { auto constexpr str = "+DEBUG_LOG"; vpi->add_argv(str); } } // NOLINTNEXTLINE int main(int argc, char *argv[]) { auto program = get_args(argc, argv); if (!program) { return EXIT_FAILURE; } namespace log = hgdb::log; auto filename = program->get("filename"); std::unique_ptr<hgdb::waveform::WaveformProvider> db; if (is_vcd(filename)) { log::log(log::log_level::info, "Building VCD database..."); auto has_store_db_flag = program->get<bool>("--db"); db = std::make_unique<hgdb::vcd::VCDDatabase>(filename, has_store_db_flag); } else { #ifdef USE_FSDB db = std::make_unique<hgdb::fsdb::FSDBProvider>(filename); #endif } if (!db) { log::log(log::log_level::error, "Unable to read file " + filename); return EXIT_FAILURE; } // notice that db will lose ownership soon. use raw pointer instead auto *db_ptr = db.get(); auto vpi = std::make_unique<hgdb::replay::ReplayVPIProvider>(std::move(db)); auto *vpi_ = vpi.get(); // set argv vpi->set_argv(argc, argv); // set port if necessary set_port(vpi.get(), program->get<uint16_t>("--port")); // we use plus args set_debug_log(vpi.get(), program->get<bool>("--debug")); vpi->set_timestamp(program->get<uint64_t>("-s")); hgdb::replay::EmulationEngine engine(vpi.get()); // set up the debug runtime log::log(log::log_level::info, "Initializing HGDB runtime..."); auto *debugger = hgdb::initialize_hgdb_runtime_vpi(std::move(vpi), false); // we use hex string by default debugger->set_option("use_hex_str", true); // set the custom vpi allocator debugger->rtl_client()->set_vpi_allocator([vpi_]() { return vpi_->get_new_handle(); }); // set callback on client connected debugger->set_on_client_connected([vpi_, debugger](hgdb::SymbolTableProvider &table) { auto names = table.get_all_array_names(); std::vector<std::string> full_names; full_names.reserve(names.size()); std::transform( names.begin(), names.end(), std::back_inserter(full_names), [debugger](const std::string &n) { return debugger->rtl_client()->get_full_name(n); }); vpi_->build_array_table(full_names); }); log::log(log::log_level::info, "Calculating design hierarchy..."); // set the custom compute function // compute the mapping if definition not available if (!db_ptr->has_inst_definition()) { auto mapping_func = [db_ptr](const std::unordered_set<std::string> &instance_names) -> std::unordered_map<std::string, std::string> { auto mapping = db_ptr->compute_instance_mapping(instance_names); return {{mapping.first, mapping.second}}; }; debugger->rtl_client()->set_custom_hierarchy_func(mapping_func); } log::log(log::log_level::info, "Starting HGDB replay..."); try { engine.run(); } catch (websocketpp::exception &) { std::cerr << "Client disconnected" << std::endl; } return EXIT_SUCCESS; }
34.089744
129
0.640278
Kuree
921f68f9d3e6cd6b4a398911de5014e0e8087c77
3,252
cpp
C++
Sources/PureStd/Private/IO/EngineIO.cpp
PierreEVEN/pure3D
b891c1e762e56851a0a6c4ef32876f18a9b3db97
[ "MIT" ]
1
2020-12-12T22:13:41.000Z
2020-12-12T22:13:41.000Z
Sources/PureStd/Private/IO/EngineIO.cpp
PierreEVEN/pure3D
b891c1e762e56851a0a6c4ef32876f18a9b3db97
[ "MIT" ]
null
null
null
Sources/PureStd/Private/IO/EngineIO.cpp
PierreEVEN/pure3D
b891c1e762e56851a0a6c4ef32876f18a9b3db97
[ "MIT" ]
null
null
null
#include "IO/EngineIO.h" #include <fstream> #if _WIN32 #include <Windows.h> #endif #include <filesystem> #include "IO/Log.h" std::ofstream outputFile; EngineInputOutput& EngineInputOutput::operator<<(bool _Val) { OutputText(_Val ? "true" : "false"); return IO; } EngineInputOutput& EngineInputOutput::operator<<(const char* _Val) { OutputText(_Val); return IO; } EngineInputOutput& EngineInputOutput::operator<<(const String& _Val) { OutputText(_Val); return IO; } EngineInputOutput& EngineInputOutput::operator<<(const IStringable& _Val) { OutputText(_Val.ToString()); return IO; } EngineInputOutput& EngineInputOutput::operator<<(char _Val) { OutputText(_Val); return IO; } EngineInputOutput EngineInputOutput::IO = EngineInputOutput(); #if _WIN32 HANDLE hConsoleout = GetStdHandle(STD_OUTPUT_HANDLE); #endif void EngineInputOutput::SetTextColor(const ConsoleColor& color) { consoleColor = color; } EngineInputOutput::EngineInputOutput() { OnSendMessage.Add(this, &EngineInputOutput::TextToLog); OnSendMessage.Add(this, &EngineInputOutput::TextToScreen); outputFile.open(FindNewLogfileName().GetData()); } EngineInputOutput::~EngineInputOutput() { outputFile.close(); } String EngineInputOutput::FindNewLogfileName() const { if (!std::filesystem::exists(DEFAULT_LOG_DIRECTORY)) { std::filesystem::create_directories(DEFAULT_LOG_DIRECTORY); } time_t now = time(0); struct tm tstruct; char buf[80]; #if _WIN32 localtime_s(&tstruct, &now); #else localtime_r(&now, &tstruct); #endif strftime(buf, sizeof(buf), "%Y-%m-%d.%H.%M.%S", &tstruct); int64_t LogIndex = -1; String fileName; do { LogIndex++; if (LogIndex == 0) { fileName = String(DEFAULT_LOG_DIRECTORY) / String("Log Engine - ") + String(buf) + ".log"; } else { fileName = String(DEFAULT_LOG_DIRECTORY) / String("Log Engine ") + ToString(LogIndex) + String(" - ") + String(buf) + ".log"; } } while (std::filesystem::exists(fileName.GetData())); bool bIsSet = false; std::filesystem::directory_entry oldestFile; int fileCount = 0;; for (const std::filesystem::directory_entry& file : std::filesystem::directory_iterator(DEFAULT_LOG_DIRECTORY)) { if (!bIsSet || std::filesystem::last_write_time(file) < std::filesystem::last_write_time(oldestFile)) oldestFile = file; bIsSet = true; fileCount++; } if (fileCount >= 10) { std::filesystem::remove(oldestFile); } return fileName; } void EngineInputOutput::OutputText(const String& value) { OnSendMessage.Execute(value); } void EngineInputOutput::TextToLog(const String& text) { outputFile.write(text.GetData(), text.Length()); outputFile.flush(); } void EngineInputOutput::TextToScreen(const String& text) { #if _WIN32 SetConsoleTextAttribute(hConsoleout, consoleColor); #endif printf(text.GetData()); #if _WIN32 SetConsoleTextAttribute(hConsoleout, CONSOLE_DEFAULT); #endif } std::vector<char> ReadFile(const String& filePath) { std::ifstream file(filePath.GetData(), std::ios::ate); if (!file.is_open()) { LOG_ASSERT(String("Failed to open file ") + filePath); } size_t fileSize = (size_t)file.tellg(); std::vector<char> buffer(fileSize); file.seekg(0); file.read(buffer.data(), fileSize); file.close(); return buffer; }
21.972973
128
0.72171
PierreEVEN
921f95c502cf3e918f90f8c792c37d907dbe7adc
515
cpp
C++
include/math/symb/Operand.cpp
philsupertramp/game-math
56526b673bfc9c71515c8402b5ffa237f1819a39
[ "MIT" ]
null
null
null
include/math/symb/Operand.cpp
philsupertramp/game-math
56526b673bfc9c71515c8402b5ffa237f1819a39
[ "MIT" ]
34
2020-11-27T13:33:04.000Z
2022-03-06T13:40:39.000Z
include/math/symb/Operand.cpp
philsupertramp/game-math
56526b673bfc9c71515c8402b5ffa237f1819a39
[ "MIT" ]
null
null
null
#include "Operand.h" bool isConstant(const std::string& in) { std::unordered_set<std::string> funList; for(const auto& elem : DefaultSymbols) { funList.insert(elem.first); } return funList.find(in) != funList.end(); } bool hasSymbol(const std::vector<std::shared_ptr<Symbolic>>& container, const std::shared_ptr<Symbolic>& sym) { for(const auto& elem : container) { if(bool(strcmp(elem->value, sym->value) == 0) && elem->isNegative == sym->isNegative) return true; } return false; }
39.615385
111
0.673786
philsupertramp
922114cbffcf25b5a8c965189d48eab319ed6965
3,275
cpp
C++
src/saiga/vulkan/pipeline/PipelineBase.cpp
SimonMederer/saiga
ff167e60c50b1cead4d19eb5ab2e93acce8c42a3
[ "MIT" ]
null
null
null
src/saiga/vulkan/pipeline/PipelineBase.cpp
SimonMederer/saiga
ff167e60c50b1cead4d19eb5ab2e93acce8c42a3
[ "MIT" ]
null
null
null
src/saiga/vulkan/pipeline/PipelineBase.cpp
SimonMederer/saiga
ff167e60c50b1cead4d19eb5ab2e93acce8c42a3
[ "MIT" ]
null
null
null
/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "PipelineBase.h" #include "saiga/vulkan/Vertex.h" #include "saiga/vulkan/VulkanInitializers.hpp" namespace Saiga { namespace Vulkan { PipelineBase::PipelineBase(vk::PipelineBindPoint type) : type(type) {} void PipelineBase::init(VulkanBase& base, uint32_t numDescriptorSetLayouts) { this->base = &base; device = base.device; descriptorSetLayouts.resize(numDescriptorSetLayouts); } void PipelineBase::destroy() { if (!device) return; VLOG(3) << "Destroying pipeline " << pipeline; vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); for (auto& l : descriptorSetLayouts) l.destroy(); device = nullptr; } vk::DescriptorSet PipelineBase::createRawDescriptorSet(uint32_t id) { SAIGA_ASSERT(isInitialized()); SAIGA_ASSERT(id >= 0 && id < descriptorSetLayouts.size()); return descriptorSetLayouts[id].createRawDescriptorSet(); } StaticDescriptorSet PipelineBase::createDescriptorSet(uint32_t id) { SAIGA_ASSERT(isInitialized()); SAIGA_ASSERT(id >= 0 && id < descriptorSetLayouts.size()); return descriptorSetLayouts[id].createDescriptorSet(); } DynamicDescriptorSet PipelineBase::createDynamicDescriptorSet(uint32_t id) { SAIGA_ASSERT(isInitialized()); SAIGA_ASSERT(id >= 0 && id < descriptorSetLayouts.size()); return descriptorSetLayouts[id].createDynamicDescriptorSet(); } bool PipelineBase::bind(vk::CommandBuffer cmd) { if (checkShader()) { cmd.bindPipeline(type, pipeline); return true; } else { return false; } } void PipelineBase::pushConstant(vk::CommandBuffer cmd, vk::ShaderStageFlags stage, size_t size, const void* data, size_t offset) { cmd.pushConstants(pipelineLayout, stage, offset, size, data); } void PipelineBase::addDescriptorSetLayout(const DescriptorSetLayout& layout, uint32_t id) { SAIGA_ASSERT(isInitialized()); SAIGA_ASSERT(id >= 0 && id < descriptorSetLayouts.size()); SAIGA_ASSERT(!layout.is_created(), "Creation must not be done beforehand"); descriptorSetLayouts[id] = layout; descriptorSetLayouts[id].create(base); } void PipelineBase::addPushConstantRange(vk::PushConstantRange pcr) { SAIGA_ASSERT(isInitialized()); pushConstantRanges.push_back(pcr); } void PipelineBase::createPipelineLayout() { SAIGA_ASSERT(isInitialized()); std::vector<vk::DescriptorSetLayout> layouts(descriptorSetLayouts.size()); std::transform(descriptorSetLayouts.begin(), descriptorSetLayouts.end(), layouts.begin(), [](auto& entry) { return static_cast<vk::DescriptorSetLayout>(entry); }); vk::PipelineLayoutCreateInfo pPipelineLayoutCreateInfo(vk::PipelineLayoutCreateFlags(), layouts.size(), layouts.data(), pushConstantRanges.size(), pushConstantRanges.data()); pipelineLayout = device.createPipelineLayout(pPipelineLayoutCreateInfo); SAIGA_ASSERT(pipelineLayout); } } // namespace Vulkan } // namespace Saiga
28.478261
113
0.695573
SimonMederer
9221415e18382ac152d76880f3a691de417c4607
817
cpp
C++
competitive_programming/programming_contests/uri/tda_rational_2.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
competitive_programming/programming_contests/uri/tda_rational_2.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
competitive_programming/programming_contests/uri/tda_rational_2.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
// https://www.urionlinejudge.com.br/judge/en/problems/view/1022 #include <iostream> #include <string> using namespace std; int mdc(int num1, int num2) { int remainder; do { remainder = num1 % num2; num1 = num2; num2 = remainder; } while (remainder != 0); return num1; } int main() { string ope, op; int n, num, num1, num2, den, den1, den2, div; cin >> n; while (n--) { cin >> num1 >> op >> den1 >> ope >> num2 >> op >> den2; den = den1 * den2; if (ope == "+") num = num1 * den2 + num2 * den1; else if (ope == "-") num = num1 * den2 - num2 * den1; else if (ope == "*") num = num1 * num2; else { num = num1 * den2; den = num2 * den1; } div = mdc(num, den); if (div < 0) div *= -1; cout << num << "/" << den << " = " << num/div << "/" << den/div << endl; } return 0; }
19.452381
74
0.537332
LeandroTk
9221e6ba8587b0635371a3f355da1beefcba429d
1,405
cpp
C++
carryarm_actionlib/src/carryarm_client.cpp
buzzer/tams_pr2
73eada99f88c300858f05d57b868e6a8109a800c
[ "BSD-2-Clause" ]
null
null
null
carryarm_actionlib/src/carryarm_client.cpp
buzzer/tams_pr2
73eada99f88c300858f05d57b868e6a8109a800c
[ "BSD-2-Clause" ]
null
null
null
carryarm_actionlib/src/carryarm_client.cpp
buzzer/tams_pr2
73eada99f88c300858f05d57b868e6a8109a800c
[ "BSD-2-Clause" ]
null
null
null
#include <ros/ros.h> #include <actionlib/client/simple_action_client.h> #include <actionlib/client/terminal_state.h> #include <carryarm_actionlib/CarryarmAction.h> int main (int argc, char **argv) { ros::init(argc, argv, "test_carryarm"); // create the action client // true causes the client to spin its own thread actionlib::SimpleActionClient<carryarm_actionlib::CarryarmAction> ac("carryarm", true); ROS_INFO("Waiting for action server to start."); // wait for the action server to start ac.waitForServer(); //will wait for infinite time ROS_INFO("Action server started, sending goal."); // send a goal to the action carryarm_actionlib::CarryarmGoal goal; uint8_t pose; uint8_t arm; // parse command line arguments if (argc == 3) { pose = atoi(argv[1]); arm = atoi(argv[2]); } else // default values { pose = 1; arm = 1; // left arm } ROS_INFO("carrypose: %d, carryarm: %s", pose, arm ? "left" : "right"); goal.carrypose = pose; goal.carryarm = arm; ac.sendGoal(goal); //wait for the action to return bool finished_before_timeout = ac.waitForResult(ros::Duration(200.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac.getState(); ROS_INFO("Action finished: %s",state.toString().c_str()); } else ROS_INFO("Action did not finish before the time out."); //exit return 0; }
25.089286
89
0.683274
buzzer
92257b0dbddb99cf36172dc9ea3dd8c3f9ea9c33
733
cpp
C++
src/0232.cpp
killf/leetcode_cpp
d1f308a9c3da55ae5416ea28ec2e7a3146533ae9
[ "MIT" ]
null
null
null
src/0232.cpp
killf/leetcode_cpp
d1f308a9c3da55ae5416ea28ec2e7a3146533ae9
[ "MIT" ]
null
null
null
src/0232.cpp
killf/leetcode_cpp
d1f308a9c3da55ae5416ea28ec2e7a3146533ae9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <sstream> #include <algorithm> #include <map> #include <hash_map> #include <hash_set> #include <queue> #include <stack> using namespace std; class MyQueue { public: explicit MyQueue() = default; void push(int x) { while (!p1->empty()) { p2->push(p1->top()); p1->pop(); } p1->push(x); while (!p2->empty()) { p1->push(p2->top()); p2->pop(); } } int pop() { int v = p1->top(); p1->pop(); return v; } int peek() { return p1->top(); } bool empty() { return p1->empty(); } private: stack<int> stack1; stack<int> stack2; stack<int> *p1 = &stack1; stack<int> *p2 = &stack2; };
14.096154
31
0.547067
killf
92258e27bebc9d404a247ecaf7959240b2946ba5
6,829
cxx
C++
Dockerized/rdpstack/cmake-3.17.2/Source/cmLoadCommandCommand.cxx
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
3
2021-10-14T07:40:15.000Z
2022-02-27T09:20:33.000Z
Dockerized/rdpstack/cmake-3.17.2/Source/cmLoadCommandCommand.cxx
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
null
null
null
Dockerized/rdpstack/cmake-3.17.2/Source/cmLoadCommandCommand.cxx
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
2
2021-10-21T06:12:36.000Z
2022-03-07T15:52:28.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmLoadCommandCommand.h" #include <csignal> #include <cstdio> #include <cstdlib> #include <cstring> #include <utility> #include <cm/memory> #include "cmCPluginAPI.h" #include "cmCommand.h" #include "cmDynamicLoader.h" #include "cmExecutionStatus.h" #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmState.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmCPluginAPI.cxx" #ifdef __QNX__ # include <malloc.h> /* for malloc/free on QNX */ #endif class cmListFileBacktrace; namespace { const char* LastName = nullptr; extern "C" void TrapsForSignals(int sig) { fprintf(stderr, "CMake loaded command %s crashed with signal: %d.\n", LastName, sig); } struct SignalHandlerGuard { explicit SignalHandlerGuard(const char* name) { LastName = name != nullptr ? name : "????"; signal(SIGSEGV, TrapsForSignals); #ifdef SIGBUS signal(SIGBUS, TrapsForSignals); #endif signal(SIGILL, TrapsForSignals); } ~SignalHandlerGuard() { signal(SIGSEGV, nullptr); #ifdef SIGBUS signal(SIGBUS, nullptr); #endif signal(SIGILL, nullptr); } SignalHandlerGuard(SignalHandlerGuard const&) = delete; SignalHandlerGuard& operator=(SignalHandlerGuard const&) = delete; }; struct LoadedCommandImpl : cmLoadedCommandInfo { explicit LoadedCommandImpl(CM_INIT_FUNCTION init) : cmLoadedCommandInfo{ 0, 0, &cmStaticCAPI, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } { init(this); } ~LoadedCommandImpl() { if (this->Destructor) { SignalHandlerGuard guard(this->Name); this->Destructor(this); } if (this->Error != nullptr) { free(this->Error); } } LoadedCommandImpl(LoadedCommandImpl const&) = delete; LoadedCommandImpl& operator=(LoadedCommandImpl const&) = delete; int DoInitialPass(cmMakefile* mf, int argc, char* argv[]) { SignalHandlerGuard guard(this->Name); return this->InitialPass(this, mf, argc, argv); } void DoFinalPass(cmMakefile* mf) { SignalHandlerGuard guard(this->Name); this->FinalPass(this, mf); } }; // a class for loadabple commands class cmLoadedCommand : public cmCommand { public: cmLoadedCommand() = default; explicit cmLoadedCommand(CM_INIT_FUNCTION init) : Impl(std::make_shared<LoadedCommandImpl>(init)) { } /** * This is a virtual constructor for the command. */ std::unique_ptr<cmCommand> Clone() override { auto newC = cm::make_unique<cmLoadedCommand>(); // we must copy when we clone newC->Impl = this->Impl; return std::unique_ptr<cmCommand>(std::move(newC)); } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ bool InitialPass(std::vector<std::string> const& args, cmExecutionStatus&) override; private: std::shared_ptr<LoadedCommandImpl> Impl; }; bool cmLoadedCommand::InitialPass(std::vector<std::string> const& args, cmExecutionStatus&) { if (!this->Impl->InitialPass) { return true; } // clear the error string if (this->Impl->Error) { free(this->Impl->Error); } // create argc and argv and then invoke the command int argc = static_cast<int>(args.size()); char** argv = nullptr; if (argc) { argv = static_cast<char**>(malloc(argc * sizeof(char*))); } int i; for (i = 0; i < argc; ++i) { argv[i] = strdup(args[i].c_str()); } int result = this->Impl->DoInitialPass(this->Makefile, argc, argv); cmFreeArguments(argc, argv); if (result) { if (this->Impl->FinalPass) { auto impl = this->Impl; this->Makefile->AddGeneratorAction( [impl](cmLocalGenerator& lg, const cmListFileBacktrace&) { impl->DoFinalPass(lg.GetMakefile()); }); } return true; } /* Initial Pass must have failed so set the error string */ if (this->Impl->Error) { this->SetError(this->Impl->Error); } return false; } } // namespace // cmLoadCommandCommand bool cmLoadCommandCommand(std::vector<std::string> const& args, cmExecutionStatus& status) { if (args.empty()) { return true; } // Construct a variable to report what file was loaded, if any. // Start by removing the definition in case of failure. std::string reportVar = cmStrCat("CMAKE_LOADED_COMMAND_", args[0]); status.GetMakefile().RemoveDefinition(reportVar); // the file must exist std::string moduleName = cmStrCat( status.GetMakefile().GetRequiredDefinition("CMAKE_SHARED_MODULE_PREFIX"), "cm", args[0], status.GetMakefile().GetRequiredDefinition("CMAKE_SHARED_MODULE_SUFFIX")); // search for the file std::vector<std::string> path; for (unsigned int j = 1; j < args.size(); j++) { // expand variables std::string exp = args[j]; cmSystemTools::ExpandRegistryValues(exp); // Glob the entry in case of wildcards. cmSystemTools::GlobDirs(exp, path); } // Try to find the program. std::string fullPath = cmSystemTools::FindFile(moduleName, path); if (fullPath.empty()) { status.SetError(cmStrCat("Attempt to load command failed from file \"", moduleName, "\"")); return false; } // try loading the shared library / dll cmsys::DynamicLoader::LibraryHandle lib = cmDynamicLoader::OpenLibrary(fullPath.c_str()); if (!lib) { std::string err = cmStrCat("Attempt to load the library ", fullPath, " failed."); const char* error = cmsys::DynamicLoader::LastError(); if (error) { err += " Additional error info is:\n"; err += error; } status.SetError(err); return false; } // Report what file was loaded for this command. status.GetMakefile().AddDefinition(reportVar, fullPath); // find the init function std::string initFuncName = args[0] + "Init"; CM_INIT_FUNCTION initFunction = reinterpret_cast<CM_INIT_FUNCTION>( cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName)); if (!initFunction) { initFuncName = cmStrCat('_', args[0], "Init"); initFunction = reinterpret_cast<CM_INIT_FUNCTION>( cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName)); } // if the symbol is found call it to set the name on the // function blocker if (initFunction) { status.GetMakefile().GetState()->AddScriptedCommand( args[0], cmLegacyCommandWrapper(cm::make_unique<cmLoadedCommand>(initFunction))); return true; } status.SetError("Attempt to load command failed. " "No init function found."); return false; }
26.468992
78
0.662176
nsimbi
9225bd900af1c8b462d8d3814f6a7f75eb74ec9d
512
hxx
C++
admin/dsutils/displayspecifierupgrade/headers.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/dsutils/displayspecifierupgrade/headers.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/dsutils/displayspecifierupgrade/headers.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (C) 1997 Microsoft Corporation // // All header files used by this project; for the purpose of creating a // pre-compiled header file // // 05-18-01 lucios // // This file must be named with a .hxx extension due to some weird and // inscrutible requirement of BUILD. #ifndef HEADERS_HXX_INCLUDED #define HEADERS_HXX_INCLUDED #include <burnslib.hpp> #include <shlobjp.h> #include <ntldap.h> #include <dsclient.h> #pragma hdrstop #endif // HEADERS_HXX_INCLUDED
18.962963
72
0.697266
npocmaka
9227bc3c0f1be4bb041cf3d4a9bb14a12002bf7e
10,204
hpp
C++
src/reconstruction/dataset.hpp
ebarjou/xpulse_recon
5c9eb8e32a2f2b84a9850fabc2103c116a0b9ce6
[ "Apache-2.0" ]
null
null
null
src/reconstruction/dataset.hpp
ebarjou/xpulse_recon
5c9eb8e32a2f2b84a9850fabc2103c116a0b9ce6
[ "Apache-2.0" ]
null
null
null
src/reconstruction/dataset.hpp
ebarjou/xpulse_recon
5c9eb8e32a2f2b84a9850fabc2103c116a0b9ce6
[ "Apache-2.0" ]
null
null
null
/** * ©2020-2022 ALPhANOV (https://www.alphanov.com/) All Rights Reserved * Author: Barjou Emile */ #pragma once namespace dataset { #include "dataset/parameters.hpp" #include "dataset/geometry.hpp" #include "dataset/geometry_chunk.hpp" #include "dataset/data_loader.hpp" /** * @brief Manage the projections data and Input/ouput for the reconstruction. Need to be initialized before use. * */ class Dataset { Parameters *_parameters; int64_t _width, _height; std::vector<std::string> _tiff_files; Geometry _geometry; DataLoader _dataLoader; public: Dataset(Parameters *parameters) : _parameters(parameters), _width(0), _height(0), _tiff_files(collectFromDirectory(prm_r.input)), //Init prm_g.projections, prm_g.dwidth, _dheight _geometry(parameters), //Init all missing fields _dataLoader(parameters, _tiff_files) { std::cout << "Exploring directory..."<< std::flush; collectFromDirectory(prm_r.input); if(_tiff_files.size() == 0 || _width == 0 || _height == 0) { throw std::runtime_error("No valid TIFF file found in the directory."); } std::cout << getElements() << "x(" << getWidth() << "," << getHeight() << ")." << std::endl; } /** * @brief Load all data and create temporary files if needed * */ void initialize(bool chunk) { _dataLoader.initializeTempImages(chunk); } /** * @brief Get the Width of the images * * @return uint64_t */ uint64_t getWidth() { return _width; } /** * @brief Get the Height of the images * * @return uint64_t */ uint64_t getHeight() { return _height; } /** * @brief Get the number of images * * @return uint64_t */ uint64_t getElements() { return _tiff_files.size(); } /** * @brief Get a single layer * * @param layer index of the layer, from 0 (top layer) to volume height - 1 (bottem layer) * @return std::vector<float> */ std::vector<float> getLayer(int64_t layer) { return _dataLoader.getLayer(layer); } /** * @brief Get a single layer * * @param layer index of the layer, from 0 (top layer) to volume height - 1 (bottem layer) * @return std::vector<float> */ std::vector<float> getLayers(int64_t index_start, int64_t index_end, bool MT = false) { std::vector<float> layers((index_end-index_start)*prm_g.vwidth*prm_g.vwidth); #pragma omp parallel for if(MT) for(int64_t i = index_start; i < index_end; ++i) { auto layer = _dataLoader.getLayer(i); std::copy(layer.begin(), layer.end(), layers.begin()+(i-index_start)*prm_g.vwidth*prm_g.vwidth); } return layers; } /** * @brief Save the layer contained in data to a single layer file * * @param data of the layer, should be of size width*width * @param layer index of the layer, from 0 (top layer) to volume height - 1 (bottem layer) */ void saveLayer(std::vector<float> &data, int64_t layer, bool finalize = false) { _dataLoader.saveLayer(data.data(), layer, finalize); } /** * @brief Save multiple continuous layer contained in data * * @param data of the layer, should be of size width*width*(end-start) * @param start first layer index * @param end last layer index, excluded */ void saveLayers(std::vector<float> &data, int64_t index_start, int64_t index_end, bool MT = false) { #pragma omp parallel for if(MT) for(int64_t i = index_start; i < index_end; ++i) { _dataLoader.saveLayer(data.data()+(i-index_start)*prm_g.vwidth*prm_g.vwidth, i, true); } } /** * @brief get all images of a given SIT * * @param sit index of the sub-iteration * @return std::vector<float> */ std::vector<float> getSitImages(int64_t sit, bool MT = false) { std::vector<float> output(((prm_g.projections-sit)/prm_r.sit)*prm_g.dwidth*prm_g.dheight); #pragma omp parallel for if(MT) for(int i = sit; i < prm_g.projections; i += prm_r.sit) { auto image = _dataLoader.getImage(i); std::copy(image.begin(), image.end(), output.begin()+((i-sit)/prm_r.sit)*prm_g.dwidth*prm_g.dheight); } } /** * @brief get a single image * * @param id of the image * @return std::vector<float> */ std::vector<float> getImage(int64_t id) { return _dataLoader.getImage(id); } /** * @brief get a single image from a path * * @param path of the image * @return std::vector<float> */ std::vector<float> getImage(std::string path) { return _dataLoader.getImage(path); } /** * @brief Get all images, cropped to fit a chunk, and separated in sub-iterations * * @param chunk * @return std::vector<std::vector<float>> a vector for each sub-iterations containing the cropped images */ std::vector<std::vector<float>> getImagesCropped(int64_t chunk, bool MT = false) { std::vector<std::vector<float>> output(prm_r.sit); for(int sit = 0; sit < prm_r.sit; ++sit) { output[sit] = std::vector<float>(((prm_g.projections-sit)/prm_r.sit)*prm_g.dwidth*prm_m2.chunks[sit].iSize); #pragma omp parallel for if(MT) for(int i = sit; i < prm_g.projections; i += prm_r.sit) { auto image = _dataLoader.getImage(chunk*prm_g.projections+i); std::copy(image.begin(), image.end(), output[sit].begin()+((i-sit)/prm_r.sit)*prm_g.dwidth*prm_m2.chunks[sit].iSize); } } } /** * @brief Save multiple images * * @param data vector containing all images * @param start offset, in images from the vector * @param end offset, im images from the vector * @param step in image */ void saveSitImages(const std::vector<float> &data, int64_t sit) { /*for(int64_t l = start; l < end; l += step) { _dataLoader.saveProjImage(&data[((l-start)/step)*prm_g.dwidth*prm_g.dheight], l); }*/ //exit(-10); } void saveImage(const std::vector<float> &data, int width, int height, int id) { _dataLoader.saveImage(data.data(), width, height, id); } /** * @brief Get the Geometry object * * @return Geometry* */ Geometry* getGeometry() { return &_geometry; } /** * @brief Etablish the list of images that will be loaded when "initialize()" is called * * @param directory * @return std::vector<std::string> */ std::vector<std::string> collectFromDirectory(std::string directory) { std::vector<std::string> tiff_files; for (const auto & entry : std::filesystem::directory_iterator(directory)) { if(entry.is_regular_file() && (entry.path().extension() == ".tif" || entry.path().extension() == ".tiff")){ if(checkTiffFileInfos(entry.path().string())) { tiff_files.push_back(entry.path().string()); } } } //Fill parameters accordingly prm_g.projections = tiff_files.size(); prm_g.concurrent_projections = int64_t(std::floor( float(prm_g.projections) / float(prm_r.sit) )); prm_g.dwidth = _width; prm_g.dheight = _height; /*for(int64_t i = 0; i < int64_t(prm_md.size()); ++i) { if(!(prm_md[i].start_x.assigned)) prm_md[i].start_x = 0; if(!(prm_md[i].end_x.assigned)) prm_md[i].end_x = prm_g.dwidth; if(!(prm_md[i].start_y.assigned)) prm_md[i].start_y = 0; if(!(prm_md[i].end_y.assigned)) prm_md[i].end_y = prm_g.dheight; }*/ return tiff_files; } private: /** * @brief Check if a tiff file is valid and have the correct size * * @param file */ bool checkTiffFileInfos(std::string file) { TinyTIFFReaderFile* tiffr=NULL; tiffr=TinyTIFFReader_open(file.c_str()); if (tiffr) { const int32_t width = TinyTIFFReader_getWidth(tiffr); const int32_t height = TinyTIFFReader_getHeight(tiffr); const uint16_t bitspersample = TinyTIFFReader_getBitsPerSample(tiffr, 0); const uint16_t format = TinyTIFFReader_getSampleFormat(tiffr); TinyTIFFReader_close(tiffr); if(format != TINYTIFF_SAMPLEFORMAT_FLOAT || bitspersample != 32) { throw std::runtime_error("Trying to load a tiff with an incompatble format (should be floating-point 32bits)"); } if(width == 0 || height == 0) { throw std::runtime_error("Trying to load a tiff with an incorrect size."); } if(_width == 0 && _height == 0) { _width = width; _height = height; } if(_width == width && _height == height) { return true; } return false; } return false; } }; }
37.653137
137
0.53136
ebarjou
92281407fff2a2121ec0282c29bf84649c118096
1,333
cpp
C++
Codeorces/new_colony.cpp
maayami/Data-Structures-Algorithms
f2f7cf808be43b85f35a7b1801460ecc20d75695
[ "CC0-1.0" ]
1
2020-05-14T18:22:10.000Z
2020-05-14T18:22:10.000Z
Codeorces/new_colony.cpp
mayank-genesis/Data-Structures-Algorithms
f2f7cf808be43b85f35a7b1801460ecc20d75695
[ "CC0-1.0" ]
null
null
null
Codeorces/new_colony.cpp
mayank-genesis/Data-Structures-Algorithms
f2f7cf808be43b85f35a7b1801460ecc20d75695
[ "CC0-1.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define gc getchar_unlocked #define fo(i, n) for (int i = 0; i < n; i++) #define Fo(i, k, n) for (int i = k; i < n; i++) #define ll long long #define pb(i) push_back(i) #define e "\n" #define traverseVector(i) for (auto i = v.begin(); i != v.end(); ++i) #define rtraverseVector(i) for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir) #define in(n) cin >> n #define out(n) cout << n << e // .fillArray int compare_then_decide_recursive(int *arr, int n, int x) // returns the index of array (latest mountain - 1) { if (x == n - 1) { return x; } else if (arr[x] < arr[x + 1]) { arr[x]++; return x; } else return compare_then_decide_recursive(arr, n, x + 1); } void solve() { int n, k; cin >> n >> k; int arr[n]; for (int j = 0; j < n; j++) cin >> arr[j]; int index; while (k-- > 0) { index = compare_then_decide_recursive(arr, n, 0); if (index == n - 1) break; } if (index == n - 1) cout << -1; else cout << index + 1; cout << endl; } int main(int argc, char const *argv[]) { // ios_base::sync_with_stdio(false); // cin.tie(NULL); int t = 1; cin >> t; while (t--) { solve(); } return 0; }
19.895522
109
0.507877
maayami
922a2535552915eda1dbffc443d98986dcb3c897
451
hpp
C++
src/rdx/rdx_loadshell.hpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
src/rdx/rdx_loadshell.hpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
src/rdx/rdx_loadshell.hpp
elasota/rdx2
e08ca09a07d3ac8675f7f950a7bdf838a9f5f907
[ "MIT" ]
null
null
null
#ifndef __RDX_LOADSHELL_HPP__ #define __RDX_LOADSHELL_HPP__ #include "rdx_coretypes.hpp" #include "rdx_objectguid.hpp" #include "rdx_typeprocessor.hpp" struct rdxSLoadShell { rdxLargeUInt fileOffset; bool isAnonymous; bool isConstant; bool isCloaked; rdxSObjectGUID typeName; rdxLargeUInt tableIndex; rdxLargeUInt numElements; }; RDX_DECLARE_COMPLEX_NATIVE_STRUCT(rdxSLoadShell); #endif
21.47619
50
0.72949
elasota
922b1feb5079da74b1f3f8f14bc1ccad0ff7d8f6
2,533
hh
C++
track/SenseContainer.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
track/SenseContainer.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
track/SenseContainer.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
//---------------------------------*-C++-*-----------------------------------// /*! * \file track/SenseContainer.hh * \brief SenseContainer class declaration * \note Copyright (c) 2020 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #pragma once #include <iosfwd> #include <vector> namespace celeritas { //---------------------------------------------------------------------------// /*! * Store surface sense state inside a cell. * * This is currently a subset of std::vector functionality. * * \todo Change value_type to Sense */ class SenseContainer { public: //@{ //! Public type aliases using Storage_t = std::vector<bool>; using value_type = bool; using size_type = Storage_t::size_type; using iterator = Storage_t::iterator; using const_iterator = Storage_t::const_iterator; using reference = Storage_t::reference; using const_reference = Storage_t::const_reference; //@} public: //@{ //! Constructors SenseContainer() = default; inline SenseContainer(std::initializer_list<value_type>); //@} //@{ //! Element access inline reference operator[](size_type); inline const_reference operator[](size_type) const; //@} //@{ //! Iterators inline iterator begin(); inline iterator end(); inline const_iterator begin() const; inline const_iterator end() const; inline const_iterator cbegin() const; inline const_iterator cend() const; //@} //@{ //! Capacity inline bool empty() const; inline size_type size() const; //@} //@{ //! Modifiers inline void clear(); inline void resize(size_type); //@} private: //// DATA //// std::vector<bool> storage_; }; //---------------------------------------------------------------------------// // FREE FUNCTIONS //---------------------------------------------------------------------------// std::ostream& operator<<(std::ostream& os, const SenseContainer& senses); //---------------------------------------------------------------------------// } // namespace celeritas //---------------------------------------------------------------------------// // INLINE DEFINITIONS //---------------------------------------------------------------------------// #include "SenseContainer.i.hh" //---------------------------------------------------------------------------//
27.835165
79
0.452033
celeritas-project
922e9f6b78b016995411b4f706e8a35fc98fb33b
13,207
cpp
C++
cbnb/domain.cpp
Thiago-AS/cbnb
544d04fb3f093e819cb8a54ae623a8304abb9cc9
[ "MIT" ]
null
null
null
cbnb/domain.cpp
Thiago-AS/cbnb
544d04fb3f093e819cb8a54ae623a8304abb9cc9
[ "MIT" ]
null
null
null
cbnb/domain.cpp
Thiago-AS/cbnb
544d04fb3f093e819cb8a54ae623a8304abb9cc9
[ "MIT" ]
null
null
null
#include "domain.h" /** * Validates the agency code, where it must be 5 digits long, and must contain only numeric values. * If the parameter does not pass validation, throws invalid argument exception. */ void Agency::Validate(string code) throw(invalid_argument) { if (code.size() != 5) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < code.size(); i++) { if (!isdigit(code.at(i))) throw invalid_argument("Invalid argument."); } } void Agency::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } /** * Validates the bank code, where it must be 3 digits long, and must contain only numeric values. * If the parameter does not pass validation, throws invalid argument exception. */ void Bank::Validate(string code) throw(invalid_argument) { if (code.size() != 3) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < code.size(); i++) { if (!isdigit(code.at(i))) throw invalid_argument("Invalid argument."); } } void Bank::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } /** * Validates the accommodation capacity, where it must be a number between 1 and 9. * If the parameter does not pass validation, throws invalid argument exception. */ void AccommodationCapacity::Validate(int amount) throw(invalid_argument) { if ((amount < 1) || (amount > 9)) throw invalid_argument("Invalid argument."); } void AccommodationCapacity::SetAmount(int amount) throw(invalid_argument) { Validate(amount); this->amount = amount; } /** * Validates the daily fee value, where it must be a number between 1 and 10000. * If the parameter does not pass validation, throws invalid argument exception. */ void DailyFee::Validate(int value) throw(invalid_argument) { if ((value < 1) || (value > 10000)) throw invalid_argument("Invalid argument."); } void DailyFee::SetValue(int value) throw(invalid_argument) { Validate(value); this->value = value; } /** * Validates the date, where it must be in the usual format (DD/MMM/AAAA), * where DD, represents the day and must be in range of 1 and 31, MMM * represents the month, and it must be in the valid_months vector defined * and the AAAA represents the year, being a number between 2000 and 2099. * If the parameter does not pass validation, throws invalid argument exception. */ void Date::Validate(string value) throw(invalid_argument) { int slash_counter = 0, int_day, int_year; bool valid_month = false, is_leap_year = false; string sub_string, day, month, year; vector <string> tokens; std::istringstream iss(value); if (value.size() != 11) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < value.size(); i++) { if (value.at(i) == '/') slash_counter++; } if (slash_counter != 2) throw invalid_argument("Invalid argument."); while (getline(iss, sub_string, '/')) { tokens.push_back(sub_string); } day = tokens.at(0); month = tokens.at(1); year = tokens.at(2); if (day.size() != 2 || month.size() != 3 ||year.size() != 4) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < day.size(); i++) { if (!isdigit(day.at(i))) throw invalid_argument("Invalid argument."); } for (unsigned int i = 0; i < month.size(); i++) { if (isdigit(month.at(i))) throw invalid_argument("Invalid argument."); } for (unsigned int i = 0; i < year.size(); i++) { if (!isdigit(year.at(i))) throw invalid_argument("Invalid argument."); } for (unsigned int i = 0; i < valid_months.size(); i++) { if (month == valid_months.at(i)) valid_month = true; } if (!valid_month) throw invalid_argument("Invalid argument."); int_day = stoi(day, nullptr); int_year = stoi(year, nullptr); if (int_year < 2000 || int_year > 2099) throw invalid_argument("Invalid argument."); if (int_day < 1 || int_day > 31) throw invalid_argument("Invalid argument."); if ((month == "abr" || month == "jun" || month == "set" || month == "nov") && int_day > 30) throw invalid_argument("Invalid argument."); if (((int_year % 4 == 0) && (int_year % 100 != 0)) || (int_year % 400 == 0)) is_leap_year = true; if ((month == "fev") && (!is_leap_year) && (int_day > 28)) throw invalid_argument("Invalid argument."); if ((month == "fev") && (is_leap_year) && (int_day > 29)){ throw invalid_argument("Invalid argument."); } } void Date::SetValue(string value) throw(invalid_argument) { Validate(value); this->value = value; } /** * Validates the expiration date, where it must be in the format MM/AA. Where * MM is the month, and must be between 01 and 12, and AA is the year, and must * be between 00 and 99. * If the parameter does not pass validation, throws invalid argument exception. */ void ExpirationDate::Validate(string value) throw(invalid_argument) { int slash_counter = 0, int_month, int_year; string sub_string, month, year; vector <string> tokens; std::istringstream iss(value); if (value.size() != 5) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < value.size(); i++) { if (value.at(i) == '/') slash_counter++; } if (slash_counter != 1) throw invalid_argument("Invalid argument."); while (getline(iss, sub_string, '/')) { tokens.push_back(sub_string); } month = tokens.at(0); year = tokens.at(1); if (month.size() != 2 || year.size() != 2) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < month.size(); i++) { if (!isdigit(month.at(i))) throw invalid_argument("Invalid argument."); } for (unsigned int i = 0; i < year.size(); i++) { if (!isdigit(year.at(i))) throw invalid_argument("Invalid argument."); } int_month = stoi(month, nullptr); int_year = stoi(year, nullptr); if (int_month < 1 || int_month > 12) throw invalid_argument("Invalid argument."); if (int_year < 0 || int_year > 99) throw invalid_argument("Invalid argument."); } void ExpirationDate::SetValue(string value) throw(invalid_argument) { Validate(value); this->value = value; } /** * Validates the state code, where it must be a code with 2 characters and must * be in the valid_states vector defined. * If the parameter does not pass validation, throws invalid argument exception. */ void State::Validate(string code) throw(invalid_argument) { bool valid_state = false; if (code.size() != 2) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < valid_states.size(); i++) { if (code == valid_states.at(i)) valid_state = true; } if (!valid_state) throw invalid_argument("Invalid argument."); } void State::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } /** * Validates the Identifier code, where it must be a code with 5 characters, * all being alpha and lower case. * If the parameter does not pass validation, throws invalid argument exception. */ void Identifier::Validate(string code) throw(invalid_argument) { if (code.size() != 5) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < code.size(); i++) { if (!islower(code.at(i)) || !isalpha(code.at(i))) throw invalid_argument("Invalid argument."); } } void Identifier::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } /** * Validates the Name, where it must be a code with max 15 characters, * all being alpha or space and dot. Cant have two spaces in a row and all * dots must be preceded by a letter. * If the parameter does not pass validation, throws invalid argument exception. */ void Name::Validate(string code) throw(invalid_argument) { bool char_is_letter = false; if (code.size() > 15) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < code.size(); i++){ if (!isalpha(code.at(i)) && code.at(i) != ' ' && code.at(i) != '.') throw invalid_argument("Invalid argument."); if (isalpha(code.at(i))) char_is_letter = true; } if(!char_is_letter) throw invalid_argument("Invalid argument."); for (unsigned int i = 1; i < code.size(); i++) { if (code.at(i-1) == ' ' && code.at(i) == ' ') throw invalid_argument("Invalid argument."); if (!isalpha(code.at(i-1)) && code.at(i) == '.' ) throw invalid_argument("Invalid argument."); } } void Name::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } bool CreditCardNumber::CheckLuhn(string card_number) { int num_digits = card_number.length(); int num_sum = 0, is_second = false; for (int i = num_digits - 1; i >= 0; i--) { int d = card_number[i] - 'a'; if (is_second == true) d = d * 2; num_sum += d / 10; num_sum += d % 10; is_second = !is_second; } return (num_sum % 10 == 0); } /** * Validates the Credit Card Number, where it must be a code with 16 digits, * all being numeric. The number must pass the Luhn algorithm. * If the parameter does not pass validation, throws invalid argument exception. */ void CreditCardNumber::Validate(string code) throw(invalid_argument) { if (code.size() != 16) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < code.size(); i++) { if (!isdigit(code.at(i))) throw invalid_argument("Invalid argument."); } if (!CheckLuhn(code)) throw invalid_argument("Invalid argument."); } void CreditCardNumber::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } /** * Validates the Checking Account Number, where it must be a code with 6 digits, * all being numeric. * If the parameter does not pass validation, throws invalid argument exception. */ void CheckingAccountNumber::Validate(string code) throw(invalid_argument) { if (code.size() != 6) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < code.size(); i++) { if (!isdigit(code.at(i))) throw invalid_argument("Invalid argument."); } } void CheckingAccountNumber::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } /** * Validates the Password, where it must be a code with max 8 characters, * where the character can be a symbol (! # $% &), A letter (A - Z to - z) or * a digit (0 to 9). There is at least 1 uppercase, 1 lowercase, 1 digit, * and 1 symbol. * If the parameter does not pass validation, throws invalid argument exception. */ void Password::Validate(string code) throw(invalid_argument) { bool char_is_upper = false, char_is_lower = false, char_is_digit = false, char_is_symbol = false; int char_count[256] = {0}; if (code.size() > 8 || code.size() < 4) throw invalid_argument("Invalid argument."); for (unsigned int i = 0; i < code.size(); i++) { if (!isdigit(code.at(i)) && !isalpha(code.at(i)) && code.at(i) != '!' && code.at(i) != '#' && code.at(i) != '$' && code.at(i) != '%' && code.at(i) != '&') throw invalid_argument("Invalid argument."); if (isupper(code.at(i))) char_is_upper = true; if (islower(code.at(i))) char_is_lower = true; if (isdigit(code.at(i))) char_is_digit = true; if (code.at(i) == '!' || code.at(i) == '#' || code.at(i) == '$' || code.at(i) == '%' || code.at(i) == '&') char_is_symbol = true; char_count[int(code.at(i))]++; } if (!(char_is_upper & char_is_lower & char_is_symbol & char_is_digit)) throw invalid_argument("Invalid argument."); for (int i = 0; i < 256; i++) { if (char_count[i] > 1) throw invalid_argument("Invalid argument."); } } void Password::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; } /** * Validates the Accommodation Type, the type must be in the valid_types vector * defined. * If the parameter does not pass validation, throws invalid argument exception. */ void AccommodationType::Validate(string code) throw(invalid_argument) { bool valid_accomodation = false; for (unsigned int i = 0; i < valid_accomodations.size(); i++) { if (code == valid_accomodations.at(i)) valid_accomodation = true; } if (!valid_accomodation) throw invalid_argument("Invalid argument."); } void AccommodationType::SetCode(string code) throw(invalid_argument) { Validate(code); this->code = code; }
31.296209
114
0.622094
Thiago-AS
923150a8beb661e41363361d78cf8605f67648c1
1,876
cpp
C++
19_RegularExpressionsMatching/RegularExpressions.cpp
tcandzq/coding-interviews
12e29cd59b0773577eddd6868d9381247f3a9fde
[ "MIT" ]
2
2020-07-26T08:57:12.000Z
2020-09-21T01:56:47.000Z
19_RegularExpressionsMatching/RegularExpressions.cpp
tcandzq/coding-interviews
12e29cd59b0773577eddd6868d9381247f3a9fde
[ "MIT" ]
null
null
null
19_RegularExpressionsMatching/RegularExpressions.cpp
tcandzq/coding-interviews
12e29cd59b0773577eddd6868d9381247f3a9fde
[ "MIT" ]
null
null
null
// 面试题19:正则表达式匹配 // 题目:请实现一个函数用来匹配包含'.'和'*'的正则表达式。模式中的字符'.' // 表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。在本题 // 中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a" // 和"ab*ac*a"匹配,但与"aa.a"及"ab*a"均不匹配。 /* 同leetcode https://leetcode-cn.com/problems/regular-expression-matching/ 10. 正则表达式匹配 分情况讨论: //如果模式串当前字符的下一位是 *: 如果当前字符匹配成功: 1. str + 1; pattern + 2; 利用* 可以匹配前面字符出现1次 2. str + 1; pattern; 利用 * 可以匹配前面字符多次(大于1) ,防止当前字符重复出现多次,这样继续留在模式串的当前位置可以匹配重复的那部分,跳过的话就失去了*的这个功能。 比如 str = "aaaaaab" pattern = .*b。 3. str; pattern + 2; 考虑 str = aaab pattern = aaabb*。此时aaab就可以匹配了,那多了的 b* 也无所谓,因为 b* 可以是匹配0次 b,相当于 b * 可以直接去掉了。 如果当前字符没有匹配成功 否则: 如果 字符串和模式串的当前字符偶读匹配成功 字符串和模式串均向后移动一位 str + 1; pattern + 1; 匹配失败 参考:https://leetcode-cn.com/problems/regular-expression-matching/solution/dong-tai-gui-hua-zen-yao-cong-0kai-shi-si-kao-da-b/ */ #include<fstream> bool match(char* str,char* pattern) { if(str == nullptr || pattern == nullptr) return false; return matchCore(str, pattern); } bool matchCore(const char* str,const char* pattern) { if(*str == '\0' && *pattern == '\0') return true; if(*str != '\0' && *pattern == '\0') return false; if (*(pattern+1) == '*') { if(*pattern == *str || (*pattern == '.' && *str != '\0')) // 进入有限状态机的下一个状态 return matchCore(str+1,pattern+2) // 继续留在有限状态机的当前状态 || matchCore(str+1,pattern) // // 略过一个'*' || matchCore(str,pattern+2); else // 略过一个'*' return matchCore(str,pattern+2); } if(*str == *pattern || (*pattern == '.' && *str != '\0')) return matchCore(str + 1, pattern + 1); return false; }
25.69863
124
0.534115
tcandzq
9236d13051c74d2f4e1d3e1bd2654c0621adb205
2,845
cc
C++
CalibTracker/SiPixelGainCalibration/test/SimpleTestPrintOutPixelCalibAnalyzer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
CalibTracker/SiPixelGainCalibration/test/SimpleTestPrintOutPixelCalibAnalyzer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
CalibTracker/SiPixelGainCalibration/test/SimpleTestPrintOutPixelCalibAnalyzer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-03-19T13:44:54.000Z
2019-03-19T13:44:54.000Z
// -*- C++ -*- // // Package: SimpleTestPrintOutPixelCalibAnalyzer // Class: SimpleTestPrintOutPixelCalibAnalyzer // /**\class SimpleTestPrintOutPixelCalibAnalyzer CalibTracker/SiPixelGainCalibration/test/SimpleTestPrintOutPixelCalibAnalyzer.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Freya Blekman // Created: Mon Nov 5 16:56:35 CET 2007 // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/SiPixelDigi/interface/SiPixelCalibDigi.h" #include "CalibTracker/SiPixelGainCalibration/test/SimpleTestPrintOutPixelCalibAnalyzer.h" // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // SimpleTestPrintOutPixelCalibAnalyzer::SimpleTestPrintOutPixelCalibAnalyzer(const edm::ParameterSet& iConfig) { tPixelCalibDigi = consumes <edm::DetSetVector<SiPixelCalibDigi> > (edm::InputTag("siPixelCalibDigis")); } SimpleTestPrintOutPixelCalibAnalyzer::~SimpleTestPrintOutPixelCalibAnalyzer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // void SimpleTestPrintOutPixelCalibAnalyzer::printInfo(const edm::Event& iEvent, const edm::EventSetup& iSetup){ using namespace edm; Handle<DetSetVector<SiPixelCalibDigi> > pIn; iEvent.getByToken(tPixelCalibDigi,pIn); DetSetVector<SiPixelCalibDigi>::const_iterator digiIter; for(digiIter=pIn->begin(); digiIter!=pIn->end(); ++digiIter){ uint32_t detid = digiIter->id; DetSet<SiPixelCalibDigi>::const_iterator ipix; for(ipix= digiIter->data.begin(); ipix!=digiIter->end(); ++ipix){ std::cout << std::endl; for(uint32_t ipoint=0; ipoint<ipix->getnpoints(); ++ipoint) std::cout << "\t Det ID " << detid << " row:" << ipix->row() << " col:" << ipix->col() << " point " << ipoint << " has " << ipix->getnentries(ipoint) << " entries, adc: " << ipix->getsum(ipoint) << ", adcsq: " << ipix->getsumsquares(ipoint) << std::endl; } } } // ------------ method called to for each event ------------ void SimpleTestPrintOutPixelCalibAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; printInfo(iEvent,iSetup); } // ------------ method called once each job just before starting event loop ------------ void SimpleTestPrintOutPixelCalibAnalyzer::beginJob() { } // ------------ method called once each job just after ending the event loop ------------ void SimpleTestPrintOutPixelCalibAnalyzer::endJob() { }
26.588785
255
0.708963
nistefan
9237ffce68c33af3456a590081ee8855b2d87591
2,520
hpp
C++
examples/interpolate1d/interpolate1d/partition.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
examples/interpolate1d/interpolate1d/partition.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
examples/interpolate1d/interpolate1d/partition.hpp
McKillroy/hpx
f1bcb93f90a0b3c96e5fb3423028f0347f17f943
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2017 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(HPX_PARTITION_AUG_04_2011_0251PM) #define HPX_PARTITION_AUG_04_2011_0251PM #include <hpx/hpx.hpp> #include <hpx/include/client.hpp> #include <cstddef> #include <string> #include "server/partition.hpp" /////////////////////////////////////////////////////////////////////////////// namespace interpolate1d { class partition : public hpx::components::client_base<partition, server::partition> { private: typedef hpx::components::client_base<partition, server::partition> base_type; public: // create a new partition instance and initialize it synchronously partition(std::string const& datafilename, dimension const& dim, std::size_t num_nodes) : base_type(hpx::new_<server::partition>(hpx::find_here())) { init(datafilename, dim, num_nodes); } partition(hpx::id_type id, std::string const& datafilename, dimension const& dim, std::size_t num_nodes) : base_type(hpx::new_<server::partition>(id)) { init(datafilename, dim, num_nodes); } partition(hpx::naming::id_type gid) : base_type(gid) {} // initialize this partition hpx::lcos::future<void> init_async(std::string const& datafilename, dimension const& dim, std::size_t num_nodes) { typedef server::partition::init_action init_action; return hpx::async(init_action(), this->get_id(), datafilename, dim, num_nodes); } void init(std::string const& datafilename, dimension const& dim, std::size_t num_nodes) { init_async(datafilename, dim, num_nodes).get(); } // ask this partition to interpolate, note that value must be in the // range valid for this partition hpx::lcos::future<double> interpolate_async(double value) const { typedef server::partition::interpolate_action interpolate_action; return hpx::async(interpolate_action(), this->get_id(), value); } double interpolate(double value) const { return interpolate_async(value).get(); } }; } #endif
30.731707
80
0.602778
McKillroy
923a618895abb3b0e851ce817c684cc1b33f9f85
1,034
cpp
C++
nn_runtime/nnrt/model_transform/transformations.cpp
phytec-mirrors/nn-imx
58525bf968e8d90004f6d782ad37cea28991a439
[ "MIT" ]
null
null
null
nn_runtime/nnrt/model_transform/transformations.cpp
phytec-mirrors/nn-imx
58525bf968e8d90004f6d782ad37cea28991a439
[ "MIT" ]
null
null
null
nn_runtime/nnrt/model_transform/transformations.cpp
phytec-mirrors/nn-imx
58525bf968e8d90004f6d782ad37cea28991a439
[ "MIT" ]
null
null
null
#include <cassert> #include "nnrt/model.hpp" #include "nnrt/error.hpp" #include "nnrt/model_transform/transformations.hpp" namespace nnrt { TransformationSet::~TransformationSet() { for (auto trans : transformations_) { delete trans; } } int TransformationSet::run(Model* model) { (void)model; // unused variable int err = NNA_ERROR_CODE(NO_ERROR); //bool modified = false; //TODO: Run tranformations until there is no modifications. assert(false); return err; } int TransformationSet::once(Model* model) { int err = NNA_ERROR_CODE(NO_ERROR); bool modified = false; for (auto trans : transformations_) { NNRT_LOGD_PRINT("Run %s", trans->name()); err = trans->run(model, &modified); if (NNA_ERROR_CODE(NO_ERROR) != err) { NNRT_LOGW_PRINT("Run %s fail.", trans->name()); return err; } } return err; } void TransformationSet::add(Transformation* transformation) { transformations_.push_back(transformation); } }
22.478261
63
0.655706
phytec-mirrors
923d20c17f78d19485a495842b2c68e518f25270
174
cpp
C++
src/Engine/Renderer2/D3D11/Renderer_ShaderD3D11.cpp
MasonLeeBack/RSEngine
9ac4a0380898cb59a48d29dc7250dfb70430932f
[ "MIT" ]
1
2019-01-03T13:42:10.000Z
2019-01-03T13:42:10.000Z
src/Engine/Renderer2/D3D11/Renderer_ShaderD3D11.cpp
MasonLeeBack/RSEngine
9ac4a0380898cb59a48d29dc7250dfb70430932f
[ "MIT" ]
2
2019-01-03T19:00:42.000Z
2019-01-03T19:02:16.000Z
src/Engine/Renderer2/D3D11/Renderer_ShaderD3D11.cpp
MasonLeeBack/RSEngine
9ac4a0380898cb59a48d29dc7250dfb70430932f
[ "MIT" ]
null
null
null
/* RSEngine Copyright (c) 2020 Mason Lee Back File name: Renderer_ShaderD3D11.cpp */ #include <Renderer2/D3D11/Renderer_ShaderD3D11.h> namespace rs { } // namespace rs
11.6
49
0.741379
MasonLeeBack
923d3315b54761616f2a1f5afb6f8a22a7b80502
9,453
cpp
C++
src/GUI/ReadWrite.cpp
Olddies710/The-Forgotten-Client
8b7979619ea76bc29581122440d09f241afc175d
[ "Zlib" ]
1
2022-01-15T00:00:27.000Z
2022-01-15T00:00:27.000Z
src/GUI/ReadWrite.cpp
Olddies710/The-Forgotten-Client
8b7979619ea76bc29581122440d09f241afc175d
[ "Zlib" ]
null
null
null
src/GUI/ReadWrite.cpp
Olddies710/The-Forgotten-Client
8b7979619ea76bc29581122440d09f241afc175d
[ "Zlib" ]
3
2021-10-14T02:36:56.000Z
2022-03-22T21:03:31.000Z
/* The Forgotten Client Copyright (C) 2020 Saiyans King 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. */ #include "GUI_UTIL.h" #include "../engine.h" #include "../GUI_Elements/GUI_Window.h" #include "../GUI_Elements/GUI_Button.h" #include "../GUI_Elements/GUI_Separator.h" #include "../GUI_Elements/GUI_Label.h" #include "../GUI_Elements/GUI_MultiTextBox.h" #include "../GUI_Elements/GUI_StaticImage.h" #include "../game.h" #include "../thingManager.h" #include "ReadWrite.h" #define TEXT_WINDOW_TITLE1 "Show Text" #define TEXT_WINDOW_TITLE2 "Edit Text" #define TEXT_WINDOW_TITLE3 "Edit List" #define TEXT_WINDOW_WIDTH 286 #define TEXT_WINDOW_HEIGHT 284 #define TEXT_WINDOW_CANCEL_EVENTID 1000 #define TEXT_WINDOW_WRITE_EVENTID 1001 #define TEXT_WINDOW_EDIT_EVENTID 1002 #define TEXT_WINDOW_DESCRIPTION_X 62 #define TEXT_WINDOW_DESCRIPTION_Y 32 #define TEXT_WINDOW_ITEM_X 18 #define TEXT_WINDOW_ITEM_Y 32 #define TEXT_WINDOW_ITEM_W GUI_UI_ICON_EDITLIST_W #define TEXT_WINDOW_ITEM_H GUI_UI_ICON_EDITLIST_H #define TEXT_WINDOW_TEXTBOX_X 18 #define TEXT_WINDOW_TEXTBOX_Y 92 #define TEXT_WINDOW_TEXTBOX_W 250 #define TEXT_WINDOW_TEXTBOX_H 132 #define TEXT_WINDOW_TEXTBOX_EVENTID 1003 extern Engine g_engine; extern Game g_game; Uint32 g_windowId = 0; Uint8 g_doorId = 0; void readwrite_Events(Uint32 event, Sint32) { switch(event) { case TEXT_WINDOW_CANCEL_EVENTID: { GUI_Window* pWindow = g_engine.getCurrentWindow(); if(pWindow && pWindow->getInternalID() == GUI_WINDOW_READWRITE) g_engine.removeWindow(pWindow); } break; case TEXT_WINDOW_WRITE_EVENTID: { GUI_Window* pWindow = g_engine.getCurrentWindow(); if(pWindow && pWindow->getInternalID() == GUI_WINDOW_READWRITE) { GUI_MultiTextBox* pTextBox = SDL_static_cast(GUI_MultiTextBox*, pWindow->getChild(TEXT_WINDOW_TEXTBOX_EVENTID)); if(pTextBox) g_game.sendTextWindow(g_windowId, pTextBox->getText()); g_engine.removeWindow(pWindow); } } break; case TEXT_WINDOW_EDIT_EVENTID: { GUI_Window* pWindow = g_engine.getCurrentWindow(); if(pWindow && pWindow->getInternalID() == GUI_WINDOW_READWRITE) { GUI_MultiTextBox* pTextBox = SDL_static_cast(GUI_MultiTextBox*, pWindow->getChild(TEXT_WINDOW_TEXTBOX_EVENTID)); if(pTextBox) g_game.sendHouseWindow(g_windowId, g_doorId, pTextBox->getText()); g_engine.removeWindow(pWindow); } } break; default: break; } } void UTIL_createReadWriteWindow(Uint32 windowId, void* item, Uint16 maxLen, const std::string& text, const std::string& writer, const std::string& date) { GUI_Window* pWindow = g_engine.getWindow(GUI_WINDOW_READWRITE); if(pWindow) g_engine.removeWindow(pWindow); g_windowId = windowId; Uint16 maxLength = maxLen; bool writeAble = false; ItemUI* itemUI = SDL_reinterpret_cast(ItemUI*, item); if(itemUI && itemUI->getThingType()) { ThingType* itemType = itemUI->getThingType(); if(itemType->hasFlag(ThingAttribute_WritableOnce) || itemType->hasFlag(ThingAttribute_Writable)) { //Should we leave maxlen that we got from server? maxLength = itemType->m_writableSize; writeAble = (itemType->hasFlag(ThingAttribute_WritableOnce) ? text.empty() : true); } } if(!text.empty()) { if(!writer.empty()) { if(!date.empty()) SDL_snprintf(g_buffer, sizeof(g_buffer), "You read the following, written by \n%s\non %s.", writer.c_str(), date.c_str()); else SDL_snprintf(g_buffer, sizeof(g_buffer), "\nYou read the following, written by \n%s", writer.c_str()); } else if(!date.empty()) SDL_snprintf(g_buffer, sizeof(g_buffer), "\nYou read the following, written on \n%s.", date.c_str()); else SDL_snprintf(g_buffer, sizeof(g_buffer), "\n\nYou read the following:"); } else { if(writeAble) SDL_snprintf(g_buffer, sizeof(g_buffer), "\n\nIt is currently empty."); else SDL_snprintf(g_buffer, sizeof(g_buffer), "\n\nIt is empty."); } std::string description(g_buffer); if(writeAble) description.append("\nYou can enter new text."); else description.insert(0, "\n"); GUI_Window* newWindow = new GUI_Window(iRect(0, 0, TEXT_WINDOW_WIDTH, TEXT_WINDOW_HEIGHT), (writeAble ? TEXT_WINDOW_TITLE2 : TEXT_WINDOW_TITLE1), GUI_WINDOW_READWRITE); GUI_Label* newLabel = new GUI_Label(iRect(TEXT_WINDOW_DESCRIPTION_X, TEXT_WINDOW_DESCRIPTION_Y, 0, 0), std::move(description)); newWindow->addChild(newLabel); GUI_ReadWriteItem* newImage = new GUI_ReadWriteItem(iRect(TEXT_WINDOW_ITEM_X, TEXT_WINDOW_ITEM_Y, TEXT_WINDOW_ITEM_W, TEXT_WINDOW_ITEM_H), itemUI); newWindow->addChild(newImage); GUI_MultiTextBox* newTextBox = new GUI_MultiTextBox(iRect(TEXT_WINDOW_TEXTBOX_X, TEXT_WINDOW_TEXTBOX_Y, TEXT_WINDOW_TEXTBOX_W, TEXT_WINDOW_TEXTBOX_H), writeAble, text, TEXT_WINDOW_TEXTBOX_EVENTID); newTextBox->setMaxLength(SDL_static_cast(Uint32, maxLength)); newTextBox->startEvents(); newWindow->addChild(newTextBox); if(writeAble) { GUI_Button* newButton = new GUI_Button(iRect(TEXT_WINDOW_WIDTH - 56, TEXT_WINDOW_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Cancel", CLIENT_GUI_ESCAPE_TRIGGER); newButton->setButtonEventCallback(&readwrite_Events, TEXT_WINDOW_CANCEL_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); newButton = new GUI_Button(iRect(TEXT_WINDOW_WIDTH - 109, TEXT_WINDOW_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Ok"); newButton->setButtonEventCallback(&readwrite_Events, TEXT_WINDOW_WRITE_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); } else { GUI_Button* newButton = new GUI_Button(iRect(TEXT_WINDOW_WIDTH - 56, TEXT_WINDOW_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Ok", CLIENT_GUI_ESCAPE_TRIGGER); newButton->setButtonEventCallback(&readwrite_Events, TEXT_WINDOW_CANCEL_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); newButton = new GUI_Button(iRect(TEXT_WINDOW_WIDTH - 56, TEXT_WINDOW_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Ok", CLIENT_GUI_ENTER_TRIGGER); newButton->setButtonEventCallback(&readwrite_Events, TEXT_WINDOW_CANCEL_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); newTextBox->setColor(175, 175, 175); } GUI_Separator* newSeparator = new GUI_Separator(iRect(13, TEXT_WINDOW_HEIGHT - 40, TEXT_WINDOW_WIDTH - 26, 2)); newWindow->addChild(newSeparator); g_engine.addWindow(newWindow); } void UTIL_createReadWriteWindow(Uint8 doorId, Uint32 windowId, const std::string& text) { GUI_Window* pWindow = g_engine.getWindow(GUI_WINDOW_READWRITE); if(pWindow) g_engine.removeWindow(pWindow); g_windowId = windowId; g_doorId = doorId; GUI_Window* newWindow = new GUI_Window(iRect(0, 0, TEXT_WINDOW_WIDTH, TEXT_WINDOW_HEIGHT), TEXT_WINDOW_TITLE3, GUI_WINDOW_READWRITE); GUI_Label* newLabel = new GUI_Label(iRect(TEXT_WINDOW_DESCRIPTION_X, TEXT_WINDOW_DESCRIPTION_Y, 0, 0), "\n\n\nEnter one name per line."); newWindow->addChild(newLabel); GUI_StaticImage* newImage = new GUI_StaticImage(iRect(TEXT_WINDOW_ITEM_X, TEXT_WINDOW_ITEM_Y, TEXT_WINDOW_ITEM_W, TEXT_WINDOW_ITEM_H), GUI_UI_IMAGE, GUI_UI_ICON_EDITLIST_X, GUI_UI_ICON_EDITLIST_Y); newWindow->addChild(newImage); GUI_MultiTextBox* newTextBox = new GUI_MultiTextBox(iRect(TEXT_WINDOW_TEXTBOX_X, TEXT_WINDOW_TEXTBOX_Y, TEXT_WINDOW_TEXTBOX_W, TEXT_WINDOW_TEXTBOX_H), true, text, TEXT_WINDOW_TEXTBOX_EVENTID); newTextBox->setMaxLength(8192); newTextBox->startEvents(); newWindow->addChild(newTextBox); GUI_Button* newButton = new GUI_Button(iRect(TEXT_WINDOW_WIDTH - 56, TEXT_WINDOW_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Cancel", CLIENT_GUI_ESCAPE_TRIGGER); newButton->setButtonEventCallback(&readwrite_Events, TEXT_WINDOW_CANCEL_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); newButton = new GUI_Button(iRect(TEXT_WINDOW_WIDTH - 109, TEXT_WINDOW_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Ok"); newButton->setButtonEventCallback(&readwrite_Events, TEXT_WINDOW_EDIT_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); GUI_Separator* newSeparator = new GUI_Separator(iRect(13, TEXT_WINDOW_HEIGHT - 40, TEXT_WINDOW_WIDTH - 26, 2)); newWindow->addChild(newSeparator); g_engine.addWindow(newWindow); } GUI_ReadWriteItem::GUI_ReadWriteItem(iRect boxRect, ItemUI* item, Uint32 internalID) { setRect(boxRect); m_internalID = internalID; m_item = item; } GUI_ReadWriteItem::~GUI_ReadWriteItem() { if(m_item) delete m_item; } void GUI_ReadWriteItem::render() { if(m_item) m_item->render(m_tRect.x1, m_tRect.y1, m_tRect.y2); }
40.055085
198
0.780281
Olddies710
923dc0f01c84100d2bdd8360b88e541c7deaed5a
3,025
cc
C++
third_party/blink/renderer/modules/indexeddb/idb_observation.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/indexeddb/idb_observation.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/indexeddb/idb_observation.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/indexeddb/idb_observation.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" #include "third_party/blink/renderer/bindings/modules/v8/to_v8_for_modules.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h" #include "third_party/blink/renderer/modules/indexed_db_names.h" #include "third_party/blink/renderer/modules/indexeddb/idb_any.h" #include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h" #include "third_party/blink/renderer/modules/indexeddb/idb_value.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { IDBObservation::~IDBObservation() = default; ScriptValue IDBObservation::key(ScriptState* script_state) { if (!key_range_) return ScriptValue::From(script_state, v8::Undefined(script_state->GetIsolate())); return ScriptValue::From(script_state, key_range_); } ScriptValue IDBObservation::value(ScriptState* script_state) { return ScriptValue::From(script_state, value_); } mojom::IDBOperationType IDBObservation::StringToOperationType( const String& type) { if (type == indexed_db_names::kAdd) return mojom::IDBOperationType::Add; if (type == indexed_db_names::kPut) return mojom::IDBOperationType::Put; if (type == indexed_db_names::kDelete) return mojom::IDBOperationType::Delete; if (type == indexed_db_names::kClear) return mojom::IDBOperationType::Clear; NOTREACHED(); return mojom::IDBOperationType::Add; } const String& IDBObservation::type() const { switch (operation_type_) { case mojom::IDBOperationType::Add: return indexed_db_names::kAdd; case mojom::IDBOperationType::Put: return indexed_db_names::kPut; case mojom::IDBOperationType::Delete: return indexed_db_names::kDelete; case mojom::IDBOperationType::Clear: return indexed_db_names::kClear; default: NOTREACHED(); return indexed_db_names::kAdd; } } IDBObservation::IDBObservation(int64_t object_store_id, mojom::IDBOperationType type, IDBKeyRange* key_range, std::unique_ptr<IDBValue> value) : object_store_id_(object_store_id), operation_type_(type), key_range_(key_range) { value_ = MakeGarbageCollected<IDBAny>(std::move(value)); } void IDBObservation::SetIsolate(v8::Isolate* isolate) { DCHECK(value_ && value_->Value()); value_->Value()->SetIsolate(isolate); } void IDBObservation::Trace(Visitor* visitor) { visitor->Trace(key_range_); visitor->Trace(value_); ScriptWrappable::Trace(visitor); } } // namespace blink
33.241758
82
0.73157
sarang-apps
923f1ca2fb8280e4e0fa9d1260373d30fb265c5b
9,021
cpp
C++
QTermWidget/lib/qtermwidget.cpp
rkoyama1623/Quantum
429d11f0b2c737164005ba70c98611baef69d1c5
[ "Unlicense" ]
35
2015-01-13T00:57:17.000Z
2022-03-16T20:39:56.000Z
QTermWidget/lib/qtermwidget.cpp
KR8T3R/Quantum
429d11f0b2c737164005ba70c98611baef69d1c5
[ "Unlicense" ]
null
null
null
QTermWidget/lib/qtermwidget.cpp
KR8T3R/Quantum
429d11f0b2c737164005ba70c98611baef69d1c5
[ "Unlicense" ]
31
2015-01-29T03:59:52.000Z
2022-03-16T20:40:43.000Z
/* Copyright (C) 2008 e_k (e_k@users.sourceforge.net) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "qtermwidget.h" #include "ColorTables.h" #include "Session.h" #include "TerminalDisplay.h" #include "KeyboardTranslator.h" #include "ColorScheme.h" using namespace Konsole; void *createTermWidget(int startnow, void *parent) { return (void*) new QTermWidget(startnow, (QWidget*)parent); } struct TermWidgetImpl { TermWidgetImpl(QWidget* parent = 0); TerminalDisplay *m_terminalDisplay; Session *m_session; Session* createSession(); TerminalDisplay* createTerminalDisplay(Session *session, QWidget* parent); }; TermWidgetImpl::TermWidgetImpl(QWidget* parent) { this->m_session = createSession(); this->m_terminalDisplay = createTerminalDisplay(this->m_session, parent); } Session *TermWidgetImpl::createSession() { Session *session = new Session(); session->setTitle(Session::NameRole, "QTermWidget"); /* Thats a freaking bad idea!!!! * /bin/bash is not there on every system * better set it to the current $SHELL * Maybe you can also make a list available and then let the widget-owner decide what to use. * By setting it to $SHELL right away we actually make the first filecheck obsolete. * But as iam not sure if you want to do anything else ill just let both checks in and set this to $SHELL anyway. */ //session->setProgram("/bin/bash"); session->setProgram(getenv("SHELL")); QStringList args(""); session->setArguments(args); session->setAutoClose(true); session->setCodec(QTextCodec::codecForName("UTF-8")); session->setFlowControlEnabled(true); session->setHistoryType(HistoryTypeBuffer(1000)); session->setDarkBackground(true); session->setKeyBindings(""); return session; } TerminalDisplay *TermWidgetImpl::createTerminalDisplay(Session *session, QWidget* parent) { // TerminalDisplay* display = new TerminalDisplay(this); TerminalDisplay* display = new TerminalDisplay(parent); display->setBellMode(TerminalDisplay::NotifyBell); display->setTerminalSizeHint(true); display->setTripleClickMode(TerminalDisplay::SelectWholeLine); display->setTerminalSizeStartup(true); display->setRandomSeed(session->sessionId() * 31); return display; } QTermWidget::QTermWidget(int startnow, QWidget *parent) :QWidget(parent) { m_impl = new TermWidgetImpl(this); init(); if (startnow && m_impl->m_session) { m_impl->m_session->run(); } this->setFocus( Qt::OtherFocusReason ); m_impl->m_terminalDisplay->resize(this->size()); this->setFocusProxy(m_impl->m_terminalDisplay); connect(m_impl->m_terminalDisplay, SIGNAL(copyAvailable(bool)), this, SLOT(selectionChanged(bool))); connect(m_impl->m_terminalDisplay, SIGNAL(termGetFocus()), this, SIGNAL(termGetFocus())); connect(m_impl->m_terminalDisplay, SIGNAL(termLostFocus()), this, SIGNAL(termLostFocus())); } void QTermWidget::selectionChanged(bool textSelected) { emit copyAvailable(textSelected); } int QTermWidget::getShellPID() { return m_impl->m_session->processId(); } void QTermWidget::changeDir(const QString & dir) { /* this is a very hackish way of trying to determine if the shell is in the foreground before attempting to change the directory. It may not be portable to anything other than Linux. */ QString strCmd; strCmd.setNum(getShellPID()); strCmd.prepend("ps -j "); strCmd.append(" | tail -1 | awk '{ print $5 }' | grep -q \\+"); int retval = system(strCmd.toStdString().c_str()); if (!retval) { QString cmd = "cd " + dir + "\n"; sendText(cmd); } } QSize QTermWidget::sizeHint() const { QSize size = m_impl->m_terminalDisplay->sizeHint(); size.rheight() = 150; return size; } void QTermWidget::startShellProgram() { if ( m_impl->m_session->isRunning() ) { return; } m_impl->m_session->run(); } void QTermWidget::init() { m_impl->m_terminalDisplay->setSize(80, 40); QFont font = QApplication::font(); font.setFamily("Monospace"); font.setPointSize(10); font.setStyleHint(QFont::TypeWriter); setTerminalFont(font); setScrollBarPosition(NoScrollBar); m_impl->m_session->addView(m_impl->m_terminalDisplay); connect(m_impl->m_session, SIGNAL(finished()), this, SLOT(sessionFinished())); } QTermWidget::~QTermWidget() { emit destroyed(); } void QTermWidget::setTerminalFont(QFont &font) { if (!m_impl->m_terminalDisplay) return; m_impl->m_terminalDisplay->setVTFont(font); } void QTermWidget::setTerminalOpacity(qreal level) { if (!m_impl->m_terminalDisplay) return; m_impl->m_terminalDisplay->setOpacity(level); } void QTermWidget::setShellProgram(const QString &progname) { if (!m_impl->m_session) return; m_impl->m_session->setProgram(progname); } void QTermWidget::setWorkingDirectory(const QString& dir) { if (!m_impl->m_session) return; m_impl->m_session->setInitialWorkingDirectory(dir); } void QTermWidget::setArgs(QStringList &args) { if (!m_impl->m_session) return; m_impl->m_session->setArguments(args); } void QTermWidget::setTextCodec(QTextCodec *codec) { if (!m_impl->m_session) return; m_impl->m_session->setCodec(codec); } void QTermWidget::setColorScheme(const QString & name) { const ColorScheme *cs; // avoid legacy (int) solution if (!availableColorSchemes().contains(name)) cs = ColorSchemeManager::instance()->defaultColorScheme(); else cs = ColorSchemeManager::instance()->findColorScheme(name); if (! cs) { QMessageBox::information(this, tr("Color Scheme Error"), tr("Cannot load color scheme: %1").arg(name)); return; } ColorEntry table[TABLE_COLORS]; cs->getColorTable(table); m_impl->m_terminalDisplay->setColorTable(table); } QStringList QTermWidget::availableColorSchemes() { QStringList ret; foreach (const ColorScheme* cs, ColorSchemeManager::instance()->allColorSchemes()) ret.append(cs->name()); return ret; } void QTermWidget::setSize(int h, int v) { if (!m_impl->m_terminalDisplay) return; m_impl->m_terminalDisplay->setSize(h, v); } void QTermWidget::setHistorySize(int lines) { if (lines < 0) m_impl->m_session->setHistoryType(HistoryTypeFile()); else m_impl->m_session->setHistoryType(HistoryTypeBuffer(lines)); } void QTermWidget::setScrollBarPosition(ScrollBarPosition pos) { if (!m_impl->m_terminalDisplay) return; m_impl->m_terminalDisplay->setScrollBarPosition((TerminalDisplay::ScrollBarPosition)pos); } void QTermWidget::sendText(QString &text) { m_impl->m_session->sendText(text); } void QTermWidget::resizeEvent(QResizeEvent*) { //qDebug("global window resizing...with %d %d", this->size().width(), this->size().height()); m_impl->m_terminalDisplay->resize(this->size()); } void QTermWidget::sessionFinished() { emit finished(); } void QTermWidget::copyClipboard() { m_impl->m_terminalDisplay->copyClipboard(); } void QTermWidget::pasteClipboard() { m_impl->m_terminalDisplay->pasteClipboard(); } void QTermWidget::setKeyBindings(const QString & kb) { m_impl->m_session->setKeyBindings(kb); } void QTermWidget::setFlowControlEnabled(bool enabled) { m_impl->m_session->setFlowControlEnabled(enabled); } QStringList QTermWidget::availableKeyBindings() { return KeyboardTranslatorManager::instance()->allTranslators(); } QString QTermWidget::keyBindings() { return m_impl->m_session->keyBindings(); } bool QTermWidget::flowControlEnabled(void) { return m_impl->m_session->flowControlEnabled(); } void QTermWidget::setFlowControlWarningEnabled(bool enabled) { if (flowControlEnabled()) { // Do not show warning label if flow control is disabled m_impl->m_terminalDisplay->setFlowControlWarningEnabled(enabled); } } void QTermWidget::setEnvironment(const QStringList& environment) { m_impl->m_session->setEnvironment(environment); }
25.627841
117
0.695156
rkoyama1623
9240205fd9fc33462aa38e45572ca65e546edbcf
834
cpp
C++
Data Structures/Prime Numbers/PrimeFactorization.cpp
ravikjha7/Competitive_Programming
86df773c258d6675bb3244030e6d71aa32e01fce
[ "MIT" ]
null
null
null
Data Structures/Prime Numbers/PrimeFactorization.cpp
ravikjha7/Competitive_Programming
86df773c258d6675bb3244030e6d71aa32e01fce
[ "MIT" ]
null
null
null
Data Structures/Prime Numbers/PrimeFactorization.cpp
ravikjha7/Competitive_Programming
86df773c258d6675bb3244030e6d71aa32e01fce
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; #define mod 1000000007 void file() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } // Time Complexity : O(sqrt(N)) void FindPrime(ll n) { for(int i = 2; i <= sqrt(n); i++) { if(n % i == 0) { while(n % i == 0) { cout << i << " "; n /= i; } } } if(n != 1) cout << n; cout << endl; } void solve() { ll n; cin >> n; int i = 2; // Brute Force // Time Complexity : O(N) // while(n > 1) // { // if(n % i == 0) { // cout << i << " "; // n /= i; // } else { // i++; // } // } // cout << endl; FindPrime(n); } int main() { file(); ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; // cin >> t; while(t--) { solve(); } return 0; }
13.03125
39
0.479616
ravikjha7
9240c2f7ba6c9aa10531027860fb1b407388a7d3
533
hh
C++
tests/applications/QuickSilver/QuickSilver_orig_ser/src/MC_Distance_To_Facet.hh
rutgers-apl/omp-racer
a8a32e186950997b8eee7864f766819129a5ee06
[ "BSD-2-Clause" ]
2
2020-09-17T15:18:49.000Z
2021-03-06T10:21:23.000Z
tests/applications/QuickSilver/QuickSilver_orig/src/MC_Distance_To_Facet.hh
rutgers-apl/omp-racer
a8a32e186950997b8eee7864f766819129a5ee06
[ "BSD-2-Clause" ]
1
2020-09-08T18:36:24.000Z
2020-09-17T15:18:27.000Z
tests/applications/QuickSilver/QuickSilver_orig_ser/src/MC_Distance_To_Facet.hh
rutgers-apl/omp-racer
a8a32e186950997b8eee7864f766819129a5ee06
[ "BSD-2-Clause" ]
1
2021-01-19T15:28:15.000Z
2021-01-19T15:28:15.000Z
#ifndef MCT_DISTANCE_INCLUDE #define MCT_DISTANCE_INCLUDE #include "DeclareMacro.hh" HOST_DEVICE_CLASS class MC_Distance_To_Facet { public: double distance; int facet; int subfacet; HOST_DEVICE_CUDA MC_Distance_To_Facet(): distance(0.0), facet(0), subfacet(0) {} private: MC_Distance_To_Facet( const MC_Distance_To_Facet& ); // disable copy constructor MC_Distance_To_Facet& operator=( const MC_Distance_To_Facet& tmp ); // disable assignment operator }; HOST_DEVICE_END #endif
23.173913
106
0.731707
rutgers-apl
924699cf6b0b84cdeeb997b187cde8ae93a8e977
8,356
cpp
C++
HW4_birdeye/src/example_18-01_from_disk.cpp
Citing/CV-Course
f3e062347fa1cea85ca57181c90f23ad577c0e8c
[ "MIT" ]
4
2019-12-14T11:21:54.000Z
2021-01-15T13:55:35.000Z
HW4_birdeye/src/example_18-01_from_disk.cpp
Citing/CV-Course
f3e062347fa1cea85ca57181c90f23ad577c0e8c
[ "MIT" ]
null
null
null
HW4_birdeye/src/example_18-01_from_disk.cpp
Citing/CV-Course
f3e062347fa1cea85ca57181c90f23ad577c0e8c
[ "MIT" ]
2
2020-11-26T13:04:08.000Z
2020-12-02T01:14:53.000Z
#define main e18_2 #define help help2 // Example 18-1. Reading a chessboard’s width and height, reading them from disk and calibrating // the requested number of views, and calibrating the camera // You need these includes for the function // #include <windows.h> // for windows systems #include <dirent.h> // for linux systems #include <sys/stat.h> // for linux systems #include <iostream> // cout #include <algorithm> // std::sort #include <opencv2/opencv.hpp> using std::string; using std::vector; using std::cout; using std::cerr; using std::endl; // Returns a list of files in a directory (except the ones that begin with a dot) int readFilenames(vector<string>& filenames, const string& directory) { DIR *dir; class dirent *ent; class stat st; dir = opendir(directory.c_str()); while ((ent = readdir(dir)) != NULL) { const string file_name = ent->d_name; const string full_file_name = directory + "/" + file_name; if (file_name[0] == '.') continue; if (stat(full_file_name.c_str(), &st) == -1) continue; const bool is_directory = (st.st_mode & S_IFDIR) != 0; if (is_directory) continue; // filenames.push_back(full_file_name); // returns full path filenames.push_back(file_name); // returns just filename } closedir(dir); std::sort(filenames.begin(), filenames.end()); // optional, sort the filenames return(filenames.size()); // return how many we found } // GetFilesInDirectory void help(const char **argv) { cout << "\n\n" << "Example 18-1 (from disk):\Enter a chessboard’s width and height,\n" << " reading in a directory of chessboard images,\n" << " and calibrating the camera\n\n" << "Call:\n" << argv[0] << " <1board_width> <2board_height> <3number_of_boards>" << " <4ms_delay_framee_capture> <5image_scaling_factor> <6path_to_calibration_images>\n\n" << "\nExample:\n" << "./example_18-01_from_disk 9 6 14 100 1.0 ../stereoData/\nor:\n" << "./example_18-01_from_disk 12 12 28 100 0.5 ../calibration/\n\n" << " * First it reads in checker boards and calibrates itself\n" << " * Then it saves and reloads the calibration matricies\n" << " * Then it creates an undistortion map and finaly\n" << " * It displays an undistorted image\n" << endl; } int main(int argc, char *argv[]) { float image_sf = 0.5f; // image scaling factor int delay = 250; // miliseconds int board_w = 0; int board_h = 0; board_w = atoi(argv[1]); board_h = atoi(argv[2]); int n_boards = atoi(argv[3]); // how many boards max to read delay = atof(argv[4]); // milisecond delay image_sf = atof(argv[5]); int board_n = board_w * board_h; // number of corners cv::Size board_sz = cv::Size(board_w, board_h); // width and height of the board string folder = argv[6]; cout << "Reading in directory " << folder << endl; vector<string> filenames; int num_files = readFilenames(filenames, folder); cout << " ... Done. Number of files = " << num_files << "\n" << endl; // PROVIDE PPOINT STORAGE // vector<vector<cv::Point2f> > image_points; vector<vector<cv::Point3f> > object_points; /////////// COLLECT ////////////////////////////////////////////// // Capture corner views: loop through all calibration images // collecting all corners on the boards that are found // cv::Size image_size; int board_count = 0; for (size_t i = 0; (i < filenames.size()) && (board_count < n_boards); ++i) { cv::Mat image, image0 = cv::imread(folder + filenames[i]); board_count += 1; if (!image0.data) { // protect against no file cerr << folder + filenames[i] << ", file #" << i << ", is not an image" << endl; continue; } image_size = image0.size(); cv::resize(image0, image, cv::Size(), image_sf, image_sf, cv::INTER_LINEAR); // Find the board // vector<cv::Point2f> corners; bool found = cv::findChessboardCorners(image, board_sz, corners); // Draw it // drawChessboardCorners(image, board_sz, corners, found); // will draw only if found // If we got a good board, add it to our data // if (found) { image ^= cv::Scalar::all(255); cv::Mat mcorners(corners); // do not copy the data mcorners *= (1.0 / image_sf); // scale the corner coordinates image_points.push_back(corners); object_points.push_back(vector<cv::Point3f>()); vector<cv::Point3f> &opts = object_points.back(); opts.resize(board_n); for (int j = 0; j < board_n; j++) { opts[j] = cv::Point3f(static_cast<float>(j / board_w), static_cast<float>(j % board_w), 0.0f); } cout << "Collected " << static_cast<int>(image_points.size()) << "total boards. This one from chessboard image #" << i << ", " << folder + filenames[i] << endl; } cv::imshow("Calibration", image); // show in color if we did collect the image if ((cv::waitKey(delay) & 255) == 27) { return -1; } } // END COLLECTION WHILE LOOP. cv::destroyWindow("Calibration"); cout << "\n\n*** CALIBRATING THE CAMERA...\n" << endl; /////////// CALIBRATE ////////////////////////////////////////////// // CALIBRATE THE CAMERA! // cv::Mat intrinsic_matrix, distortion_coeffs; double err = cv::calibrateCamera( object_points, image_points, image_size, intrinsic_matrix, distortion_coeffs, cv::noArray(), cv::noArray(), cv::CALIB_ZERO_TANGENT_DIST | cv::CALIB_FIX_PRINCIPAL_POINT); // SAVE THE INTRINSICS AND DISTORTIONS cout << " *** DONE!\n\nReprojection error is " << err << "\nStoring Intrinsics.xml and Distortions.xml files\n\n"; cv::FileStorage fs("intrinsics.xml", cv::FileStorage::WRITE); fs << "image_width" << image_size.width << "image_height" << image_size.height << "camera_matrix" << intrinsic_matrix << "distortion_coefficients" << distortion_coeffs; fs.release(); // EXAMPLE OF LOADING THESE MATRICES BACK IN: fs.open("intrinsics.xml", cv::FileStorage::READ); cout << "\nimage width: " << static_cast<int>(fs["image_width"]); cout << "\nimage height: " << static_cast<int>(fs["image_height"]); cv::Mat intrinsic_matrix_loaded, distortion_coeffs_loaded; fs["camera_matrix"] >> intrinsic_matrix_loaded; fs["distortion_coefficients"] >> distortion_coeffs_loaded; cout << "\nintrinsic matrix:" << intrinsic_matrix_loaded; cout << "\ndistortion coefficients: " << distortion_coeffs_loaded << "\n" << endl; // Build the undistort map which we will use for all // subsequent frames. // cv::Mat map1, map2; cv::initUndistortRectifyMap(intrinsic_matrix_loaded, distortion_coeffs_loaded, cv::Mat(), intrinsic_matrix_loaded, image_size, CV_16SC2, map1, map2); ////////// DISPLAY ////////////////////////////////////////////// cout << "*****************\nPRESS A KEY TO SEE THE NEXT IMAGE, ESQ TO QUIT\n" << "****************\n" << endl; board_count = 0; // resent max boards to read for (size_t i = 0; (i < filenames.size()) && (board_count < n_boards); ++i) { cv::Mat image, image0 = cv::imread(folder + filenames[i]); ++board_count; if (!image0.data) { // protect against no file cerr << folder + filenames[i] << ", file #" << i << ", is not an image" << endl; continue; } // Just run the camera to the screen, now showing the raw and // the undistorted image. // cv::remap(image0, image, map1, map2, cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar()); cv::imshow("Original", image0); cv::imshow("Undistorted", image); if ((cv::waitKey(0) & 255) == 27) { break; } } return 0; }
38.865116
99
0.575156
Citing
924e33aff8698577d8e01d40e776b8930c09ca31
920
hpp
C++
SDK/ARKSurvivalEvolved_BoneModifiersContainer_ChibiThylacoleo_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_BoneModifiersContainer_ChibiThylacoleo_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_BoneModifiersContainer_ChibiThylacoleo_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_BoneModifiersContainer_ChibiThylacoleo_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BoneModifiersContainer_ChibiThylacoleo.BoneModifiersContainer_ChibiThylacoleo_C // 0x0000 (0x0038 - 0x0038) class UBoneModifiersContainer_ChibiThylacoleo_C : public UBoneModifiersContainer_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BoneModifiersContainer_ChibiThylacoleo.BoneModifiersContainer_ChibiThylacoleo_C"); return ptr; } void ExecuteUbergraph_BoneModifiersContainer_ChibiThylacoleo(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
23.589744
146
0.68587
2bite
924eaf825e68dc10d0511708d21f41cd7c5bfb8a
518
cpp
C++
Codeforces/1291D.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
Codeforces/1291D.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
Codeforces/1291D.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <bits/stdc++.h> #define MAXN 200005 using namespace std; char s[MAXN]; int T,n,l,r,cnt[MAXN][26]; int main() { scanf("%s",s+1);n=strlen(s+1); for (int i=1;i<=n;i++) for (int j=0;j<26;j++) cnt[i][j]=cnt[i-1][j]+(s[i]-'a'==j); scanf("%d",&T); while (T--) { scanf("%d %d",&l,&r); if (l==r) puts("Yes"); else { int t=0; for (int i=0;i<26;i++) t+=((cnt[r][i]-cnt[l-1][i])>0); if (t>=3){puts("Yes");continue;} if (s[l]!=s[r]){puts("Yes");continue;} puts("No"); } } return 0; }
17.862069
57
0.494208
HeRaNO