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
8be613f577fd369a92cf747a51ff5fc0ac3c9ded
678
hpp
C++
include/sprout/preprocessor/u16str.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/preprocessor/u16str.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/preprocessor/u16str.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_PREPROCESSOR_U16STR_HPP #define SPROUT_PREPROCESSOR_U16STR_HPP #include <sprout/config.hpp> // // SPROUT_PP_U16STR // #define SPROUT_PP_U16STR(str) SPROUT_PP_U16STR_I(str) #define SPROUT_PP_U16STR_I(str) u ## str #endif // #ifndef SPROUT_PREPROCESSOR_U16STR_HPP
33.9
79
0.60767
thinkoid
8bf4ae03c6a823d072c08f0afd8d61fbadebcccc
13,444
cpp
C++
ssc/cmod_pv6parmod.cpp
gjsoto/ssc
70ef4fdafb9afe0418a9c552485a7116a1b3a743
[ "BSD-3-Clause" ]
61
2017-08-09T15:10:59.000Z
2022-02-15T21:45:31.000Z
ssc/cmod_pv6parmod.cpp
gjsoto/ssc
70ef4fdafb9afe0418a9c552485a7116a1b3a743
[ "BSD-3-Clause" ]
462
2017-07-31T21:26:46.000Z
2022-03-30T22:53:50.000Z
ssc/cmod_pv6parmod.cpp
gjsoto/ssc
70ef4fdafb9afe0418a9c552485a7116a1b3a743
[ "BSD-3-Clause" ]
73
2017-08-24T17:39:31.000Z
2022-03-28T08:37:47.000Z
/** BSD-3-Clause Copyright 2019 Alliance for Sustainable Energy, LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #ifndef M_PI #define M_PI 3.141592653589793238462643 #endif #include "core.h" #include "lib_cec6par.h" #include "lib_irradproc.h" static var_info _cm_vtab_pv6parmod[] = { /* VARTYPE DATATYPE NAME LABEL UNITS META GROUP REQUIRED_IF CONSTRAINTS UI_HINTS*/ { SSC_INPUT, SSC_ARRAY, "poa_beam", "Incident direct normal radiation","W/m2", "", "Weather", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "poa_skydiff", "Incident sky diffuse radiation", "W/m2", "", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_ARRAY, "poa_gnddiff", "Incident ground diffuse irradiance","W/m2","", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_ARRAY, "tdry", "Dry bulb temperature", "'C", "", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_ARRAY, "wspd", "Wind speed", "m/s", "", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_ARRAY, "wdir", "Wind direction", "deg", "", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_ARRAY, "sun_zen", "Sun zenith angle", "deg", "", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_ARRAY, "incidence", "Incidence angle to surface", "deg", "", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_ARRAY, "surf_tilt", "Surface tilt angle", "deg", "", "Weather", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_INPUT, SSC_NUMBER, "elev", "Site elevation", "m", "", "Weather", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "opvoltage", "Module operating voltage", "Volt", "", "CEC 6 Parameter PV Module Model", "?" "", "" }, { SSC_INPUT, SSC_NUMBER, "area", "Module area", "m2", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Vmp", "Maximum power point voltage", "V", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Imp", "Maximum power point current", "A", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Voc", "Open circuit voltage", "V", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Isc", "Short circuit current", "A", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "alpha_isc", "Temp coeff of current at SC", "A/'C", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "beta_voc", "Temp coeff of voltage at OC", "V/'C", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "gamma_pmp", "Temp coeff of power at MP", "%/'C", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "tnoct", "NOCT cell temperature", "'C", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "a", "Modified nonideality factor", "1/V", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Il", "Light current", "A", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Io", "Saturation current", "A", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Rs", "Series resistance", "ohm", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Rsh", "Shunt resistance", "ohm", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Adj", "OC SC temp coeff adjustment", "%", "", "CEC 6 Parameter PV Module Model", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "standoff", "Mounting standoff option", "0..6", "0=bipv, 1= >3.5in, 2=2.5-3.5in, 3=1.5-2.5in, 4=0.5-1.5in, 5= <0.5in, 6=ground/rack", "CEC 6 Parameter PV Module Model", "?=6", "INTEGER,MIN=0,MAX=6", "" }, { SSC_INPUT, SSC_NUMBER, "height", "System installation height", "0/1", "0=less than 22ft, 1=more than 22ft", "CEC 6 Parameter PV Module Model", "?=0", "INTEGER,MIN=0,MAX=1", "" }, { SSC_OUTPUT, SSC_ARRAY, "tcell", "Cell temperature", "'C", "", "CEC 6 Parameter PV Module Model", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_OUTPUT, SSC_ARRAY, "dc_voltage", "DC module voltage", "Volt", "", "CEC 6 Parameter PV Module Model", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_OUTPUT, SSC_ARRAY, "dc_current", "DC module current", "Ampere", "", "CEC 6 Parameter PV Module Model", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_OUTPUT, SSC_ARRAY, "eff", "Conversion efficiency", "0..1", "", "CEC 6 Parameter PV Module Model", "*", "LENGTH_EQUAL=poa_beam", "" }, { SSC_OUTPUT, SSC_ARRAY, "dc", "DC power output", "Watt", "", "CEC 6 Parameter PV Module Model", "*", "LENGTH_EQUAL=poa_beam", "" }, var_info_invalid }; class cm_pv6parmod : public compute_module { private: public: cm_pv6parmod() { add_var_info( _cm_vtab_pv6parmod ); } void exec( ) { size_t arr_len; ssc_number_t *p_poabeam = as_array( "poa_beam", &arr_len ); ssc_number_t *p_poaskydiff = as_array( "poa_skydiff", &arr_len ); ssc_number_t *p_poagnddiff = as_array( "poa_gnddiff", &arr_len ); ssc_number_t *p_tdry = as_array( "tdry", &arr_len ); ssc_number_t *p_wspd = as_array( "wspd", &arr_len ); ssc_number_t *p_wdir = as_array( "wdir", &arr_len ); ssc_number_t *p_inc = as_array( "incidence", &arr_len ); ssc_number_t *p_zen = as_array( "sun_zen", &arr_len ); ssc_number_t *p_stilt = as_array( "surf_tilt", &arr_len ); double site_elevation = as_double("elev"); cec6par_module_t mod; mod.Area = as_double("area"); mod.Vmp = as_double("Vmp"); mod.Imp = as_double("Imp"); mod.Voc = as_double("Voc"); mod.Isc = as_double("Isc"); mod.alpha_isc = as_double("alpha_isc"); mod.beta_voc = as_double("beta_voc"); mod.a = as_double("a"); mod.Il = as_double("Il"); mod.Io = as_double("Io"); mod.Rs = as_double("Rs"); mod.Rsh = as_double("Rsh"); mod.Adj = as_double("Adj"); noct_celltemp_t tc; tc.Tnoct = as_double("tnoct"); int standoff = as_integer("standoff"); tc.standoff_tnoct_adj = 0; switch(standoff) { //source for standoff adjustment constants: https://prod-ng.sandia.gov/techlib-noauth/access-control.cgi/1985/850330.pdf page 12 case 2: tc.standoff_tnoct_adj = 2; break; // between 2.5 and 3.5 inches case 3: tc.standoff_tnoct_adj = 6; break; // between 1.5 and 2.5 inches case 4: tc.standoff_tnoct_adj = 11; break; // between 0.5 and 1.5 inches case 5: tc.standoff_tnoct_adj = 18; break; // less than 0.5 inches // note: all others, standoff_tnoct_adj = 0; } int height = as_integer("height"); tc.ffv_wind = 0.51; if ( height == 1 ) tc.ffv_wind = 0.61; ssc_number_t *opvoltage = 0; if ( is_assigned("opvoltage") ) { size_t opvlen = 0; opvoltage = as_array( "opvoltage", &opvlen ); if ( opvlen != arr_len ) throw general_error("operating voltage array must be same length as input vectors"); } ssc_number_t *p_tcell = allocate("tcell", arr_len); ssc_number_t *p_volt = allocate("dc_voltage", arr_len); ssc_number_t *p_amp = allocate("dc_current", arr_len); ssc_number_t *p_eff = allocate("eff", arr_len); ssc_number_t *p_dc = allocate("dc", arr_len); for (size_t i = 0; i < arr_len; i++ ) { pvinput_t in; in.Ibeam = (double) p_poabeam[i]; in.Idiff = (double) p_poaskydiff[i]; in.Ignd = (double) p_poagnddiff[i]; in.Tdry = (double) p_tdry[i]; in.Wspd = (double) p_wspd[i]; in.Wdir = (double) p_wdir[i]; in.Zenith = (double) p_zen[i]; in.IncAng = (double) p_inc[i]; in.Elev = site_elevation; in.Tilt = (double) p_stilt[i]; pvoutput_t out; double opv = -1; // by default, calculate MPPT if ( opvoltage != 0 ) opv = opvoltage[i]; double tcell = in.Tdry; if (! tc( in, mod, opv, tcell ) ) throw general_error("error calculating cell temperature", (float)i); if (! mod( in, tcell, opv, out ) ) throw general_error( "error calculating module power and temperature with given parameters", (float) i); p_tcell[i] = (ssc_number_t)out.CellTemp; p_volt[i] = (ssc_number_t)out.Voltage; p_amp[i] = (ssc_number_t)out.Current; p_eff[i] = (ssc_number_t)out.Efficiency; p_dc[i] = (ssc_number_t)out.Power; } } }; DEFINE_MODULE_ENTRY( pv6parmod, "CEC 6 Parameter PV module model performance calculator. Does not include weather file reading or irradiance processing, or inverter (DC to AC) modeling.", 1 )
73.065217
280
0.484677
gjsoto
8bf637641a08b16fe882aa46ed76f6273956e075
1,374
cpp
C++
DataFormats/Math/test/crossV4_t.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DataFormats/Math/test/crossV4_t.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DataFormats/Math/test/crossV4_t.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include <iostream> #include "DataFormats/Math/interface/SSEVec.h" int main() { #ifdef CMS_USE_SSE { mathSSE::Vec4<float> yAxis(-0.0144846, 0.932024, -0.362108); mathSSE::Vec4<float> zAxis(-0.204951, 0.351689, 0.913406); auto xAxis = ::cross(yAxis, zAxis); const mathSSE::Vec4<float> correctXAxis(0.978666, 0.0874447, 0.185925); std::cout << " x axis " << xAxis << std::endl; if (abs(xAxis.o.theX - correctXAxis.o.theX) > 0.000001 or abs(xAxis.o.theY - correctXAxis.o.theY) > 0.000001 or abs(xAxis.o.theZ - correctXAxis.o.theZ) > 0.000001) { std::cout << "BAD since not same as " << correctXAxis << std::endl; return 1; } } { mathSSE::Vec4<double> yAxis(-0.0144846, 0.932024, -0.362108); mathSSE::Vec4<double> zAxis(-0.204951, 0.351689, 0.913406); auto xAxis = ::cross(yAxis, zAxis); const mathSSE::Vec4<float> correctXAxis(0.978666, 0.0874447, 0.185925); std::cout << " x axis " << xAxis << std::endl; if (abs(xAxis.o.theX - correctXAxis.o.theX) > 0.000001 or abs(xAxis.o.theY - correctXAxis.o.theY) > 0.000001 or abs(xAxis.o.theZ - correctXAxis.o.theZ) > 0.000001) { std::cout << "BAD since not same as " << correctXAxis << std::endl; return 1; } } std::cout << "arch->x86" << std::endl; #else std::cout << "arch->non-x86" << std::endl; #endif return 0; }
33.512195
115
0.617904
ckamtsikis
8bf69f8423f32cfb609cfdb6b7f59e56fe348989
324
cc
C++
leetcode/1164-missing-number-in-arithmetic-progression.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
leetcode/1164-missing-number-in-arithmetic-progression.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
leetcode/1164-missing-number-in-arithmetic-progression.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
class Solution { public: int missingNumber(vector<int>& arr) { int diff=abs(arr[arr.size()-1]-arr[0])/arr.size(); if(arr[0]>arr[1]){ diff=0-diff; } for(int i=0;i<arr.size();i++){ if(arr[i]!=arr[0]+diff*i){ return arr[0]+diff*i; } } return 0; } };
21.6
56
0.469136
Magic07
8bfc7e95107e1db49c1a3c010f370e23e3a56f3f
3,138
hpp
C++
Inc/Inner/ImplHudNode.hpp
MJYCo-Ltd/Map
48ccc120a3c2cd3080fb046da72c7588b1faebc0
[ "MIT" ]
7
2021-11-25T02:12:09.000Z
2022-03-20T12:48:18.000Z
Inc/Inner/ImplHudNode.hpp
MJYCo-Ltd/Map
48ccc120a3c2cd3080fb046da72c7588b1faebc0
[ "MIT" ]
1
2022-03-25T20:47:21.000Z
2022-03-29T02:02:44.000Z
Inc/Inner/ImplHudNode.hpp
MJYCo-Ltd/Map
48ccc120a3c2cd3080fb046da72c7588b1faebc0
[ "MIT" ]
2
2021-12-07T06:22:47.000Z
2021-12-30T05:54:04.000Z
#ifndef IMPL_HUD_NODE_H #define IMPL_HUD_NODE_H #include <osgEarth/Controls> #include <Inner/ImplSceneNode.hpp> /** * 实现IHudNode所有的接口 */ template <typename T> class ImplHudNode:public ImplSceneNode<T> { public: CONSTRUCTOR(ImplHudNode,ImplSceneNode<T>) protected: void SetControlNode(osgEarth::Controls::Control* pControl) { m_pControl = pControl; m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_BOTTOM); m_pProgramNode=pControl; } /// 位置更改 void HudPosChanged()SET_TRUE_NODE_UPDATE(m_bPosChanged) /// 状态更改 void HudTypeChanged()SET_TRUE_NODE_UPDATE(m_bTypeChanged) void FrameCall() { if(m_bPosChanged) { if(HUD_FIXED == T::m_emHudPosType) { m_pControl->setPosition(T::m_stHudPos.nX,T::m_stHudPos.nY); } m_bPosChanged = false; } if(m_bTypeChanged) { switch (T::m_emHudPosType) { case HUD_FIXED: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_NONE,osgEarth::Controls::Control::ALIGN_NONE); m_pControl->setPosition(T::m_stHudPos.nX,T::m_stHudPos.nY); break; case HUD_UP_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_CENTER,osgEarth::Controls::Control::ALIGN_TOP); break; case HUD_DOWN_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_CENTER,osgEarth::Controls::Control::ALIGN_BOTTOM); break; case HUD_UP_RIGHT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_RIGHT,osgEarth::Controls::Control::ALIGN_TOP); break; case HUD_DOWN_RIGHT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_RIGHT,osgEarth::Controls::Control::ALIGN_BOTTOM); break; case HUD_UP_LEFT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_TOP); break; case HUD_DOWN_LEFT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_BOTTOM); break; case HUD_RIGHT_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_RIGHT,osgEarth::Controls::Control::ALIGN_CENTER); break; case HUD_LEFT_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_CENTER); break; case HUD_CENTER_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_CENTER,osgEarth::Controls::Control::ALIGN_CENTER); break; } m_bTypeChanged = false; } ImplSceneNode<T>::FrameCall(); } protected: osg::observer_ptr<osgEarth::Controls::Control> m_pControl; bool m_bPosChanged{false}; bool m_bTypeChanged{false}; }; #endif // IMPL_HUD_NODE_H
35.659091
122
0.620459
MJYCo-Ltd
8bff2df37bf13bddbad8bdcf563fab3550a4754a
1,948
cpp
C++
libraries/Crypto/SHA384.cpp
rweather/arduinolibs
662329f1fd1ba57d1312253dfe81ff0e0e2ec706
[ "MIT" ]
356
2015-01-11T15:34:14.000Z
2022-03-30T13:57:24.000Z
libraries/Crypto/SHA384.cpp
rweather/arduinolibs
662329f1fd1ba57d1312253dfe81ff0e0e2ec706
[ "MIT" ]
57
2015-09-25T09:34:37.000Z
2022-01-30T19:51:50.000Z
libraries/Crypto/SHA384.cpp
rweather/arduinolibs
662329f1fd1ba57d1312253dfe81ff0e0e2ec706
[ "MIT" ]
174
2015-01-11T15:42:25.000Z
2022-03-26T21:46:08.000Z
/* * Copyright (C) 2015 Southern Storm Software, Pty Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "SHA384.h" #include "Crypto.h" #include "utility/ProgMemUtil.h" /** * \class SHA384 SHA384.h <SHA384.h> * \brief SHA-384 hash algorithm. * * Reference: http://en.wikipedia.org/wiki/SHA-2 * * \sa SHA256, SHA512, SHA3_256, BLAKE2s */ /** * \brief Constructs a SHA-384 hash object. */ SHA384::SHA384() { reset(); } size_t SHA384::hashSize() const { return 48; } void SHA384::reset() { static uint64_t const hashStart[8] PROGMEM = { 0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL, 0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL }; memcpy_P(state.h, hashStart, sizeof(hashStart)); state.chunkSize = 0; state.lengthLow = 0; state.lengthHigh = 0; }
31.419355
78
0.728439
rweather
bdd8da38d6159b982615e22b638db9b06612e392
223
cpp
C++
test/unit-tests/array_models/interface/i_array_state_subscription_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
test/unit-tests/array_models/interface/i_array_state_subscription_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
test/unit-tests/array_models/interface/i_array_state_subscription_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
#include "src/array_models/interface/i_array_state_subscription.h" #include <gtest/gtest.h> namespace pos { TEST(IArrayStateSubscription, Register_) { } TEST(IArrayStateSubscription, Unregister_) { } } // namespace pos
13.9375
66
0.780269
so931
bddb33ff331e58560b240663f7ed3c75f8e633f3
955
cpp
C++
Rubbish/ht6/ht6/6588.cpp
albarkan/school.tests
07861b884f1bc6ccf852ac60074afaeeccf40ef2
[ "Apache-2.0" ]
null
null
null
Rubbish/ht6/ht6/6588.cpp
albarkan/school.tests
07861b884f1bc6ccf852ac60074afaeeccf40ef2
[ "Apache-2.0" ]
null
null
null
Rubbish/ht6/ht6/6588.cpp
albarkan/school.tests
07861b884f1bc6ccf852ac60074afaeeccf40ef2
[ "Apache-2.0" ]
null
null
null
/* Дан целочисленный массив из 30 элементов. Элементы массива могут принимать целые значения от 0 до 10000 включительно. Опишите на естественном языке или на // одном из языков программирования алгоритм, позволяющий найти и вывести произведение двузначных элементов массива, с суммой цифр не кратной 6. Гарантируется, что в исходном массиве есть хотя бы один элемент, значение которого является двузначным числом, и при этом сумма его цифр не делится на 6. Исходные данные объявлены так, как показано ниже на примерах для некоторых языков программирования и естественного языка. */ #include <iostream> #define N 6 using namespace std; int task6588() { int i, p; p = 1; i = 0; int A[N]; for (i = 0; i < N; i++) cin >> A[i]; for ( i= 0; i < N; i++) { if(((A[i] % 10 + A[i] / 10) % 6 != 0) && A[i] >= 10 && A[i] <= 99) { p *= A[i]; } } cout << p; return 0; }
31.833333
423
0.628272
albarkan
bddcb6b4bca10f4244aea6e556ec8fd0b2b3e1da
6,687
cxx
C++
src-plugins/libs/vtkInria/Examples/CompareImageManager/CompareImageManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/libs/vtkInria/Examples/CompareImageManager/CompareImageManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/libs/vtkInria/Examples/CompareImageManager/CompareImageManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <vtkRenderingAddOn/vtkViewImage3D.h> #include <vtkRenderingAddOn/vtkViewImage2D.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkStructuredPointsReader.h> #include <vtkStructuredPoints.h> #include "vtkImageFuse.h" #include "vtkImageMapToColors.h" #include "vtkLookupTable.h" #include "vtkImageBlend.h" #include "vtkImageCheckerboard.h" #include "vtkImageClamp.h" #include "vtkImageMapToColors.h" #include "vtkLookupTableManager.h" int main (int argc, char*argv[]) { if( argc<3 ) { std::cout << "Usage: " << std::endl; std::cout << "\t" << argv[0] << " <image file 1> <image file 2>" << std::endl; std::cout << "Example: " << std::endl; std::cout << "\t" << argv[0] << " [vtkINRIA3D_DATA_DIR]/MRI.vtk vtkINRIA3D_DATA_DIR]/MRI2.vtk" << std::endl; exit (-1); } /** In this example, we illustrate the use of the vtkCompareImageManager. We first set up four vtkImageView2D/3D to display an image. */ vtkViewImage2D* view1 = vtkViewImage2D::New(); vtkViewImage2D* view2 = vtkViewImage2D::New(); vtkViewImage2D* view3 = vtkViewImage2D::New(); vtkViewImage3D* view4 = vtkViewImage3D::New(); vtkRenderWindowInteractor* iren1 = vtkRenderWindowInteractor::New(); vtkRenderWindowInteractor* iren2 = vtkRenderWindowInteractor::New(); vtkRenderWindowInteractor* iren3 = vtkRenderWindowInteractor::New(); vtkRenderWindowInteractor* iren4 = vtkRenderWindowInteractor::New(); vtkRenderWindow* rwin1 = vtkRenderWindow::New(); vtkRenderWindow* rwin2 = vtkRenderWindow::New(); vtkRenderWindow* rwin3 = vtkRenderWindow::New(); vtkRenderWindow* rwin4 = vtkRenderWindow::New(); vtkRenderer* renderer1 = vtkRenderer::New(); vtkRenderer* renderer2 = vtkRenderer::New(); vtkRenderer* renderer3 = vtkRenderer::New(); vtkRenderer* renderer4 = vtkRenderer::New(); iren1->SetRenderWindow (rwin1); iren2->SetRenderWindow (rwin2); iren3->SetRenderWindow (rwin3); iren4->SetRenderWindow (rwin4); rwin1->AddRenderer (renderer1); rwin2->AddRenderer (renderer2); rwin3->AddRenderer (renderer3); rwin4->AddRenderer (renderer4); view1->SetRenderWindow ( rwin1 ); view2->SetRenderWindow ( rwin2 ); view3->SetRenderWindow ( rwin3 ); view4->SetRenderWindow ( rwin4 ); view1->SetRenderer ( renderer1 ); view2->SetRenderer ( renderer2 ); view3->SetRenderer ( renderer3 ); view4->SetRenderer ( renderer4 ); view1->SetAboutData ("Powered by vtkINRIA3D"); view2->SetAboutData ("Powered by vtkINRIA3D"); view3->SetAboutData ("Powered by vtkINRIA3D"); view4->SetAboutData ("Powered by vtkINRIA3D"); view1->AddChild (view2); view2->AddChild (view3); view3->AddChild (view4); view4->AddChild (view1); view1->SetLeftButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION); view1->SetMiddleButtonInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view1->SetWheelInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view1->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION); view2->SetLeftButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION); view2->SetMiddleButtonInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view2->SetWheelInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view2->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION); view3->SetLeftButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION); view3->SetMiddleButtonInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view3->SetWheelInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view3->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION); view1->SetLinkZoom (true); view2->SetLinkZoom (true); view3->SetLinkZoom (true); view1->SetLinkWindowLevel (0); view2->SetLinkWindowLevel (0); view3->SetLinkWindowLevel (0); vtkStructuredPointsReader* reader1 = vtkStructuredPointsReader::New(); reader1->SetFileName (argv[1]); reader1->GetOutput()->Update(); vtkStructuredPointsReader* reader2 = vtkStructuredPointsReader::New(); reader2->SetFileName (argv[2]); reader2->GetOutput()->Update(); view1->SetImage (reader1->GetOutput()); view2->SetImage (reader2->GetOutput()); vtkLookupTable* spectrumlut = vtkLookupTableManager::GetSpectrumLookupTable(); vtkLookupTable* gelut = vtkLookupTableManager::GetGEColorLookupTable(); view2->SetLookupTable (gelut); view1->SyncReset(); vtkImageFuse* manager1 = vtkImageFuse::New(); vtkImageFuse* manager2 = vtkImageFuse::New(); manager1->UseClampOff(); manager1->UseColorMapsOn(); manager1->SetLookupTable1 (vtkLookupTable::SafeDownCast (view1->GetLookupTable())); manager1->SetLookupTable2 (vtkLookupTable::SafeDownCast (view2->GetLookupTable())); manager2->SetLookupTable1 (vtkLookupTable::SafeDownCast (view1->GetLookupTable())); manager2->SetLookupTable2 (vtkLookupTable::SafeDownCast (view2->GetLookupTable())); manager1->SetInput ( 0, reader1->GetOutput() ); manager1->SetInput ( 1, reader2->GetOutput() ); manager2->SetInput ( 0, reader1->GetOutput() ); manager2->SetInput ( 1, reader2->GetOutput() ); manager1->SetFuseMode ( vtkImageFuse::FUSEMODE_BLEND ); manager2->SetFuseMode ( vtkImageFuse::FUSEMODE_GRID ); manager1->SetBlendAlpha (0.5); manager2->SetCheckerAlpha (0.06); manager1->Update(); manager2->Update(); view3->SetImage (manager1->GetOutput()); view4->SetImage (manager2->GetOutput()); view1->SyncReset(); rwin1->Render(); rwin2->Render(); rwin3->Render(); rwin4->Render(); iren1->Start(); iren2->Start(); iren3->Start(); iren4->Start(); spectrumlut->Delete(); gelut->Delete(); manager1->Delete(); manager2->Delete(); view1->Detach(); view2->Detach(); view3->Detach(); view4->Detach(); view1->Delete(); view2->Delete(); view3->Delete(); view4->Delete(); iren1->Delete(); iren2->Delete(); iren3->Delete(); iren4->Delete(); rwin1->Delete(); rwin2->Delete(); rwin3->Delete(); rwin4->Delete(); renderer1->Delete(); renderer2->Delete(); renderer3->Delete(); renderer4->Delete(); reader1->Delete(); reader2->Delete(); return 0; }
29.073913
112
0.701959
ocommowi
bddd56037c47e9677b2602fdb4e9233b0568a832
29,999
cc
C++
TimingAnalyzer/plugins/CommonUtils.cc
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
2
2017-10-19T12:28:53.000Z
2019-05-22T14:36:05.000Z
TimingAnalyzer/plugins/CommonUtils.cc
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
null
null
null
TimingAnalyzer/plugins/CommonUtils.cc
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
6
2017-09-13T13:16:10.000Z
2019-01-28T17:39:51.000Z
#include "Timing/TimingAnalyzer/plugins/CommonUtils.hh" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" namespace oot { /////////////////////////// // Object Prep Functions // /////////////////////////// void ReadInTriggerNames(const std::string & inputPaths, std::vector<std::string> & pathNames, strBitMap & triggerBitMap) { if (Config::file_exists(inputPaths)) { std::ifstream pathStream(inputPaths.c_str(),std::ios::in); std::string path; while (pathStream >> path) { if (path != "") { pathNames.emplace_back(path); triggerBitMap[path] = false; } } } // check to make sure text file exists } void ReadInFilterNames(const std::string & inputFilters, std::vector<std::string> & filterNames, std::map<std::string,std::vector<pat::TriggerObjectStandAlone> > & triggerObjectsByFilterMap) { if (Config::file_exists(inputFilters)) { std::ifstream filterStream(inputFilters.c_str(),std::ios::in); std::string label;// instance, processName; while (filterStream >> label) { if (label != "") { filterNames.emplace_back(label); triggerObjectsByFilterMap[label].clear(); } } } // check to make sure text file exists } void PrepNeutralinos(const edm::Handle<std::vector<reco::GenParticle> > & genparticlesH, std::vector<reco::GenParticle> & neutralinos) { auto nNeutoPhGr = 0; for (const auto & genparticle : *genparticlesH) // loop over gen particles { if (nNeutoPhGr == 2) break; if (genparticle.pdgId() == 1000022 && genparticle.numberOfDaughters() == 2) { if ((genparticle.daughter(0)->pdgId() == 22 && genparticle.daughter(1)->pdgId() == 1000039) || (genparticle.daughter(1)->pdgId() == 22 && genparticle.daughter(0)->pdgId() == 1000039)) { nNeutoPhGr++; neutralinos.emplace_back(genparticle); } // end conditional over matching daughter ids } // end conditional over neutralino id } // end loop over gen particles std::sort(neutralinos.begin(),neutralinos.end(),oot::sortByPt); } void PrepVPions(const edm::Handle<std::vector<reco::GenParticle> > & genparticlesH, std::vector<reco::GenParticle> & vPions) { for (const auto & genparticle : *genparticlesH) // loop over gen particles { if (genparticle.pdgId() == 4900111 && genparticle.numberOfDaughters() == 2) { if (genparticle.daughter(0)->pdgId() == 22 && genparticle.daughter(1)->pdgId() == 22) { vPions.emplace_back(genparticle); } // end check over both gen photons } // end check over vPions } // end loop over gen particles std::sort(vPions.begin(),vPions.end(),oot::sortByPt); } void PrepToys(const edm::Handle<std::vector<reco::GenParticle> > & genparticlesH, std::vector<reco::GenParticle> & toys) { for (const auto & genparticle : *genparticlesH) // loop over gen particles { if (genparticle.pdgId() == 22) { toys.emplace_back(genparticle); } // end check over photons } // end loop over gen particles std::sort(toys.begin(),toys.end(),oot::sortByPt); } void PrepTriggerBits(edm::Handle<edm::TriggerResults> & triggerResultsH, const edm::Event & iEvent, strBitMap & triggerBitMap) { for (auto & triggerBitPair : triggerBitMap) { triggerBitPair.second = false; } const auto & triggerNames = iEvent.triggerNames(*triggerResultsH); for (auto itrig = 0U; itrig < triggerNames.size(); itrig++) { const auto & triggerName = triggerNames.triggerName(itrig); for (auto & triggerBitPair : triggerBitMap) { if (triggerName.find(triggerBitPair.first) != std::string::npos) triggerBitPair.second = triggerResultsH->accept(itrig); } // end loop over user path names } // end loop over trigger names } void PrepTriggerObjects(const edm::Handle<edm::TriggerResults> & triggerResultsH, const edm::Handle<std::vector<pat::TriggerObjectStandAlone> > & triggerObjectsH, const edm::Event & iEvent, std::map<std::string,std::vector<pat::TriggerObjectStandAlone> > & triggerObjectsByFilterMap) { // clear first for (auto & triggerObjectsByFilterPair : triggerObjectsByFilterMap) { triggerObjectsByFilterPair.second.clear(); } // store all the trigger objects needed to be checked later const auto & triggerNames = iEvent.triggerNames(*triggerResultsH); for (pat::TriggerObjectStandAlone triggerObject : *triggerObjectsH) { triggerObject.unpackPathNames(triggerNames); triggerObject.unpackFilterLabels(iEvent, *triggerResultsH); for (auto & triggerObjectsByFilterPair : triggerObjectsByFilterMap) { if (triggerObject.hasFilterLabel(triggerObjectsByFilterPair.first)) triggerObjectsByFilterPair.second.emplace_back(triggerObject); } // end loop over user filter names } // end loop over trigger objects for (auto & triggerObjectsByFilterPair : triggerObjectsByFilterMap) { std::sort(triggerObjectsByFilterPair.second.begin(),triggerObjectsByFilterPair.second.end(),oot::sortByPt); } } void PrepJets(const edm::Handle<std::vector<pat::Jet> > & jetsH, std::vector<pat::Jet> & jets, const float jetpTmin, const float jetEtamax, const int jetIDmin) { for (const auto & jet : *jetsH) { if (jet.pt() < jetpTmin) continue; if (std::abs(jet.eta()) > jetEtamax) continue; const auto jetID = oot::GetPFJetID(jet); if (jetID < jetIDmin) continue; // save the jets, and then store the ID jets.emplace_back(jet); jets.back().addUserInt(Config::JetID,jetID); std::sort(jets.begin(),jets.end(),oot::sortByPt); } } void PrepRecHits(const EcalRecHitCollection * recHitsEB, const EcalRecHitCollection * recHitsEE, uiiumap & recHitMap, const float rhEmin) { auto i = 0; for (const auto & recHit : *recHitsEB) { if (recHit.energy() > rhEmin) { recHitMap[recHit.detid().rawId()] = i++; } } for (const auto & recHit : *recHitsEE) { if (recHit.energy() > rhEmin) { recHitMap[recHit.detid().rawId()] = i++; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Photon Cross-Cleaning and MET Corrections // // // // The photon cross-cleaning is applied to remove overlapping photon objects from the two photon collections (GED and OOT). // // If photond in one collection overlaps with photons in the other collection, the one with higher pT is kept, and the other photons are dropped. // // // // Since OOT photons are not used in the computation of the MET, we have to apply the appropriate correction to the MET when an OOT photon is // // either completely unmatched or is matched to a GED photon and is higher in pT than the GED photon. // // // // Namely, we __subtract__ the 4-vector of any added OOT photons, and __add__ the 4-vector of any dropped GED photons. // // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void PrepPhotonsCorrectMET(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, std::vector<pat::Photon> & photons, pat::MET & t1pfMET, const float rho, const float dRmin, const float phpTmin, const std::string & phIDmin) { // container for which photons to keep/drop std::vector<oot::ReducedPhoton> reducedPhotons; /////////////////// // Find overlaps // /////////////////// oot::FindOverlapPhotons(gedPhotonsH,ootPhotonsH,reducedPhotons,dRmin); /////////////////////////////// // Produce merged collection // /////////////////////////////// oot::MergePhotons(gedPhotonsH,ootPhotonsH,reducedPhotons,photons,rho,phpTmin,phIDmin); ///////////////////// // Correct the MET // ///////////////////// oot::CorrectMET(gedPhotonsH,ootPhotonsH,reducedPhotons,t1pfMET); } void FindOverlapPhotons(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, std::vector<oot::ReducedPhoton> & reducedPhotons, const float dRmin) { /////////////////////////////////////////////////// // First, store all photons in single collection // /////////////////////////////////////////////////// // loop over all GED photons const auto nGED = gedPhotonsH->size(); for (auto iGED = 0U; iGED < nGED; iGED++) { reducedPhotons.emplace_back(iGED,false,false); } // loop over all OOT photons const auto nOOT = ootPhotonsH->size(); for (auto iOOT = 0U; iOOT < nOOT; iOOT++) { reducedPhotons.emplace_back(iOOT,true ,false); } /////////////////////////////////// // Second, sort the vector by pT // /////////////////////////////////// std::sort(reducedPhotons.begin(),reducedPhotons.end(), [&](const auto & i_reducedPhoton, const auto & j_reducedPhoton) { // tmps const auto i_idx = i_reducedPhoton.idx; const auto j_idx = j_reducedPhoton.idx; const auto i_isOOT = i_reducedPhoton.isOOT; const auto j_isOOT = j_reducedPhoton.isOOT; const auto & i_photon = (i_isOOT ? (*ootPhotonsH)[i_idx] : (*gedPhotonsH)[i_idx]); const auto & j_photon = (j_isOOT ? (*ootPhotonsH)[j_idx] : (*gedPhotonsH)[j_idx]); return oot::GetPhotonPt(i_photon) > oot::GetPhotonPt(j_photon); }); ////////////////////////////////////////////////////////// // Mark for removal overlaps from different collections // ////////////////////////////////////////////////////////// // loop over full merged collection const auto nPHO = reducedPhotons.size(); for (auto iPHO = 0U; iPHO < nPHO; iPHO++) { // get tmps for 1st photon const auto & i_reducedPhoton = reducedPhotons[iPHO]; const auto i_idx = i_reducedPhoton.idx; // skip if already marked for removal! if (i_reducedPhoton.toRemove) continue; // get remainder of tmps for 1st photon const auto i_isOOT = i_reducedPhoton.isOOT; const auto & i_photon = (i_isOOT ? (*ootPhotonsH)[i_idx] : (*gedPhotonsH)[i_idx]); // only check those that are lower in pT for (auto jPHO = iPHO+1; jPHO < nPHO; jPHO++) { // get tmps for 2nd photon auto & j_reducedPhoton = reducedPhotons[jPHO]; const auto j_idx = j_reducedPhoton.idx; // skip if already marked for removal! if (j_reducedPhoton.toRemove) continue; // skip if from the same collection const auto j_isOOT = j_reducedPhoton.isOOT; if (i_isOOT == j_isOOT) continue; // get 2nd photon const auto & j_photon = (j_isOOT ? (*ootPhotonsH)[j_idx] : (*gedPhotonsH)[j_idx]); // if photons overlap, mark lower pT one for removal if (reco::deltaR(i_photon,j_photon) < dRmin) { j_reducedPhoton.toRemove = true; } // end check over dR } // end loop over lower pT photons } // end loop over all photons } void MergePhotons(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, const std::vector<oot::ReducedPhoton> & reducedPhotons, std::vector<pat::Photon> & photons, const float rho, const float phpTmin, const std::string & phIDmin) { // loop over all photons, check if it passes cuts, then save it for (const auto & reducedPhoton : reducedPhotons) { // get tmps const auto idx = reducedPhoton.idx; const auto isOOT = reducedPhoton.isOOT; // get the photon const auto & photon = (isOOT ? (*ootPhotonsH)[idx] : (*gedPhotonsH)[idx]); // check to ensure it was not marked for removal! if (reducedPhoton.toRemove) continue; // cut on low pt if (oot::GetPhotonPt(photon) < phpTmin) continue; // store the GED and OOT VID std::vector<pat::Photon::IdPair> idpairs = {{Config::LooseGED,false}, {Config::MediumGED,false}, {Config::TightGED,false}, {Config::TightOOT,false}}; oot::GetGEDPhoVID(photon,idpairs); if (isOOT) oot::GetOOTPhoVID (photon,idpairs); else oot::GetOOTPhoVIDByHand(photon,idpairs,rho); // skip bad ID'ed photons if (phIDmin != Config::EmptyVID) { auto isGoodID = true; for (const auto & idpair : idpairs) { if (idpair.first.find(phIDmin) != std::string::npos) // correct for GED or OOT! { if ((isOOT && idpair.first.find("oot")) || (!isOOT && idpair.first.find("ged"))) { if (!idpair.second) isGoodID = false; break; } } } if (!isGoodID) continue; } // end check for bad ID // save it in the final vector! photons.emplace_back(photon); // and then modify it! auto & tmpphoton = photons.back(); tmpphoton.setPhotonIDs(idpairs); tmpphoton.addUserData<bool>(Config::IsOOT,isOOT); } // end loop over photons } void CorrectMET(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, const std::vector<ReducedPhoton> & reducedPhotons, pat::MET & t1pfMET) { //////////////////////////////// // Compute Correction Factors // //////////////////////////////// // inputs to MET correction auto t1pfMETpx = t1pfMET.px(); auto t1pfMETpy = t1pfMET.py(); auto t1pfMETsumEt = t1pfMET.sumEt(); // loop over all photons, correct for DROPPED GED and STORED OOT for (const auto & reducedPhoton : reducedPhotons) { // get tmps const auto idx = reducedPhoton.idx; const auto isOOT = reducedPhoton.isOOT; const auto toRemove = reducedPhoton.toRemove; // get the photon const auto & photon = (isOOT ? (*ootPhotonsH)[idx] : (*gedPhotonsH)[idx]); // apply met corrections as needed if (isOOT && !toRemove) // add the OOT photons if being stored! { // get inputs const auto pt = oot::GetPhotonPt(photon); const auto phi = photon.phi(); // set MET t1pfMETpx -= pt*std::cos(phi); t1pfMETpy -= pt*std::sin(phi); t1pfMETsumEt += oot::GetPhotonEt(photon); } else if (!isOOT && toRemove) // subtract the GED photons if being dropped! { // get inputs const auto pt = oot::GetPhotonPt(photon); const auto phi = photon.phi(); // set MET t1pfMETpx += pt*std::cos(phi); t1pfMETpy += pt*std::sin(phi); t1pfMETsumEt -= oot::GetPhotonEt(photon); } } // end loop over all photons //////////////////// // Set MET Object // //////////////////// t1pfMET.addUserFloat(Config::OOTMETPt,Config::hypo(t1pfMETpx,t1pfMETpy)); t1pfMET.addUserFloat(Config::OOTMETPhi,Config::phi(t1pfMETpx,t1pfMETpy)); t1pfMET.addUserFloat(Config::OOTMETSumEt,t1pfMETsumEt); } /////////////////////// // Pruning Functions // /////////////////////// void PrunePhotons(std::vector<pat::Photon> & photons, const EcalRecHitCollection * recHitsEB, const EcalRecHitCollection * recHitsEE, const float seedTimemin) { photons.erase(std::remove_if(photons.begin(),photons.end(), [seedTimemin,&recHitsEB,&recHitsEE](const auto & photon) { const auto & phosc = photon.superCluster().isNonnull() ? photon.superCluster() : photon.parentSuperCluster(); const auto & seedDetId = phosc->seed()->seed(); // get seed detid const auto recHits = ((seedDetId.subdetId() == EcalSubdetector::EcalBarrel) ? recHitsEB : recHitsEE); // which recHits to use const auto seedHit = recHits->find(seedDetId); // get the underlying rechit const auto seedTime = ((seedHit != recHits->end()) ? seedHit->time() : -9999.f); return (seedTime < seedTimemin); }),photons.end()); } void PruneJets(std::vector<pat::Jet> & jets, const std::vector<pat::Photon> & photons, const int nPhosmax, const float dRmin) { // clean out w.r.t. to nMaxPhos const auto nPhos = std::min<int>(photons.size(),nPhosmax); // loop over at most the leading photons and clean... for (auto ipho = 0; ipho < nPhos; ipho++) { const auto & photon = photons[ipho]; // apply loose selection on photon const auto HoverE = photon.hadTowOverEm(); const auto Sieie = photon.full5x5_sigmaIetaIeta(); const auto eta = std::abs(photon.superCluster()->eta()); // cuts set to be looser than trigger values by .05 in H/E and 0.005 in Sieie if ( ((eta < Config::etaEBcutoff) && (HoverE < 0.25) && (Sieie < 0.019)) || ((eta >= Config::etaEBcutoff && eta < Config::etaEEmax) && (HoverE < 0.2) && (Sieie < 0.04)) ) { jets.erase(std::remove_if(jets.begin(),jets.end(), [dRmin,&photon](const auto & jet) { return (reco::deltaR(jet,photon) < dRmin); }),jets.end()); } } } /////////////////////////////// // Effective Areas Functions // /////////////////////////////// float GetChargedHadronEA(const float eta) { if (eta < 1.0 ) return 0.0112; else if (eta >= 1.0 && eta < 1.479) return 0.0108; else if (eta >= 1.479 && eta < 2.0 ) return 0.0106; else if (eta >= 2.0 && eta < 2.2 ) return 0.01002; else if (eta >= 2.2 && eta < 2.3 ) return 0.0098; else if (eta >= 2.3 && eta < 2.4 ) return 0.0089; else if (eta >= 2.4 ) return 0.0087; else return 0.; } float GetNeutralHadronEA(const float eta) { if (eta < 1.0 ) return 0.0668; else if (eta >= 1.0 && eta < 1.479) return 0.1054; else if (eta >= 1.479 && eta < 2.0 ) return 0.0786; else if (eta >= 2.0 && eta < 2.2 ) return 0.0233; else if (eta >= 2.2 && eta < 2.3 ) return 0.0078; else if (eta >= 2.3 && eta < 2.4 ) return 0.0028; else if (eta >= 2.4 ) return 0.0137; else return 0.; } float GetGammaEA(const float eta) { if (eta < 1.0 ) return 0.1113; else if (eta >= 1.0 && eta < 1.479) return 0.0953; else if (eta >= 1.479 && eta < 2.0 ) return 0.0619; else if (eta >= 2.0 && eta < 2.2 ) return 0.0837; else if (eta >= 2.2 && eta < 2.3 ) return 0.1070; else if (eta >= 2.3 && eta < 2.4 ) return 0.1212; else if (eta >= 2.4 ) return 0.1466; else return 0.; } float GetEcalPFClEA(const float eta) { if (eta < 0.8 ) return 0.1324; else if (eta >= 0.8 && eta < 1.4422) return 0.08638; else return 0.f; } float GetHcalPFClEA(const float eta) { if (eta < 0.8 ) return 0.1094; else if (eta >= 0.8 && eta < 1.4422) return 0.09392; else return 0.f; } float GetTrackEA(const float eta) { if (eta < 0.8 ) return 0.02276; else if (eta >= 0.8 && eta < 1.4422) return 0.00536; else return 0.f; } ////////////////////////// // pT Scaling Functions // ////////////////////////// float GetNeutralHadronPtScale(const float eta, const float pt) { if (eta < Config::etaEBcutoff) return 0.01512*pt+0.00002259*pt*pt; else if (eta >= Config::etaEBcutoff && eta < Config::etaEEmax) return 0.0117 *pt+0.00002305*pt*pt; else return 0.f; } float GetGammaPtScale(const float eta, const float pt) { if (eta < Config::etaEBcutoff) return 0.004017*pt; else if (eta >= Config::etaEBcutoff && eta < Config::etaEEmax) return 0.0037 *pt; else return 0.f; } float GetEcalPFClPtScale(const float eta, const float pt) { if (eta < 1.4442) return 0.003008*pt; else return 0.f; } float GetHcalPFClPtScale(const float eta, const float pt) { if (eta < 1.4442) return 0.00002921*pt*pt-0.005802*pt; else return 0.f; } ////////////////////////// // Object VID Functions // ////////////////////////// void GetGEDPhoVID(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs) { idpairs[2].second = photon.photonID(Config::GEDPhotonTightVID); idpairs[1].second = photon.photonID(Config::GEDPhotonMediumVID); idpairs[0].second = photon.photonID(Config::GEDPhotonLooseVID); } void GetGEDPhoVIDByHand(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs, const float rho) { // needed for cuts const auto eta = std::abs(photon.superCluster()->eta()); const auto pt = photon.pt(); // uncorrected pt: https://twiki.cern.ch/twiki/bin/view/CMS/EgammaPostRecoRecipes#Advanced_usage_of_EgammaPostReco // cut variables const auto HoverE = photon.hadTowOverEm(); const auto Sieie = photon.full5x5_sigmaIetaIeta(); const auto ChgHadIso = std::max(photon.chargedHadronIso() - (rho * oot::GetChargedHadronEA(eta)) ,0.f); const auto NeuHadIso = std::max(photon.neutralHadronIso() - (rho * oot::GetNeutralHadronEA(eta)) - (oot::GetNeutralHadronPtScale(eta,pt)),0.f); const auto PhoIso = std::max(photon.photonIso() - (rho * oot::GetGammaEA (eta)) - (oot::GetGammaPtScale (eta,pt)),0.f); if (eta < Config::etaEBcutoff) { if ((HoverE < 0.02148) && (Sieie < 0.0096) && (ChgHadIso < 0.65) && (NeuHadIso < 0.317) && (PhoIso < 2.044)) { idpairs[2].second = true; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.02197) && (Sieie < 0.0105) && (ChgHadIso < 1.141) && (NeuHadIso < 1.189) && (PhoIso < 2.08)) { idpairs[2].second = false; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.04596) && (Sieie < 0.0106) && (ChgHadIso < 1.694) && (NeuHadIso < 24.032) && (PhoIso < 2.876)) { idpairs[2].second = false; idpairs[1].second = false; idpairs[0].second = true; } } else if (eta >= Config::etaEBcutoff && eta < Config::etaEEmax) { if ((HoverE < 0.0321) && (Sieie < 0.0271) && (ChgHadIso < 0.517) && (NeuHadIso < 2.716) && (PhoIso < 3.032)) { idpairs[2].second = true; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.0326) && (Sieie < 0.0272) && (ChgHadIso < 1.051) && (NeuHadIso < 2.718) && (PhoIso < 3.867)) { idpairs[2].second = false; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.059) && (Sieie < 0.0272) && (ChgHadIso < 2.089) && (NeuHadIso < 19.722) && (PhoIso < 4.162)) { idpairs[2].second = false; idpairs[1].second = false; idpairs[0].second = true; } } } void GetOOTPhoVID(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs) { idpairs[3].second = photon.photonID(Config::OOTPhotonTightVID); } void GetOOTPhoVIDByHand(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs, const float rho) { // needed for cuts const auto eta = std::abs(photon.superCluster()->eta()); const auto pt = photon.pt(); // cut variables const auto HoverE = photon.hadTowOverEm(); const auto Sieie = photon.full5x5_sigmaIetaIeta(); const auto EcalPFClIso = std::max(photon.ecalPFClusterIso() - (rho * oot::GetEcalPFClEA(eta)) - (oot::GetEcalPFClPtScale(eta,pt)),0.f); const auto HcalPFClIso = std::max(photon.hcalPFClusterIso() - (rho * oot::GetHcalPFClEA(eta)) - (oot::GetHcalPFClPtScale(eta,pt)),0.f); const auto TrkIso = std::max(photon.trackIso() - (rho * oot::GetTrackEA (eta)) ,0.f); if ((HoverE < 0.02148) && (Sieie < 0.014) && (EcalPFClIso < 5.f) && (HcalPFClIso < 4.f) && (TrkIso < 4.f)) { idpairs[3].second = true; } } int GetPFJetID(const pat::Jet & jet) // https://twiki.cern.ch/twiki/bin/view/CMS/JetID13TeVRun2017 { const auto eta = std::abs(jet.eta()); const auto NHF = jet.neutralHadronEnergyFraction(); const auto NEMF = jet.neutralEmEnergyFraction(); const auto CHF = jet.chargedHadronEnergyFraction(); const auto CEMF = jet.chargedEmEnergyFraction(); const auto NHM = jet.neutralMultiplicity(); const auto CHM = jet.chargedMultiplicity(); const auto SHM = jet.chargedMultiplicity()+jet.neutralMultiplicity(); const auto MUF = jet.muonEnergyFraction(); // 2 == TightLepVeto // 1 == Tight if (eta <= 2.4) { if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1) && (MUF < 0.80) && (CHF > 0) && (CHM > 0) && (CEMF < 0.80)) return 2; else if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1) && (CHF > 0) && (CHM > 0)) return 1; else return 0; } else if (eta > 2.4 && eta <= 2.7) { if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1) && (MUF < 0.80)) return 2; else if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1)) return 1; else return 0; } else if (eta > 2.7 && eta <= 3.0) { if ((NEMF > 0.02) && (NEMF < 0.99) && (NHM > 2)) return 1; else return 0; } else { if ((NEMF < 0.90) && (NHF > 0.02) && (NHM > 10)) return 1; else return 0; } return -1; // should not happen } /////////////////////// // Storing Functions // /////////////////////// void SplitPhotons(std::vector<pat::Photon> & photons, const int nmax) { std::vector<int> gedphos; std::vector<int> ootphos; auto ipho = 0; for (const auto & photon : photons) { (!*(photon.userData<bool>(Config::IsOOT)) ? gedphos : ootphos).emplace_back(ipho++); } std::vector<pat::Photon> tmpphotons; const int ngedphos = gedphos.size(); for (auto i = 0; i < nmax; i++) { if (ngedphos > i) tmpphotons.emplace_back(photons[gedphos[i]]); } const int nootphos = ootphos.size(); for (auto i = 0; i < nmax; i++) { if (nootphos > i) tmpphotons.emplace_back(photons[ootphos[i]]); } photons.swap(tmpphotons); } void StoreOnlyPho(std::vector<pat::Photon> & photons, const int nmax, const bool isOOT) { std::vector<pat::Photon> tmpphotons; auto ipho = 0; for (const auto & photon : photons) { if (ipho >= nmax) break; ipho++; if (*(photon.userData<bool>(Config::IsOOT)) == isOOT) tmpphotons.emplace_back(photon); } photons.swap(tmpphotons); } ///////////////////// // Debug Functions // ///////////////////// void DumpPhoton(const pat::Photon & photon, const bool isOOT, const EcalRecHitCollection * recHitsEB, const EcalRecHitCollection * recHitsEE) { std::cout << (isOOT ? "OOT" : "GED") << " Photon Info -->" << " pT: " << std::setprecision(3) << oot::GetPhotonPt(photon) << " phi: " << std::setprecision(3) << photon.phi() << " eta: " << std::setprecision(3) << photon.eta() << std::endl; const auto & phosc = photon.superCluster().isNonnull() ? photon.superCluster() : photon.parentSuperCluster(); const auto & seedDetId = phosc->seed()->seed(); // get seed detid const auto isEB = (seedDetId.subdetId() == EcalSubdetector::EcalBarrel); std::cout << " isEB: " << isEB << " seedId: " << seedDetId.rawId() << std::endl; const auto recHits = (isEB ? recHitsEB : recHitsEE); // get rechits const auto & hitsAndFractions = phosc->hitsAndFractions(); // get vector of detids // loop over all rec hits in SC for (auto hafitr = hitsAndFractions.begin(); hafitr != hitsAndFractions.end(); ++hafitr) { const auto & recHitDetId = hafitr->first; // get detid of crystal const auto & recHit = recHits->find(recHitDetId); const auto recHitId = recHitDetId.rawId(); // standard check if (recHit != recHits->end()) { if (recHit->energy() < 1) continue; std::cout << " rhId: " << recHitId; if (isEB) { const EBDetId recHitEB(recHitId); std::cout << " ieta: " << recHitEB.ieta() << " iphi: " << recHitEB.iphi(); } else { const EEDetId recHitEE(recHitId); std::cout << " ix: " << recHitEE.ix() << " iy: " << recHitEE.iy(); } std::cout << " isOOT: " << recHit->checkFlag(EcalRecHit::kOutOfTime) << " energy: " << std::setprecision(3) << recHit->energy() << " time: " << std::setprecision(3) << recHit->time() << std::endl; } } // end loop over hits and fractions } };
37.173482
176
0.560985
kmcdermo
bdde2152b74138579d8da71f7595eb4d4ae8c05c
527
hpp
C++
include/mgcpp/expressions/placeholder.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
48
2018-01-02T03:47:18.000Z
2021-09-09T05:55:45.000Z
include/mgcpp/expressions/placeholder.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
24
2017-12-27T18:03:13.000Z
2018-07-02T09:00:30.000Z
include/mgcpp/expressions/placeholder.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
6
2018-01-14T14:06:10.000Z
2018-10-16T08:43:01.000Z
#ifndef PLACEHOLDER_HPP #define PLACEHOLDER_HPP #include <mgcpp/expressions/forward.hpp> namespace mgcpp { struct placeholder_node_type; template <size_t PlaceholderID, typename ResultType> using placeholder_node = generic_expr<placeholder_node_type, PlaceholderID, ResultType::template result_expr_type, ResultType, 0>; } // namespace mgcpp #endif // PLACEHOLDER_HPP
27.736842
76
0.582543
MGfoundation
bddfc32b9fb917c116a4db07b56e45c23dd2481f
1,622
hpp
C++
rsked/inetcheck.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
rsked/inetcheck.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
rsked/inetcheck.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
1
2020-10-04T22:14:55.000Z
2020-10-04T22:14:55.000Z
#pragma once /// You may optionally configure this in rsked.json like: /// { ... /// "Inet_checker" : { /// "enabled" : true, /// "status_path" : "/run/user/1000/netstat", /// "refresh" : 60 /// }, ... /// /// Without configuration, it will be enabled with reasonable defaults. /// /* Part of the rsked package. * Copyright 2020 Steven A. Harp farlies(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/filesystem.hpp> class Config; class Inet_checker { private: bool m_enabled {true}; boost::filesystem::path m_status_path; time_t m_last_check {0}; bool m_last_status {true}; time_t m_refresh_secs {60}; bool get_current_status(); public: time_t refresh_secs() const { return m_refresh_secs; } void set_refresh_secs(time_t); time_t last_check_time() const { return m_last_check; } boost::filesystem::path status_path() const { return m_status_path; } void configure( Config& ); bool enabled() const { return m_enabled; } bool inet_ready(); // Inet_checker(); };
30.037037
77
0.673243
farlies
bde11ce8b7ac613af0e4ce53a540b02c23a7f684
604
hpp
C++
third_party/boost/simd/arch/common/detail/scalar/exponential.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/arch/common/detail/scalar/exponential.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/common/detail/scalar/exponential.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_EXPONENTIAL_HPP_INCLUDED #define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_EXPONENTIAL_HPP_INCLUDED #include <boost/simd/arch/common/detail/scalar/expo_base.hpp> #endif
33.555556
100
0.541391
SylvainCorlay
bde11d680c6a77f55fe61b2aa3ffaef6d459c452
1,026
cpp
C++
L-Value_vs_R-Value.cpp
WarlonZeng/Data-Structures-Algorithms
87df91ec7f8867d9affbd713b12a86f39ba4a7b1
[ "MIT" ]
1
2016-09-07T04:31:48.000Z
2016-09-07T04:31:48.000Z
L-Value_vs_R-Value.cpp
WarlonZeng/Data-Structures-Algorithms
87df91ec7f8867d9affbd713b12a86f39ba4a7b1
[ "MIT" ]
null
null
null
L-Value_vs_R-Value.cpp
WarlonZeng/Data-Structures-Algorithms
87df91ec7f8867d9affbd713b12a86f39ba4a7b1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; template <class Something> void testMe(Something& val) { cout << "This is an lval!\n"; } template <class Something> void testMe(const Something&& val) { cout << "This is an rval!\n"; } int& dummyRef(int& thing) { return thing; } int dummy(int& thing) { return thing; } string dummyString() { return "test"; } int main() { // Which 'testMe' do you expect to be called? // Make a guess before you run the code! cout << "For ints:\n"; int blah = 5; testMe(blah); testMe(5); cout << "\nFor chars:\n"; char thing = 'a'; testMe(thing); testMe('a'); cout << "\nFor addresses/pointers:\n"; int* point = &blah; testMe(point); testMe(&blah); cout << "\nFor return type:\n"; testMe(dummyRef(blah)); testMe(dummy(blah)); cout << "\nFor strings:\n"; string test = "hello"; testMe(test); // These are tricky, for reasons that aren't immediately obvious: testMe("hello"); testMe((string)"hello"); testMe(test + "hello"); testMe(dummyString()); cin.get(); }
17.389831
66
0.6423
WarlonZeng
bde24956c5faa172c8cdfd4cba1977b538e2f62f
5,687
hpp
C++
include/cynodelic/metaflags/detail/string_parsing_helper.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
include/cynodelic/metaflags/detail/string_parsing_helper.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
include/cynodelic/metaflags/detail/string_parsing_helper.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #ifndef CYNODELIC_METAFLAGS_DETAIL_STRING_PARSING_HELPER_HPP #define CYNODELIC_METAFLAGS_DETAIL_STRING_PARSING_HELPER_HPP #include <cstdlib> #include <cstddef> #include <cstdint> #include <string> #include <stdexcept> #include <limits> #include <cynodelic/mulinum/if.hpp> #include <cynodelic/mulinum/integer_c.hpp> #include <cynodelic/mulinum/equals.hpp> #include <cynodelic/mulinum/logical_or.hpp> #include <cynodelic/metaflags/config.hpp> #include <cynodelic/metaflags/flag_arguments.hpp> namespace cynodelic { namespace metaflags { namespace detail { /** * @brief Tag selector for `string_parsing_helper` */ template <typename FlagArg> using select_sp_tag = mulinum::if_< mulinum::equals<typename FlagArg::value_type,std::int64_t>::value, mulinum::int_c<1>, mulinum::if_< mulinum::logical_or< mulinum::equals<typename FlagArg::value_type,std::int8_t>, mulinum::equals<typename FlagArg::value_type,std::int16_t>, mulinum::equals<typename FlagArg::value_type,std::int32_t> >::value, mulinum::int_c<2>, mulinum::if_< mulinum::equals<typename FlagArg::value_type,std::uint64_t>::value, mulinum::int_c<3>, mulinum::if_< mulinum::logical_or< mulinum::equals<typename FlagArg::value_type,std::uint8_t>, mulinum::equals<typename FlagArg::value_type,std::uint16_t>, mulinum::equals<typename FlagArg::value_type,std::uint32_t> >::value, mulinum::int_c<4>, mulinum::int_c<0> > > > >; /** * @brief Undefined */ template <typename,typename> struct string_parsing_helper_impl; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<1>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { return static_cast<typename FlagArg<Chars...>::value_type>(std::stoll(x)); } }; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<2>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { using val_type_ = typename FlagArg<Chars...>::value_type; long res = std::stol(x); if (res < static_cast<long>(std::numeric_limits<val_type_>::min()) || res > static_cast<long>(std::numeric_limits<val_type_>::max())) { throw std::out_of_range("[cynodelic::metaflags::detail::string_parsing_helper_impl<...,cynodelic::mulinum::int_c<2>>::call()] The parsed value is outside the range for the specified argument type."); } else { return static_cast<val_type_>(res); } } }; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<3>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { return static_cast<typename FlagArg<Chars...>::value_type>(std::stoull(x)); } }; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<4>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { using val_type_ = typename FlagArg<Chars...>::value_type; unsigned long res = std::stoul(x); if (res < static_cast<unsigned long>(std::numeric_limits<val_type_>::min()) || res > static_cast<unsigned long>(std::numeric_limits<val_type_>::max())) { throw std::out_of_range("[cynodelic::metaflags::detail::string_parsing_helper_impl<...,cynodelic::mulinum::int_c<4>>::call()] The parsed value is outside the range for the specified argument type."); } else { return static_cast<typename FlagArg<Chars...>::value_type>(res); } } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<flt_arg<Chars...>,mulinum::int_c<0>> { static inline typename flt_arg<Chars...>::value_type call(const std::string& x) { return std::stof(x); } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<dbl_arg<Chars...>,mulinum::int_c<0>> { static inline typename dbl_arg<Chars...>::value_type call(const std::string& x) { return std::stod(x); } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<bln_arg<Chars...>,mulinum::int_c<0>> { static inline typename bln_arg<Chars...>::value_type call(const std::string& x) { if (x == "1" || x == "true") return true; else if (x == "0" || x == "false") return false; else throw std::invalid_argument("Not a valid boolean argument"); } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<str_arg<Chars...>,mulinum::int_c<0>> { static inline typename str_arg<Chars...>::value_type call(const std::string& x) { return x; } }; /** * @brief Helper type for string parsing */ template <typename FlagArg> using string_parsing_helper = string_parsing_helper_impl<FlagArg,select_sp_tag<FlagArg>>; } // end of "detail" namespace }} // end of "cynodelic::metaflags" namespace #endif // CYNODELIC_METAFLAGS_DETAIL_STRING_PARSING_HELPER_HPP
27.080952
203
0.697204
cynodelic
bde28cbdddddd64c2e0c9ccc289e5c8dd12c653b
197
c++
C++
Jcoord.c++
SRTCpp/Code
67c311566cee7b3e5cd8440ac2f7531f1737e293
[ "Apache-2.0" ]
1
2018-09-24T21:58:03.000Z
2018-09-24T21:58:03.000Z
Jcoord.c++
SRTCpp/Code
67c311566cee7b3e5cd8440ac2f7531f1737e293
[ "Apache-2.0" ]
null
null
null
Jcoord.c++
SRTCpp/Code
67c311566cee7b3e5cd8440ac2f7531f1737e293
[ "Apache-2.0" ]
null
null
null
#include "Jcoord.h" coord::coord() { x=0; y=0; z=0; } coord::coord(int a, int b, int c) { x=a; y=b; z=c; } int& coord::A() { if (a==X) return x; if (a==Y) return y; if (a==Z) return z; }
10.368421
33
0.507614
SRTCpp
bde72c91c21ae01c7ea1dc19aa70757e68f5aa59
126
cpp
C++
Phoebe-core/src/ph/app/Settings.cpp
JRBonilla/Slate
9bcb3befced30d8f9ffb2dcce0a0209ba76093e4
[ "MIT" ]
1
2017-02-26T23:37:37.000Z
2017-02-26T23:37:37.000Z
Phoebe-core/src/ph/app/Settings.cpp
JRBonilla/Slate
9bcb3befced30d8f9ffb2dcce0a0209ba76093e4
[ "MIT" ]
null
null
null
Phoebe-core/src/ph/app/Settings.cpp
JRBonilla/Slate
9bcb3befced30d8f9ffb2dcce0a0209ba76093e4
[ "MIT" ]
null
null
null
#include "Settings.h" namespace ph { Settings::Settings() { } void Settings::Load() { } void Settings::Save() { } }
9
24
0.595238
JRBonilla
bdef93891bfc25d82a7ea8e684f766fdaaf1f01b
1,230
cpp
C++
src/main/java/Subsystems/Lift/LiftStringPot.cpp
frc4646/2018-competition-code
6fd8288c1789849ab3054de6186f2040161588a8
[ "MIT" ]
1
2018-01-31T20:23:38.000Z
2018-01-31T20:23:38.000Z
src/main/java/Subsystems/Lift/LiftStringPot.cpp
frc4646/2018-competition-code
6fd8288c1789849ab3054de6186f2040161588a8
[ "MIT" ]
null
null
null
src/main/java/Subsystems/Lift/LiftStringPot.cpp
frc4646/2018-competition-code
6fd8288c1789849ab3054de6186f2040161588a8
[ "MIT" ]
null
null
null
#include "LiftStringPot.h" #include <RobotMap.h> #include <Config.h> LiftStringPot::LiftStringPot(int pin) : Subsystem("LiftStringPot"), LiftStringPotPin(pin) { //LiftStringPotPin = new AnalogInput(pin); } void LiftStringPot::InitDefaultCommand() {} double LiftStringPot::GetHeight() { #ifdef PRACTICE_BOT double height; double m; double b; double value = LiftStringPotPin.GetVoltage(); // @suppress("Invalid arguments") m = (MinHeight - MaxHeight) / (double)(MinValue - MaxValue); b = MinHeight - ((MinValue)*(m)); height = ((m)*(value)) + b; return height; #else return LiftStringPotPin.GetVoltage(); /* double height; double m; double b; double value = LiftStringPotPin.GetVoltage(); // @suppress("Invalid arguments") m = (MinHeight - MaxHeight) / (double)(MinValue - MaxValue); b = MinHeight - ((MinValue)*(m)); height = ((m)*(value)) + b; return height; */ #endif } double LiftStringPot::GetMaxHeight() { #ifdef PRACTICE_BOT return MaxHeight; #else return MaxValue; //return MaxHeight; #endif } double LiftStringPot::GetMinHeight() { #ifdef PRACTICE_BOT return MinHeight; #else return MinValue; //return MinHeight; #endif } double LiftStringPot::GetSwitchHeight() { return SwitchValue; }
20.163934
91
0.711382
frc4646
bdefb7a6a45c426b85062b43b3fc490da76dcaca
1,576
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgWidget/StyleInterface.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgWidget/StyleInterface.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgWidget/StyleInterface.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osgWidget/StyleInterface> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_VALUE_REFLECTOR(osgWidget::StyleInterface) I_DeclaringFile("osgWidget/StyleInterface"); I_Constructor0(____StyleInterface, "", ""); I_Constructor1(IN, const osgWidget::StyleInterface &, si, Properties::NON_EXPLICIT, ____StyleInterface__C5_StyleInterface_R1, "", ""); I_Method1(void, setStyle, IN, const std::string &, style, Properties::NON_VIRTUAL, __void__setStyle__C5_std_string_R1, "", ""); I_Method0(std::string &, getStyle, Properties::NON_VIRTUAL, __std_string_R1__getStyle, "", ""); I_Method0(const std::string &, getStyle, Properties::NON_VIRTUAL, __C5_std_string_R1__getStyle, "", ""); I_SimpleProperty(const std::string &, Style, __C5_std_string_R1__getStyle, __void__setStyle__C5_std_string_R1); END_REFLECTOR
29.735849
78
0.574873
UM-ARM-Lab
bdf137723168827fdd28582d70cf8bb08743ef79
5,425
cpp
C++
pyspk/src/pyspk_GL/OpenGL/GLLineTrailRenderer.cpp
chromia/pyspk
b13f2b4f3c651376747003761ea88590a6014eda
[ "Zlib" ]
null
null
null
pyspk/src/pyspk_GL/OpenGL/GLLineTrailRenderer.cpp
chromia/pyspk
b13f2b4f3c651376747003761ea88590a6014eda
[ "Zlib" ]
null
null
null
pyspk/src/pyspk_GL/OpenGL/GLLineTrailRenderer.cpp
chromia/pyspk
b13f2b4f3c651376747003761ea88590a6014eda
[ "Zlib" ]
null
null
null
// generate by pypp <https://github.com/mugwort-rc/pypp> // original source code: SPK_GLLineTrailRenderer.h #include <RenderingAPIs/OpenGL/SPK_GLLineTrailRenderer.h> #include <Core/SPK_Group.h> #include <boost/python.hpp> class GLLineTrailRendererWrapper : public SPK::GL::GLLineTrailRenderer, public boost::python::wrapper<SPK::GL::GLLineTrailRenderer> { public: using SPK::GL::GLLineTrailRenderer::GLLineTrailRenderer; std::string getClassName () const { if ( auto getClassName = this->get_override("getClassName") ) { return getClassName(); } else { return GLLineTrailRenderer::getClassName(); } } void enableBlending (bool blendingEnabled) { if ( auto enableBlending = this->get_override("enableBlending") ) { enableBlending(blendingEnabled); } else { GLLineTrailRenderer::enableBlending(blendingEnabled); } } void createBuffers (const SPK::Group & group) { if ( auto createBuffers = this->get_override("createBuffers") ) { createBuffers(group); } else { GLLineTrailRenderer::createBuffers(group); } } void destroyBuffers (const SPK::Group & group) { if ( auto destroyBuffers = this->get_override("destroyBuffers") ) { destroyBuffers(group); } else { GLLineTrailRenderer::destroyBuffers(group); } } void render (const SPK::Group & group) { if ( auto render = this->get_override("render") ) { render(group); } else { GLLineTrailRenderer::render(group); } } bool checkBuffers (const SPK::Group & group) { if ( auto checkBuffers = this->get_override("_checkBuffers") ) { return checkBuffers(group); } else { return GLLineTrailRenderer::checkBuffers(group); } } }; void init_SPK_GLLineTrailRenderer_h() { void (SPK::GL::GLLineTrailRenderer::*init0)(const SPK::Group&) = &SPK::GL::GLLineTrailRenderer::init; boost::python::class_<GLLineTrailRendererWrapper, boost::python::bases<SPK::GL::GLRenderer>, std::shared_ptr<SPK::GL::GLLineTrailRenderer>>("GLLineTrailRenderer", ":brief: Default constructor of GLLineTrailRenderer") .def("getClassName", &SPK::GL::GLLineTrailRenderer::getClassName) .def("create", &SPK::GL::GLLineTrailRenderer::create, ":brief: Creates and registers a new GLLineTrailRenderer\n" ":return: A new registered GLLineTrailRenderer\n" ":since: 1.04.00\n", boost::python::return_value_policy<boost::python::reference_existing_object>()) .def("setNbSamples", &SPK::GL::GLLineTrailRenderer::setNbSamples, ":brief: Sets the number of samples in a trail\n" "\n" "The number of samples defines the number of points used to construct the trail.\n" "The bigger the number of samples, the smoother the trail but the bigger the compution time and the memory consumption.\n" "\n" ":param nbSamples: the number of samples to construct the trails\n") .def("setWidth", &SPK::GL::GLLineTrailRenderer::setWidth, ":brief: Sets the width of a trail\n" "\n" "Like for GLLineRenderer, the width is defined in pixels and is not dependant of the distance of the trail from the camera\n" "\n" ":param width: the width of trails in pixels\n") .def("setDuration", &SPK::GL::GLLineTrailRenderer::setDuration, ":brief: Sets the duration of a sample\n" "\n" "The duration of a sample is defined by its life time from its creation to its destruction.\n" "Note that the alpha of a sample will decrease linearly from its initial alpha to 0.\n" "\n" ":param duration: the duration of a sample\n") .def("setDegeneratedLines", &SPK::GL::GLLineTrailRenderer::setDegeneratedLines, ":brief: Sets the color components of degenerated lines\n" ":param r: the red component\n" ":param g: the green component\n" ":param b: the blue component\n" ":param a: the alpha component\n") .def("enableBlending", &SPK::GL::GLLineTrailRenderer::enableBlending) .def("getNbSamples", &SPK::GL::GLLineTrailRenderer::getNbSamples, ":brief: Gets the number of samples per trail\n" ":return: the number of samples per trail\n") .def("getWidth", &SPK::GL::GLLineTrailRenderer::getWidth, ":brief: Gets the width of a trail\n" ":return: the width of a trail (in pixels)\n") .def("getDuration", &SPK::GL::GLLineTrailRenderer::getDuration, ":brief: Gets the duration of a sample\n" ":return: the duration of a sample\n") .def("createBuffers", &SPK::GL::GLLineTrailRenderer::createBuffers) .def("destroyBuffers", &SPK::GL::GLLineTrailRenderer::destroyBuffers) .def("init", init0, ":brief: Inits all the trails of the particle of the group\n" "\n" "All the samples are set to the current position of the particle.\n" "The trail of each particle has therefore a length of 0 and is ready for update.\n" "This function allows to clear the buffers for GLLineTrailRenderer of the given group.\n" "\n" ":param group: the Group whose buffers need to be initialized\n") .def("render", &SPK::GL::GLLineTrailRenderer::render) .staticmethod("create") ; }
44.467213
167
0.65235
chromia
bdf1f361639e5dc85e7bd8746cb23b34c63be69f
2,675
cpp
C++
Photon/Plugins/PhilipsHue/src/HueLight.cpp
rlisle/ProjectIoT
abdb7efa36657fcd942626975d2156ef5d02c8bc
[ "MIT" ]
null
null
null
Photon/Plugins/PhilipsHue/src/HueLight.cpp
rlisle/ProjectIoT
abdb7efa36657fcd942626975d2156ef5d02c8bc
[ "MIT" ]
null
null
null
Photon/Plugins/PhilipsHue/src/HueLight.cpp
rlisle/ProjectIoT
abdb7efa36657fcd942626975d2156ef5d02c8bc
[ "MIT" ]
null
null
null
/****************************************************************** HueLight plugin Features: - Control Philips Hue light. http://www.github.com/rlisle/Patriot Example code used from https://www.digikey.com/en/maker/blogs/2019/how-to-post-data-using-the-particle-photon Written by Ron Lisle BSD license, check license.txt for more information. All text above must be included in any redistribution. ******************************************************************/ #include "HueLight.h" #include "IoT.h" /** * Constructor * @param name String name of the checklist item */ HueLight::HueLight(String name, String room, String hueId, byte *server, String userid) : Device(name, room) { _hueId = hueId; memcpy(_server, server, 4); _userID = userid; _value = 0; _type = 'L'; } void HueLight::begin() { if(_tcpClient.connect(_server,80)) { Log("HueLight "+_name+" connected"); _tcpClient.stop(); } else { Log("HueLight "+_name+" failed to connect!"); } } /** * loop() * This is called repeatedly to allow device to do its work. */ void HueLight::loop() { //May want to implement fading? } /** * Set value * @param value Int 0 to 100 */ void HueLight::setValue(int value) { Log.info("HueLight " + _name + " setValue: " + String(value)); if(_value == value) { Log.info("HueLight value already set, but writing again!"); } _value = value; writeToHue(); } // Private Helper Methods // Using the HUE API, we'll set on/off and bri // Much more is possible through the API. void HueLight::writeToHue() { //TODO: lookup ID from name if(_tcpClient.connect(_server,80)) { String json; if(_value == 0) { json = "{\"on\":false}"; } else { // Convert 0-100% to 0-254 int newValue = (_value * 254) / 100; if(newValue > 254) newValue = 254; json = "{\"on\":true, \"bri\": " + String(newValue) + "}"; } Log.info("Hue json = " + json); _tcpClient.print("PUT /api/"); _tcpClient.print(_userID); _tcpClient.print("/lights/"); _tcpClient.print(_hueId); _tcpClient.println("/state HTTP/1.0"); _tcpClient.print("Content-Length: "); _tcpClient.println(json.length()); _tcpClient.println(); _tcpClient.println(json); } else { Log("HueLight "+_name+" not connected"); } } /** * notify() * Publish switch state */ void HueLight::notify() { String topic = "patriot/" + _name; String message = String(_value); IoT::mqttPublish(topic,message); }
23.883929
109
0.565607
rlisle
bdf71b4724a3c469b097fd77df4739bb67b89d75
482
cpp
C++
Arrays/169. Majority Element/Solution-sorting.cpp
VarunSAthreya/LeetCode-Solutions
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
[ "MIT" ]
1
2021-11-24T16:20:32.000Z
2021-11-24T16:20:32.000Z
Arrays/169. Majority Element/Solution-sorting.cpp
VarunSAthreya/LeetCode-Solutions
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
[ "MIT" ]
null
null
null
Arrays/169. Majority Element/Solution-sorting.cpp
VarunSAthreya/LeetCode-Solutions
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
[ "MIT" ]
3
2021-09-03T15:14:12.000Z
2022-03-07T04:04:32.000Z
class Solution { public: int majorityElement(vector<int> &nums) { sort(nums.begin(), nums.end()); int ele = nums[0], count = 0; for (auto i : nums) { if (i == ele) { count++; if (count > (nums.size() / 2)) return i; } else { count = 1; ele = i; } } return -1; } };
18.538462
46
0.319502
VarunSAthreya
bdfa451f5aa3b83e21d923b2c5a222cb3a852e1e
2,371
cpp
C++
Source/Engine/src/util/CommandLine.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
null
null
null
Source/Engine/src/util/CommandLine.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
null
null
null
Source/Engine/src/util/CommandLine.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
1
2021-10-30T20:43:01.000Z
2021-10-30T20:43:01.000Z
/* * cmdline.cpp * Command Line */ #include <algorithm> #include <Util/CommandLine.hpp> #ifdef WINDOWS #include <Windows.h> #include <io.h> #include <fcntl.h> #endif namespace Util { CommandLine::CommandLine(int argc, char* argv[]) : flags() { for(int i = 1; i < argc; ++i) { // Parse arguments starting with '--' as a flag std::string value = argv[i]; if (value.find_first_of("--") == std::string::npos) continue; // Parse argument if there is one std::string argument = ""; if (i + 1 < argc) { std::string tmp = argv[i + 1]; if (tmp.find_first_of("--") == std::string::npos) { argument = tmp; argument.erase(remove(argument.begin(), argument.end(), '"'), argument.end()); ++i; } } flags[value.substr(2)] = argument; } } bool CommandLine::RedirectIOToConsole() { #ifdef WINDOWS // Allocate a console for this app if (!AllocConsole()) return false; // Redirect unbuffered STDOUT to the console HANDLE lStdHandle = GetStdHandle(STD_OUTPUT_HANDLE); int hConHandle = _open_osfhandle(reinterpret_cast<intptr_t>(lStdHandle), _O_TEXT); FILE* fp = _fdopen(hConHandle, "w"); if (fp == NULL) return false; *stdout = *fp; setvbuf(stdout, NULL, _IONBF, 0); // Redirect unbuffered STDIN to the console lStdHandle = GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(reinterpret_cast<intptr_t>(lStdHandle), _O_TEXT); fp = _fdopen(hConHandle, "r"); if (fp == NULL) return false; *stdin = *fp; setvbuf(stdin, NULL, _IONBF, 0); // Redirect unbuffered STDERR to the console lStdHandle = GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(reinterpret_cast<intptr_t>(lStdHandle), _O_TEXT); fp = _fdopen(hConHandle, "w"); if (fp == NULL) return false; *stderr = *fp; setvbuf(stderr, NULL, _IONBF, 0); /* * Make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog * point to console as well. */ return std::ios::sync_with_stdio(); #else return true; #endif } std::string CommandLine::GetFlagArgument(const std::string& value) const { for(auto& flag : flags) { if (flag.first == value) return flag.second; } return ""; } bool CommandLine::IsFlagSet(const std::string& value) const { for(auto& flag : flags) { if (flag.first == value) return true; } return false; } }
20.982301
84
0.645719
DatZach
bdfc91c31dd3374b65f1939a4bae784cab8236ff
916
cpp
C++
_includes/leet755/leet755.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet755/leet755.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet755/leet755.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
class Solution { public: vector<int> pourWater(vector<int>& heights, int count, int pos) { int n = (int)heights.size(); for (int k = 0; k < count; k++) { // drop to x int minIndex = pos, minHeight = heights[pos]; int i = pos; while (i - 1 >= 0 && heights[i] >= heights[i - 1]) { if (heights[i] > heights[i - 1]) { minIndex = i - 1; minHeight = heights[i - 1]; } i --; } if (minIndex < pos) { heights[minIndex] ++; continue; } i = pos; while (i + 1 < n && heights[i] >= heights[i + 1]) { if (heights[i] > heights[i + 1]) { minIndex = i + 1; minHeight = heights[i + 1]; } i ++; } heights[minIndex] ++; } return heights; } };
26.941176
69
0.394105
mingdaz
bdfce103ac76a7718ceeac654f2a674bb924bd68
12,678
cc
C++
crypto/openssl/bignum.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
crypto/openssl/bignum.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
10
2022-02-27T18:52:11.000Z
2022-03-21T14:11:35.000Z
crypto/openssl/bignum.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, Stable Cloud Computing, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <crypto/bignum.h> #include <sstream> #include <openssl/bn.h> #include <openssl/err.h> #include <cctype> #include <crypto/random.h> struct BignumCtx { BIGNUM* m_bn; BN_CTX* m_ctx; BignumCtx() : m_ctx{nullptr} { m_bn = BN_new(); if (!m_bn) { auto e = ERR_get_error(); std::stringstream s; s << "BN_new: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } ~BignumCtx() { BN_free(m_bn); if (m_ctx) { BN_CTX_free(m_ctx); } } BIGNUM* bn() const { return m_bn; } BN_CTX* ctx() { if (!m_ctx) { m_ctx = BN_CTX_new(); if (!m_ctx) { auto e = ERR_get_error(); std::stringstream s; s << "BN_CTX_new: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } return m_ctx; } }; using namespace scc::crypto; Bignum exp(const Bignum& a, const Bignum& b) { scc::crypto::Bignum r(a); r.exp(b); return r; } Bignum exp(const Bignum& a, uint32_t b) { scc::crypto::Bignum r(a); r.exp(b); return r; } Bignum gcd(const Bignum& a, const Bignum& b) { Bignum r(a); r.gcd(b); return r; } Bignum gcd(const Bignum& a, uint32_t b) { Bignum r(a), bn(b); r.gcd(bn); return r; } std::ostream& operator <<(std::ostream& os, const scc::crypto::Bignum& sa) { std::string s; if (os.flags() & std::ios_base::hex) { s = sa.str(true); } else { s = sa.str(); } return os.write(s.c_str(), s.size()); } void scc::crypto::PrintTo(const scc::crypto::Bignum& bn, std::ostream* os) { *os << bn; } Bignum::Bignum() : m_bnctx(new BignumCtx()) { } Bignum::~Bignum() { } void* Bignum::bn() { return reinterpret_cast<void*>(m_bnctx->bn()); } const void* Bignum::const_bn() const { return reinterpret_cast<const void*>(m_bnctx->bn()); } void Bignum::copy(const Bignum& other) { if (!BN_copy(m_bnctx->bn(), other.m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_copy: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::move(Bignum& other) { m_bnctx.reset(other.m_bnctx.release()); other.m_bnctx.reset(new BignumCtx()); } void Bignum::clear() { BN_clear(m_bnctx->bn()); } int Bignum::width() const { if (BN_is_zero(m_bnctx->bn())) { return 1; } return BN_num_bits(m_bnctx->bn()); } void Bignum::exp(const Bignum& b) { Bignum orig(*this); if (!BN_exp(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_exp modulus: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::gcd(const Bignum& b) { Bignum orig(*this); if (!BN_gcd(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_gcd modulus: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } bool Bignum::is_prime(int trials) { int r = BN_is_prime_ex(m_bnctx->bn(), trials <= 0 ? BN_prime_checks : trials, m_bnctx->ctx(), nullptr); if (r == -1) { auto e = ERR_get_error(); std::stringstream s; s << "BN_is_prime_ex: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } return r == 1; } void Bignum::gen_rand(int bit_width, bool strong, bool odd) { if ((bit_width <= 0) || (strong && bit_width == 1)) { throw std::runtime_error("gen_rand bit width invalid"); } if (!BN_rand(m_bnctx->bn(), bit_width, strong ? BN_RAND_TOP_TWO : 0, odd ? BN_RAND_BOTTOM_ODD : 0)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_rand: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::gen_prime(int bit_width) { if (bit_width < 2) { throw std::runtime_error("gen_prime bit size too low"); } int r = BN_generate_prime_ex(m_bnctx->bn(), bit_width, 0, 0, 0, 0); if (r == 0) { auto e = ERR_get_error(); std::stringstream s; s << "BN_generate_prime_ex: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::negate() { BN_set_negative(m_bnctx->bn(), 1); } bool Bignum::is_negative() const { return BN_is_negative(m_bnctx->bn()) == 1 ? true : false; } int Bignum::cmp(const Bignum& other) const { return BN_cmp(m_bnctx->bn(), other.m_bnctx->bn()); } int Bignum::cmp(uint32_t w) const { if (is_negative()) { return -1; } if (w == 0) { if (BN_is_zero(m_bnctx->bn())) { return 0; } return 1; } if (w == 1) { if (BN_is_zero(m_bnctx->bn())) { return -1; } if (BN_is_one(m_bnctx->bn())) { return 0; } return 1; } Bignum b(w); return cmp(b); } void Bignum::lshift(int shift) { Bignum orig(*this); if (!BN_lshift(m_bnctx->bn(), orig.m_bnctx->bn(), shift)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_lshift: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::rshift(int shift) { Bignum orig(*this); if (!BN_rshift(m_bnctx->bn(), orig.m_bnctx->bn(), shift)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_rshift: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::add(const Bignum& b) { Bignum orig(*this); if (!BN_add(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_add: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::sub(const Bignum& b) { Bignum orig(*this); if (!BN_sub(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_sub: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::mul(const Bignum& b) { Bignum orig(*this); if (!BN_mul(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_mul: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::div(const Bignum& b, Bignum* rem) { Bignum orig(*this); if (!BN_div(m_bnctx->bn(), rem?rem->m_bnctx->bn():nullptr, orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_div divide: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::mod(const Bignum& b) { Bignum orig(*this); if (!BN_div(nullptr, m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_div modulus: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } bool Bignum::is_bit_set(int bit_number) const { if (bit_number < 0) { throw std::runtime_error("is_bit_set() bit number invalid"); } if (bit_number >= width()) { return false; } return BN_is_bit_set(m_bnctx->bn(), bit_number) == 1; } void Bignum::set_bit(int bit_number) { if (bit_number < 0) { throw std::runtime_error("set_bit() bit number invalid"); } if (!BN_set_bit(m_bnctx->bn(), bit_number)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_set_bit: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::clear_bit(int bit_number) { if (bit_number < 0) { throw std::runtime_error("clear_bit() bit number invalid"); } if (bit_number >= width()) { return; } if (!BN_clear_bit(m_bnctx->bn(), bit_number)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_clear_bit: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } std::string Bignum::str(bool hex) const { char * bns; if (!hex) { bns = BN_bn2dec(m_bnctx->bn()); } else { bns = BN_bn2hex(m_bnctx->bn()); // library returns in upper case char* c = bns; for (; *c != 0; c++) { *c = static_cast<char>(std::tolower(static_cast<unsigned char>(*c))); } } if (!bns) { auto e = ERR_get_error(); std::stringstream s; s << (hex ? "BN_bn2hex" : "BN_bn2dec") << ": " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } std::string s(bns); OPENSSL_free(bns); return s; } int Bignum::len() const { if (BN_is_zero(m_bnctx->bn())) { return 1; } return BN_num_bytes(m_bnctx->bn()); } void Bignum::get(void * inloc, int inlen) const { if (inlen != len()) { std::stringstream s; s << "get() called with buffer len " << inlen << ", expected " << len(); throw std::runtime_error(s.str()); } if (BN_is_negative(m_bnctx->bn())) { throw std::runtime_error("get() called with negative number"); } if (BN_is_zero(m_bnctx->bn())) { *((char*)inloc) = 0; return; } if (!BN_bn2bin(m_bnctx->bn(), static_cast<unsigned char*>(inloc))) { auto e = ERR_get_error(); std::stringstream s; s << "BN_bn2bin: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::set(uint32_t w) { if (w == 0) { BN_zero(m_bnctx->bn()); } else if (w == 1) { if (!BN_one(m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_one: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } else if (!BN_set_word(m_bnctx->bn(), w)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_set_word: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::set(const void * loc, int len) { if (!BN_bin2bn(reinterpret_cast<const unsigned char *>(loc), len, m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_bin2bn: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } int Bignum::len_2sc() const { int w = width(); int bitw = (w+7)&~7; if (!is_negative()) { return w == bitw ? bitw/8+1 : bitw/8; // will pad with 0 byte if the msb is set } if (w < bitw) return bitw/8; // msb is set, if any other bits are set, will add a byte when converted to 2s complement for (int i = 0; i < w-1; i++) { if (is_bit_set(i)) return bitw/8+1; } return bitw/8; } void Bignum::get_2sc(void * inloc, int len) const { int w = width(); int bitw = (w+7)&~7; uint8_t* loc = static_cast<uint8_t*>(inloc); if (len <= 0) return; if (!is_negative()) { if (w == bitw) // msb is set, pad with 0 { *loc = '\x00'; loc++; len--; } get(loc, len); return; } /* 128 0000 0000 1000 0000 - 00 80 127 0111 1111 - 7f -1 1111 1111 - ff -127 1000 0001 - 81 -128 1000 0000 - 80 -129 1111 1111 0111 1111 - ff 7f */ Bignum bn(1); bn <<= bitw; if (w == bitw) // if any other bits are on, add an additional byte, otherwise, this is the boundary value { for (int i = 0; i < w-1; i++) { if (is_bit_set(i)) { bn <<= 8; break; } } } bn += *this; // subtract the absolute value bn.get(loc, len); } void Bignum::set_2sc(const void * loc, int len) { if (len <= 0) return; bool neg = (*(uint8_t*)loc & 0x80) == 0x80 ? true : false; // check if msb is on set(loc, len); // sets as a positive number if (!neg) return; int w = width(); clear_bit(w-1); // clear the msb Bignum bn(1); // form the number with msb set bn <<= w-1; *this -= bn; // i.e. 10000001 = 00000001 - 10000000 }
20.614634
113
0.638508
stablecc
da04c1d17590550cf7078410bfa145ac5faaf168
2,784
cpp
C++
framework/egl/egluUnique.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
354
2017-01-24T17:12:38.000Z
2022-03-30T07:40:19.000Z
framework/egl/egluUnique.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
275
2017-01-24T20:10:36.000Z
2022-03-24T16:24:50.000Z
framework/egl/egluUnique.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
190
2017-01-24T18:02:04.000Z
2022-03-27T13:11:23.000Z
/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief EGL unique resources *//*--------------------------------------------------------------------*/ #include "egluUnique.hpp" #include "eglwLibrary.hpp" #include "eglwEnums.hpp" namespace eglu { using namespace eglw; UniqueDisplay::UniqueDisplay (const Library& egl, EGLDisplay display) : m_egl (egl) , m_display (display) { } UniqueDisplay::~UniqueDisplay (void) { if (m_display != EGL_NO_DISPLAY) m_egl.terminate(m_display); } UniqueDisplay::operator bool (void) const { return m_display != EGL_NO_DISPLAY; } UniqueSurface::UniqueSurface (const Library& egl, EGLDisplay display, EGLSurface surface) : m_egl (egl) , m_display (display) , m_surface (surface) { } UniqueSurface::~UniqueSurface (void) { if (m_surface != EGL_NO_SURFACE) m_egl.destroySurface(m_display, m_surface); } UniqueSurface::operator bool (void) const { return m_surface != EGL_NO_SURFACE; } UniqueContext::UniqueContext (const Library& egl, EGLDisplay display, EGLContext context) : m_egl (egl) , m_display (display) , m_context (context) { } UniqueContext::~UniqueContext (void) { if (m_context != EGL_NO_CONTEXT) m_egl.destroyContext(m_display, m_context); } UniqueContext::operator bool (void) const { return m_context != EGL_NO_CONTEXT; } ScopedCurrentContext::ScopedCurrentContext (const Library& egl, EGLDisplay display, EGLSurface draw, EGLSurface read, EGLContext context) : m_egl (egl) , m_display (display) { EGLU_CHECK_CALL(m_egl, makeCurrent(display, draw, read, context)); } ScopedCurrentContext::~ScopedCurrentContext (void) { m_egl.makeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } UniqueImage::UniqueImage (const Library& egl, EGLDisplay display, EGLImage image) : m_egl (egl) , m_display (display) , m_image (image) { } UniqueImage::~UniqueImage (void) { if (m_image != EGL_NO_IMAGE) m_egl.destroyImageKHR(m_display, m_image); } UniqueImage::operator bool (void) const { return m_image != EGL_NO_IMAGE; } } // eglu
23.794872
137
0.691451
iabernikhin
da06759d52886e8a3a347a2d69bc62b1c0c27bd3
657
cpp
C++
Raven.CppClient/ConflictSolver.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
3
2019-04-24T02:34:53.000Z
2019-08-01T08:22:26.000Z
Raven.CppClient/ConflictSolver.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
2
2019-03-21T09:00:02.000Z
2021-02-28T23:49:26.000Z
Raven.CppClient/ConflictSolver.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
3
2019-03-04T11:58:54.000Z
2021-03-01T00:25:49.000Z
#include "stdafx.h" #include "ConflictSolver.h" #include "json_utils.h" namespace ravendb::client::serverwide { void to_json(nlohmann::json& j, const ConflictSolver& cs) { using ravendb::client::impl::utils::json_utils::set_val_to_json; set_val_to_json(j, "ResolveByCollection", cs.resolve_by_collection); set_val_to_json(j, "ResolveToLatest", cs.resolve_to_latest); } void from_json(const nlohmann::json& j, ConflictSolver& cs) { using ravendb::client::impl::utils::json_utils::get_val_from_json; get_val_from_json(j, "ResolveByCollection", cs.resolve_by_collection); get_val_from_json(j, "ResolveToLatest", cs.resolve_to_latest); } }
29.863636
72
0.767123
maximburyak
da08643228212a407c42fbff89abfd63a7200535
1,415
cc
C++
src/abc075/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc075/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc075/d.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll MX = pow(10, 9) + 1; ll res = -1; void dfs(int pointer, int n, int k, int comb, vector<ll> &x, vector<ll> &y, vector<int> &a) { if((int)a.size() == comb) { ll ax, bx, ay, by; ax = ay = -1 * MX; bx = by = MX; for(int i = 0; i < (int)a.size(); i++) { ax = max(x[a[i]], ax); bx = min(x[a[i]], bx); ay = max(y[a[i]], ay); by = min(y[a[i]], by); } int count = 0; for(int i = 0; i < n; i++) { if(ax >= x[i] && x[i] >= bx && ay >= y[i] && y[i] >= by) { count++; } } if(count >= k) { ll temp = (ax - bx) * (ay - by); if(res == -1) { res = temp; } else { res = min(res, temp); } } return; } if(pointer >= n) { return; } a.push_back(pointer); dfs(pointer + 1, n, k, comb, x, y, a); a.pop_back(); dfs(pointer + 1, n, k, comb, x, y, a); } ll solve(int n, int k, vector<ll> x, vector<ll> y) { vector<int> a; dfs(0, n, k, min(k, 4), x, y, a); return res; } /* int main() { ll n, k; cin >> n >> k; vector<ll> x(n), y(n); for(int i = 0; i < n; i++) { cin >> x[i] >> y[i]; } cout << solve(n, k, x, y); } */
22.460317
75
0.374558
nryotaro
da0a9246a213e0dd5f4d8895848e991a9e6470e9
1,523
cpp
C++
solutions/binary_tree_maximum_path_sum.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/binary_tree_maximum_path_sum.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/binary_tree_maximum_path_sum.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <map> #include <string> #include <stack> using namespace std; // Given a non-empty binary tree, find the maximum path sum. // For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. // Example 1: // Input: [1,2,3] // 1 // / \ // 2 3 // Output: 6 // Example 2: // Input: [-10,9,20,null,null,15,7] // -10 // / \ // 9 20 // / \ // 15 7 // Output: 42 // solution: dfs /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int maxPath = INT_MIN; int dfs(TreeNode* root) { if (!root) { return 0; } int left = dfs(root->left); int right = dfs(root->right); if (left < 0) left = 0; if (right < 0) right = 0; int temp1 = left + right + root->val; int temp2 = max(left, right) + root->val; maxPath = max(maxPath, temp1); return temp2; } int maxPathSum(TreeNode* root) { dfs(root); return maxPath; } };
20.581081
229
0.560079
kmykoh97
da0cad0e4928c0e3f3fa039f4da396520876082b
11,900
cc
C++
CalibCalorimetry/EcalLaserAnalyzer/test/MusEcal/src/MECanvasHolder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CalibCalorimetry/EcalLaserAnalyzer/test/MusEcal/src/MECanvasHolder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CalibCalorimetry/EcalLaserAnalyzer/test/MusEcal/src/MECanvasHolder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include <cstdlib> #include <cstdio> #include <fstream> #include <iostream> #include <assert.h> using namespace std; #include <math.h> #include <TStyle.h> #include "TImage.h" #include "TAttImage.h" #include "MECanvasHolder.hh" ClassImp(MECanvasHolder); MECanvasHolder::MECanvasHolder() : fCanvas(0), fWelcomePave(0), fWelcomeState(true), fWelcomeTitle(0), fWelcomeL0(0), _h(0), _scale(1), _refw(1092) {} MECanvasHolder::~MECanvasHolder() { ClearWelcome(); } void MECanvasHolder::CanvasModified() { //Something has been modified in fCanvas TPad* pad = (TPad*)gPad; fCanvas->cd(); fCanvas->Modified(); fCanvas->Update(); pad->cd(); } void MECanvasHolder::ClearWelcome() { if (fWelcomePave) { delete fWelcomePave; fWelcomePave = 0; gPad->Clear(); } } void MECanvasHolder::SetCanvas( TCanvas* canvas, const char* textTL, const char* textBL, const char* textTR, const char* textBR) { assert(canvas != 0); // fCanvas = fEcanvas->GetCanvas(); fCanvas = canvas; fCanvas->Clear(); fTopXGen = fCanvas->GetWindowTopX(); fTopYGen = fCanvas->GetWindowTopY(); // fWidthGen = fCanvas->GetWindowWidth(); // fHeigthGen = fCanvas->GetWindowHeight(); fWidthGen = fCanvas->GetWw(); fHeigthGen = fCanvas->GetWh(); // cout << "fTopXGen/fTopYGen/fWidthGen/fHeigthGen " << fTopXGen << "/" << fTopYGen << "/" << fWidthGen << "/" << fHeigthGen << endl; if (fWidthGen != 0) { _scale = fWidthGen / _refw; } _scale = 1; // fixme ! // Various settings Color_t fColCan = 45; Style_t fStyleCan = 1001; Color_t fStyleHistColor = 45; Color_t fStyleTitleColor = 1; Color_t fStyleTFColor = 191; Color_t fStyleTTextColor = 1; Style_t fStylePad1 = 1001; Int_t fPadLogX = 0; Int_t fPadLogY = 0; Color_t fColFrame = 18; Color_t fColPad1 = 30; TString fStringTL(textTL); // = "Welcome to MusEcal - Monitoring and Useful Survey of Ecal"; TString fStringBL( textBL); // = "Visit our Twiki page at https://twiki.cern.ch/twiki/bin/view/CMS/EcalLaserMonitoring"; TString fStringTR(textTR); // = "MusEcal Version 2.0"; TString fStringBR(textBR); // = "J. Malcles & G. Hamel de Monchenault, CEA-Saclay"; double fXTexTL = 0.02; double fYTexTL = 0.975; double fXTexBL = 0.02; double fYTexBL = 0.01; double fXTexBR = 0.65; double fYTexBR = 0.01; double fXTexTR = 0.65; double fYTexTR = 0.975; Font_t fFontTex = 132; Float_t fSizeTex = 0.02; Short_t fBszCan = 4; Short_t fBszPad = 6; Width_t fWidthTex = 2; double fEmptyX = _scale * 0.005; double fEmptyY = _scale * 0.03; double wpad = _scale * 0.5 * (1.0 - 4 * fEmptyX); double fXLowPad1 = fEmptyX; double fXUpPad1 = fXLowPad1 + wpad; double fXLowPad2 = fXUpPad1 + 2 * fEmptyX; double fXUpPad2 = fXLowPad2 + wpad; double fYLowPad = fEmptyY; double fYUpPad = 1.0 - fEmptyY; fCanvas->SetEditable(); fCanvas->Range(0, 0, 1, 1); fCanvas->SetFillColor(fColCan); fCanvas->SetFillStyle(fStyleCan); fCanvas->SetBorderSize(fBszCan); gStyle->SetOptStat(1111); gStyle->SetStatFont(22); gStyle->SetStatColor(18); if (fHeigthGen >= 700) { gStyle->SetStatH(0.1); gStyle->SetTitleSize(0.01); } else { gStyle->SetStatH(_scale * 0.15); gStyle->SetTitleSize(_scale * 0.015); } gStyle->SetTitleFillColor(fStyleTFColor); gStyle->SetTitleTextColor(fStyleTTextColor); gStyle->SetTitleW(_scale * 0.76); gStyle->SetHistFillColor(fStyleHistColor); gStyle->SetTitleFont(22); gStyle->SetTitleColor(173); gStyle->SetTitleFillColor(18); gStyle->SetTitleColor(fStyleTitleColor); gStyle->SetTitleTextColor(46); gStyle->SetLabelSize(_scale * 0.02, "XYZ"); fTexTL = new TLatex(fXTexTL, fYTexTL, fStringTL.Data()); fTexTR = new TLatex(fXTexTR, fYTexTR, fStringTR.Data()); fTexBL = new TLatex(fXTexBL, fYTexBL, fStringBL.Data()); fTexBR = new TLatex(fXTexBR, fYTexBR, fStringBR.Data()); // from DrawLabels() //Draws the 4 labels on the Canvas fTexTL->SetTextFont(fFontTex); fTexTL->SetTextSize(fSizeTex); fTexTL->SetLineWidth(fWidthTex); fTexBL->SetTextFont(fFontTex); fTexBL->SetTextSize(fSizeTex); fTexBL->SetLineWidth(fWidthTex); fTexBR->SetTextFont(fFontTex); fTexBR->SetTextSize(fSizeTex); fTexBR->SetLineWidth(fWidthTex); fTexTR->SetTextFont(fFontTex); fTexTR->SetTextSize(fSizeTex); fTexTR->SetLineWidth(fWidthTex); fCanvas->cd(); fTexTL->Draw(); fTexBL->Draw(); fTexBR->Draw(); fTexTR->Draw(); // from BookPad1() fCanvas->cd(); fPad = new TPad("LeftPad", "Left pad", fXLowPad1, fYLowPad, fXUpPad2, fYUpPad); fPad->SetNumber(1); fPad->SetFillColor(fColPad1); fPad->SetFillStyle(fStylePad1); fPad->SetBorderSize(fBszPad); fPad->SetGridx(); fPad->SetGridy(); fPad->SetLogx(fPadLogX); fPad->SetLogy(fPadLogY); fPad->SetFrameFillColor(fColFrame); fPad->SetFillStyle(fStylePad1); fPad->Draw(); fPad->cd(); setSessionStyle(); ShowWelcome(false); } void MECanvasHolder::ShowWelcome(bool image) { gPad->Clear(); if (image) { TString imgpath = TString(std::getenv("MECONFIG")); TImage* img = TImage::Open(imgpath + "/LVB.jpg"); assert(img != 0); // img->SetConstRatio(0); TText* ttext1 = new TText(450, 500, "MusEcal"); ttext1->SetTextSize(0.5); ttext1->SetTextColor(kRed); ttext1->SetTextFont(62); img->SetImageQuality(TAttImage::kImgBest); img->DrawText(ttext1, 450, 500); TText* ttext2 = new TText(450, 800, "ECAL Laser Monitoring"); ttext2->SetTextSize(0.3); ttext2->SetTextColor(kRed); ttext2->SetTextFont(62); img->DrawText(ttext2, 450, 800); img->Draw("xxx"); img->SetEditable(kTRUE); } gPad->Modified(); gPad->Update(); } void MECanvasHolder::setSessionStyle() { // use plain black on white colors gStyle->SetFrameBorderMode(0); gStyle->SetCanvasBorderMode(0); gStyle->SetPadBorderMode(0); gStyle->SetPadColor(0); gStyle->SetCanvasColor(0); gStyle->SetTitleBorderSize(0); // gStyle->SetTitleColor(0); // gStyle->SetStatColor(0); // gStyle->SetFillColor(0); // set the paper & margin sizes gStyle->SetPaperSize(20, 26); // gStyle->SetPadTopMargin(_scale*0.05); gStyle->SetPadTopMargin(_scale * 0.10); gStyle->SetPadRightMargin(_scale * 0.165); gStyle->SetPadBottomMargin(_scale * 0.15); gStyle->SetPadLeftMargin(_scale * 0.135); // use large Times-Roman fonts gStyle->SetTextFont(132); gStyle->SetTextSize(0.08); gStyle->SetLabelFont(132, "x"); gStyle->SetLabelFont(132, "y"); gStyle->SetLabelFont(132, "z"); gStyle->SetTitleFont(132, "x"); gStyle->SetTitleFont(132, "y"); gStyle->SetTitleFont(132, "z"); gStyle->SetTitleFont(132); gStyle->SetLabelSize(_scale * 0.05, "x"); gStyle->SetLabelOffset(_scale * 0.01, "x"); gStyle->SetTitleOffset(_scale * 1, "x"); gStyle->SetTitleSize(_scale * 0.06, "x"); gStyle->SetLabelSize(_scale * 0.05, "y"); gStyle->SetLabelOffset(_scale * 0.01, "y"); gStyle->SetTitleSize(_scale * 0.06, "y"); gStyle->SetTitleOffset(_scale * 1, "y"); gStyle->SetLabelSize(_scale * 0.05, "z"); gStyle->SetLabelOffset(_scale * 0.01, "z"); gStyle->SetTitleSize(_scale * 0.06, "z"); gStyle->SetTitleOffset(_scale * 1, "z"); // use bold lines and markers // gStyle->SetMarkerStyle(8); gStyle->SetHistLineWidth(2); gStyle->SetLineStyleString(2, "[12 12]"); // postscript dashes // do not display any of the standard histogram decorations // gStyle->SetOptTitle(0); gStyle->SetOptStat(111111); gStyle->SetOptFit(0); // put tick marks on top and RHS of plots // gStyle->SetPadTickX(1); // gStyle->SetPadTickY(1); // TColor::CreateColorWheel(); gStyle->SetPalette(1); // setHessPalette(); const int ncol = 60; gStyle->SetNumberContours(ncol); fCanvas->SetFillColor(kYellow); fCanvas->SetGridx(0); fCanvas->SetGridx(1); fPad->SetFillColor(kWhite); fPad->SetGridx(0); fPad->SetGridy(0); fPad->SetCrosshair(0); fPad->SetFrameFillColor(kWhite); } void MECanvasHolder::setHistoStyle(TH1* h) { if (h == 0) return; h->SetLineColor(4); h->SetLineWidth(1); h->SetFillColor(38); TAxis* axis[3]; axis[0] = h->GetXaxis(); axis[1] = h->GetYaxis(); axis[2] = h->GetZaxis(); for (int ii = 0; ii < 3; ii++) { TAxis* a = axis[ii]; if (!a) continue; a->SetLabelFont(132); a->SetLabelOffset(0.005); a->SetLabelSize(0.04); a->SetTitleFont(132); a->SetTitleOffset(1); a->SetTitleSize(0.04); } h->SetStats(kTRUE); } void MECanvasHolder::SetDate() { // from F-X Gentit const Int_t cent = 100; Int_t date, time; Int_t day, month, year; Int_t hour, minute, second; TDatime td; date = td.GetDate(); time = td.GetTime(); // day = date % cent; date /= cent; month = date % cent; date /= cent; year = date; second = time % cent; time /= cent; minute = time % cent; time /= cent; hour = time; // fDate = " "; fDate += day; fDate.Append(" / "); fDate += month; fDate.Append(" / "); fDate += year; fDate.Append(" "); // fTime = ""; fTime += hour; fTime.Append('_'); fTime += minute; } void MECanvasHolder::setPxAndPy(int px, int py) { _px = px; _py = py; _x = 0; _y = 0; if (_h != 0) { TString objectInfo; objectInfo = _h->GetObjectInfo(_px, _py); // cout << "_px/_py/_h " << _px << "/" << _py << endl; // _h->Print(); // cout << objectInfo << endl; // // Yuk !!! // int istart1 = objectInfo.Index("(x="); int iend1 = istart1 + 3; int istart2 = objectInfo.Index(", y="); int iend2 = istart2 + 4; int istart3 = objectInfo.Index(", binx="); // int iend3 = istart3+7; _x = TString(objectInfo(iend1, istart2 - iend1)).Atof(); _y = TString(objectInfo(iend2, istart3 - iend2)).Atof(); // cout << "x/y " << _x << "/" << _y << endl; } } void MECanvasHolder::setPad() { if (fPad == 0) return; fPad->cd(); } void MECanvasHolder::setHessPalette() { const int nfix = 5; const float Pi = acos(-1.); const int ninter = 10; int nstep = ninter + 1; double step = Pi / nstep; const int ncoltot = (nfix - 1) * ninter + nfix; TColor* myCol; Int_t palette[ncoltot]; for (int i = 0; i < ncoltot; i++) palette[i] = 1; // 1:black, 4:blue, 2:red, 5:yellow, 10:white int colfix[nfix] = {1, 4, 2, 5, 10}; int colOff7 = 4300; int icol = colOff7; // new color number float red, green, blue; int ifix = 0; for (int ii = 0; ii < nfix; ii++) { TString myColName("myHessCol_"); myColName += icol; TColor* theCol = (TColor*)gROOT->GetColor(colfix[ii]); theCol->GetRGB(red, green, blue); myCol = new TColor(icol, red, green, blue, myColName); cout << "ifix " << ifix << " r/g/b " << red << "/" << green << "/" << blue << endl; palette[ifix] = icol++; ifix += nstep; } float r1, g1, b1; float r2, g2, b2; int ifix1 = 0; int ifix2 = 0; for (int ii = 0; ii < nfix - 1; ii++) { ifix2 = ifix1 + nstep; int icol1 = palette[ifix1]; int icol2 = palette[ifix2]; TColor* col1 = gROOT->GetColor(icol1); col1->Print(); col1->GetRGB(r1, g1, b1); TColor* col2 = gROOT->GetColor(icol2); col2->Print(); col2->GetRGB(r2, g2, b2); ifix = ifix1; double x = -Pi / 2.; for (int istep = 0; istep < ninter; istep++) { x += step; ifix++; double sinx = sin(x); red = 0.5 * ((r2 - r1) * sinx + (r1 + r2)); green = 0.5 * ((g2 - g1) * sinx + (g1 + g2)); blue = 0.5 * ((b2 - b1) * sinx + (b1 + b2)); TString myColName("myHessCol_"); myColName += icol; myCol = new TColor(icol, red, green, blue, myColName); cout << "ifix " << ifix << " r/g/b " << red << "/" << green << "/" << blue << endl; palette[ifix] = icol++; } ifix1 = ifix2; } gStyle->SetPalette(ncoltot, palette); }
26.801802
136
0.628908
ckamtsikis
da15175ead432a169cc30b1e65f514ecb19d4f07
1,516
cpp
C++
Graphs/FloydWarshall.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
687
2015-02-23T17:31:00.000Z
2022-03-27T02:57:23.000Z
Graphs/FloydWarshall.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
9
2018-08-27T06:41:24.000Z
2020-12-17T13:39:07.000Z
Graphs/FloydWarshall.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
253
2015-03-16T00:42:18.000Z
2022-03-23T06:01:36.000Z
/************************************************************************************** Floyd-Warshall algorithm finding shortest distance between all pairs of vertices in graph. Works in O(N^3) Based on problem 95 from informatics.mccme.ru http://informatics.mccme.ru/mod/statements/view.php?id=218#1 **************************************************************************************/ #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <cassert> #include <utility> #include <iomanip> using namespace std; const int MAXN = 55; const int INF = (int) 1e9; int n; int s, t; int d[MAXN][MAXN]; int main() { //assert(freopen("input.txt","r",stdin)); //assert(freopen("output.txt","w",stdout)); scanf("%d %d %d", &n, &s, &t); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { scanf("%d", &d[i][j]); if (d[i][j] == -1) d[i][j] = INF; } for (int k = 1; k <= n; k++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j]; if (d[s][t] == INF) printf("-1\n"); else printf("%d\n", d[s][t]); return 0; }
24.063492
88
0.435356
mayukhsen1301
da1964b39b65de793fa7b7f9e46652c840abb7e0
3,560
cpp
C++
riscv-sim/src/RISCVSTypeInstruction.cpp
tomli380576/riscv-console
a0129af4e41ecdde752f40c7b239c9bd98c1e049
[ "BSD-3-Clause" ]
9
2021-01-12T13:18:26.000Z
2022-03-10T20:20:45.000Z
riscv-sim/src/RISCVSTypeInstruction.cpp
helloparthshah/riscv-console
5b20edc4f54c8edf2f2f4e6769e2f02676eaf994
[ "BSD-3-Clause" ]
16
2021-01-17T04:17:21.000Z
2021-11-12T17:46:54.000Z
riscv-sim/src/RISCVSTypeInstruction.cpp
helloparthshah/riscv-console
5b20edc4f54c8edf2f2f4e6769e2f02676eaf994
[ "BSD-3-Clause" ]
21
2021-01-13T00:50:13.000Z
2022-03-14T21:30:53.000Z
#include "RISCVSTypeInstruction.h" class CRISCVSBInstruction : public CRISCVSTypeInstruction{ public: CRISCVSBInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CRISCVSTypeInstruction(addr,raw, pc, regs, mem){ }; bool Execute(){ DMemory->StoreUINT8(DSource1->load() + DOffset,DSource2->load()); DProgramCounter->fetch_add(DInstructionAlignment); return true; }; std::string ToString() const{ return CRISCVSTypeInstruction::ToString().replace(0,2,"sb"); }; }; class CRISCVSHInstruction : public CRISCVSTypeInstruction{ public: CRISCVSHInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CRISCVSTypeInstruction(addr,raw, pc, regs, mem){ }; bool Execute(){ DMemory->StoreUINT16(DSource1->load() + DOffset,DSource2->load()); DProgramCounter->fetch_add(DInstructionAlignment); return true; }; std::string ToString() const{ return CRISCVSTypeInstruction::ToString().replace(0,2,"sh"); }; }; class CRISCVSWInstruction : public CRISCVSTypeInstruction{ public: CRISCVSWInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CRISCVSTypeInstruction(addr,raw, pc, regs, mem){ }; bool Execute(){ DMemory->StoreUINT32(DSource1->load() + DOffset,DSource2->load()); DProgramCounter->fetch_add(DInstructionAlignment); return true; }; std::string ToString() const{ return CRISCVSTypeInstruction::ToString().replace(0,2,"sw"); }; }; CRISCVSTypeInstruction::CRISCVSTypeInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CInstruction(addr,raw){ SRISCVSType *Encoded = (SRISCVSType *)&raw; DProgramCounter = pc; DSource1 = regs[Encoded->rs1]; DSource2 = regs[Encoded->rs2]; DMemory = mem; DOffset = (uint32_t(Encoded->imm11_5)<<5) | Encoded->imm4_0; DOffset |= DOffset & 0x800 ? 0xFFFFF000 : 0; } std::string CRISCVSTypeInstruction::ToString() const{ SRISCVSType *Encoded = (SRISCVSType *)&DRawInstruction; return std::string(" ") + RegisterName(Encoded->rs2) + "," + std::to_string(DOffset) + "(" + RegisterName(Encoded->rs1) + ")"; } std::shared_ptr< CRISCVCPU::CInstruction > CRISCVSTypeInstruction::DecodeSType(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem){ SRISCVSType *Encoded = (SRISCVSType *)&raw; switch(Encoded->funct3){ case 0x0: return std::make_shared<CRISCVSBInstruction>(addr,raw,pc,regs,mem); case 0x1: return std::make_shared<CRISCVSHInstruction>(addr,raw,pc,regs,mem); case 0x2: return std::make_shared<CRISCVSWInstruction>(addr,raw,pc,regs,mem); default: return nullptr; } }
44.5
270
0.665449
tomli380576
da19a3b2024a92ac77b016b91b425d389397fbdb
2,689
cpp
C++
test/tstKokkosToolsDistributedAnnotations.cpp
dalg24/ArborX
d298c924ce93902a285168de5dc5003e4d761627
[ "BSD-3-Clause" ]
null
null
null
test/tstKokkosToolsDistributedAnnotations.cpp
dalg24/ArborX
d298c924ce93902a285168de5dc5003e4d761627
[ "BSD-3-Clause" ]
null
null
null
test/tstKokkosToolsDistributedAnnotations.cpp
dalg24/ArborX
d298c924ce93902a285168de5dc5003e4d761627
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2012-2020 by the ArborX authors * * All rights reserved. * * * * This file is part of the ArborX library. ArborX 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 "ArborX_EnableDeviceTypes.hpp" // ARBORX_DEVICE_TYPES #include <ArborX_DistributedSearchTree.hpp> #include <boost/test/unit_test.hpp> #include <string> #include "Search_UnitTestHelpers.hpp" #if (KOKKOS_VERSION >= 30200) // callback registriation from within the program // was added in Kokkkos v3.2 BOOST_AUTO_TEST_SUITE(KokkosToolsDistributedAnnotations) namespace tt = boost::test_tools; bool isPrefixedWith(std::string const &s, std::string const &prefix) { return s.find(prefix) == 0; } BOOST_AUTO_TEST_CASE(is_prefixed_with) { BOOST_TEST(isPrefixedWith("ArborX::Whatever", "ArborX")); BOOST_TEST(!isPrefixedWith("Nope", "ArborX")); BOOST_TEST(!isPrefixedWith("Nope::ArborX", "ArborX")); } BOOST_AUTO_TEST_CASE_TEMPLATE(regions_prefixed, DeviceType, ARBORX_DEVICE_TYPES) { Kokkos::Tools::Experimental::set_push_region_callback([](char const *label) { std::cout << label << '\n'; BOOST_TEST((isPrefixedWith(label, "ArborX::") || isPrefixedWith(label, "Kokkos::"))); }); // DistributedSearchTree::DistriibutedSearchTree { // empty auto tree = makeDistributedSearchTree<DeviceType>(MPI_COMM_WORLD, {}); } // DistributedSearchTree::query auto tree = makeDistributedSearchTree<DeviceType>( MPI_COMM_WORLD, { {{{0, 0, 0}}, {{1, 1, 1}}}, {{{0, 0, 0}}, {{1, 1, 1}}}, }); // spatial predicates query(tree, makeIntersectsBoxQueries<DeviceType>({ {{{0, 0, 0}}, {{1, 1, 1}}}, {{{0, 0, 0}}, {{1, 1, 1}}}, })); // nearest predicates query(tree, makeNearestQueries<DeviceType>({ {{{0, 0, 0}}, 1}, {{{0, 0, 0}}, 2}, })); Kokkos::Tools::Experimental::set_push_region_callback(nullptr); } BOOST_AUTO_TEST_SUITE_END() #endif
33.6125
80
0.518408
dalg24
da1abc7efe31b4d8f3ca42ca3161429bbd16e6de
5,890
cpp
C++
swig/share/c++/examples/testsort.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
4
2021-01-23T14:36:34.000Z
2021-06-07T10:02:28.000Z
swig/share/c++/examples/testsort.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
1
2019-08-04T19:15:56.000Z
2019-08-04T19:15:56.000Z
swig/share/c++/examples/testsort.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
1
2022-01-29T22:41:01.000Z
2022-01-29T22:41:01.000Z
#include <exodus/program.h> //for the sake of multivalue gurus new to exodus programming this is written //with multivalue-mimicking "everything is a global function" syntax //instead of exodus's OO-style syntax "xxx.yyy().zzz()" var filename="myclients"; programinit() function main() { if (not connect()) abort("Cannot connect to database. Please check configuration or run configexodus."); var dictfilename="dict_"^ filename; //leave the test data files around for playing with var cleanup=false; if (cleanup) { deletefile(filename); deletefile(dictfilename); } printl("\nOpen or create test file ", filename); var file; if (not open(filename, file)) { createfile(filename); if (not open(filename, file)) abort("Cannot open "^filename); } printl("\nOpen or create the test files dictionary ", dictfilename); var dictfile; if (not open(dictfilename, dictfile)) { createfile(dictfilename); if (not open(dictfilename, dictfile)) abort("Cannot open dictionary "^ dictfilename); } printl("\nPrepare some dictionary records"); var dictrecs = ""; dictrecs = "CLIENT_CODE |F|0|Code |||| ||L|8"; dictrecs ^= FM ^ "CLIENT_NAME |F|1|Name |||| ||T|15"; dictrecs ^= FM ^ "CLIENT_TYPE |F|2|Type |||| ||L|5"; dictrecs ^= FM ^ "DATE_CREATED|F|3|Date ||||D4 ||L|12"; dictrecs ^= FM ^ "TIME_CREATED|F|4|Time ||||MTH ||L|12"; dictrecs ^= FM ^ "BALANCE |F|5|Balance ||||MD20P ||R|10"; dictrecs ^= FM ^ "TIMESTAMP |F|6|Timestamp||||[DATETIME]||L|12"; dictrecs ^= FM ^ "@CRT |G| |CLIENT_CODE CLIENT_NAME CLIENT_TYPE BALANCE DATE_CREATED TIME_CREATED TIMESTAMP"; printl("\nWrite the dictionary records to the dictionary"); var nrecs=dcount(dictrecs, FM); for (var recn = 1; recn <= nrecs; recn++) { var dictrec=extract(dictrecs, recn); var key=field(dictrec, "|", 1); var rec=field(dictrec, "|", 2, 9999); printl(key, ": ", rec); key=trim(key); rec=trim(rec); rec=swap(rec, " |", "|"); rec=convert(rec, "|", FM); write(rec, dictfile, key); //check we can read the record back var rec2; dictfile.outputl("dictfile"); //key.outputl("key"); if (read(rec2,dictfile, key)) { if (rec2 ne rec) printl("record differs?!"); } else printl("Cant read ", key, " back"); } var rec; if (not read(rec,dictfile,"BALANCE")) printl("Cant read BALANCE record from dictionary"); printl("\nClear the client file"); clearfile(filename); printl("\nPrepare some data records in a readable format"); var recs = ""; recs ^= FM ^ "SB001|Client AAA |A |15070|76539|1000.00|15070.76539"; recs ^= FM ^ "JB002|Client BBB |B |15000|50539|200.00|15000.50539"; recs ^= FM ^ "JB001|Client CCC |B |15010|60539|2000.00|15010.60539"; recs ^= FM ^ "SB1 |Client SB1 |1 | | | | "; recs ^= FM ^ "JB2 |Client JB2 |2 |14000|10539|0 |14000.10539"; recs ^= FM ^ "JB10 |Client JB10|10|14010|10539|2000.00|14010.10539"; splicer(recs, 1, 1, ""); printl("\nWrite the data records to the data file"); nrecs=dcount(recs, FM); for (var recn = 1; recn <= nrecs; recn++) { var rec=extract(recs, recn); var key=field(rec, "|", 1); rec=field(rec, "|", 2, 9999); printl(key, ": ", rec); while (index(rec, " |")) swapper(rec, " |", "|"); write(trimb(convert(rec, "|", FM)), file, trim(key)); } var prefix="SELECT "^ filename; gosub sortselect(file, prefix^ " BY CLIENT_CODE"); gosub sortselect(file, prefix^ " BY BALANCE BY CLIENT_CODE"); gosub sortselect(file, prefix^ " BY TIMESTAMP"); gosub sortselect(file, prefix^ " WITH CLIENT_TYPE 'B' BY BALANCE"); var cmd="list "^ filename^ " id-supp"; printl("\nList the file using ", quote(cmd)); osshell(cmd); cmd="list "^ dictfilename; printl("\nList the dict using ", quote(cmd)); osshell(cmd); if (cleanup) { printl("\nCleaning up. Delete the files"); deletefile(file); deletefile(dictfile); } printl("\nJust type 'list' to see the syntax of list"); printl("or list dict_"^ filename^ " to see the dictionary"); printl("Type edic cli/src/testsort to see or edit/recompile this program."); return 0; } subroutine sortselect(in file, in sortselectcmd) { printl("\nSSELECT the data - ", sortselectcmd); if (!select(sortselectcmd)) { printl("Cannot sselect"); return; } printl("Read the data"); var record; var key; //could also use the readnextrecord() function here // if we had used the new selectrecord() function above while (readnext(key)) { if (not read(record, file, key)) { printl(key, " missing from file"); continue; } print(key, ": "); printl(convert(record, FM, "|")); } } programexit()
33.657143
124
0.509847
rdmenezes
da1ccb7d0d83491a7f8b46dc942db55c704031d0
1,565
cpp
C++
example/visitation_example.cpp
friendlyanon/cpp_enum_set
248a98ee768def5b4a32d3719d6ee46863377114
[ "MIT" ]
21
2021-05-25T07:59:08.000Z
2021-06-04T01:54:23.000Z
example/visitation_example.cpp
friendlyanon/cpp_enum_set
248a98ee768def5b4a32d3719d6ee46863377114
[ "MIT" ]
11
2021-05-25T09:28:51.000Z
2021-07-01T09:59:15.000Z
example/visitation_example.cpp
friendlyanon/cpp_enum_set
248a98ee768def5b4a32d3719d6ee46863377114
[ "MIT" ]
2
2021-05-25T11:52:04.000Z
2021-06-02T16:17:24.000Z
#include <enum_set/type_set.hpp> #include <iostream> #include <string> #include <vector> // Define an option as a "strong enum". struct option { class A; class B; class C; }; // Define a set of options as a `type_set`. using option_set = enum_set::type_set< option::A, option::B, option::C >; // Define a an `option_tag` class that can be used for tag dispatching. template <typename T> struct option_tag { }; // Define a functor `option_name` that maps an `option_tag` to a `std::string`. struct option_name { std::string operator()(option_tag<option::A>) { return "A"; } std::string operator()(option_tag<option::B>) { return "B"; } std::string operator()(option_tag<option::C>) { return "C"; } }; // Define a visitor that can be used on a `enum_set::type_set`. // The visitor should define an templated call operators without parameters. struct option_set_visitor { std::vector<std::string> result; template <typename Option> void operator()() { result.push_back(option_name()(option_tag<Option>())); } }; int main() { // Select the options we want to use. const option_set options = option_set::make<option::A>() | option_set::make<option::C>() ; // Make a visitor and visit the options. option_set_visitor visitor; visit(visitor, options); // Print the names of the selected options. std::cout << "Options given:\n"; for (auto const& name : visitor.result) { std::cout << " - " << name << '\n'; } }
22.681159
79
0.631949
friendlyanon
da223609230c4b427f3999b12afb8fe315af639f
8,366
cpp
C++
hackathon/MK/Deep_Learning_Handler/Deep_Learning_Handler_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/MK/Deep_Learning_Handler/Deep_Learning_Handler_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
hackathon/MK/Deep_Learning_Handler/Deep_Learning_Handler_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/* Deep_Learning_Handler_plugin.cpp * This is a test plugin, you can use it as a demo. * 2017-11-29 : by YourName */ #include "v3d_message.h" #include <vector> #include "Deep_Learning_Handler_plugin.h" #include <iostream> #include <qfileinfo.h> #include <qdir.h> #include <v3d_interface.h> #include <string> #include <basic_4dimage.h> using namespace std; Q_EXPORT_PLUGIN2(Deep_Learning_Handler, DL_Handler); QStringList DL_Handler::menulist() const { return QStringList() <<tr("menu1") <<tr("menu2") <<tr("about"); } QStringList DL_Handler::funclist() const { return QStringList() <<tr("func1") <<tr("func2") <<tr("help"); } void DL_Handler::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent) { if (menu_name == tr("menu1")) { v3d_msg("To be implemented."); } else if (menu_name == tr("menu2")) { v3d_msg("To be implemented."); } else { v3d_msg(tr("This is a test plugin, you can use it as a demo.. " "Developed by YourName, 2017-11-29")); } } bool DL_Handler::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent) { vector<char*> infiles, inparas, outfiles; if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); if (func_name == tr("imageCrop4CaffePredict")) { string deployFile = inparas.at(0); string trainedModel = inparas.at(1); string meanFile = inparas.at(2); string outputDir = infiles.at(1); QString curPath = QDir::currentPath(); QString patchPath = curPath + "/patches"; if (!QDir(patchPath).exists()) QDir().mkpath(patchPath); QString swcPath = curPath + "/SWCs"; if (!QDir(swcPath).exists()) QDir().mkpath(swcPath); unsigned char* ImgPtr = 0; V3DLONG in_sz[4]; int datatype; if (!simple_loadimage_wrapper(callback, infiles.at(0), ImgPtr, in_sz, datatype)) { cerr << "Error reading image file [" << infiles.at(0) << "]. Exit." << endl; return true; } int imgX = in_sz[0]; int imgY = in_sz[1]; int imgZ = in_sz[2]; int channel = in_sz[3]; int i_incres = imgX / 256; int j_incres = imgY / 256; qDebug() << i_incres << " " << j_incres; int zlb = 1; int zhb = imgZ; for (int j = 0; j < j_incres; ++j) { for (int i = 0; i < i_incres; ++i) { int xlb = 256 * i + 1; int xhb = 256 * (i+1); int ylb = 256 * j + 1; int yhb = 256 * (j+1); V3DLONG VOIsz = 256 * 256 * imgZ; unsigned char* VOIPtr = new unsigned char[VOIsz]; V3DLONG VOIxyz[4]; VOIxyz[0] = 256; VOIxyz[1] = 256; VOIxyz[2] = imgZ; VOIxyz[3] = in_sz[3]; this->cropStack(ImgPtr, VOIPtr, xlb, xhb, ylb, yhb, 1, zhb, imgX, imgY, imgZ); QString outimg_file = patchPath + QString("/x%1_y%2.v3draw").arg(xlb-1).arg(ylb-1); char* filenameNew = const_cast<char *>(outimg_file.toStdString().c_str()); string filename = outimg_file.toStdString(); qDebug() << VOIPtr[40000] << " " << outimg_file << endl; const char* filenameptr = filename.c_str(); /*Image4DSimple* patch; patch->setDatatype(V3D_UINT8); patch->setXDim(256); patch->setYDim(256); patch->setZDim(imgZ); patch->setCDim(1); patch->setTDim(1); patch->setNewRawDataPointer(VOIPtr); patch->saveImage(filenameNew);*/ simple_saveimage_wrapper(callback, filenameptr, VOIPtr, VOIxyz, 1); //qDebug() << VOIPtr[40000] << " " << outimg_file << endl; delete[] VOIPtr; } } QString m_InputfolderName = patchPath; QStringList imgList = importSeriesFileList_addnumbersort(m_InputfolderName); cout << "patch number: " << imgList.size() << endl; for (QStringList::iterator imgIt=imgList.begin(); imgIt!=imgList.end(); ++imgIt) { QStringList imgNameparse = (*imgIt).split("/"); QString name1 = *(imgNameparse.end()-1); QStringList name1parse = name1.split("."); QString name = name1parse[0]; QString indiSWCPath = swcPath + "/" + name; if (!QDir(indiSWCPath).exists()) QDir().mkpath(indiSWCPath); string fileFullName = (*imgIt).toStdString(); string command = "vaa3d -x prediction_caffe -f 3D_Axon_detection_raw -i "; command = command + fileFullName + " -p "; command = command + deployFile + " " + trainedModel + " " + meanFile + " 4 128 -o " + indiSWCPath.toStdString() + "/traced.swc"; cout << command << endl; const char* command_cStr = command.c_str(); system(command_cStr); } NeuronTree newTree; QString SWCsPath = swcPath; QDir dir(SWCsPath); foreach (QString folderName, dir.entryList(QDir::AllDirs)) { if (folderName == "." || folderName == "..") continue; QString tileSWCPath = swcPath + "/" + folderName + "/traced.swc_0.9.swc"; QStringList tileNameParse = folderName.split("_"); QStringList xParse = tileNameParse[0].split("x"); QStringList yParse = tileNameParse[1].split("y"); float xLoc = xParse[1].toFloat(); float yLoc = yParse[1].toFloat(); //cout << xLoc << " " << yLoc << endl; const char* tileSWCCString = tileSWCPath.toStdString().c_str(); NeuronTree nt = readSWC_file(tileSWCCString); newTree.listNeuron.push_back(nt.listNeuron.at(0)); for (QList<NeuronSWC>::iterator it=nt.listNeuron.begin()+1; it!=nt.listNeuron.end(); ++it) { bool flag = false; for (int newi=0; newi<newTree.listNeuron.size(); ++newi) { float adX = it->x + xLoc; float adY = it->y + yLoc; if (adX==newTree.listNeuron[newi].x && adY==newTree.listNeuron[newi].y && it->z==newTree.listNeuron[newi].z) { //cout << it->x << " " << it->y << " " << it->z << " "; //cout << newTree.listNeuron[newi].x << " " << newTree.listNeuron[newi].y << " " << newTree.listNeuron[newi].z << endl; flag = true; break; } } //cout << "===================" << endl; /*for (QList<NeuronSWC>::iterator newIt=newTree.listNeuron.begin(); newIt!=newTree.listNeuron.end(); ++newIt) { if (it->x==newIt->x && it->y==newIt->y && it->z==newIt->z) { flag = true; break; } }*/ if (flag == true) continue; else { NeuronSWC newNode; newNode.x = it->x + xLoc; newNode.y = it->y + yLoc; newNode.z = it->z; newNode.type = it->type; newNode.n = it->n; newNode.parent = it->parent; newTree.listNeuron.push_back(newNode); } } } QString saveSWCName = SWCsPath + "/combined.swc"; const char* saveSWCNameCString = saveSWCName.toStdString().c_str(); writeSWC_file(saveSWCName, newTree); return true; } else if (func_name == tr("func2")) { v3d_msg("To be implemented."); } else if (func_name == tr("help")) { v3d_msg("To be implemented."); } else return false; return true; }
37.348214
159
0.51267
zzhmark
da24fdf648a483e505b23713c32ba5fca72e66bd
800
cpp
C++
MirageENGiNE_Engine/src/util/txtfile.cpp
Harha/MirageEngine
6d0634385f514bbfce08cfacc8d743ce78c461fc
[ "MIT" ]
1
2017-05-27T23:23:28.000Z
2017-05-27T23:23:28.000Z
MirageENGiNE_Engine/src/util/txtfile.cpp
Harha/MirageEngine
6d0634385f514bbfce08cfacc8d743ce78c461fc
[ "MIT" ]
null
null
null
MirageENGiNE_Engine/src/util/txtfile.cpp
Harha/MirageEngine
6d0634385f514bbfce08cfacc8d743ce78c461fc
[ "MIT" ]
null
null
null
#include "txtfile.h" // std includes #include <fstream> // mirage includes #include "macros.h" #include "strutil.h" namespace mirage { TxtFile::TxtFile(const std::string & filePath) : m_filePath(filePath), m_lines() { // Read the file into memory std::ifstream file(m_filePath); if (file.is_open() == false) { MLOG_ERROR("TxtFile::TxtFile, error loading file (%s) into memory.", m_filePath.c_str()); return; } std::string line; while (std::getline(file, line)) { m_lines.push_back(line); } MLOG_DEBUG("TxtFile::TxtFile, loaded file (%s) into memory. Lines: %zu", m_filePath.c_str(), m_lines.size()); } const std::string TxtFile::getFilePath() const { return m_filePath; } std::vector<std::string> TxtFile::getLines() const { return m_lines; } }
17.777778
111
0.66625
Harha
da25843555203655458f0226be20436cd630a792
32,935
hpp
C++
include/Crafterra/Terrain/FieldMap.hpp
AsPJT/CrafterraProterozoic
d0531d2052b1bb5c10b6763f74034e6e3c678d1f
[ "CC0-1.0" ]
null
null
null
include/Crafterra/Terrain/FieldMap.hpp
AsPJT/CrafterraProterozoic
d0531d2052b1bb5c10b6763f74034e6e3c678d1f
[ "CC0-1.0" ]
null
null
null
include/Crafterra/Terrain/FieldMap.hpp
AsPJT/CrafterraProterozoic
d0531d2052b1bb5c10b6763f74034e6e3c678d1f
[ "CC0-1.0" ]
null
null
null
/*########################################################################################## Crafterra Library 🌏 [Planning and Production] 2017-2022 Kasugaccho 2018-2022 As Project [Contact Us] wanotaitei@gmail.com https://github.com/AsPJT/Crafterra [License] Distributed under the CC0 1.0. https://creativecommons.org/publicdomain/zero/1.0/ ##########################################################################################*/ #ifndef INCLUDED_CRAFTERRA_LIBRARY_CRAFTERRA_TERRAIN_FIELD_MAP_HPP #define INCLUDED_CRAFTERRA_LIBRARY_CRAFTERRA_TERRAIN_FIELD_MAP_HPP #include <Crafterra/Terrain/TerrainInformation.hpp> #include <AsLib2/DataType/ArrayDataType.hpp> #include <Crafterra/Terrain/MapChip.hpp> #include <AsLib2/DataType/PrimitiveDataType.hpp> #include <Crafterra/DataType/CrafterraPrimitiveDataType.hpp> #include <memory> #include <Crafterra/Macro/New.hpp> // CRAFTERRA_NEW #include <Crafterra/Terrain/TileConnection.hpp> // パーリンノイズ #include <Crafterra/TerrainGeneration/PerlinNoise2D.hpp> // パーリンノイズをフィールドマップ上に生成 #include <Crafterra/TerrainGeneration/TerrainPerlinNoise.hpp> namespace Crafterra { unsigned int getDxColor(const int r_, const int g_, const int b_) { return (r_ * 256 + g_) * 256 + b_; } class XorShift32 { private: ::As::Uint32 seed; public: ::As::Uint32 getRand() { seed ^= seed << 13; seed ^= seed >> 17; seed ^= seed << 5; return seed; } double getRand2() { return double(getRand() - 1) / 4294967295.0; } bool getProbability(const double probability_) { return (probability_ > getRand2()); } As::Int32 getProbabilityDivision(const double probability_, const As::Int32 division_) { if (probability_ <= getRand2() || division_ <= 0) return -1; return As::Int32(getRand2() / probability_ * double(division_)); } void setSeed(const ::As::Uint32 seed_) { seed = seed_; } XorShift32(const ::As::Uint32 seed_) : seed(seed_) {} }; class Terrain { // 暫定的なマップデータ using MapMat = ::As::UniquePtrMatrix<::Crafterra::TerrainInformation>; using ObjectMapMat = ::As::UniquePtrMatrix4D<TerrainObject>; using DrawMapMat = ::As::UniquePtrMatrix<DrawMapChip>; using shape_t = ElevationUint; public: // 描画マップの描画範囲を作成 void setDrawRange(DrawMapMat& draw_map_matrix) const { // 崖上のバイオームオートタイルを調べる #ifdef _OPENMP #pragma omp parallel for for (::As::Int64 col{}; col < ::As::Int64(draw_map_matrix.getWidth()); ++col) #else for (::As::IndexUint col{}; col < draw_map_matrix.getWidth(); ++col) #endif for (::As::IndexUint row{}; row < draw_map_matrix.getDepth(); ++row) for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { DrawMapChipUnit& draw_map = draw_map_matrix[row][col].getTile(layer); draw_map.setIsBiomeCliffTop(isBiomeCliff(draw_map.getBiomeAutoTile(), draw_map)); } } // 描画マップのオートタイルの接続を計算する void setDrawAutoTileConnection(DrawMapMat& draw_map_matrix) const { // 崖のオートタイルを計算 for (::As::IndexUint col{ 1 }; col < draw_map_matrix.getWidth() - 1; ++col) for (::As::IndexUint row{}; row < draw_map_matrix.getDepth() - 1; ++row) for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { DrawMapChipUnit& draw_map_tile = draw_map_matrix[row][col].getTile(layer); if (draw_map_tile.getTerrainObject() != TerrainObject::cliff) continue; // 崖じゃなかったら返す bool is_left = true; bool is_right = true; bool is_down = true; for (::As::IndexUint layer2 = 0; layer2 < draw_map_layer_max; ++layer2) { const DrawMapChipUnit& left_tile = draw_map_matrix[row][col - 1].cgetTile(layer2); const DrawMapChipUnit& right_tile = draw_map_matrix[row][col + 1].cgetTile(layer2); const DrawMapChipUnit& down_tile = draw_map_matrix[row + 1][col].cgetTile(layer2); if (is_left) is_left = (left_tile.getIsCliff() || ((!left_tile.getIsCliff()) && draw_map_tile.getElevation() < left_tile.getElevation())); if (is_right) is_right = (right_tile.getIsCliff() || ((!right_tile.getIsCliff()) && draw_map_tile.getElevation() < right_tile.getElevation())); if (is_down) is_down = (down_tile.getIsCliff()); } draw_map_tile.setCliff( getHomogeneousConnectionCliff( is_left , is_right , is_down ) ); } for (::As::IndexUint col{ 1 }; col < draw_map_matrix.getWidth() - 1; ++col) for (::As::IndexUint row{ 1 }; row < draw_map_matrix.getDepth() - 1; ++row) { for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { DrawMapChipUnit& draw_map_tile = draw_map_matrix[row][col].getTile(layer); if (draw_map_tile.getIsCliff()) continue; bool is_cliff_top_up = false; bool is_cliff_top_left = false; bool is_cliff_top_right = false; bool is_cliff_top_down = false; bool is_cliff_top_upper_left = false; bool is_cliff_top_upper_right = false; bool is_cliff_top_lower_left = false; bool is_cliff_top_lower_right = false; bool is_biome_auto_tile_up = false; bool is_biome_auto_tile_left = false; bool is_biome_auto_tile_right = false; bool is_biome_auto_tile_down = false; bool is_biome_auto_tile_upper_left = false; bool is_biome_auto_tile_upper_right = false; bool is_biome_auto_tile_lower_left = false; bool is_biome_auto_tile_lower_right = false; bool is_auto_tile_up = false; bool is_auto_tile_left = false; bool is_auto_tile_right = false; bool is_auto_tile_down = false; bool is_auto_tile_upper_left = false; bool is_auto_tile_upper_right = false; bool is_auto_tile_lower_left = false; bool is_auto_tile_lower_right = false; const ElevationUint center_elevation = draw_map_matrix[row][col].getTile(layer).getElevation(); for (::As::IndexUint layer2 = 0; layer2 < draw_map_layer_max; ++layer2) { const ElevationUint up_elevation = draw_map_matrix[row - 1][col].getTile(layer2).getElevation(); const ElevationUint left_elevation = draw_map_matrix[row][col - 1].getTile(layer2).getElevation(); const ElevationUint right_elevation = draw_map_matrix[row][col + 1].getTile(layer2).getElevation(); const ElevationUint down_elevation = draw_map_matrix[row + 1][col].getTile(layer2).getElevation(); const ElevationUint upper_left_elevation = draw_map_matrix[row - 1][col - 1].getTile(layer2).getElevation(); const ElevationUint upper_right_elevation = draw_map_matrix[row - 1][col + 1].getTile(layer2).getElevation(); const ElevationUint lower_left_elevation = draw_map_matrix[row + 1][col - 1].getTile(layer2).getElevation(); const ElevationUint lower_right_elevation = draw_map_matrix[row + 1][col + 1].getTile(layer2).getElevation(); if (!is_cliff_top_up) is_cliff_top_up = (center_elevation == up_elevation); if (!is_cliff_top_left) is_cliff_top_left = (center_elevation == left_elevation); if (!is_cliff_top_right) is_cliff_top_right = (center_elevation == right_elevation); if (!is_cliff_top_down) is_cliff_top_down = (center_elevation == down_elevation); if (!is_cliff_top_upper_left) is_cliff_top_upper_left = (center_elevation == upper_left_elevation); if (!is_cliff_top_upper_right) is_cliff_top_upper_right = (center_elevation == upper_right_elevation); if (!is_cliff_top_lower_left) is_cliff_top_lower_left = (center_elevation == lower_left_elevation); if (!is_cliff_top_lower_right) is_cliff_top_lower_right = (center_elevation == lower_right_elevation); if (!is_biome_auto_tile_up) is_biome_auto_tile_up = draw_map_matrix[row - 1][col].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row - 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_left) is_biome_auto_tile_left = draw_map_matrix[row][col - 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col - 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_right) is_biome_auto_tile_right = draw_map_matrix[row][col + 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col + 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_down) is_biome_auto_tile_down = draw_map_matrix[row + 1][col].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row + 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_upper_left) is_biome_auto_tile_upper_left = draw_map_matrix[row - 1][col - 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row - 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col - 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_upper_right) is_biome_auto_tile_upper_right = draw_map_matrix[row - 1][col + 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row - 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col + 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_lower_left) is_biome_auto_tile_lower_left = draw_map_matrix[row + 1][col - 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row + 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col - 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_lower_right) is_biome_auto_tile_lower_right = draw_map_matrix[row + 1][col + 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row + 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col + 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_up) is_auto_tile_up = draw_map_matrix[row - 1][col].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row - 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col].getTile(layer2).getIsCliff()); if (!is_auto_tile_left) is_auto_tile_left = draw_map_matrix[row][col - 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col - 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_right) is_auto_tile_right = draw_map_matrix[row][col + 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col + 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_down) is_auto_tile_down = draw_map_matrix[row + 1][col].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row + 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col].getTile(layer2).getIsCliff()); if (!is_auto_tile_upper_left) is_auto_tile_upper_left = draw_map_matrix[row - 1][col - 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row - 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col - 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_upper_right) is_auto_tile_upper_right = draw_map_matrix[row - 1][col + 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row - 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col + 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_lower_left) is_auto_tile_lower_left = draw_map_matrix[row + 1][col - 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row + 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col - 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_lower_right) is_auto_tile_lower_right = draw_map_matrix[row + 1][col + 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row + 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col + 1].getTile(layer2).getIsCliff()); } // 崖上のオートタイルを計算 ( 一部バグがあり、未完成 ) draw_map_matrix[row][col].getTile(layer).setCliffTop( getHomogeneousConnection( is_cliff_top_up , is_cliff_top_left , is_cliff_top_right , is_cliff_top_down , is_cliff_top_upper_left , is_cliff_top_upper_right , is_cliff_top_lower_left , is_cliff_top_lower_right ) ); // ウディタ規格オートタイルの計算 // 同質接続の条件:同じバイオーム&同じ標高&崖ではない draw_map_tile.setBiomeAutoTile( getHomogeneousConnectionAutoTile( is_biome_auto_tile_up , is_biome_auto_tile_left , is_biome_auto_tile_right , is_biome_auto_tile_down , is_biome_auto_tile_upper_left , is_biome_auto_tile_upper_right , is_biome_auto_tile_lower_left , is_biome_auto_tile_lower_right ) ); // ウディタ規格オートタイルの計算 // 同質接続の条件:同じバイオーム&同じ標高&崖ではない draw_map_tile.setAutoTile( getHomogeneousConnectionAutoTile( is_auto_tile_up , is_auto_tile_left , is_auto_tile_right , is_auto_tile_down , is_auto_tile_upper_left , is_auto_tile_upper_right , is_auto_tile_lower_left , is_auto_tile_lower_right ) ); } } } // 地形から描画マップを作成 void setDrawMapFromTerrain(ObjectMapMat& terrain_object_matrix, const MapMat& terrain_information_matrix, DrawMapMat& draw_map_matrix, const ::As::IndexUint start_x_, const ::As::IndexUint start_z_, const ::As::IndexUint width_, const ::As::IndexUint depth_) const { for (::As::IndexUint row{ start_z_ }, mat_index{}; row < depth_; ++row) { for (::As::IndexUint col{ start_x_ }; col < width_; ++col, ++mat_index) { const ::As::IndexUint index_zx = terrain_object_matrix.getIndexMulZX(mat_index); const TerrainInformation& terrain_info = terrain_information_matrix[row][col]; DrawMapChip& draw_map = draw_map_matrix[row][col]; draw_map.setTileNum(0); draw_map.clearTile(); for (::As::Int64 layer{}; layer < ::As::Int64(draw_map_layer_max); ++layer) draw_map.getTile(::As::IndexUint(layer)).setElevation(0); // 初期化 for (::As::IndexUint row3{ ::As::IndexUint(row) }, terrain_obj_index{}; terrain_obj_index < terrain_object_matrix.getHeight(); --row3, ++terrain_obj_index) { const ::As::IndexUint index_zxy = terrain_object_matrix.getIndexMulZXY(index_zx, terrain_obj_index); for (::As::IndexUint terrain_obj_layer_index = 0; terrain_obj_layer_index < terrain_object_matrix.getLayer(); ++terrain_obj_layer_index) { const TerrainObject terrain_obj = terrain_object_matrix.getValueZXYL(index_zxy + ::As::IndexUint(terrain_obj_layer_index)); if (terrain_obj != TerrainObject::empty) { DrawMapChip& draw_map_2 = draw_map_matrix[row3][col]; draw_map_2.setNextTile(); draw_map_2.setIsCliff(terrain_obj == TerrainObject::cliff); // どこが崖になっているか調べる draw_map_2.setIsCliffTop(terrain_obj_index == ::As::IndexUint(terrain_info.getBlockElevation())); // どこが崖上になっているか調べる draw_map_2.setTerrainObject(terrain_obj); // ブロックを格納 draw_map_2.setX(col); draw_map_2.setY(terrain_obj_index); draw_map_2.setZ(row); if (ElevationUint(terrain_obj_index) <= terrain_info.getBlockElevation()) { if (draw_map_2.getTile().getElevation() < ElevationUint(terrain_obj_index)) draw_map_2.setElevation(ElevationUint(terrain_obj_index)); } } } if (row3 == 0) break; } const As::Int32 row2 = As::Int32(row) - As::Int32(terrain_info.getBlockElevation()); if (row2 >= 0) { for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { draw_map_matrix[row2][col].getTile(layer).setDrawBiome(terrain_info.getBiome()); } } } } } // フィールドマップの下半分の地形が上半分へ移動する void moveUp(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_height_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(field_height_half_); ++row) for (::As::Int32 col{}; col < ::As::Int32(terrain_information_matrix.getWidth()); ++col) { #else for (::As::IndexUint row{}; row < field_height_half_; ++row) for (::As::IndexUint col{}; col < terrain_information_matrix.getWidth(); ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row + field_height_half_, col); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row][col]; const TerrainInformation& field_map_before = terrain_information_matrix[row + field_height_half_][col]; field_map_after = field_map_before; } } // フィールドマップの上半分の地形が下半分へ移動する void moveDown(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_height_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(field_height_half_); ++row) for (::As::Int32 col{}; col < ::As::Int32(terrain_information_matrix.getWidth()); ++col) { #else for (::As::IndexUint row{}; row < field_height_half_; ++row) for (::As::IndexUint col{}; col < terrain_information_matrix.getWidth(); ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row + field_height_half_, col); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row + field_height_half_][col]; const TerrainInformation& field_map_before = terrain_information_matrix[row][col]; field_map_after = field_map_before; } } // フィールドマップの右半分の地形が左半分へ移動する void moveLeft(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_width_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(terrain_information_matrix.getDepth()); ++row) for (::As::Int32 col{}; col < ::As::Int32(field_width_half_); ++col) { #else for (::As::IndexUint row{}; row < terrain_information_matrix.getDepth(); ++row) for (::As::IndexUint col{}; col < field_width_half_; ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col + field_width_half_); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row][col]; const TerrainInformation& field_map_before = terrain_information_matrix[row][col + field_width_half_]; field_map_after = field_map_before; } } // フィールドマップの左半分の地形が右半分へ移動する void moveRight(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_width_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(terrain_information_matrix.getDepth()); ++row) for (::As::Int32 col{}; col < ::As::Int32(field_width_half_); ++col) { #else for (::As::IndexUint row{}; row < terrain_information_matrix.getDepth(); ++row) for (::As::IndexUint col{}; col < field_width_half_; ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col + field_width_half_); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row][col + field_width_half_]; const TerrainInformation& field_map_before = terrain_information_matrix[row][col]; field_map_after = field_map_before; } } // フィールドマップの左半分の地形が右半分へ移動する void moveRightDraw(DrawMapMat& draw_map_matrix, const ::As::IndexUint field_width_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(draw_map_matrix.getDepth()); ++row) for (::As::Int32 col{}; col < ::As::Int32(field_width_half_); ++col) { #else for (::As::IndexUint row{}; row < draw_map_matrix.getDepth(); ++row) for (::As::IndexUint col{}; col < field_width_half_; ++col) { #endif DrawMapChip& field_map_after = draw_map_matrix[row][col + field_width_half_]; const DrawMapChip& field_map_before = draw_map_matrix[row][col]; field_map_after = field_map_before; } } // 木の生成 void generationTree(ObjectMapMat& terrain_object_matrix, const ::As::IndexUint bo_index_2d, TerrainInformation& field_map) const { const ElevationUint temperature = field_map.getTemperature(); const ElevationUint elevation = field_map.getElevation(); const ElevationUint block_elevation = elevation / 2; const ElevationUint amount_of_rainfall = field_map.getAmountOfRainfall(); const ::As::Uint32 flower_num = 9; const double flower_probability = 0.02; const double default_max = (flower_probability * flower_num); double coniferous_tree_generation_probability = 0.0; // 針葉樹の生成確率 double green_broadleaf_tree_generation_probability = 0.0; // 緑色の広葉樹の生成確率 double yellow_green_broadleaf_tree_generation_probability = 0.0; // 黄緑色の広葉樹の生成確率 if (amount_of_rainfall >= 100 && temperature >= 20) { if (temperature < 44) { coniferous_tree_generation_probability = ((temperature - 20.0) / (44.0 - 20.0)) * 0.3; // 針葉樹の生成確率 } else if (temperature < 64) { coniferous_tree_generation_probability = (1.0 - ((temperature - 44.0) / (64.0 - 44.0))) * 0.3; // 針葉樹の生成確率 } if (temperature >= 44) { if (temperature < 72) { green_broadleaf_tree_generation_probability = ((temperature - 44.0) / (72.0 - 44.0)) * 0.1; // 緑色の広葉樹の生成確率 } else { green_broadleaf_tree_generation_probability = 0.1 + ((temperature - 72.0) / (240.0 - 72.0)) * 0.6; // 緑色の広葉樹の生成確率 } } } // 生成される確率 const double probability_of_generation = (default_max + coniferous_tree_generation_probability + green_broadleaf_tree_generation_probability + yellow_green_broadleaf_tree_generation_probability); // 生成されない確率 const double probability_of_no_generation = (1.0 - probability_of_generation); double probability = field_map.getFlower(); //if (probability == 0.0) { // field_map.setBlock(TerrainObject::red_broadleaf_tree_down, block_elevation); // テスト // return; //} //if (probability == 1.0) { // field_map.setBlock(TerrainObject::red_broadleaf_tree_up, block_elevation); // テスト // return; //} if (probability < probability_of_no_generation) return; probability -= probability_of_no_generation; ::As::IndexUint block_layer_index = 0; for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { if (TerrainObject::empty == terrain_object_matrix.getValueMulZXYL(bo_index_2d, block_elevation, layer)) { block_layer_index = layer; break; } } // 草花の生成テスト if (probability < flower_probability) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_1, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 2)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_2, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 3)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_3, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 4)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_4, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 5)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_1, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 6)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_2, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 7)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_3, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 8)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_4, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < default_max) { terrain_object_matrix.setValueMulZXYL(TerrainObject::cultivated_land, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::planted_carrot, bo_index_2d, block_elevation, block_layer_index + 1); return; } else if (probability < (default_max + coniferous_tree_generation_probability)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::green_coniferous_tree_down, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::green_coniferous_tree_up, bo_index_2d, block_elevation + 1, block_layer_index); return; } else if (probability < (default_max + coniferous_tree_generation_probability + green_broadleaf_tree_generation_probability)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::green_broadleaf_tree_down, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::green_broadleaf_tree_up, bo_index_2d, block_elevation + 1, block_layer_index); return; } else if (probability < (default_max + coniferous_tree_generation_probability + green_broadleaf_tree_generation_probability + yellow_green_broadleaf_tree_generation_probability)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::yellow_green_broadleaf_tree_down, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::yellow_green_broadleaf_tree_up, bo_index_2d, block_elevation + 1, block_layer_index); return; } } // フィールドマップを生成 void generation(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, TerrainPerlinNoise& terrain_noise_, const ::As::IndexUint chunk_index_x_, const ::As::IndexUint chunk_index_y_, const ::As::IndexAreaXZ& area) const { constexpr ElevationUint sea_elevation = ElevationUint(::Crafterra::getElevationOfSeaLevel()); terrain_noise_.generation(terrain_information_matrix, chunk_index_x_, chunk_index_y_, area); XorShift32 xs32(terrain_noise_.getElevationSeed()); const ::As::IndexUint end_x_ = area.start_x + area.width; const ::As::IndexUint end_y_ = area.start_z + area.depth; //バイオームの分類分け #ifdef _OPENMP #pragma omp parallel for for (::As::Int64 row{ ::As::Int64(area.start_z) }; row < ::As::Int64(end_y_); ++row) for (::As::Int64 col{ ::As::Int64(area.start_x) }; col < ::As::Int64(end_x_); ++col) { #else for (::As::IndexUint row{ area.start_z }; row < end_y_; ++row) for (::As::IndexUint col{ area.start_x }; col < end_x_; ++col) { #endif const ::As::IndexUint bo_index_2d = terrain_object_matrix.getIndexMulZX(::As::IndexUint(row), ::As::IndexUint(col)); TerrainInformation& field_map = terrain_information_matrix[::As::IndexUint(row)][::As::IndexUint(col)]; const ElevationUint elevation = field_map.getElevation(); const ElevationUint block_elevation = elevation / 2; const ElevationUint amount_of_rainfall = field_map.getAmountOfRainfall(); const ElevationUint temperature = ((field_map.getTemperature() < block_elevation) ? 0 : (field_map.getTemperature() - block_elevation)); field_map.setTemperature(temperature); // 標高がある定数値よりも少ない場合は海になる if (elevation <= sea_elevation) field_map.setBiome(TerrainBiome::sea); // 気温が低い場合はツンドラになる else if (temperature < 24) field_map.setBiome(TerrainBiome::tundra); // 降水量が少ない場合は砂漠になる else if (amount_of_rainfall < 24) field_map.setBiome(TerrainBiome::desert); else if (amount_of_rainfall < 72) { if (temperature < 128) field_map.setBiome(TerrainBiome::rock); // ステップ? else field_map.setBiome(TerrainBiome::savannah); } else if (temperature < 69) field_map.setBiome(TerrainBiome::forest); // grass else if (temperature < 96) field_map.setBiome(TerrainBiome::normal); else if (temperature < 120) field_map.setBiome(TerrainBiome::forest); else if (amount_of_rainfall < 125) field_map.setBiome(TerrainBiome::mountain); else if (temperature < 132) field_map.setBiome(TerrainBiome::mountain); else field_map.setBiome(TerrainBiome::mountain); const ::As::IndexUint block_layer_index = 0; // ブロックを初期化 for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) { const ::As::IndexUint bo_index_3d = terrain_object_matrix.getIndexMulZXY(bo_index_2d, i); if (i < block_elevation) { terrain_object_matrix.setValueMulZXYL(TerrainObject::cliff, bo_index_3d, block_layer_index); // 崖 for (As::IndexUint layer = block_layer_index + 1; layer < terrain_object_matrix.getLayer(); ++layer) { terrain_object_matrix.setValueMulZXYL(TerrainObject::empty, bo_index_3d, layer); // から } } else for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { terrain_object_matrix.setValueMulZXYL(TerrainObject::empty, bo_index_3d, layer); // からの場合 ( 崖上を除く ) } } terrain_object_matrix.setValueMulZXYL(TerrainObject::cliff_top, bo_index_2d, block_elevation, block_layer_index); // からだけど崖上の場合 // 海 if (field_map.getBiome() == TerrainBiome::sea) { field_map.setElevation(sea_elevation); field_map.setBlockElevation(sea_elevation / 2); for (As::IndexUint i = block_elevation; i <= sea_elevation / 2; ++i) { terrain_object_matrix.setValueMulZXYL(TerrainObject::cliff_top, bo_index_2d, i, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::sea, bo_index_2d, i, block_layer_index + 1); } } // 陸 else { field_map.setBlockElevation(block_elevation); this->generationTree(terrain_object_matrix, bo_index_2d, field_map); // 木の生成 } } } void initialGeneration(ObjectMapMat& terrain_object_matrix, MapMat& field_map_matrix_, TerrainPerlinNoise& terrain_noise_, const TerrainChunk& chunk) const { generation(terrain_object_matrix, field_map_matrix_, terrain_noise_, chunk.getX(), chunk.getZ(), ::As::IndexAreaXZ(0, 0, field_map_matrix_.getWidth(), field_map_matrix_.getDepth())); } }; } #endif //Included Crafterra Library
53.120968
343
0.717565
AsPJT
da25e8acda7ed97bfb7da32eb8ede58be0b2bb07
993
cpp
C++
pbinfo/anagrame-pfv/anagrame-pfv.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
1
2022-01-27T17:13:08.000Z
2022-01-27T17:13:08.000Z
pbinfo/anagrame-pfv/anagrame-pfv.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
null
null
null
pbinfo/anagrame-pfv/anagrame-pfv.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
null
null
null
#include <cstring> #include <iostream> char s[12]; char vocale[] = "aeiou"; int n, st[12], p[12]; void afis() { for (int i = 1; i <= n; ++i) { std::cout << s[st[i]]; } std::cout << '\n'; } bool valid(int k) { if (strchr("aeiou", s[st[k]]) && st[k] != k - 1) return false; return true; } void bkt(int k) { for (int i = 0; i < n; ++i) { if (!p[i]) { st[k] = i; p[i] = 1; if (valid(k)) { if (k == n) { afis(); } else { bkt(k + 1); } } p[i] = 0; } } } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cin >> s; n = strlen(s); for (int i = 0; i < n; ++i) { if (strchr(vocale, s[i]) == 0) { for (int j = i + 1; j < n; ++j) { if (strchr(vocale, s[j]) == 0) { if (s[i] > s[j]) { char aux = s[i]; s[i] = s[j]; s[j] = aux; } } } } } bkt(1); return 0; }
15.515625
64
0.380665
cristicretu
da2785de81a97e7d470bbcaa04b0d76c76b27def
216
cpp
C++
src/engine/network/NetAdr.cpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
1
2018-06-22T15:46:42.000Z
2018-06-22T15:46:42.000Z
src/engine/network/NetAdr.cpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
3
2018-05-13T14:15:53.000Z
2018-05-29T08:06:26.000Z
src/engine/network/NetAdr.cpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
null
null
null
#include "NetAdr.hpp" CNetAdr::CNetAdr() = default; CNetAdr::~CNetAdr() = default; bool CNetAdr::IsLocal() const { return false; // TODO }; INetAdr::Type CNetAdr::GetType() const { return INetAdr::Type::Temp; };
15.428571
38
0.680556
BlackPhrase
da2d7f858984a4d3bb09ca8e485fe1599bea7ded
3,568
cc
C++
tensorflow/contrib/lite/kernels/comparisons_test.cc
tucaiyong/tensorflow
3cc3c87f375f1bc292bd58db4928b810ac888bc6
[ "Apache-2.0" ]
14
2018-12-06T06:51:33.000Z
2021-03-23T11:29:24.000Z
tensorflow/contrib/lite/kernels/comparisons_test.cc
tucaiyong/tensorflow
3cc3c87f375f1bc292bd58db4928b810ac888bc6
[ "Apache-2.0" ]
10
2018-02-04T18:41:52.000Z
2018-05-02T09:00:46.000Z
tensorflow/contrib/lite/kernels/comparisons_test.cc
tucaiyong/tensorflow
3cc3c87f375f1bc292bd58db4928b810ac888bc6
[ "Apache-2.0" ]
4
2018-01-17T14:22:49.000Z
2018-02-27T15:06:41.000Z
/* Copyright 2018 The TensorFlow Authors. 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 <gtest/gtest.h> #include "tensorflow/contrib/lite/interpreter.h" #include "tensorflow/contrib/lite/kernels/register.h" #include "tensorflow/contrib/lite/kernels/test_util.h" #include "tensorflow/contrib/lite/model.h" namespace tflite { namespace { using ::testing::ElementsAreArray; class LessOpModel : public SingleOpModel { public: LessOpModel(std::initializer_list<int> input1_shape, std::initializer_list<int> input2_shape, TensorType input_type) { input1_ = AddInput(input_type); input2_ = AddInput(input_type); output_ = AddOutput(TensorType_BOOL); SetBuiltinOp(BuiltinOperator_LESS, BuiltinOptions_LessOptions, CreateLessOptions(builder_).Union()); BuildInterpreter({input1_shape, input2_shape}); } int input1() { return input1_; } int input2() { return input2_; } std::vector<bool> GetOutput() { return ExtractVector<bool>(output_); } std::vector<int> GetOutputShape() { return GetTensorShape(output_); } private: int input1_; int input2_; int output_; }; TEST(ArgMaxOpTest, LessFloat) { LessOpModel model({1, 1, 1, 4}, {1, 1, 1, 4}, TensorType_FLOAT32); model.PopulateTensor<float>(model.input1(), {0.1, 0.9, 0.7, 0.3}); model.PopulateTensor<float>(model.input2(), {0.1, 0.2, 0.6, 0.5}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({false, false, false, true})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 1, 4})); } TEST(ArgMaxOpTest, LessInt) { LessOpModel model({1, 1, 1, 4}, {1, 1, 1, 4}, TensorType_INT32); model.PopulateTensor<int>(model.input1(), {-1, 9, 7, 3}); model.PopulateTensor<int>(model.input2(), {1, 2, 6, 5}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({true, false, false, true})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 1, 4})); } TEST(ArgMaxOpTest, LessBroadcast) { LessOpModel model({1, 1, 1, 4}, {1, 1, 1, 1}, TensorType_INT32); model.PopulateTensor<int>(model.input1(), {-1, 9, 7, 3}); model.PopulateTensor<int>(model.input2(), {7}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({true, false, false, true})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 1, 4})); } TEST(ArgMaxOpTest, LessBroadcastTwoD) { LessOpModel model({1, 1, 2, 4}, {1, 1, 1, 4}, TensorType_INT32); model.PopulateTensor<int>(model.input1(), {-1, 9, 7, 3, 2, 4, 6, 8}); model.PopulateTensor<int>(model.input2(), {7, 1, 2, 4}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({true, false, false, true, true, false, false, false})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 2, 4})); } } // namespace } // namespace tflite int main(int argc, char** argv) { ::tflite::LogToStderr(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
36.040404
80
0.679933
tucaiyong
da2f05c8568cedef9b8239d008a65fe6d59c854b
13,126
cpp
C++
hmi/sweetie_bot_joint_trajectory_editor/src/joint_trajectory_data.cpp
sweetie-bot-project/sweetie_bot
f15f9cb01f2763d0b9d62624a400a01961609762
[ "BSD-3-Clause" ]
9
2019-08-11T17:40:11.000Z
2022-01-17T00:50:24.000Z
hmi/sweetie_bot_joint_trajectory_editor/src/joint_trajectory_data.cpp
sweetie-bot-project/sweetie_bot
f15f9cb01f2763d0b9d62624a400a01961609762
[ "BSD-3-Clause" ]
null
null
null
hmi/sweetie_bot_joint_trajectory_editor/src/joint_trajectory_data.cpp
sweetie-bot-project/sweetie_bot
f15f9cb01f2763d0b9d62624a400a01961609762
[ "BSD-3-Clause" ]
2
2019-12-23T05:06:34.000Z
2020-07-14T10:07:33.000Z
#include "joint_trajectory_data.h" #include <cmath> #include <functional> #include <exception> using namespace std; namespace sweetie_bot { namespace hmi { unsigned int JointTrajectoryData::crc(const std::vector<double>& positions) { size_t crc = 0; std::hash<double> hash_fn; for(auto it = positions.begin(); it != positions.end(); it++) crc ^= hash_fn(std::floor(*it * 100)); return crc; } void JointTrajectoryData::loadFromMsg(const FollowJointTrajectoryGoal& msg) { clear(); // get joints names for(unsigned int i = 0; i < msg.trajectory.joint_names.size(); i++) { const std::string& name = msg.trajectory.joint_names[i]; if (name.compare(0,8,"support/") == 0) { Support support; support.name = name.substr(8); support.index = i; // push it to supports list supports_.push_back(support); } else { // add joint Joint joint; joint.name = msg.trajectory.joint_names[i]; joint.path_tolerance = 0.0; joint.goal_tolerance = 0.0; joint.index = i; // push it to joint list joints_.push_back(joint); } } sort(joints_.begin(), joints_.end()); sort(supports_.begin(), supports_.end()); // check if all joints are unique if(std::unique(joints_.begin(), joints_.end()) != joints_.end()) { clear(); throw std::invalid_argument("Joints are not unique."); } if(std::unique(supports_.begin(), supports_.end()) != supports_.end()) { clear(); throw std::invalid_argument("Supports are not unique."); } // load trajectory points // because joints are rearanged by sort() we have to trajectory_points_.resize(msg.trajectory.points.size()); for(unsigned int k = 0; k < msg.trajectory.points.size(); ++k) { // get time trajectory_points_[k].time_from_start = msg.trajectory.points[k].time_from_start.toSec(); // check number of positions if (msg.trajectory.points[k].positions.size() != msg.trajectory.joint_names.size()) { clear(); throw std::invalid_argument("Inconsistent number of joints in FollowJointTrajectoryGoal message: trajectory.joint_names.size() != trajectory.points[k].positions.size(), k = " + std::to_string(k)); } // fill positions in proper order trajectory_points_[k].positions.resize(joints_.size()); for(unsigned int i = 0; i < joints_.size(); i++) { unsigned int old_index = joints_[i].index; trajectory_points_[k].positions[i] = msg.trajectory.points[k].positions[old_index]; } trajectory_points_[k].crc = crc(trajectory_points_[k].positions); // fill supports in proper oder trajectory_points_[k].supports.resize(supports_.size()); for(unsigned int i = 0; i < supports_.size(); i++) { unsigned int old_index = supports_[i].index; trajectory_points_[k].supports[i] = msg.trajectory.points[k].positions[old_index]; } // ignore velocities, accelerations and efforts } // fix joint induces for(unsigned int i = 0; i < joints_.size(); i++) joints_[i].index = i; for(unsigned int i = 0; i < supports_.size(); i++) supports_[i].index = i; // load path and goal tolerance (if present) // default values (zeros) are already present in joints_ structures. for(auto it = msg.path_tolerance.begin(); it != msg.path_tolerance.end(); it++) { // find joint name in joints_ using binary search auto joint = lower_bound(joints_.begin(), joints_.end(), it->name); if (joint != joints_.end() && joint->name == it->name) { // assign path tolerance joint->path_tolerance = it->position; } } for(auto it = msg.goal_tolerance.begin(); it != msg.goal_tolerance.end(); it++) { // find joint name in joints_ using binary search auto joint = lower_bound(joints_.begin(), joints_.end(), it->name); if (joint != joints_.end() && joint->name == it->name) { // assign path tolerance joint->goal_tolerance = it->position; // ignore velocity, acceleration and efforts } } // load time tolerance goal_time_tolerance_ = msg.goal_time_tolerance.toSec(); } control_msgs::FollowJointTrajectoryGoal JointTrajectoryData::getTrajectoryMsg(bool reverse, double scale) { FollowJointTrajectoryGoal msg; // set header msg.trajectory.header.stamp = ros::Time::now(); // set joints' names and tolerances for(auto it = joints_.begin(); it != joints_.end(); it++) { // joint_names msg.trajectory.joint_names.push_back(it->name); // tolerances msg.path_tolerance.emplace_back(); msg.path_tolerance.back().name = it->name; msg.path_tolerance.back().position = it->path_tolerance; msg.goal_tolerance.emplace_back(); msg.goal_tolerance.back().name = it->name; msg.goal_tolerance.back().position = it->goal_tolerance; } msg.goal_time_tolerance.fromSec( goal_time_tolerance_ ); // add supports for(auto it = supports_.begin(); it != supports_.end(); it++) { msg.trajectory.joint_names.push_back("support/" + it->name); } // Load trajectory into message. Do not set velocities, accelerations and efforts. if (!reverse) { for(auto it = trajectory_points_.begin(); it != trajectory_points_.end(); it++) { // add new point msg.trajectory.points.emplace_back(); JointTrajectoryPoint& point = msg.trajectory.points.back(); // set postions, ignore (leave empty) velocities, accelerations and efforts point.positions = it->positions; // set supports values point.positions.insert(point.positions.end(), it->supports.begin(), it->supports.end()); // set time point.time_from_start.fromSec(scale * it->time_from_start); } } else { if (!trajectory_points_.empty()) { double end_time = trajectory_points_.back().time_from_start; for(auto it = trajectory_points_.rbegin(); it != trajectory_points_.rend(); it++) { // add new point msg.trajectory.points.emplace_back(); JointTrajectoryPoint& point = msg.trajectory.points.back(); // set postions, ignore (leave empty) velocities, accelerations and efforts point.positions = it->positions; // set supports values auto next = it + 1; // they must be shifted in time if (next != trajectory_points_.rend()) point.positions.insert(point.positions.end(), next->supports.begin(), next->supports.end()); else point.positions.insert(point.positions.end(), it->supports.begin(), it->supports.end()); // set time point.time_from_start.fromSec( scale*(end_time - it->time_from_start) ); } } } return msg; } void JointTrajectoryData::clear() { joints_.clear(); supports_.clear(); trajectory_points_.clear(); goal_time_tolerance_ = 0.0; } bool JointTrajectoryData::addJoint(const string& name, double path_tolerance /* = 0.0 */, double goal_tolerance /* = 0.0 */) { auto it = lower_bound(joints_.begin(), joints_.end(), name); if (it != joints_.end() && it->name == name) { // joint already exists so only change tolerance it->path_tolerance = path_tolerance; it->goal_tolerance = goal_tolerance; return false; } // now add new joint AFTER lower bound auto new_joint = joints_.emplace(it); // call default constructor new_joint->name = name; new_joint->path_tolerance = path_tolerance; new_joint->goal_tolerance = goal_tolerance; new_joint->index = distance(joints_.begin(), new_joint); // modify indexes of last joints for(auto it = new_joint + 1; it != joints_.end(); it++) it->index++; // now insert position for(auto point = trajectory_points_.begin(); point != trajectory_points_.end(); point++) { point->positions.insert(point->positions.begin() + new_joint->index, 0.0); } return true; } void JointTrajectoryData::removeJoint(unsigned int index) { // check diapazone if (index >= joints_.size()) throw std::out_of_range("joint index"); // delete joint joints_.erase(joints_.begin() + index); // delete corresponding trajectory points for(auto point = trajectory_points_.begin(); point != trajectory_points_.end(); point++) { point->positions.erase(point->positions.begin() + index); } } int JointTrajectoryData::getJointIndex(const std::string& name) { //TODO exception? auto it = lower_bound(joints_.begin(), joints_.end(), name); if (it == joints_.end() || it->name != name) return -1; // joint not found return distance(joints_.begin(), it); } bool JointTrajectoryData::addSupport(const std::string& name) { auto it = lower_bound(supports_.begin(), supports_.end(), name); if (it != supports_.end() && it->name == name) { // support already exists return false; } // now add new support AFTER lower bound auto new_support = supports_.emplace(it); // call default constructor new_support->name = name; new_support->index = distance(supports_.begin(), new_support); // modify indexes of last supports for(auto it = new_support + 1; it != supports_.end(); it++) it->index++; // now insert position for(auto point = trajectory_points_.begin(); point != trajectory_points_.end(); point++) { point->supports.insert(point->supports.begin() + new_support->index, 0.0); } return true; } void JointTrajectoryData::removeSupport(unsigned int index) { // check diapazone if (index >= supports_.size()) throw std::out_of_range("support index"); // delete support supports_.erase(supports_.begin() + index); // delete corresponding trajectory points for(auto point = trajectory_points_.begin(); point != trajectory_points_.end(); point++) { point->supports.erase(point->supports.begin() + index); } } int JointTrajectoryData::getSupportIndex(const std::string& name) { //TODO exception? auto it = lower_bound(supports_.begin(), supports_.end(), name); if (it == supports_.end() || it->name != name) return -1; // support not found return distance(supports_.begin(), it); } void JointTrajectoryData::addPoint(const TrajectoryPoint& point) { if (point.positions.size() != joints_.size() || point.supports.size() != supports_.size()) throw std::invalid_argument("Position or support size is incorrect."); if (point.time_from_start < 0.0) throw std::invalid_argument("time_from_start must be nonegative."); // find appropriate place to insert new element auto it = upper_bound(trajectory_points_.begin(), trajectory_points_.end(), point.time_from_start, [](double t, const TrajectoryPoint& p) { return t < p.time_from_start; } ); // insert it it = trajectory_points_.insert(it, point); it->crc = crc(it->positions); } void JointTrajectoryData::addPointMsg(const sensor_msgs::JointState& msg, double time_from_start) { unsigned int n_joints = joints_.size(); // convert msg to TrajectoryPoint TrajectoryPoint point; point.time_from_start = time_from_start; point.positions.assign(n_joints, 0.0); // default values // now add position values from msg if (msg.name.size() != msg.position.size()) throw std::invalid_argument("JointState name and position sizes are not consistent."); for (int i = 0; i < n_joints; ++i) { auto it = find(msg.name.begin(), msg.name.end(), joints_[i].name); if (it != msg.name.end()) { int index = distance(msg.name.begin(), it); point.positions[i] = msg.position[index]; } } // add supports point.supports.assign(supports_.size(), 0.0); // add point return addPoint(point); } sensor_msgs::JointState JointTrajectoryData::getPointMsg(unsigned int index) { const TrajectoryPoint& point = getPoint(index); // construct message JointState msg; // header msg.header.stamp = ros::Time::now(); // name msg.name.reserve(joints_.size()); for (auto it = joints_.begin(); it != joints_.end(); it++) msg.name.push_back(it->name); // position msg.position = getPoint(index).positions; // do not set velocities and efforts return msg; } void JointTrajectoryData::setPointJointPosition(unsigned int index, unsigned int joint_index, double value) { TrajectoryPoint& point = trajectory_points_.at(index); point.positions.at(joint_index) = value; point.crc = crc(point.positions); } void JointTrajectoryData::setPointSupport(unsigned int index, unsigned int support_index, double value) { TrajectoryPoint& point = trajectory_points_.at(index); point.supports.at(support_index) = value; } void JointTrajectoryData::setPointTimeFromStart(unsigned int index, double time_from_start) { TrajectoryPoint& point = trajectory_points_.at(index); if (time_from_start < 0.0) return; // TODO exception? point.time_from_start = time_from_start; sort(trajectory_points_.begin(), trajectory_points_.end()); } void JointTrajectoryData::scaleTrajectory(double scale) { if (scale <= 0.0) return; for(auto it = trajectory_points_.begin(); it != trajectory_points_.end(); it++) { it->time_from_start *= scale; } } void JointTrajectoryData::removePoint(unsigned int index) { // check diapazone if (index >= trajectory_points_.size()) throw std::out_of_range("trajectory point index"); // delete joint trajectory_points_.erase(trajectory_points_.begin() + index); } void JointTrajectoryData::setPathTolerance(double path_tolerance) { for (auto it = joints_.begin(); it != joints_.end(); it++) it->path_tolerance = path_tolerance; } void JointTrajectoryData::setGoalTolerance(double goal_tolerance) { for (auto it = joints_.begin(); it != joints_.end(); it++) it->goal_tolerance = goal_tolerance; } } // namespace hmi } // namespace sweetie_bot
35.475676
199
0.707984
sweetie-bot-project
da2f0f734ad4a71704a2ff8b6a9a922fcd6df66f
4,459
cpp
C++
PGTProject/Source/PGTProject/Private/GameTickManager.cpp
dylanpiera/IVGT6
b5696222d53a0d3a8369b8c5eb9e35c03e8afab8
[ "MIT" ]
null
null
null
PGTProject/Source/PGTProject/Private/GameTickManager.cpp
dylanpiera/IVGT6
b5696222d53a0d3a8369b8c5eb9e35c03e8afab8
[ "MIT" ]
null
null
null
PGTProject/Source/PGTProject/Private/GameTickManager.cpp
dylanpiera/IVGT6
b5696222d53a0d3a8369b8c5eb9e35c03e8afab8
[ "MIT" ]
null
null
null
#include "GameTickManager.h" #include "Engine/World.h" #include "Engine/Engine.h" #include "ActiveState.h" #include "BuildingState.h" #include <iostream> #include "Utility.h" #include "Runtime/Engine/Classes/Kismet/GameplayStatics.h" // Sets default values AGameTickManager::AGameTickManager() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; currentHour = 0; currentDay = 0; dayOfWeek = 0; currentMonth = 0; currentYear = 2100; currentYearFirst = 2; currentYearSecond = 100; timer = 4.0f; timeMultiplier = 1; days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; dayName = days[currentDay]; monthName = months[currentMonth]; bCanTick = true; } // Called when the game starts or when spawned void AGameTickManager::BeginPlay() { Super::BeginPlay(); TArray<AActor*> FoundActors; UGameplayStatics::GetAllActorsOfClass(GetWorld(), AEconomyManager::StaticClass(), FoundActors); EconomyManager = Cast<AEconomyManager>(FoundActors[0]); EconomyManager->InitResources(); } // Called every frame void AGameTickManager::Tick(float DeltaTime) { Super::Tick(DeltaTime); GameTick(); if (Debug) { UE_LOG(LogTemp, Warning, TEXT("%d"), currentHour); UE_LOG(LogTemp, Warning, TEXT("%d"), dayOfWeek); UE_LOG(LogTemp, Warning, TEXT("%d"), currentDay); UE_LOG(LogTemp, Warning, TEXT("%d"), currentMonth); UE_LOG(LogTemp, Warning, TEXT("%d"), currentYear); } } void AGameTickManager::GameTick() { GameTickHour(); if (Debug) { UE_LOG(LogTemp, Warning, TEXT("Energy: %d"), EconomyManager->resources._energy); UE_LOG(LogTemp, Warning, TEXT("Minerals: %d"), EconomyManager->resources._minerals); UE_LOG(LogTemp, Warning, TEXT("Money: %d"), EconomyManager->resources._money); UE_LOG(LogTemp, Warning, TEXT("Population: %d"), EconomyManager->resources._population); } } //managed the hourly tick void AGameTickManager::GameTickHour() { UINT32 hourNow = currentHour; if (bCanTick) { bCanTick = false; hourNow++; //Starts the timer UE_LOG(LogTemp, Display, TEXT("%d"), hourNow); UE_LOG(LogTemp, Display, TEXT("%d"), currentHour); GetWorldTimerManager().SetTimer(GameTickTimerHandle, this, &AGameTickManager::ResetTimer, 0.005f, false); currentHour = hourNow; // if the day ends reset currentHour if(currentHour > 23) { GameTickDay(); currentHour = 0; } } } //This is where the magic should happen! //Manages the daily tick void AGameTickManager::GameTickDay() { // Update Resources EconomyManager->resources._population = 0; // Itterates through all buildings added to the building list for (UBuilding* building : EconomyManager->ActiveBuildings) { //Reflects BuildingStates to see what buildings are active and use Functions accordingly if (Utility::compare_ptrs<ActiveState, BuildingState>(building->GetState())) { building->BuildingFunction(EconomyManager->resources); } } if (EconomyManager->resources._population < 0) // can't have negative population { EconomyManager->resources._population = 0; } if (EconomyManager->resources._food < 0) // can't have negative food { EconomyManager->resources._food = 0; } if (EconomyManager->resources._money < 0) { EconomyManager->resources._money = 0; } dayOfWeek++; currentDay++; //keeps track on what day of the week it is if(dayOfWeek > 6) { dayOfWeek = 0; } dayName = days[dayOfWeek]; //keeps track of the day in the month and ticks when month is done. if(currentDay > 29) { GameTickMonth(); currentDay = 0; } } void AGameTickManager::GameTickMonth() { currentMonth++; //keeps track if a year in months has passed. if(currentMonth > 11) { GameTickYear(); currentMonth = 0; } monthName = months[currentMonth]; } //add years void AGameTickManager::GameTickYear() { currentYearSecond++; if (currentYearSecond > 999) { currentYearFirst++; currentYearSecond = 000; } } void AGameTickManager::ResetTimer() { bCanTick = true; GetWorldTimerManager().ClearTimer(GameTickTimerHandle); } //set multiplier to 1 void AGameTickManager::SetSpeedTimeOne() { timeMultiplier = 1; } //set multiplier to 2 void AGameTickManager::SetSpeedTimeTwo() { timeMultiplier = 2; } //set multiplier to 4 void AGameTickManager::SetSpeedTimeFour() { timeMultiplier = 4; }
22.634518
115
0.708679
dylanpiera
da3d9dc9ff9da2beb3fdccc4071f0cb40b44972f
1,846
cc
C++
lib/tensor/opdefs/tensor_shape.cc
cezheng/runtime
0866034bbc9bbe3ac513abf249edcaae13319909
[ "Apache-2.0" ]
2
2021-08-09T21:26:39.000Z
2021-11-17T10:57:43.000Z
lib/tensor/opdefs/tensor_shape.cc
cezheng/runtime
0866034bbc9bbe3ac513abf249edcaae13319909
[ "Apache-2.0" ]
null
null
null
lib/tensor/opdefs/tensor_shape.cc
cezheng/runtime
0866034bbc9bbe3ac513abf249edcaae13319909
[ "Apache-2.0" ]
1
2020-08-03T20:23:58.000Z
2020-08-03T20:23:58.000Z
// Copyright 2020 The TensorFlow Runtime Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //===- tensor_shape.cc ----------------------------------------------------===// // // This file implements MLIR operation functions for the tensor shape dialect. // //===----------------------------------------------------------------------===// #include "tfrt/tensor/opdefs/tensor_shape.h" #include "mlir/IR/Builders.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/StandardTypes.h" #include "mlir/IR/TypeUtilities.h" #include "tfrt/tensor/opdefs/tensor_shape.h" namespace tfrt { namespace ts { //===----------------------------------------------------------------------===// // TensorShape Dialect //===----------------------------------------------------------------------===// TensorShapeDialect::TensorShapeDialect(MLIRContext *context) : Dialect(/*name=*/"ts", context) { allowUnknownTypes(); addOperations< #define GET_OP_LIST #include "tfrt/tensor/opdefs/tensor_shape.cpp.inc" >(); } //===----------------------------------------------------------------------===// // TableGen'd op method definitions //===----------------------------------------------------------------------===// #define GET_OP_CLASSES #include "tfrt/tensor/opdefs/tensor_shape.cpp.inc" } // namespace ts } // namespace tfrt
34.185185
80
0.557421
cezheng
da4579210b5f46d2fa3acbed37d3cd2521540aec
882
cpp
C++
FrameWorkCode/eddis.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
1
2022-01-25T19:27:55.000Z
2022-01-25T19:27:55.000Z
FrameWorkCode/eddis.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
null
null
null
FrameWorkCode/eddis.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
null
null
null
#include <cassert> #include <string> #include <vector> #include "eddis.h" size_t eddis :: min(size_t x, size_t y, size_t z) { if (x < y) return x < z ? x : z; else return y < z ? y : z; } size_t eddis::editDist(const string& A, const string& B) { size_t NA = A.size(); size_t NB = B.size(); vector<vector<size_t>> M(NA + 1, vector<size_t>(NB + 1)); for (size_t a = 0; a <= NA; ++a) M[a][0] = a; for (size_t b = 0; b <= NB; ++b) M[0][b] = b; for (size_t a = 1; a <= NA; ++a) for (size_t b = 1; b <= NB; ++b) { size_t x = M[a-1][b] + 1; size_t y = M[a][b-1] + 1; size_t z = M[a-1][b-1] + (A[a-1] == B[b-1] ? 0 : 1); M[a][b] = min(x,y,z); } return M[A.size()][B.size()]; }
21
67
0.408163
ayushbits
da4620def666b28d1fe5f0079b55004008292c2e
2,704
cpp
C++
chapter_5_meta_programming/ex_1_type_traits.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
chapter_5_meta_programming/ex_1_type_traits.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
chapter_5_meta_programming/ex_1_type_traits.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
// // Created by Josh Levy-Kramer on 02/04/2020. // #include <iostream> #include <typeinfo> // ---- remove_reference // Overload for a normal type, type reference and rvalue type reference template <typename T> struct remove_reference { using type = T; }; template <typename T> struct remove_reference<T&> { using type = T; }; template <typename T> struct remove_reference<T&&> { using type = T; }; template <typename T> struct remove_reference<T*> { using type = T; }; // ---- add_reference template <typename T> struct add_reference { using type = T&; }; template <typename T> struct add_reference<T&> { using type = T&; }; template <typename T> struct add_reference<T&&> { using type = T&; }; template <typename T> struct add_reference<T*> { using type = T&; }; int main() { // -- remove_reference // Could use `using` syntax here. Taken from cpp reference typedef int&& rval_int; typedef remove_reference<int>::type A; typedef remove_reference<int&>::type B; typedef remove_reference<int&&>::type C; typedef remove_reference<rval_int>::type D; typedef remove_reference<int*>::type E; std::cout << std::boolalpha; std::cout << "typedefs of int:" << std::endl; std::cout << "A: " << std::is_same<int,A>::value << std::endl; std::cout << "B: " << std::is_same<int,B>::value << std::endl; std::cout << "C: " << std::is_same<int,C>::value << std::endl; std::cout << "D: " << std::is_same<int,D>::value << std::endl; std::cout << "E: " << std::is_same<int,E>::value << std::endl << std::endl; // All these are executed at compile time. Will throw error at compile time if not true static_assert(std::is_same<int,A>::value, ""); static_assert(std::is_same<int,B>::value, ""); static_assert(std::is_same<int,C>::value, ""); static_assert(std::is_same<int,D>::value, ""); static_assert(std::is_same<int,E>::value, ""); //static_assert(std::is_same<int,double>::value, ""); // does not compile // -- add_reference typedef add_reference<int>::type A2; // int& typedef add_reference<int&>::type B2; // int& typedef add_reference<int&&>::type C2; // int& typedef add_reference<int*>::type D2; // int*& std::cout << std::boolalpha; std::cout << "typedefs of int&:" << std::endl; //std::cout << "A: " << typeid(tst::trans(A2)).name() << std::endl; std::cout << "A: " << std::is_same<int&,A2>::value << std::endl; std::cout << "B: " << std::is_same<int&,B2>::value << std::endl; std::cout << "C: " << std::is_same<int&,C2>::value << std::endl; std::cout << "D: " << std::is_same<int&,D2>::value << std::endl; return 0; }
29.075269
91
0.610577
joshlk
da47bb180c38a09c8d2c906289d0f5daabb813e5
1,931
hpp
C++
include/ast/ExpressionTypeNode.hpp
aviralg/tastr
184e6324de86831c1e4162112d446f537ad8f50c
[ "Apache-2.0" ]
1
2021-03-25T04:05:35.000Z
2021-03-25T04:05:35.000Z
include/ast/ExpressionTypeNode.hpp
aviralg/tastr
184e6324de86831c1e4162112d446f537ad8f50c
[ "Apache-2.0" ]
null
null
null
include/ast/ExpressionTypeNode.hpp
aviralg/tastr
184e6324de86831c1e4162112d446f537ad8f50c
[ "Apache-2.0" ]
null
null
null
#ifndef TASTR_AST_EXPRESSION_TYPE_NODE_HPP #define TASTR_AST_EXPRESSION_TYPE_NODE_HPP #include "ast/KeywordNode.hpp" #include "ast/TypeNode.hpp" namespace tastr { namespace ast { class ExpressionTypeNode final: public TypeNode { public: explicit ExpressionTypeNode(KeywordNodeUPtr keyword) : TypeNode(), keyword_(std::move(keyword)) { } ~ExpressionTypeNode() = default; ExpressionTypeNode(const ExpressionTypeNode& node) : TypeNode(node), keyword_(node.keyword_->clone()) { } ExpressionTypeNode(ExpressionTypeNode&& node) : TypeNode(std::move(node)), keyword_(std::move(node.keyword_)) { } ExpressionTypeNode& operator=(const ExpressionTypeNode& node) { if (&node == this) { return *this; } TypeNode::operator=(node); keyword_ = node.keyword_->clone(); return *this; } ExpressionTypeNode& operator=(ExpressionTypeNode&& node) { TypeNode::operator=(std::move(node)); keyword_ = std::move(node.keyword_); return *this; } void accept(tastr::visitor::ConstNodeVisitor& visitor) const override final; void accept(tastr::visitor::MutableNodeVisitor& visitor) override final; std::unique_ptr<ExpressionTypeNode> clone() const { return std::unique_ptr<ExpressionTypeNode>(this->clone_impl()); } Kind get_kind() const override final { return kind_; } const KeywordNode& get_keyword() const { return *keyword_.get(); } private: virtual ExpressionTypeNode* clone_impl() const override final { return new ExpressionTypeNode(*this); }; KeywordNodeUPtr keyword_; static const Kind kind_; }; using ExpressionTypeNodePtr = ExpressionTypeNode*; using ExpressionTypeNodeUPtr = std::unique_ptr<ExpressionTypeNode>; } // namespace ast } // namespace tastr #endif /* TASTR_AST_EXPRESSION_TYPE_NODE_HPP */
26.094595
80
0.681512
aviralg
da4b930b5e24547a4d15259ed86d2718a1c5cd3e
24,270
cpp
C++
src/main/cpp/Robot.cpp
FRC830/2022Robot
32d3db27190cf48d5885832e1b734ddf8fdcc048
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Robot.cpp
FRC830/2022Robot
32d3db27190cf48d5885832e1b734ddf8fdcc048
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Robot.cpp
FRC830/2022Robot
32d3db27190cf48d5885832e1b734ddf8fdcc048
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "Robot.h" #include <iostream> #include <math.h> using namespace std; void Robot::RobotInit() { PlaceShuffleboardTiles(); GetRobotShuffleoardValues(); motorGroupLeft.SetInverted(true); frc::CameraServer::StartAutomaticCapture(); // motorFR.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); // motorBR.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); // motorBL.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); // motorFL.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); } /* * This function is called every robot packet, no matter the mode. Use * this for items like diagnostics that you want ran during disabled, * autonomous, teleoperated and test. * * <p> This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ void Robot::RobotPeriodic() {} void Robot::AutonomousInit() { motorFR.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); motorBR.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); motorBL.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); motorFL.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); firstCallToAuton = true; firstCallToAuton = true; autonMovingMotor = false; autonStep = 1; newAutonCall = true; motorFLEncoder.SetPosition(0.0); motorFREncoder.SetPosition(0.0); motorBLEncoder.SetPosition(0.0); motorBREncoder.SetPosition(0.0); if (motorBREncoder.SetPosition(0.0) == rev::REVLibError::kOk) { std::cout << std::endl << "BR Encoder successfully set to: " << motorBREncoder.GetPosition() << std::endl; } std::cout << "FL Encoder " << motorFLEncoder.GetPosition() << std::endl; std::cout << "BL Encoder " << motorBLEncoder.GetPosition() << std::endl; std::cout << "FR Encoder " << motorFREncoder.GetPosition() << std::endl; // look at suffleboard... autonMode = frc::SmartDashboard::GetNumber("Auton Mode", 2); firstCallToAuton = true; // motorFLEncoder.SetPosition(0); // motorFREncoder.SetPosition(0); // motorBLEncoder.SetPosition(0); // motorBREncoder.SetPosition(0); leftFlywheelTalon.Set(TalonFXControlMode::Velocity, 0); rightFlywheelTalon.Set(TalonFXControlMode::Follower, leftFlywheelTalon.GetDeviceID()); backSpinTalon.Set(TalonFXControlMode::Velocity, 0); rightFlywheelTalon.SetInverted(true); backSpinTalon.SetInverted(true); } void Robot::AutonomousPeriodic() { if (firstCallToAuton) { firstCallToAuton = false; return; } std::cout << "BR Encoder " << motorFLEncoder.GetPosition() << std::endl; std::cout << "FL Encoder " << motorFLEncoder.GetPosition() << std::endl; std::cout << "BL Encoder " << motorBLEncoder.GetPosition() << std::endl; std::cout << "FR Encoder " << motorFREncoder.GetPosition() << std::endl; switch(autonMode) { case 1: Taxi(); break; case 2: BackupAndShootAuton(); break; case 3: TestAuton(); break; default: Taxi(); break; } } void Robot::TeleopInit() { GetTeleopShuffleBoardValues(); pilot.setDeadzone(); copilot.setDeadzone(); pilot.setDeadzoneLimit(0.1); copilot.setDeadzoneLimit(0.1); pilot.setSensitivity(); pilot.setSensitivityLevel(defaultInputSensitivity); if (ebrake) { motorFR.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); motorBR.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); motorBL.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); motorFL.SetIdleMode(rev::CANSparkMax::IdleMode::kBrake); } } void Robot::TeleopPeriodic() { GetTeleopShuffleBoardValues(); autoAligning = pilot.GetAButton(); if (autoAligning) { //KEEP THESE TWO SEPERATE IF STATEMENTS!!! VERY IMPROTANT!!! if (AimRobotAtHub(0.4)){ //rumble pilot.SetRumble(frc::GenericHID::RumbleType::kLeftRumble, 1); pilot.SetRumble(frc::GenericHID::RumbleType::kRightRumble, 1); } } else { autoAligning = false; } HandleDrivetrain(); HandleShooter(); HandleBallManagement(); HandleIntake(); } void Robot::DisabledInit() { firstCallToAuton = true; firstCallToAuton = true; autonMovingMotor = false; autonStep = 1; newAutonCall = true; motorFR.SetIdleMode(rev::CANSparkMax::IdleMode::kCoast); motorBR.SetIdleMode(rev::CANSparkMax::IdleMode::kCoast); motorBL.SetIdleMode(rev::CANSparkMax::IdleMode::kCoast); motorFL.SetIdleMode(rev::CANSparkMax::IdleMode::kCoast); } void Robot::DisabledPeriodic() {} void Robot::TestInit() {} void Robot::TestPeriodic() {} void Robot::HandleDrivetrain() { //original input sensitivity code + turbo. Uncomment if needed // if (pilot.GetRightStickButtonPressed()) // { // pilot.setSensitivityLevel(driftInputSensitivity); // } // else if (pilot.GetRightStickButtonReleased()) // { // pilot.setSensitivityLevel(defaultInputSensitivity); // } //new, more advanced input sensitivity. Revert to old version if this does not work. pilot.setSensitivityLevel(defaultInputSensitivity + (((pilot.GetRightTriggerAxis("noS") < 0.9) ? pilot.GetRightTriggerAxis("noS") : 1) * (1 - defaultInputSensitivity))); //inputSentivityReduction = false; if (arcadeDrive) { double turningSpeed = pilot.GetLeftX() * turningSensitivity * -1; double forwardSpeed = pilot.GetRightY(); if (autoAligning) { turningSpeed = 0; } drivetrain.ArcadeDrive(forwardSpeed, turningSpeed * -1, inputSentivityReduction); } else { //tank drive std::cout << "tankDrive" << std::endl; // if the values are close, average them if (abs(pilot.GetLeftY() - pilot.GetRightY()) < tankAssist) { //if we are using tank drive and the sticks are pretty close together, pretend that they are all the way togetehr double AveragePosition = Robot::Avg(pilot.GetLeftY(), pilot.GetRightY()); //set the right stick equal to the left stick so that they are equal //the *-1 is because electrical refuses to let us flip the wire polarity and insisted we do it in code drivetrain.TankDrive(AveragePosition, AveragePosition, inputSentivityReduction); } else { drivetrain.TankDrive(pilot.GetLeftY(), pilot.GetRightY(), inputSentivityReduction); } } } void Robot::HandleShooter(){ int dist = frc::SmartDashboard::GetNumber("Shuffleboard/vision/distance",180); double ratio = frc::SmartDashboard::GetNumber("ratio backspin to flywheel",3.6); longSHOTHANGER = copilot.GetYButton(); frc::SmartDashboard::PutBoolean("GET Y BUTTON", longSHOTHANGER); //index is the index of the distance data point right above, -1 if its above everything int index=-1; for(int i =0; i< distances.size(); i++){ if (dist<distances[i]){ index=i; break; } } if(index !=-1 && index ==0){ int indexabove=index; int indexbelow=index; double proportionBetweenDistancePoints=(dist-distances[indexbelow])/(distances[indexabove]-distances[indexbelow]); double targetRatio=((ratioMap[distances[indexabove]] - ratioMap[distances[indexbelow]])*proportionBetweenDistancePoints)+ratioMap[distances[indexbelow]]; ratio=targetRatio; double targetSpeed=((speedMap[distances[indexabove]] - speedMap[distances[indexbelow]])*proportionBetweenDistancePoints)+speedMap[distances[indexbelow]]; shooterMaximum=targetSpeed; } // shooterOutput = ((copilot.GetRightTriggerAxis("noS") > 0.6) && !(copilot.GetLeftTriggerAxis("noS") > 0.6)) ? shooterMaximum : shooterMaximum; // shooterOutput = shooterOutput == 0 && (copilot.GetLeftTriggerAxis("noS")) ? shooterMaximum * -0.5 : 0; //shooterOutput = ((copilot.GetRightTriggerAxis("noS") > 0.6) && !(copilot.GetLeftTriggerAxis("noS") > 0.6)) ? shooterMaximum * 1 : shooterOutput; //shooterOutput = copilot.GetLeftTriggerAxis("nos") > 0.6 && !copilot.GetRightTriggerAxis("noS") > 0.6 ? shooterOutput * -0.5 : shooterOutput; //shooterOutput = !copilot.GetLeftTriggerAxis("nos") > 0.6 && !copilot.GetRightTriggerAxis("noS") > 0.6 ? shooterOutput : 0; //comment out //static bool lastCopilotRightTrigger = false; static bool risingEdgeFound = false; if (copilot.GetRightTriggerAxis("noS") <= 0.6) { //lastCopilotRightTrigger = true; // if (shooterOutput!=shooterMaximum && !risingEdgeFound){ // //call on the rising edge // risingEdgeFound = true; shootStablizer = TIMERLENGTH; std::cout << "stopped" << std::endl; // std::cout << shooterOutput << "," << shooterMaximum << std::endl; // } //shooterOutput = shooterMaximum; } // if ((copilot.GetRightTriggerAxis("noS") > 0.6) && (copilot.GetLeftTriggerAxis("noS") > 0.6)) // { // } if (copilot.GetRightTriggerAxis("noS") > 0.6 && !longSHOTHANGER) { //lastCopilotRightTrigger = true; // if (shooterOutput!=shooterMaximum && !risingEdgeFound){ // //call on the rising edge // risingEdgeFound = true; // shootStablizer = 20; // std::cout << shooterOutput << "," << shooterMaximum << std::endl; // } shooterOutput = shooterMaximum; } // else if (copilot.GetLeftTriggerAxis("noS") > 0.6) // { // shooterMaximum = shooterMaximum * -0.5; // } else if (longSHOTHANGER && copilot.GetRightTriggerAxis("nos") > 0.6) { shooterOutput = shooterHANGER; } if (copilot.GetLeftTriggerAxis("noS") < 0.2) { risingEdgeFound = false; } //Apply Ryan's confusing Deadzone math: //The following line serves as a deadzone maximum ex: 0.7- (0.7-0.6) shooterOutput = longSHOTHANGER ? shooterHANGER-Deadzone(shooterHANGER-shooterOutput) : shooterMaximum - Deadzone(shooterMaximum - shooterOutput); if (shooterOutput > 200) { leftFlywheelTalon.Set(TalonFXControlMode::Velocity, shooterOutput); rightFlywheelTalon.Set(TalonFXControlMode::Follower, leftFlywheelTalon.GetDeviceID()); backSpinTalon.Set(TalonFXControlMode::Velocity, shooterOutput * ratio); rightFlywheelTalon.SetInverted(true); backSpinTalon.SetInverted(true); } else { leftFlywheelTalon.Set(TalonFXControlMode::PercentOutput, 0); rightFlywheelTalon.Set(TalonFXControlMode::Follower, leftFlywheelTalon.GetDeviceID()); backSpinTalon.Set(TalonFXControlMode::PercentOutput, 0); rightFlywheelTalon.SetInverted(true); backSpinTalon.SetInverted(true); } frc::SmartDashboard::PutNumber("closed loop error", leftFlywheelTalon.GetClosedLoopError()); //Change this to be much much much much slower!! } void Robot::HandleBallManagement(){ std::cout << std::to_string(shootStablizer) << std::endl; shootStablizer--; // leftVictor.Set(VictorSPXControlMode::Follower, leftFlywheelTalon.GetDeviceID()); // middleVictor.Set(VictorSPXControlMode::Follower, leftFlywheelTalon.GetDeviceID()); // rightVictor.SetInverted(true); // rightVictor.Set(VictorSPXControlMode::Follower, leftFlywheelTalon.GetDeviceID()); // ballManageOutput = (copilot.GetAButton() && abs(leftFlywheelTalon.GetClosedLoopError() < 145)) ? frc::SmartDashboard::GetNumber("Ball Management Maximum", 0.5) : 0; ballManageOutput = (copilot.GetXButton() || (copilot.GetAButton() && (shootStablizer < 0 || shootStablizer == TIMERLENGTH))) ? frc::SmartDashboard::GetNumber("Ball Management Maximum", 0.5) : 0; bool ballManageReverse = copilot.GetBButton(); //ballManageOutput = ballManageMaximum-Deadzone(ballManageMaximum-ballManageOutput); if (ballManageOutput > 0) { leftVictor.Set(VictorSPXControlMode::PercentOutput, ballManageOutput); middleVictor.Set(VictorSPXControlMode::PercentOutput, -ballManageOutput); rightVictor.SetInverted(true); rightVictor.Set(VictorSPXControlMode::Follower, leftVictor.GetDeviceID()); ballManageReverse = false; } else if (ballManageReverse) { leftVictor.Set(VictorSPXControlMode::PercentOutput, -1 * frc::SmartDashboard::GetNumber("Ball Management Maximum", 0.5) ); middleVictor.Set(VictorSPXControlMode::PercentOutput, frc::SmartDashboard::GetNumber("Ball Management Maximum", 0.5)); rightVictor.Set(VictorSPXControlMode::Follower, leftVictor.GetDeviceID()); } else { leftVictor.Set(VictorSPXControlMode::PercentOutput, 0); middleVictor.Set(VictorSPXControlMode::PercentOutput, 0); rightVictor.Set(VictorSPXControlMode::Follower, leftVictor.GetDeviceID()); } if (pilot.GetAButtonPressed()) { frc::SmartDashboard::PutNumber("\nerror at shoot: ", leftFlywheelTalon.GetClosedLoopError()); } } void Robot::HandleIntake(){ bool isIntaking = pilot.GetLeftTriggerAxis() > 0.2; intakeOutput = int(isIntaking) * intakeMaximum; intakeMotor.Set(VictorSPXControlMode::PercentOutput, -intakeOutput); frc::SmartDashboard::PutNumber("Intake Output", intakeOutput); if (isIntaking){ leftSolenoid.Set(true); rightSolenoid.Set(true); frc::SmartDashboard::PutBoolean("Intake Extended", true); } else{ leftSolenoid.Set(false); rightSolenoid.Set(false); frc::SmartDashboard::PutBoolean("Intake Extended", false); } } bool Robot::AimRobotAtHub(double motorSpeed) { //tab stands for table double distance = visionTab -> GetNumber("Hub Center X Distance", -2); std::cout << std::to_string(distance) << std::endl; if (distance == -1) { std::cout << "No Hub Detected" << std::endl; return false; } else { std::cout << "Hub Detected" << std::endl; } double goal = frc::SmartDashboard::GetNumber("X resolution", 1080) / 2; if (abs(distance - goal) > frc::SmartDashboard::GetNumber("aim tolerance", 25)) { autonStep++; return false; } if (distance > goal) { drivetrain.ArcadeDrive(0, motorSpeed, false); } else { drivetrain.ArcadeDrive(0, motorSpeed * -1, false); } return true; } double Robot::Deadzone(double amm){ //deadzoneLimit is arbitrary //make it smartdashboard if (abs(amm) < deadzoneLimit) { amm = 0; } return amm; } double Robot::Avg(double val1, double val2) { return (val1 + val2) / 2; } void Robot::PlaceShuffleboardTiles() { //Initially place values to Shuffleboard frc::SmartDashboard::PutBoolean("Arcade Drive", true); frc::SmartDashboard::PutNumber("Tank Assist", 0.05); frc::SmartDashboard::PutNumber("Input Sensitivity", 0.4); frc::SmartDashboard::PutNumber("Turning Sensitivity", 0.91); frc::SmartDashboard::PutNumber("Deadzone Size", 0.05); frc::SmartDashboard::PutNumber("Auton Mode", 2); frc::SmartDashboard::PutBoolean("Invert Robot", false); frc::SmartDashboard::PutBoolean("Ebrake", true); //frc::SmartDashboard::PutNumber("GearRatio", gearRatio); frc::SmartDashboard::PutNumber("Shooter Maximum", 4000); frc::SmartDashboard::PutNumber("Shooter HANGER", 100); frc::SmartDashboard::PutNumber("Shooter Output", 0); frc::SmartDashboard::PutNumber("ratio backspin to flywheel",4); frc::SmartDashboard::PutNumber("Ball Management Output", 0); frc::SmartDashboard::PutNumber("Ball Management Maximum", 0.5); frc::SmartDashboard::PutNumber("Intake Maximum", 0.5); frc::SmartDashboard::PutNumber("Intake Output", 0); frc::SmartDashboard::PutBoolean("Intake Extended", false); frc::SmartDashboard::PutBoolean("GET Y BUTTON", false); } void Robot::GetTeleopShuffleBoardValues() { //Collect values from Shuffleboard arcadeDrive = frc::SmartDashboard::GetBoolean("Arcade Drive", true); tankAssist = frc::SmartDashboard::GetNumber("Tank Assist", 0.08); defaultInputSensitivity = frc::SmartDashboard::GetNumber("Input Sensitivity", 0.4); turningSensitivity = frc::SmartDashboard::GetNumber("Turning Sensitivity", 0.91); deadzoneLimit = frc::SmartDashboard::GetNumber("Deadzone Size", 0.05); ebrake = frc::SmartDashboard::GetNumber("Ebrake", true); shooterMaximum = frc::SmartDashboard::GetNumber("Shooter Maximum", 4000); shooterHANGER = frc::SmartDashboard::GetNumber("Shooter HANGER MAX", 100); shooterOutput = frc::SmartDashboard::GetNumber("Shooter Output", 0); ballManageOutput = frc::SmartDashboard::GetNumber("Ball Management Output", 0); shooterOutput = frc::SmartDashboard::GetNumber("Ball Management Maximum",0.5); intakeOutput = frc::SmartDashboard::GetNumber("Intake Output", 0); intakeMaximum = frc::SmartDashboard::GetNumber("Intake Maximum", 0.5); intakeExtended = frc::SmartDashboard::GetBoolean("Intake Extended", false); //longSHOTHANGER = frc::SmartDashboard::GetBoolean("GET Y BUTTON", false); } void Robot::GetRobotShuffleoardValues() { invertRobot = frc::SmartDashboard::GetBoolean("Invert Robot", false); frc::SmartDashboard::PutNumber("aim tolerance", 40); //gearRatio = frc::SmartDashboard::GetNumber("GearRatio", gearRatio); } void Robot::Taxi() { if (autonStep == 1) { LinearMove(-84.75, 0.5); } } void Robot::TestAuton() { // std::cout << "gear ratio: " << std::to_string(gearRatio) << std::endl; //drivetrain.TankDrive(0.3, 0.3, true); //std::printf("Basic move ton"); //autonStep = 1; std::cout << "Basic Auton is running!" << std::endl; switch(autonStep) { case 1: //std::printf("In the switch"); CenterPointTurn(90.0, 0.0009); break; case 2: CenterPointTurn(-90.0, 0.0009); break; default: break; } return; } void Robot::BackupAndShootAuton() { frc::SmartDashboard::PutNumber("closed loop error", leftFlywheelTalon.GetClosedLoopError()); // std::cout << "gear ratio: " << std::to_string(gearRatio) << std::endl; //drivetrain.TankDrive(0.3, 0.3, true); //std::printf("Basic move ton"); //autonStep = 1; std::cout << "Auton Step is : " << std::to_string(autonStep) << std::endl; runIntake(0.5); switch(autonStep) { case 1: LinearMove(-84.75, 0.55); break; case 10: AccelerateFlywheelDuringAuton(4500, 4.0); break; case 110: RunBallManagement(0.5); break; // case 220: // RunBallManagement(0); // break; // case 350: // RunBallManagement(0.5); // break; default: autonStep++; break; } return; } void Robot::runIntake(double speed) { intakeOutput = speed * intakeMaximum; intakeMotor.Set(VictorSPXControlMode::PercentOutput, -intakeOutput); frc::SmartDashboard::PutNumber("Intake Output", intakeOutput); leftSolenoid.Set(true); rightSolenoid.Set(true); frc::SmartDashboard::PutBoolean("Intake Extended", true); } void Robot::AccelerateFlywheelDuringAuton(int speed, double ratio) { leftFlywheelTalon.Set(TalonFXControlMode::Velocity, speed); rightFlywheelTalon.Set(TalonFXControlMode::Follower, leftFlywheelTalon.GetDeviceID()); backSpinTalon.Set(TalonFXControlMode::Velocity, speed * ratio); rightFlywheelTalon.SetInverted(true); backSpinTalon.SetInverted(true); autonStep++; std::cout << std::to_string(leftFlywheelTalon.GetClosedLoopError()) << std::endl; } void Robot::RunBallManagement(double speed) { leftVictor.Set(VictorSPXControlMode::PercentOutput, speed); middleVictor.Set(VictorSPXControlMode::PercentOutput, -speed); rightVictor.SetInverted(true); rightVictor.Set(VictorSPXControlMode::Follower, leftVictor.GetDeviceID()); } void Robot::LinearMove(double distance, double motorSpeed) { assert (motorSpeed > 0); assert (distance != 0); double encoderDistance = InchesToEncoderTicks(distance); std::cout << "encoder distance in ticks: " << std::to_string(encoderDistance) << std::endl; if (newAutonCall) { std::cout << std::noboolalpha << newAutonCall << std::endl; std::printf("Here"); motorFLEncoderTarget = motorFLEncoder.GetPosition() + encoderDistance; motorFREncoderTarget = motorFREncoder.GetPosition() + encoderDistance; motorBLEncoderTarget = motorBLEncoder.GetPosition() + encoderDistance; motorBREncoderTarget = motorBREncoder.GetPosition() + encoderDistance; newAutonCall = false; std::cout << std::noboolalpha << newAutonCall << std::endl; } int direction; //here //std::printf("in the function"); direction = distance / abs(distance); // std::cout << ((std::to_string(motorFLEncoder.GetPosition()) + std::to_string(motorFLEncoderTarget) + // std::to_string(motorFREncoder.GetPosition()) +std::to_string( motorFREncoderTarget) )) << std::endl; if ((motorFLEncoder.GetPosition() * direction < motorFLEncoderTarget * direction) && (motorFREncoder.GetPosition() * direction < motorFREncoderTarget * direction)) { std::cout << "Distance to target: " << std::to_string(motorFLEncoderTarget - motorFLEncoder.GetPosition()) << std::endl; drivetrain.TankDrive(motorSpeed * direction, motorSpeed * direction, true); return; } else { std::cout << "Done with the drive" << std::endl; drivetrain.TankDrive(0, 0, false); std::cout << "auton step before: " << std::to_string(autonStep) << std::endl; autonStep++; std::cout << "auton step after: " << std::to_string(autonStep) << std::endl; newAutonCall = true; return; } } void Robot::CenterPointTurn(double degrees, double motorSpeed) { // // std::printf("Distance: " + std::str(distance)); // // std::printf("motor Speed: " + std::str(motorSpeed)); assert (motorSpeed > 0); assert (degrees != 0); double distance = DegreesToInches(degrees); double encoderDistance = InchesToEncoderTicks(distance); std::cout << std::to_string(encoderDistance) << std::endl; int direction; //here //std::printf("in the function"); direction = distance / -1 * abs(distance); if (newAutonCall) { std::cout << std::noboolalpha << newAutonCall << std::endl; std::printf("Here"); motorFLEncoderTarget = motorFLEncoder.GetPosition() + encoderDistance; motorBLEncoderTarget = motorBLEncoder.GetPosition() + encoderDistance; motorFREncoderTarget = motorFREncoder.GetPosition() - encoderDistance; motorBREncoderTarget = motorBREncoder.GetPosition() - encoderDistance; newAutonCall = false; std::cout << std::noboolalpha << newAutonCall << std::endl; } // The "if" continuously checks to see if we're done with the auton rotation // The body underneath continues to run if we're not // The "else" body runs once it sees that we are (and increases the autonStep) if ((motorFLEncoder.GetPosition() * direction * -1 < motorFLEncoderTarget * direction * -1) && (motorFREncoder.GetPosition() * direction < motorFREncoderTarget * direction)) { std::printf((motorFLEncoder.GetPosition() * direction * -1 < motorFLEncoderTarget * direction * -1) ? "First: True\n" : "First: False\n"); std::printf( (motorFREncoder.GetPosition() * direction < motorFREncoderTarget * direction) ? "Second: True\n" : "Second: False\n"); drivetrain.TankDrive(motorSpeed * direction * -1, motorSpeed * direction, true); std::cout << "motorspeed: " << std::to_string(motorSpeed) << std::endl; } else { std::cout << "Done with the drive" << std::endl; drivetrain.TankDrive(0, 0, false); std::cout << "auton step before: " << std::to_string(autonStep) << std::endl; autonStep++; std::cout << "auton step after: " << std::to_string(autonStep) << std::endl; newAutonCall = true; return; } } double Robot::EncoderTicksToInches(double ticks) { double c = WheelRadiusInches * PI * 2; return (c * (ticks) * gearRatio); } double Robot::InchesToEncoderTicks(double inches) { assert(inches != 0); double c = WheelRadiusInches * PI * 2; return ((inches / c) * gearRatio); } double Robot::EncoderTicksToInches(double ticks, double TicksPerRev) { double c = WheelRadiusInches * PI * 2; return (c * (ticks / TicksPerRev) * gearRatio); } double Robot::InchesToEncoderTicks(double inches, double TicksPerRev) { double c = WheelRadiusInches * PI * 2; return ((inches / c) * TicksPerRev * gearRatio); } double Robot::DegreesToInches(double degrees) { double RobotC = rotationAxisRadius * PI * 2; double radialPortion = degrees / 360; return (RobotC * radialPortion); } #ifndef RUNNING_FRC_TESTS int main() { return frc::StartRobot<Robot>(); } #endif
32.48996
196
0.693943
FRC830
da4fc46853af53398f362ade68d409801ac40d54
1,965
cpp
C++
mod/wrd/ast/exprs/getExpr.cpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/wrd/ast/exprs/getExpr.cpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/wrd/ast/exprs/getExpr.cpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#include "getExpr.hpp" #include "../../loader/interpreter/tverification.hpp" #include "../../loader/interpreter/verification.inl" #include "../../loader/interpreter/verifier.hpp" #include "../../frame/thread.hpp" #include "../node.inl" namespace wrd { WRD_DEF_ME(getExpr) const node& me::getFrom() const { if(!_from) return thread::get().getNowFrame(); return *_from; } const wtype& me::getEvalType() const { const node& got = _get(); if(nul(got)) return nulOf<wtype>(); return got.getEvalType(); } str me::run(const ucontainable& args) { // believe that this expression was checked to be valid. return str(_get()); } const std::string& me::getSubName() const { return _name; } /// @return nullable const narr& me::getSubArgs() const { return *_args; } node& me::_get() const { str evalMe = getFrom().isSub<expr>() ? getFrom().as<node>() : getFrom(); if(!evalMe) return WRD_E("from == null"), nulOf<node>(); WRD_DI("_name=%s", _name.c_str()); if(!_args) return evalMe->sub(_name); return evalMe->sub(_name, *_args); } WRD_VERIFY(getExpr, isRunnable, { // TODO: I have to check that the evalType has what matched to given _params. // Until then, I rather use as() func and it makes slow emmersively. if(nul(it.getEvalType())) return _srcErr(errCode::EVAL_NULL_TYPE); const node& got = it._get(); if(nul(got)) { const node& from = it.getFrom(); return _srcErr(errCode::CANT_ACCESS, from.getType().getName().c_str(), it._name.c_str()); WRD_DI("verify: getExpr: isRunnable: got=%s, it=%s", got.getType().getName().c_str(), it.getType().getName().c_str()); } }) WRD_VERIFY({ WRD_DI("verify: getExpr: visit 'from' subnodes"); verify((node&) it.getFrom()); }) }
30.230769
101
0.582697
kniz
da546e7ff22adfeb0f5082b616cbd9c2032fac3d
4,060
cpp
C++
teleop_and_haptics/sss/Source/MyVolumesWidget.cpp
atp42/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
3
2017-02-02T13:27:45.000Z
2018-06-17T11:52:13.000Z
teleop_and_haptics/sss/Source/MyVolumesWidget.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
teleop_and_haptics/sss/Source/MyVolumesWidget.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
#include "MyVolumesWidget.h" #include <QtGui> MyVolumesWidget::MyVolumesWidget(MyVolumesModel *model, QWidget *parent) : QWidget(parent) { m_volumesModel = model; int first = 1; // index of the first "real" volume (0 is a dummy) QBoxLayout *layout = new QHBoxLayout(this); // construct the left side with volume list and details QLayout *leftSide = new QVBoxLayout; m_listView = new QListView(); m_listView->setAlternatingRowColors(true); m_listView->setModel(m_volumesModel); m_listView->setRowHidden(0, true); m_listView->setCurrentIndex(m_volumesModel->index(first, 0)); leftSide->addWidget(m_listView); // some ugly buttons to remove and clear the list QLayout *buttons = new QHBoxLayout(); m_removeButton = new QPushButton("Remove"); connect(m_removeButton, SIGNAL(clicked()), this, SLOT(removeCurrentVolume())); buttons->addWidget(m_removeButton); leftSide->addItem(buttons); m_detailsWidget = new MyVolumeDetailsWidget(); leftSide->addWidget(m_detailsWidget); layout->addLayout(leftSide, 0); // construct the center panel with the image and histogram QLayout *center = new QVBoxLayout; m_imageWidget = new MyVolumeImageWidget; center->addWidget(m_imageWidget); m_histogramWidget = new MyVolumeHistogramWidget; center->addWidget(m_histogramWidget); layout->addLayout(center, 2); // set up data mappings QDataWidgetMapper *mapper = new QDataWidgetMapper(this); mapper->setModel(m_volumesModel); mapper->addMapping(m_detailsWidget, 1); mapper->addMapping(m_histogramWidget, 2); mapper->setCurrentIndex(first); // a mapper can only map section 1 to one widget, so we need another... QDataWidgetMapper *mapper2 = new QDataWidgetMapper(this); mapper2->setModel(m_volumesModel); mapper2->addMapping(m_imageWidget, 1); mapper2->setCurrentIndex(first); // connect the list view to the data mapper QItemSelectionModel *sm = m_listView->selectionModel(); connect(sm, SIGNAL(currentChanged(QModelIndex,QModelIndex)), mapper, SLOT(setCurrentModelIndex(QModelIndex))); connect(sm, SIGNAL(currentChanged(QModelIndex,QModelIndex)), mapper2, SLOT(setCurrentModelIndex(QModelIndex))); } void MyVolumesWidget::openDirectory(QString path) { // open a dialog to get a directory if we're not passed one if (path.isEmpty()) path = QFileDialog::getExistingDirectory(this, "Open Directory"); if (!path.isEmpty()) { // do a quick sanity check by counting directories int tally = 0, limit = 20; QStringList q(""); while (!q.isEmpty() && tally < limit) { QDir d(path + "/" + q.takeFirst()); QStringList entries = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot); tally += entries.count(); q.append(entries); } if (tally >= limit) { QMessageBox::StandardButton response = QMessageBox::question(this, "Open Directory", path + " contains a large number of subdirectories." " Locating volumes may take a long time. Proceed?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (response == QMessageBox::No) return; } m_volumesModel->addVolumeFromPath(path); emit logUpdated(VolumeRepository::instance()); QDir::setCurrent(path); } } void MyVolumesWidget::openFile(QString path) { QMessageBox::information(this, "Simulation Message", "This feature has not yet been implemented"); } void MyVolumesWidget::saveFile(QString path) { QMessageBox::information(this, "Simulation Message", "This feature has not yet been implemented"); } void MyVolumesWidget::removeCurrentVolume() { m_volumesModel->removeRow(m_listView->currentIndex().row()); } void MyVolumesWidget::clearVolumes() { }
33.00813
91
0.65936
atp42
da5877105526619ca73d5088738be3b076b79c7b
73
hh
C++
dependencies/include/pimpl_ptr.hh
Wedrew/rpclib
eff0f0c7270ca8c17d46edf5ebc4ee97e4b2444f
[ "MIT" ]
1,316
2016-07-03T10:01:37.000Z
2022-03-31T18:40:35.000Z
dependencies/include/pimpl_ptr.hh
Wedrew/rpclib
eff0f0c7270ca8c17d46edf5ebc4ee97e4b2444f
[ "MIT" ]
239
2016-06-29T07:16:26.000Z
2022-03-23T09:21:15.000Z
dependencies/include/pimpl_ptr.hh
Wedrew/rpclib
eff0f0c7270ca8c17d46edf5ebc4ee97e4b2444f
[ "MIT" ]
315
2016-08-24T13:08:20.000Z
2022-03-29T10:59:08.000Z
#ifndef PIMPL_PTR_HH_ #define PIMPL_PTR_HH_ #endif /* PIMPL_PTR_HH_ */
12.166667
26
0.767123
Wedrew
da601ca52d43594f01ab3b5b7d423f4843df7771
425
cpp
C++
dynamic/4811.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
dynamic/4811.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
dynamic/4811.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
// 알약 #include <iostream> #include <vector> using namespace std; int main(void) { int t, i, j; cin >> t; vector<vector<long long>> a(31,vector<long long> (31)); for(i = 1; i <= 30; i++) a[0][i] = 1; for(i = 1; i <= 30; i++) { for(j = 0; j <= 30 - i; j++) { if(j == 0) a[i][j] = a[i-1][1]; else a[i][j] = a[i-1][j+1] + a[i][j-1]; } } while(t) { cout << a[t][0] << "\n"; cin >> t; } return 0; }
15.178571
56
0.449412
SiverPineValley
da651f99e46e19ddd884a3bb312b7c74a2eb2cd4
427
hpp
C++
NWNXLib/API/Mac/API/IncrMerger.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/IncrMerger.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/IncrMerger.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include "SorterFile.hpp" #include "unknown_sqlite_int64.hpp" namespace NWNXLib { namespace API { // Forward class declarations (defined in the source file) struct MergeEngine; struct SortSubtask; struct IncrMerger { SortSubtask* pTask; MergeEngine* pMerger; sqlite_int64 iStartOff; int32_t mxSz; int32_t bEof; int32_t bUseThread; SorterFile aFile[2]; }; } }
14.233333
58
0.721311
Qowyn
da69a96972a8e31e7d55fef320e0885d8fce8583
879
cpp
C++
Leetcode/C++/Delete a given Node when a node is given.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
289
2021-05-15T22:56:03.000Z
2022-03-28T23:13:25.000Z
Leetcode/C++/Delete a given Node when a node is given.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
1,812
2021-05-09T13:49:58.000Z
2022-01-15T19:27:17.000Z
Leetcode/C++/Delete a given Node when a node is given.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
663
2021-05-09T16:57:58.000Z
2022-03-27T14:15:07.000Z
// Problem Link : https://leetcode.com/problems/delete-node-in-a-linked-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { //copy the node into the given node. node->val=node->next->val; //point the node to the null to delete it. node->next=node->next->next; } }; // Input: head = [4,5,1,9], node = 1 // Output: [4,5,9] // Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. // Example 3: // Input: head = [1,2,3,4], node = 3 // Output: [1,2,4] // Example 4: // Input: head = [0,1], node = 0 // Output: [1] // Example 5: // Input: head = [-3,5,-99], node = -3 // Output: [5,-99]
23.756757
129
0.577929
abdzitter
da6a4b71e2d7c27b5f5705ae22199d15008bb1d6
4,108
hpp
C++
Misc/APE Scripts/ShepardTone.hpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Misc/APE Scripts/ShepardTone.hpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Misc/APE Scripts/ShepardTone.hpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#include "../../../../RS-MET/Misc/APE Scripts/rapt_for_ape.cpp" // relative path from "Audio Programming Environment/includes" #include <effect.h> // or maybe we should use generator.h? //================================================================================================= // The core DSP object template<class T> class rsShepardToneGenerator { public: //----------------------------------------------------------------------------------------------- // \name Setup /** Sets the sample rate at which this object runs. This determines the time increment for our phasor */ inline void setSampleRate(T newRate) { dt = T(1) / newRate; } /** Sets the lower und upper cutoff frequency between which all the action happens. */ inline void setCutoffFrequencies(T lowCutoff, T highCutoff) { wLo = T(2) * PI * lowCutoff * dt; wHi = T(2) * PI * highCutoff * dt; } //----------------------------------------------------------------------------------------------- // \name Processing /** Computes the desired gain factor for a given radian frequency w. */ inline T getGainForOmega(T w) { return T(1); // preliminary - todo: implement a bell curve here } /** Produces one output sample at a time. */ inline T getSample() { T y = T(0); // output // Create all frequencies from wRef up to the upper cutoff: T w = wRef; while(w <= wHi) { y += getGainForOmega(w) * sin(w*t); w *= T(2); } // Create all frequencies from 0.5*wRef down to the lower cutoff: w = T(0.5)*wRef; while(w >= wLo) { y += getGainForOmega(w) * sin(w*t); w *= T(0.5); } // Increment time and return output: t += dt; return y; } inline void reset() { t = T(0); } protected: T t; // current time, normalized to 0..1. our phasor T dt; // time increment per sample for t. equal to 1/sampleRate T wRef; // current reference omega T wLo, wHi; // high and low cutoff omegas }; //================================================================================================= // The APE effect GlobalData(ShepardTone, "Endless glissando generator"); class ShepardTone : public ape::Effect { public: ShepardTone() {} // Shorthands for convenience to reduce boilerplate: using Par = ape::Param<float>; using Rng = ape::Range; using Map = Rng::Mapping; Par parGain{ "Gain", Rng(-48, 12) }; // in dB Par parFreqLo{ "FreqLo", Rng(20, 20000, Map::Exp) }; // lower cutoff in Hz Par parFreqHi{ "FreqHi", Rng(20, 20000, Map::Exp) }; // upper cutoff in Hz Par parFreq{ "Freq", Rng(20, 20000, Map::Exp) }; // current reference freq // this is preliminary - later this is the freq that should automatically increase or decrease // and wrap around when it reaches to times its original value private: rsShepardToneGenerator<float> core; /** Resets the internal state. */ void reset() { core.reset(); } //----------------------------------------------------------------------------------------------- // \name Overriden callbacks (why are they private?) void start(const ape::IOConfig& cfg) override { reset(); } void process(ape::umatrix<const float> ins, ape::umatrix<float> outs, size_t numFrames) override { // Pull the values of the parameters for this block and update the DSP object: const float gain = RAPT::rsDbToAmp((float)parGain); float s = 2*PI / config().sampleRate; float wl = s * (float)parFreqLo; float wh = s * (float)parFreqHi; //core.setOmegas(wl, wh); // Loop over the sample frames: const auto numChannels = sharedChannels(); // shared? with whom? for(size_t n = 0; n < numFrames; ++n) { float y = gain * core.getSample(); // compute output for(size_t c = 0; c < numChannels; ++c) // write generated sample into all channels outs[c][n] = y; } clear(outs, numChannels); // what does this do? clear unused channels? } };
27.756757
99
0.542113
RobinSchmidt
da6a5d89591ce71da2a1488e769d888696c4add6
9,277
cpp
C++
src/core/btrc/core/volume/bvh.cpp
AirGuanZ/Btrc
8865eb1506f96fb0230fb394b9fadb1e38f2b9d8
[ "MIT" ]
17
2022-02-03T09:35:14.000Z
2022-03-28T04:27:05.000Z
src/core/btrc/core/volume/bvh.cpp
AirGuanZ/Btrc
8865eb1506f96fb0230fb394b9fadb1e38f2b9d8
[ "MIT" ]
1
2022-02-09T15:11:55.000Z
2022-02-09T15:11:55.000Z
src/core/btrc/core/volume/bvh.cpp
AirGuanZ/Btrc
8865eb1506f96fb0230fb394b9fadb1e38f2b9d8
[ "MIT" ]
null
null
null
#include <bvh/bvh.hpp> #include <bvh/leaf_collapser.hpp> #include <bvh/locally_ordered_clustering_builder.hpp> #include <bvh/parallel_reinsertion_optimizer.hpp> #include <btrc/core/volume/bvh.h> #include <btrc/utils/enumerate.h> BTRC_BEGIN namespace { constexpr int TRAVERSAL_STACK_SIZE = 16; bvh::Vector3<float> convert(const Vec3f &v) { return bvh::Vector3<float>(v.x, v.y, v.z); } bvh::BoundingBox<float> convert(const AABB3f &bbox) { return bvh::BoundingBox(convert(bbox.lower), convert(bbox.upper)); } f32 max(f32 a, f32 b, f32 c, f32 d) { return cstd::max(cstd::max(a, b), cstd::max(c, d)); } f32 min(f32 a, f32 b, f32 c, f32 d) { return cstd::min(cstd::min(a, b), cstd::min(c, d)); } } // namespace anonymous volume::BVH::BVH(const std::vector<RC<VolumePrimitive>> &vols) { if(vols.empty()) return; AABB3f global_bbox; std::vector<bvh::BoundingBox<float>> aabbs(vols.size()); std::vector<bvh::Vector3<float>> centers(vols.size()); for(auto &&[i, vol] : enumerate(vols)) { const AABB3f aabb = vol->get_bounding_box(); aabbs[i] = convert(aabb); centers[i] = convert(0.5f * (aabb.lower + aabb.upper)); global_bbox = union_aabb(global_bbox, aabb); } bvh::Bvh<float> tree; bvh::LocallyOrderedClusteringBuilder<bvh::Bvh<float>, uint64_t> builder(tree); builder.build(convert(global_bbox), aabbs.data(), centers.data(), vols.size()); bvh::ParallelReinsertionOptimizer bvh_optimizer(tree); bvh_optimizer.optimize(); bvh::LeafCollapser leaf_collapser(tree); leaf_collapser.collapse(); std::vector<BVHNode> nodes(tree.node_count); std::vector<BVHPrimitive> prims; for(size_t ni = 0; ni < tree.node_count; ++ni) { auto &src_node = tree.nodes[ni]; auto &dst_node = nodes[ni]; dst_node.lower.x = src_node.bounds[0]; dst_node.lower.y = src_node.bounds[2]; dst_node.lower.z = src_node.bounds[4]; dst_node.upper.x = src_node.bounds[1]; dst_node.upper.y = src_node.bounds[3]; dst_node.upper.z = src_node.bounds[5]; if(src_node.is_leaf()) { const size_t prim_beg = prims.size(); const size_t i_end = src_node.first_child_or_primitive + src_node.primitive_count; for(size_t i = src_node.first_child_or_primitive; i < i_end; ++i) { const size_t pi = tree.primitive_indices[i]; auto &vol = vols[pi]; const VolumePrimitive::VolumeGeometryInfo geo = vol->get_geometry_info(); const BVHPrimitive prim_info = { .o = geo.o, .vol_id = static_cast<uint32_t>(pi), .x_div_x2 = geo.x / length_square(geo.x), .y_div_y2 = geo.y / length_square(geo.y), .z_div_z2 = geo.z / length_square(geo.z) }; prims.push_back(prim_info); } const size_t prim_end = prims.size(); assert(prim_end > prim_beg); dst_node.prim_beg = static_cast<int32_t>(prim_beg); dst_node.prim_end = static_cast<int32_t>(prim_end); } else { dst_node.prim_beg = -1; dst_node.prim_end = static_cast<int32_t>(src_node.first_child_or_primitive); } } nodes_.swap(nodes); prims_.swap(prims); } bool volume::BVH::is_empty() const { return nodes_.empty(); } boolean volume::BVH::find_closest_intersection(ref<CVec3f> a, ref<CVec3f> b, ref<CVec3f> output_position) const { if(nodes_.empty()) return false; boolean result; $scope { var nodes = cuj::const_data(nodes_); var prims = cuj::const_data(prims_); var dir = b - a; var inv_dir = 1.0f / dir; var final_t = btrc_max_float, t_max = 1.0f; cuj::arr<u32, TRAVERSAL_STACK_SIZE> traversal_stack; traversal_stack[0] = 0; var top = 1; $while(top > 0) { top = top - 1; var task_node_idx = traversal_stack[top]; ref<CBVHNode> node = nodes[task_node_idx]; $if(is_leaf_node(node)) { $forrange(i, node.prim_beg, node.prim_end) { var t = find_closest_intersection(a, dir, t_max, prims[i]); $if(t >= 0.0f) { final_t = cstd::min(final_t, t); t_max = final_t; }; }; } $else { var left = nodes[node.prim_end]; $if(intersect_ray_aabb(left.lower, left.upper, a, inv_dir, t_max)) { traversal_stack[top] = u32(node.prim_end); top = top + 1; }; var right = nodes[node.prim_end + 1]; $if(intersect_ray_aabb(right.lower, right.upper, a, inv_dir, t_max)) { traversal_stack[top] = u32(node.prim_end + 1); top = top + 1; }; }; }; $if(final_t > 10) { result = false; $exit_scope; }; CUJ_ASSERT(final_t >= 0.0f); CUJ_ASSERT(final_t <= 1.0f); output_position = a * (1.0f - final_t) + b * final_t; result = true; }; return result; } volume::BVH::Overlap volume::BVH::get_overlap(ref<CVec3f> position) const { Overlap result; result.count = 0; if(nodes_.empty()) return result; $scope { var nodes = cuj::const_data(nodes_); var prims = cuj::const_data(prims_); cuj::arr<u32, TRAVERSAL_STACK_SIZE> traversal_stack; traversal_stack[0] = 0; var top = 1; $while(top > 0) { top = top - 1; ref node = nodes[traversal_stack[top]]; $if(is_leaf_node(node)) { $forrange(i, node.prim_beg, node.prim_end) { ref prim = prims[i]; $if(is_in_prim(position, prim)) { result.data[result.count] = prim.vol_id; result.count = result.count + 1; $if(result.count >= MAX_OVERLAP_COUNT) { $exit_scope; }; }; }; } $else { var left = nodes[node.prim_end]; $if(is_in_aabb(position, left.lower, left.upper)) { traversal_stack[top] = u32(node.prim_end); top = top + 1; }; var right = nodes[node.prim_end + 1]; $if(is_in_aabb(position, right.lower, right.upper)) { traversal_stack[top] = u32(node.prim_end + 1); top = top + 1; }; }; }; }; return result; } boolean volume::BVH::is_leaf_node(ref<CBVHNode> node) const { return node.prim_beg >= 0; } boolean volume::BVH::is_in_prim(ref<CVec3f> pos, ref<CBVHPrimitive> prim) const { var op = pos - prim.o; var u = dot(op, prim.x_div_x2); var v = dot(op, prim.y_div_y2); var w = dot(op, prim.z_div_z2); return 0.0f <= u & u <= 1.0f & 0.0f <= v & v <= 1.0f & 0.0f <= w & w <= 1.0f; } boolean volume::BVH::is_in_aabb(ref<CVec3f> pos, ref<CVec3f> lower, ref<CVec3f> upper) const { return lower.x <= pos.x & pos.x <= upper.x & lower.y <= pos.y & pos.y <= upper.y & lower.z <= pos.z & pos.z <= upper.z; } boolean volume::BVH::intersect_ray_aabb(ref<CVec3f> lower, ref<CVec3f> upper, ref<CVec3f> o, ref<CVec3f> inv_d, f32 t_max) const { var n = inv_d * (lower - o); var f = inv_d * (upper - o); var t0 = max(0.0f, cstd::min(n.x, f.x), cstd::min(n.y, f.y), cstd::min(n.z, f.z)); var t1 = min(t_max, cstd::max(n.x, f.x), cstd::max(n.y, f.y), cstd::max(n.z, f.z)); return t0 <= t1; } f32 volume::BVH::find_closest_intersection(ref<CVec3f> p, ref<CVec3f> d, f32 t_max, ref<CBVHPrimitive> prim) const { var op = p - prim.o; var t0 = 0.0f, t1 = t_max; auto process_interval = [&](ref<CVec3f> d_div_d2) { var opd = dot(op, d_div_d2); var dd = dot(d, d_div_d2); var nd = (0.0f - opd) / dd; var fd = (1.0f - opd) / dd; t0 = cstd::max(t0, cstd::min(nd, fd)); t1 = cstd::min(t1, cstd::max(nd, fd)); }; process_interval(prim.x_div_x2); process_interval(prim.y_div_y2); process_interval(prim.z_div_z2); f32 result; $scope { $if(t0 > t1) { result = -1; $exit_scope; }; $if(t0 > 0) { result = t0; $exit_scope; }; $if(t1 < t_max) { result = t1; $exit_scope; }; result = -1; }; return result; } BTRC_END
28.283537
128
0.514067
AirGuanZ
da718d0199de3de971410d10c487de0b34a802ee
6,879
cxx
C++
ZDC/ZDCrec/AliZDCRecoParamPbPb.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
ZDC/ZDCrec/AliZDCRecoParamPbPb.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
ZDC/ZDCrec/AliZDCRecoParamPbPb.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// // // // Class with ZDC reconstruction parameters // // Origin: Chiara.Oppedisano@to.infn.it // // // /////////////////////////////////////////////////////////////////////////////// #include <TFile.h> #include <TTree.h> #include <TH2F.h> #include <TH1D.h> #include "AliZDCRecoParam.h" #include "AliZDCRecoParamPbPb.h" ClassImp(AliZDCRecoParamPbPb) //_____________________________________________________________________________ AliZDCRecoParamPbPb::AliZDCRecoParamPbPb() : AliZDCRecoParam(), fhNpartDist(0x0), fhbDist(0x0), fClkCenter(0) { // //Default constructor } //_____________________________________________________________________________ AliZDCRecoParamPbPb::AliZDCRecoParamPbPb(TH1D *hNpart, TH1D *hb, Float_t clkCent) : AliZDCRecoParam(), fhNpartDist(hNpart), fhbDist(hb), fClkCenter(clkCent) { // //Standard constructor } //______________________________________________________________________________ AliZDCRecoParamPbPb::AliZDCRecoParamPbPb(const AliZDCRecoParamPbPb &oldrecopar) : AliZDCRecoParam(), fhNpartDist(0x0), fhbDist(0x0), fClkCenter(oldrecopar.fClkCenter) { //Copy constructor if(oldrecopar.fhNpartDist){ fhNpartDist = new TH1D(*oldrecopar.fhNpartDist); fhNpartDist->SetDirectory(0); } if(oldrecopar.fhbDist){ fhbDist = new TH1D(*oldrecopar.fhbDist); fhbDist->SetDirectory(0); } } //_____________________________________________________________________________ AliZDCRecoParamPbPb &AliZDCRecoParamPbPb::operator =(const AliZDCRecoParamPbPb &recpar) { // Equal operator. this->~AliZDCRecoParamPbPb(); new(this) AliZDCRecoParamPbPb(recpar); return *this; } //_____________________________________________________________________________ AliZDCRecoParamPbPb::~AliZDCRecoParamPbPb() { // destructor if(fhNpartDist) delete fhNpartDist; if(fhbDist) delete fhbDist; } //_____________________________________________________________________________ void AliZDCRecoParamPbPb::SetGlauberMCDist(Float_t beamEnergy) { // Setting Glauber MC distributions // from histos file stored in $ALICE_ROOT/ZDC TH1::AddDirectory(0); TH2::AddDirectory(0); TFile *fileGlauberMC = TFile::Open("$ALICE_ROOT/ZDC/GlauberMCDist.root"); if(!fileGlauberMC) { AliError((" Opening file $ALICE_ROOT/ZDC/GlauberMCDist.root failed\n")); return; } Float_t sqrtS = 2*beamEnergy; // if(TMath::Abs(sqrtS-5500) < 100.){ AliDebug(2, " ZDC -> Looking for energy5500 in file $ALICE_ROOT/ZDC/GlauberMCDist.root"); fileGlauberMC->cd("energy5500"); fileGlauberMC->GetObject("energy5500/hbGlauber;1", fhbDist); if(!fhbDist) AliError(" PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy5500/hNpartGlauber;1", fhNpartDist); if(!fhNpartDist) AliError(" PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); } else if(TMath::Abs(sqrtS-2760) < 100.){ AliDebug(2, " ZDC -> Looking for energy2760 in file $ALICE_ROOT/ZDC/GlauberMCDist.root"); fileGlauberMC->cd("energy2760"); fileGlauberMC->GetObject("energy2760/hbGlauber;1", fhbDist); if(!fhbDist) AliError(" PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy2760/hNpartGlauber;1", fhNpartDist); if(!fhNpartDist) AliError(" PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); } else AliError(Form(" No AliZDCRecoParam provided for Pb-Pb @ sqrt(s) = %1.0f GeV\n", sqrtS)); // fhNpartDist->SetDirectory(0); fhbDist->SetDirectory(0); fileGlauberMC->Close(); } //_____________________________________________________________________________ AliZDCRecoParamPbPb *AliZDCRecoParamPbPb::GetHighFluxParam(Float_t beamEnergy) { // Create high flux reco parameter TH1::AddDirectory(0); TH2::AddDirectory(0); TFile *fileGlauberMC = TFile::Open("$ALICE_ROOT/ZDC/GlauberMCDist.root"); if(!fileGlauberMC) { printf(" Opening file $ALICE_ROOT/ZDC/GlauberMCDist.root failed\n"); return NULL; } Float_t sqrtS = 2*beamEnergy; TH1D *hNpartDist=0x0, *hbDist=0x0; if(TMath::Abs(sqrtS-5500)<100.){ fileGlauberMC->cd("energy5500"); fileGlauberMC->GetObject("energy5500/hNpartGlauber;1", hNpartDist); if(!hNpartDist) printf(" AliZDCRecoParamPbPb::GetHighFluxParam() PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy5500/hbGlauber;1", hbDist); if(!hbDist) printf(" AliZDCRecoParamPbPb::GetHighFluxParam() PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); } else if(TMath::Abs(sqrtS-2760)<100.){ fileGlauberMC->cd("energy2760"); fileGlauberMC->GetObject("energy2760/hNpartGlauber;1", hNpartDist); if(!hNpartDist) printf(" PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy2760/hbGlauber;1", hbDist); if(!hbDist) printf(" AliZDCRecoParamPbPb::GetHighFluxParam() PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); } else printf(" No AliZDCRecoParam provided for Pb-Pb @ sqrt(s) = %1.0f GeV\n", sqrtS); // if(hNpartDist) hNpartDist->SetDirectory(0); if(hbDist) hbDist->SetDirectory(0); AliZDCRecoParamPbPb* zdcRecoParam = new AliZDCRecoParamPbPb(hNpartDist, hbDist, 0.1); // fileGlauberMC->Close(); return zdcRecoParam; }
39.763006
154
0.661579
AllaMaevskaya
da7555f9e196ed7ce8379f7f07916457df86e790
992
cpp
C++
libs/ncurses_lib/libncurses.cpp
elivet/Nibbler
9e2e07d9e3fa3dc86a8e25a6db419359fa0e0e8a
[ "Apache-2.0" ]
null
null
null
libs/ncurses_lib/libncurses.cpp
elivet/Nibbler
9e2e07d9e3fa3dc86a8e25a6db419359fa0e0e8a
[ "Apache-2.0" ]
null
null
null
libs/ncurses_lib/libncurses.cpp
elivet/Nibbler
9e2e07d9e3fa3dc86a8e25a6db419359fa0e0e8a
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libncurses.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elivet <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/03/17 13:54:17 by elivet #+# #+# */ /* Updated: 2015/03/17 13:54:20 by elivet ### ########.fr */ /* */ /* ************************************************************************** */ #include "NcursesLib.hpp" extern "C" ILib * getInstance( void ) { return ( new NcursesLib() ); }
49.6
80
0.157258
elivet
da7f9db3fbf4bb584c0f68caedc692302ca0bcb9
181
cpp
C++
test/simple_consumer.cpp
mmha/gltfpp
9e9e2fe5f8da374838a5b6b03d97963bed87956d
[ "BSL-1.0" ]
25
2017-05-03T04:09:50.000Z
2021-06-06T04:23:54.000Z
test/simple_consumer.cpp
mmha/gltfpp
9e9e2fe5f8da374838a5b6b03d97963bed87956d
[ "BSL-1.0" ]
9
2017-06-02T16:53:11.000Z
2017-06-02T18:05:45.000Z
test/simple_consumer.cpp
mmha/gltfpp
9e9e2fe5f8da374838a5b6b03d97963bed87956d
[ "BSL-1.0" ]
5
2017-06-01T14:38:11.000Z
2019-09-18T07:04:15.000Z
#include <cstdio> #include <gltfpp.h> int main(int argc, char **argv) { gltfpp::glTF g; nlohmann::json j(argv[1]); from_json(j, g); printf("%s", g.asset.copyright->c_str()); }
18.1
42
0.640884
mmha
da816a5740ebbd66adff15d7f6c185d906b311e1
41,955
cpp
C++
tests/tests.cpp
leopoldcambier/spaND_public
fc344dc1ff4b36832aad3f86adb4a23111c67366
[ "MIT" ]
6
2019-05-06T21:17:07.000Z
2022-02-11T14:56:30.000Z
tests/tests.cpp
leopoldcambier/spaND_public
fc344dc1ff4b36832aad3f86adb4a23111c67366
[ "MIT" ]
null
null
null
tests/tests.cpp
leopoldcambier/spaND_public
fc344dc1ff4b36832aad3f86adb4a23111c67366
[ "MIT" ]
1
2019-06-23T12:04:28.000Z
2019-06-23T12:04:28.000Z
#include <gtest/gtest.h> #include <iostream> #include <assert.h> #include <algorithm> #include <random> #include "spaND.h" #include "mmio.hpp" #include "cxxopts.hpp" #include <Eigen/SparseCholesky> using namespace std; using namespace Eigen; using namespace spaND; bool VERB = false; int N_THREADS = 4; int RUN_MANY = 4; SymmKind symm2syk(int symm) { switch(symm) { case 0: return SymmKind::SPD; case 1: return SymmKind::SYM; case 2: return SymmKind::GEN; default: assert(false); }; return SymmKind::SPD; } PartKind pki2pk(int pki) { switch(pki) { case 0: return PartKind::MND; case 1: return PartKind::RB; default: assert(false); }; return PartKind::MND; } ScalingKind ski2sk(int ski) { switch(ski) { case 0: return ScalingKind::LLT; case 1: return ScalingKind::EVD; case 2: return ScalingKind::SVD; case 3: return ScalingKind::PLU; case 4: return ScalingKind::PLUQ; case 5: return ScalingKind::LDLT; default: assert(false); }; return ScalingKind::LLT; } bool is_valid(SymmKind syk, ScalingKind sk, bool preserve) { if(syk == SymmKind::SPD) { if (sk != ScalingKind::LLT) return false; } if(syk == SymmKind::SYM) { if (sk != ScalingKind::LDLT) return false; } if(syk == SymmKind::GEN) { if (sk != ScalingKind::PLU && sk != ScalingKind::PLUQ) return false; } if(preserve) return false; return true; } struct params { SymmKind syk; PartKind pk; ScalingKind sk; bool preserve; }; vector<params> get_params() { vector<params> configs; for(int symm = 0; symm < 3; symm++) { for(int pki = 0; pki < 2; pki++) { for(int ski = 0; ski < 6; ski++) { for(int pres = 0; pres < 2; pres++) { PartKind pk = pki2pk(pki); ScalingKind sk = ski2sk(ski); SymmKind syk = symm2syk(symm); if(! is_valid(syk, sk, pres)) continue; configs.push_back({syk, pk, sk, pres == 1}); } } } } return configs; }; SpMat neglapl(int n, int d) { stringstream s; s << "../mats/neglapl_" << d << "_" << n << ".mm"; string file = s.str(); SpMat A = mmio::sp_mmread<double,int>(file); return A; } SpMat neglapl_unsym(int n, int d, int seed) { SpMat A = neglapl(n, d); default_random_engine gen; gen.seed(seed); uniform_real_distribution<double> rand(-0.1, 0.1); for(int k = 0; k < A.outerSize(); ++k) { for(SpMat::InnerIterator it(A, k); it; ++it) { A.coeffRef(it.row(), it.col()) += rand(gen); } } return A; } SpMat make_indef(SpMat& A, int seed) { Eigen::SimplicialLLT<SpMat, Eigen::Lower> sllt(A); VectorXd random_diagonal = random(A.rows(), seed); for(int i = 0; i < A.rows(); i++) { if(random_diagonal[i] <= 0.9) { random_diagonal[i] = -1; } else { random_diagonal[i] = 1; } } SpMat L = sllt.matrixL(); return L * (random_diagonal.asDiagonal() * L.transpose()); } SpMat random_SpMat(int n, double p, int seed) { default_random_engine gen; gen.seed(seed); uniform_real_distribution<double> dist(0.0,1.0); vector<Triplet<double>> triplets; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { auto v_ij = dist(gen); if(v_ij < p) { triplets.push_back(Triplet<double>(i,j,v_ij)); } } } SpMat A(n,n); A.setFromTriplets(triplets.begin(), triplets.end()); return A; } SpMat identity_SpMat(int n) { vector<Triplet<double>> triplets; for(int i = 0; i < n; ++i) { triplets.push_back(Triplet<double>(i,i,1.0)); } SpMat A(n,n); A.setFromTriplets(triplets.begin(), triplets.end()); return A; } TEST(MatrixMarket, Sparse) { // 1 SpMat A = mmio::sp_mmread<double,int>("../mats/test1.mm"); SpMat Aref(2, 3); Aref.insert(0, 0) = 1; Aref.insert(0, 1) = -2e2; Aref.insert(1, 1) = 3e3; Aref.insert(1, 2) = -4.4e4; EXPECT_EQ(A.nonZeros(), 4); EXPECT_EQ((Aref - A).norm(), 0.0); // 2 A = mmio::sp_mmread<double,int>("../mats/test2.mm"); Aref = SpMat(3, 3); Aref.insert(0, 0) = 1.1; Aref.insert(1, 1) = 2e2; Aref.insert(2, 0) = -3.3; Aref.insert(0, 2) = -3.3; EXPECT_EQ(A.nonZeros(), 4); EXPECT_EQ((Aref - A).norm(), 0.0); // 3 A = mmio::sp_mmread<double,int>("../mats/test3.mm"); Aref = SpMat(4, 1); Aref.insert(3, 0) = -1; EXPECT_EQ(A.nonZeros(), 1); EXPECT_EQ((Aref - A).norm(), 0.0); // 4 A = mmio::sp_mmread<double,int>("../mats/test4.mm"); Aref = SpMat(2, 2); Aref.insert(1, 0) = -3.3; Aref.insert(0, 1) = -3.3; EXPECT_EQ(A.nonZeros(), 2); EXPECT_EQ((Aref - A).norm(), 0.0); } TEST(MatrixMarket, Array) { // 5 MatrixXd A = mmio::dense_mmread<double>("../mats/test5.mm"); EXPECT_EQ(A.rows(), 2); EXPECT_EQ(A.cols(), 3); MatrixXd Aref(2, 3); Aref << 1, 3, -5, 2, 4, 1e6; // row-wise filling in eigen EXPECT_EQ((Aref - A).norm(), 0.0); // 6 A = mmio::dense_mmread<double>("../mats/test6.mm"); Aref = MatrixXd(2, 2); EXPECT_EQ(A.rows(), 2); EXPECT_EQ(A.cols(), 2); Aref << 1, -2, -2, 3; // row-wise filling in eigen EXPECT_EQ((Aref - A).norm(), 0.0); } /** Util.cpp tests **/ TEST(Util, AreConnected) { // 3x3 laplacian SpMat A = mmio::sp_mmread<double,int>("../mats/neglapl_2_3.mm"); VectorXi a(2); VectorXi b(3); a << 0, 1; b << 6, 7, 8; EXPECT_FALSE(are_connected(a, b, A)); a = VectorXi(2); b = VectorXi(3); a << 0, 1; b << 2, 5, 8; EXPECT_TRUE(are_connected(a, b, A)); a = VectorXi(2); b = VectorXi(1); a << 3, 4; b << 5; EXPECT_TRUE(are_connected(a, b, A)); a = VectorXi(1); b = VectorXi(1); a << 6; b << 6; EXPECT_TRUE(are_connected(a, b, A)); } TEST(Util, ShouldBeDisconnected) { EXPECT_TRUE(should_be_disconnected(0, 0, 0, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 1, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 4, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 5, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 1000, 2)); EXPECT_TRUE(should_be_disconnected(1, 2, 2, 0)); EXPECT_TRUE(should_be_disconnected(0, 1, 1, 1)); EXPECT_TRUE(should_be_disconnected(0, 2, 1, 1)); EXPECT_TRUE(should_be_disconnected(2, 0, 0, 5)); EXPECT_TRUE(should_be_disconnected(2, 2, 0, 1)); EXPECT_FALSE(should_be_disconnected(0, 1, 0, 0)); EXPECT_FALSE(should_be_disconnected(0, 2, 0, 0)); EXPECT_FALSE(should_be_disconnected(0, 10, 0, 0)); EXPECT_FALSE(should_be_disconnected(2, 0, 1, 5)); EXPECT_FALSE(should_be_disconnected(2, 0, 1, 6)); EXPECT_FALSE(should_be_disconnected(2, 1, 1, 2)); EXPECT_FALSE(should_be_disconnected(2, 1, 1, 3)); } TEST(Util, ChooseRank) { VectorXd errs = VectorXd(5); errs << 1.0, -0.1, 0.01, -0.001, 1e-4; EXPECT_EQ(choose_rank(errs, 1e-1), 2); EXPECT_EQ(choose_rank(errs, 1e-2), 3); EXPECT_EQ(choose_rank(errs, 1.0), 0); EXPECT_EQ(choose_rank(errs, 0), 5); EXPECT_EQ(choose_rank(errs, 1e-16), 5); } TEST(Util, Block2Dense) { // Usual case { SpMat A(5, 5); A.insert(0, 0) = 1.0; A.insert(2, 2) = -2.0; A.insert(1, 3) = 3.0; A.makeCompressed(); VectorXi rowval = Map<VectorXi>(A.innerIndexPtr(), A.nonZeros()); VectorXi colptr = Map<VectorXi>(A.outerIndexPtr(), 6); VectorXd nnzval = Map<VectorXd>(A.valuePtr(), A.nonZeros()); MatrixXd Ad = MatrixXd::Zero(3, 3); block2dense(rowval, colptr, nnzval, 1, 1, 3, 3, &Ad, false); MatrixXd Adref = MatrixXd::Zero(3, 3); Adref << 0, 0, 3, 0, -2, 0, 0, 0, 0; EXPECT_EQ((Adref - Ad).norm(), 0); } // Transpose { SpMat A(3, 4); A.insert(0, 1) = 1.0; A.insert(1, 0) = 2.0; A.insert(1, 2) = 3.0; A.insert(2, 1) = 4.0; A.insert(0, 3) = 5.0; A.makeCompressed(); VectorXi rowval = Map<VectorXi>(A.innerIndexPtr(), A.nonZeros()); VectorXi colptr = Map<VectorXi>(A.outerIndexPtr(), 5); VectorXd nnzval = Map<VectorXd>(A.valuePtr(), A.nonZeros()); MatrixXd Ad = MatrixXd::Zero(3, 2); block2dense(rowval, colptr, nnzval, 0, 0, 2, 3, &Ad, true); MatrixXd Adref = MatrixXd::Zero(3, 2); Adref << 0, 2, 1, 0, 0, 3; EXPECT_EQ((Adref - Ad).norm(), 0); } } TEST(Util, LinspaceNd) { MatrixXd X2 = linspace_nd(3, 2); MatrixXd X2ref(2, 9); X2ref << 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2; EXPECT_EQ((X2ref - X2).norm(), 0); MatrixXd X3 = linspace_nd(2, 3); MatrixXd X3ref(3, 8); X3ref << 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1; EXPECT_EQ((X3ref - X3).norm(), 0); } TEST(Util, SymmPerm) { vector<int> dims = {2, 2, 2, 3, 3, 3, 3 }; vector<int> sizes = {5, 10, 20, 5, 15, 25, 30}; for(int test = 0; test < dims.size(); test++) { int s = sizes[test]; int d = dims[test]; stringstream ss; ss << "../mats/neglapl_" << d << "_" << s << ".mm"; SpMat A = mmio::sp_mmread<double,int>(ss.str()); // Create random perm int N = A.rows(); VectorXi p = VectorXi::LinSpaced(N, 0, N-1); random_device rd; mt19937 g(rd()); shuffle(p.data(), p.data() + N, g); // Compare SpMat pAp = symm_perm(A, p); SpMat pApref = p.asPermutation().inverse() * A * p.asPermutation(); EXPECT_EQ((pAp - pApref).norm(), 0.0); } } TEST(Util, isperm) { VectorXi perm1(10); VectorXi perm2(10); VectorXi noperm1(10); VectorXi noperm2(5); perm1 << 0, 9, 8, 1, 4, 2, 3, 7, 5, 6; perm2 << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9; noperm1 << 0, 9, 8, 1, 4, 2, 3, 5, 5, 6; noperm2 << 0, 9, 8, 1, 4; EXPECT_TRUE(isperm(&perm1)); EXPECT_TRUE(isperm(&perm2)); EXPECT_FALSE(isperm(&noperm1)); EXPECT_FALSE(isperm(&noperm2)); } TEST(Util, swap2perm) { VectorXi swap(6); VectorXi perm(6); VectorXi permRef(6); swap << 3, 3, 2, 5, 4, 5; permRef << 3, 0, 2, 5, 4, 1; swap2perm(&swap, &perm); // perm.asPermutation().transpose() * x <=> x[perm] EXPECT_EQ((perm - permRef).norm(), 0.0); } SpMat symmetric_graph_ref(SpMat A) { SpMat ATabs = A.cwiseAbs().transpose(); return A.cwiseAbs() + ATabs + identity_SpMat(A.rows()); } TEST(Util, symmetric_graph) { for(int i = 1; i < 100; i++) { SpMat A = random_SpMat(i, 0.2, i); SpMat AAT = symmetric_graph(A); EXPECT_LT( (AAT - symmetric_graph_ref(A)).norm(), 1e-12); } } /** Partitioning tests **/ /** * Check the partitioning of a square laplacian 5x5 */ TEST(PartitionTest, Square) { SpMat A = mmio::sp_mmread<double,int>("../mats/neglapl_2_5.mm"); MatrixXd X = linspace_nd(5, 2); Tree t(3); t.set_verb(VERB); t.set_use_geo(true); t.set_Xcoo(&X); auto part = t.partition(A); vector<SepID> sepidref { SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1), SepID(2,0), SepID(2,0), SepID(2,0), SepID(2,0), SepID(2,0), SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3), } ; vector<SepID> leftref { SepID(0,0), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1), SepID(0,2), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), } ; vector<SepID> rightref { SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,1), SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,3), } ; for(int i = 0; i < part.size(); i++) { ASSERT_TRUE(part[i].self == sepidref[i]); ASSERT_TRUE(part[i].l == leftref[i]); ASSERT_TRUE(part[i].r == rightref[i]); } } /** * Check consistency of the partitioning */ TEST(PartitionTest, Consistency) { vector<int> dims = {2, 2, 2, 3, 3, 3 }; vector<int> sizes = {5, 20, 100, 5, 15, 25}; for(int test = 0; test < dims.size(); test++) { int s = sizes[test]; int d = dims[test]; stringstream ss; ss << "../mats/neglapl_" << d << "_" << s << ".mm"; int n = pow(s, d); string file = ss.str(); for(int nlevels = 1; nlevels < 8; nlevels++) { for(int geoi = 0; geoi < 2; geoi++) { for(int pki = 0; pki < 2; pki++) { bool geo = (geoi == 0); PartKind pk = pki == 0 ? PartKind::MND : PartKind::RB; // Partition tree MatrixXd X = linspace_nd(s, d); Tree t(nlevels); t.set_verb(VERB); SpMat A = mmio::sp_mmread<double,int>(file); t.set_use_geo(geo); t.set_Xcoo(&X); t.set_part_kind(pk); auto part = t.partition(A); // (1) Lengths ASSERT_EQ(part.size(), n); // (2) Check ordering integrity for(int i = 0; i < n; i++) { auto pi = part[i].self; for (SpMat::InnerIterator it(A,i); it; ++it) { int j = it.row(); auto pj = part[j].self; ASSERT_FALSE(should_be_disconnected(pi.lvl, pj.lvl, pi.sep, pj.sep)); } } // (3) Check left/right integrity for(int i = 0; i < n; i++) { auto pi = part[i].self; auto li = part[i].l; auto ri = part[i].r; if(pi.lvl == 0) { ASSERT_TRUE(pi == li); ASSERT_TRUE(pi == ri); } else { ASSERT_TRUE(pi.lvl > li.lvl); ASSERT_TRUE(pi.lvl > ri.lvl); while(li.lvl < pi.lvl - 1) { li.lvl += 1; li.sep /= 2; } while(ri.lvl < pi.lvl - 1) { ri.lvl += 1; ri.sep /= 2; } ASSERT_TRUE(li.lvl == pi.lvl - 1); ASSERT_TRUE(ri.lvl == pi.lvl - 1); ASSERT_TRUE(li.sep == 2 * pi.sep); ASSERT_TRUE(ri.sep == 2 * pi.sep + 1); } } } } } } } /** Assembly tests **/ /** * Check assembly */ TEST(Assembly, Consistency) { vector<int> dims = {2, 2, 2, 3, 3, 3}; vector<int> sizes = {5, 10, 20, 5, 10, 15}; for(int spandlorasp = 0; spandlorasp < 2; spandlorasp++) { for(int test = 0; test < dims.size(); test++) { for(int pki = 0; pki < 2; pki++) { PartKind pk = pki == 0 ? PartKind::MND : PartKind::RB; int s = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test); for(int nlevels = 2; nlevels < 5 ; nlevels++) { /** * Symmetric case */ { // Partition and assemble Tree t(nlevels); t.set_verb(VERB); t.set_use_geo(false); t.set_part_kind(pk); if(spandlorasp == 0) t.partition(Aref); else t.partition_lorasp(Aref); t.assemble(Aref); // Get permutation VectorXi p = t.get_assembly_perm(); // Check it's indeed a permutation ASSERT_TRUE(isperm(&p)); auto P = p.asPermutation(); // Check get_mat() SpMat A2 = t.get_trailing_mat(); EXPECT_EQ((P.inverse() * Aref * P - A2).norm(), 0.0); } /** * Unsymmetric case */ { // Partition and assemble Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(SymmKind::GEN); t.set_use_geo(false); t.set_part_kind(pk); if(spandlorasp == 0) t.partition(Arefunsym); else t.partition_lorasp(Arefunsym); t.assemble(Arefunsym); // Get permutation VectorXi p = t.get_assembly_perm(); // Check it's indeed a permutation ASSERT_TRUE(isperm(&p)); auto P = p.asPermutation(); // Check get_mat() SpMat A2 = t.get_trailing_mat(); EXPECT_EQ((P.inverse() * Arefunsym * P - A2).norm(), 0.0); } } } } } } /** Factorization tests **/ TEST(ApproxTest, PrintConfigs) { vector<params> configs = get_params(); cout << "Preserve ? PartKind ? ScalingKind ? SymmKind ?" << endl; for(auto c: configs) { cout << c.preserve << " " << part2str(c.pk) << " " << scaling2str(c.sk) << " " << symm2str(c.syk) << endl; } } /** * Test that with eps=0, we get exact solutions */ TEST(ApproxTest, Exact) { vector<int> dims = {2, 2, 2, 3, 3}; vector<int> sizes = {5, 10, 20, 5, 15}; vector<double> tols = {1e-14, 1e-14, 0.0}; vector<int> skips = {0, 4, 1000}; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { cout << "Test " << test << "... "; int count = 0; int s = sizes[test]; int d = dims[test]; int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test); SpMat Arefsym = make_indef(Aref, 2019+test); for(int nlevels = nlevelsmin; nlevels < nlevelsmin+5 ; nlevels++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? Arefsym : Arefunsym)); assert(! c.preserve); MatrixXd phi = random(Aref.rows(), 3, test+nlevels+2019); for(int it = 0; it < tols.size(); it++) { double tol = tols[it]; double skip = skips[it]; Tree t(nlevels); t.set_verb(VERB); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); t.set_symm_kind(c.syk); t.partition(A); t.assemble(A); t.set_tol(tol); t.set_skip(skip); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); t.factorize(); VectorXd b = random(n, test+nlevels+2019+1); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); EXPECT_LE(err, 1e-10) << err; count++; } } } cout << count << " tested.\n"; } } /** * Test SPD on A (laplacian) and SYM+LDLT on -A (- laplacian) give the same, with or without compression */ TEST(ApproxTest, SPD_vs_LDLT) { vector<int> dims = {2, 3, 3}; vector<int> sizes = {128, 5, 15}; vector<double> tols = {0, 1e-4, 1e-14}; vector<int> skips = {100, 1, 0}; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { cout << "Test " << test << "... "; int count = 0; int s = sizes[test]; int d = dims[test]; int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; SpMat A = neglapl(s, d); SpMat Aneg = -A; for(int nlevels = nlevelsmin; nlevels < nlevelsmin+5 ; nlevels++) { for(auto c: configs) { if(c.sk != ScalingKind::LLT && !c.preserve) continue; for(int it = 0; it < tols.size(); it++) { double tol = tols[it]; double skip = skips[it]; VectorXd b = random(n, test+nlevels+2019+1); // Use LLT on A Tree t_llt(nlevels); t_llt.set_verb(VERB); t_llt.set_part_kind(c.pk); t_llt.set_scaling_kind(ScalingKind::LLT); t_llt.set_symm_kind(SymmKind::SPD); t_llt.partition(A); t_llt.assemble(A); t_llt.set_tol(tol); t_llt.set_skip(skip); t_llt.set_preserve(false); t_llt.factorize(); VectorXd x_llt = b; t_llt.solve(x_llt); // Use LDLT on -A Tree t_ldlt(nlevels); t_ldlt.set_verb(VERB); t_ldlt.set_part_kind(c.pk); t_ldlt.set_scaling_kind(ScalingKind::LDLT); t_ldlt.set_symm_kind(SymmKind::SYM); t_ldlt.partition(Aneg); t_ldlt.assemble(Aneg); t_ldlt.set_tol(tol); t_ldlt.set_skip(skip); t_ldlt.set_preserve(false); t_ldlt.factorize(); VectorXd x_ldlt = - b; t_ldlt.solve(x_ldlt); // Compare double err_llt = (A*x_llt-b).norm() / b.norm(); double err_ldlt = (A*x_ldlt-b).norm() / b.norm(); double diff = (x_llt - x_ldlt).norm() / x_llt.norm(); if (tol == 0.0) { EXPECT_LE(err_llt, 1e-12); EXPECT_LE(err_ldlt, 1e-12); EXPECT_LE(diff, 1e-12); } else { EXPECT_LE(err_llt, tol * 1e2); EXPECT_LE(err_ldlt, tol * 1e2); EXPECT_LE(diff, tol * 1e2); } count++; } } } cout << count << " tested.\n"; } } /** * Test conservation is correct */ TEST(ApproxTest, Preservation) { vector<int> dims = {2, 2, 2, 3, 3, 3}; vector<int> sizes = {5, 10, 20, 5, 10, 25}; for(int test = 0; test < dims.size(); test++) { cout << "Test " << test; int s = sizes[test]; int d = dims[test]; stringstream ss; ss << "../mats/neglapl_" << d << "_" << s << ".mm"; int n = pow(s, d); string file = ss.str(); SpMat A_spd = mmio::sp_mmread<double,int>(file); SpMat A_sym = - A_spd; int nlevelsmin = n < 1000 ? 1 : 8; vector<double> tols = {10, 1e-2, 1e-3, 1e-4, 1e-6, 0.0}; for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) { for(int it = 0; it < tols.size(); it++) { for(int skip = 0; skip < 3; skip++) { for(int symm = 0; symm < 2; symm++) { printf("."); fflush(stdout); SpMat A; if(symm == 0) A = A_spd; else A = A_sym; // Check a 1 is preserved { Tree t(nlevels); if(symm == 0) { t.set_scaling_kind(ScalingKind::LLT); t.set_symm_kind(SymmKind::SPD); } else { t.set_scaling_kind(ScalingKind::LDLT); t.set_symm_kind(SymmKind::SYM); } t.set_verb(VERB); t.partition(A); t.assemble(A); MatrixXd phi = MatrixXd::Ones(n, 1); t.set_tol(tols[it]); t.set_skip(skip); t.set_preserve(true); t.set_phi(&phi); t.factorize(); for(int c = 0; c < phi.cols(); c++) { VectorXd b = A * phi.col(c); VectorXd x = b; t.solve(x); double err1 = (A*x-b).norm() / b.norm(); double err2 = (x-phi.col(c)).norm() / phi.col(c).norm(); EXPECT_TRUE(err1 < 1e-12) << "err1 = " << err1 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; EXPECT_TRUE(err2 < 1e-12) << "err2 = " << err2 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; } VectorXd b = random(n, nlevels+it+skip+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); if (tols[it] == 0.0) { EXPECT_TRUE(err < 1e-12); } else { EXPECT_TRUE(err < tols[it] * 1e2); } } // Check that a multiple random b are preserved { Tree t(nlevels); if(symm == 0) { t.set_scaling_kind(ScalingKind::LLT); t.set_symm_kind(SymmKind::SPD); } else { t.set_scaling_kind(ScalingKind::LDLT); t.set_symm_kind(SymmKind::SYM); } t.set_verb(VERB); t.partition(A); t.assemble(A); MatrixXd phi = random(n, 5, nlevels+it+skip+2019); t.set_tol(tols[it]); t.set_skip(skip); t.set_preserve(true); t.set_phi(&phi); t.factorize(); for(int c = 0; c < phi.cols(); c++) { VectorXd b = A * phi.col(c); VectorXd x = b; t.solve(x); double err1 = (A*x-b).norm() / b.norm(); double err2 = (x-phi.col(c)).norm() / phi.col(c).norm(); EXPECT_TRUE(err1 < 1e-12) << "err1 = " << err1 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; EXPECT_TRUE(err2 < 1e-12) << "err2 = " << err2 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; } VectorXd b = random(n, nlevels+it+skip+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); if (tols[it] == 0.0) { EXPECT_TRUE(err < 1e-12); } else { EXPECT_TRUE(err < tols[it] * 1e2); } } } } } } printf("\n"); } } /** * Test that the approximations are reasonnable accurate * with and without preservation */ TEST(ApproxTest, Approx) { vector<int> dims = {2, 2, 2, 2, 3, 3}; vector<int> sizes = {5, 10, 20, 128, 5, 15}; vector<double> tols = {0.0, 1e-10, 1e-6, 1e-2, 10}; matrix_hash<VectorXd> hash; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { vector<size_t> allhashes; int count = 0; cout << "Test " << test << "... "; int s = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test+2019); SpMat Arefsym = - Aref; int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) { for(int it = 0; it < tols.size(); it++) { for(int skip = 0; skip < 3; skip++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? Arefsym : Arefunsym)); assert(! c.preserve); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); t.partition(A); t.assemble(A); MatrixXd phi = random(A.rows(), 2, nlevels+it+skip+2019); t.set_tol(tols[it]); t.set_skip(skip); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); t.factorize(); VectorXd b = random(n, nlevels+it+skip+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); auto hb = hash(b); auto hx = hash(x); allhashes.push_back(hb); allhashes.push_back(hx); if (tols[it] == 0.0) { EXPECT_LE(err, 5e-12); } else { EXPECT_LE(err, tols[it] * 2e2); } count++; } } } } size_t h = hashv(allhashes); cout << count << " tested. Overall hash(x,b) = " << h << endl; } } TEST(ApproxTest, ApproxLoRaSp) { vector<int> dims = {2, 2, 2, 2, 3, 3}; vector<int> sizes = {5, 10, 20, 64, 5, 15}; vector<double> tols = {0.0, 1e-10, 1e-6, 1e-4}; matrix_hash<VectorXd> hash; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { vector<size_t> allhashes; int count = 0; cout << "Test " << test << "... "; int s = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test+2019); int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) { for(int it = 0; it < tols.size(); it++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym)); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_scaling_kind(c.sk); t.partition_lorasp(A); t.assemble(A); MatrixXd phi = random(A.rows(), 2, nlevels+it+2019); t.set_tol(tols[it]); try { t.factorize_lorasp(); VectorXd b = random(n, nlevels+it+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); auto hb = hash(b); auto hx = hash(x); allhashes.push_back(hb); allhashes.push_back(hx); if (tols[it] == 0.0) { EXPECT_LE(err, 5e-12); } else { EXPECT_LE(err, tols[it] * 2e2); } } catch (exception& ex) { cout << ex.what(); EXPECT_TRUE(false); } count++; } } } size_t h = hashv(allhashes); cout << count << " tested. Overall hash(x,b) = " << h << endl; } } /** * Test that the code produce reproducable results */ TEST(ApproxTest, Repro) { int dims[3] = {2, 2, 2}; int sizes[3] = {20, 64, 16}; double tols[4] = {1e-5, 10, 1e-8, 0.1}; double skips[4] = {1, 2, 0, 1}; int repeat = 10; vector<params> configs = get_params(); for(int test = 0; test < 3; test++) { printf("Tests "); fflush(stdout); int count = 0; int s = sizes[test]; int d = dims[test]; int n = pow(s, d); SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test); for(int nlevels = 5; nlevels < 7; nlevels++) { for(int pr = 0; pr < 6; pr++) { for(auto c: configs) { for(int lrsp = 0; lrsp < 2; lrsp++) { printf("."); fflush(stdout); SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym)); MatrixXd phi = random(A.rows(), 3, test+nlevels+pr+2019); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); if(lrsp == 0) { t.partition(A); } else { t.partition_lorasp(A); } t.assemble(A); t.set_tol(tols[pr]); t.set_skip(skips[pr]); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); if(lrsp == 0) { t.factorize(); } else { t.factorize_lorasp(); } VectorXd b = random(n, nlevels+test); auto xref = b; t.solve(xref); count++; for(int i = 0; i < repeat; i++) { Tree t2(nlevels); t2.set_verb(VERB); t2.set_symm_kind(c.syk); t2.set_part_kind(c.pk); t2.set_scaling_kind(c.sk); if(lrsp == 0) { t2.partition(A); } else { t2.partition_lorasp(A); } t2.assemble(A); t2.set_tol(tols[pr]); t2.set_skip(skips[pr]); t2.set_preserve(c.preserve); t2.set_phi(&phi); if(lrsp == 0) { t2.factorize(); } else { t2.factorize_lorasp(); } auto x = b; t2.solve(x); EXPECT_EQ((xref - x).norm(), 0.0); } } } } } printf(": %d tested.\n", count); fflush(stdout); } } TEST(Run, Many) { vector<int> dims = {2, 2, 2, 3, 3, 3 }; vector<int> sizes = {5, 16, 64, 5, 10, 15}; vector<double> tols = {0.0, 1e-2, 1.0, 10.0}; RUN_MANY = RUN_MANY > dims.size() ? dims.size() : RUN_MANY; matrix_hash<VectorXd> hash; vector<size_t> allhashes; vector<params> configs = get_params(); for(int test = 0; test < RUN_MANY; test++) { cout << "Run " << test << "... \n"; int count = 0; int n = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(n, d); SpMat Arefunsym = neglapl_unsym(n, d, test); int N = Aref.rows(); int nlevelsmin = N < 1000 ? 1 : 8; for(int nlevels = nlevelsmin; nlevels < nlevelsmin+3; nlevels++) { for(double tol : tols) { for(int skip = 0; skip < 3; skip++) { for(int geo = 0; geo < 2; geo++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym)); MatrixXd phi = random(A.rows(), 3, test+nlevels+2019); MatrixXd X = linspace_nd(n, d); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); t.set_use_geo(geo); t.set_Xcoo(&X); t.set_tol(tol); t.set_skip(skip); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); t.partition(A); t.assemble(A); t.factorize(); VectorXd b = random(N, nlevels+test); auto x = b; t.solve(x); double res = (A*x-b).norm() / b.norm(); auto h = hash(x); allhashes.push_back(h); printf("%6d %4d %d] %3d %3.2e %d %d %d %d %d %d %d %d | %3.2e | %lu\n", N, n, d, nlevels, tol, skip, geo, c.preserve, int(c.syk), int(c.pk), int(c.sk), 1, 1, res, h); count++; } } } } } cout << "Ran " << count << " tests\n"; size_t h = hashv(allhashes); cout << "Overall hash so far: " << h << endl; } size_t h = hashv(allhashes); cout << "Overall hash: " << h << endl; } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); cxxopts::Options options("spaND tests", "Test suite for the spaND algorithms."); options.add_options() ("help", "Print help") ("v,verb", "Verbose (default: false)", cxxopts::value<bool>()->default_value("false")) ("n_threads", "Number of threads", cxxopts::value<int>()->default_value("4")) ("run", "How many Run.Many to run", cxxopts::value<int>()->default_value("4")) ; auto result = options.parse(argc, argv); if (result.count("help")) { cout << options.help({"", "Group"}) << endl; exit(0); } VERB = result["verb"].as<bool>(); N_THREADS = result["n_threads"].as<int>(); RUN_MANY = result["run"].as<int>(); cout << "n_threads: " << N_THREADS << endl; cout << "verb: " << VERB << endl; cout << "run: " << RUN_MANY << endl; return RUN_ALL_TESTS(); }
38.526171
150
0.420307
leopoldcambier
da81b258e5dc04a7f321af81e570619d695af003
2,531
cpp
C++
COMToys/src/MfcModule.cpp
skst/Timekeeper
4aba38fe891cd8681f2ef290d47a147e2fef5f29
[ "MIT" ]
4
2021-05-28T03:27:21.000Z
2022-02-17T02:09:16.000Z
COMToys/src/MfcModule.cpp
skst/Timekeeper
4aba38fe891cd8681f2ef290d47a147e2fef5f29
[ "MIT" ]
2
2021-05-03T20:00:53.000Z
2021-10-31T16:05:39.000Z
COMToys/src/MfcModule.cpp
skst/Timekeeper
4aba38fe891cd8681f2ef290d47a147e2fef5f29
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////// // ComToys(TM) Copyright 1999 Paul DiLascia // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // #include "StdAfx.h" #include "COMtoys/ComToys.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNAMIC(CTMfcModule, COleControlModule); CTMfcModule::CTMfcModule() { } CTMfcModule::~CTMfcModule() { } BOOL CTMfcModule::InitInstance() { CTTRACEFN(_T(__FUNCTION__) _T("\n")); //skst /* CTRegistrar uses IRegistrar--a completely undocumented ATL interface. What's also undocumented is that it requires atl.dll, which is not present on Windows 98 with IE 5.0. It is present after we install IE 6.0. Who knows about IE 5.5? Thanks, Microsoft. */ CTTRACE(_T("\tbefore CTRegistrar ctor\n")); CTRegistrar r; CTTRACE(_T("\tafter CTRegistrar ctor\n")); if (!r) { ::AfxMessageBox(_T("This requires Microsoft Internet Explorer 6.0.")); return FALSE; } //skst if (!CTModule::InitInstance(CWinApp::m_hInstance)) return FALSE; return COleControlModule::InitInstance(); } int CTMfcModule::ExitInstance() { CTTRACEFN(_T("CTMfcModule::ExitInstance\n")); CTModule::ExitInstance(); return COleControlModule::ExitInstance(); } ///////////////////////////////////////////////////////////////////////////// // Implementation special DLL entry points. // Call MFC to do the work. HRESULT CTMfcModule::OnGetClassObject(REFCLSID clsid, REFIID iid, LPVOID* ppv) { CTTRACEFN(_T("CTMfcModule::OnGetClassObject\n")); HRESULT hr = AfxDllGetClassObject(clsid, iid, ppv); if (*ppv==NULL) { TRACE(_T("***CTMfcModule::OnGetClassObject failed\n")); TRACE(_T("***Did you create factories before calling CTMfcModule::InitInstance?\n")); } return hr; } HRESULT CTMfcModule::OnCanUnloadNow(void) { CTTRACEFN(_T("CTMfcModule::OnCanUnloadNow\n")); return AfxDllCanUnloadNow(); } HRESULT CTMfcModule::OnRegisterServer(BOOL bRegister) { CTTRACEFN(_T("CTMfcModule::OnRegisterServer\n")); HRESULT hr =CTModule::OnRegisterServer(bRegister); if (hr!=S_OK) return hr; return COleObjectFactory::UpdateRegistryAll(bRegister) ? S_OK : SELFREG_E_CLASS; } HRESULT CTMfcModule::OnInstall(BOOL bInstall, LPCWSTR pszCmdLine) { CTTRACEFN(_T("CTMfcModule::OnInstall\n")); return CTModule::OnInstall(bInstall, pszCmdLine); }
26.642105
88
0.657053
skst
da849d94b46b8367d17b45f3d35438e7a47dc893
2,101
cc
C++
riscos/libs/tbx/tbx/showfullobject.cc
riscoscloverleaf/chatcube
a7184ef76108f90a74a88d3183a3d21c1249a0f5
[ "MIT" ]
null
null
null
riscos/libs/tbx/tbx/showfullobject.cc
riscoscloverleaf/chatcube
a7184ef76108f90a74a88d3183a3d21c1249a0f5
[ "MIT" ]
null
null
null
riscos/libs/tbx/tbx/showfullobject.cc
riscoscloverleaf/chatcube
a7184ef76108f90a74a88d3183a3d21c1249a0f5
[ "MIT" ]
null
null
null
/* * tbx RISC OS toolbox library * * Copyright (C) 2010-2012 Alan Buckley 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. */ /* * showfullobject.cc * * Created on: 28-Nov-2008 * Author: alanb */ #include "showfullobject.h" #include "swixcheck.h" #include <swis.h> namespace tbx { /** * Show object with full position specified * */ void ShowFullObject::show(const ShowFullSpec &full_spec) { swix_check(_swix(0x44EC3, _INR(0,5), 0, _handle, 1, &(full_spec.visible_area), 0, -1)); } /** * Show object with full position specified */ void ShowFullObject::show(const ShowFullSpec &full_spec, const Object &parent) { swix_check(_swix(0x44EC3, _INR(0,5), 0, _handle, 1, &(full_spec.visible_area), parent.handle(), -1)); } /** * Show object with full position specified */ void ShowFullObject::show(const ShowFullSpec &full_spec, const Component &parent) { swix_check(_swix(0x44EC3, _INR(0,5), 0, _handle, 1, &(full_spec.visible_area), parent.handle(), parent.id())); } }
26.2625
81
0.712994
riscoscloverleaf
da8713d45b134a834101c7b33493fbe16708ffaf
2,927
cpp
C++
DialogTools/GetisOrdChoiceDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
DialogTools/GetisOrdChoiceDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
DialogTools/GetisOrdChoiceDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
/** * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved * * This file is part of GeoDa. * * GeoDa 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. * * GeoDa 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, see <http://www.gnu.org/licenses/>. */ #include <wx/xrc/xmlres.h> #include "../logger.h" #include "GetisOrdChoiceDlg.h" BEGIN_EVENT_TABLE( GetisOrdChoiceDlg, wxDialog ) EVT_BUTTON( wxID_OK, GetisOrdChoiceDlg::OnOkClick ) EVT_RADIOBUTTON( XRCID("IDC_W_ROW_STAND"), GetisOrdChoiceDlg::OnRadioWStand ) EVT_RADIOBUTTON( XRCID("IDC_W_BINARY"), GetisOrdChoiceDlg::OnRadioWBinary ) END_EVENT_TABLE() GetisOrdChoiceDlg::GetisOrdChoiceDlg( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { SetParent(parent); CreateControls(); Centre(); row_standardize_weights = true; } void GetisOrdChoiceDlg::CreateControls() { wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_GETIS_ORD_CHOICE"); gi_clus_map_perm_check = wxDynamicCast(FindWindow(XRCID("IDC_GI_CHECK")), wxCheckBox); gi_star_clus_map_perm_check = wxDynamicCast(FindWindow(XRCID("IDC_GI_STAR_CHECK")), wxCheckBox); show_sig_map_check = wxDynamicCast(FindWindow(XRCID("IDC_SIG_MAPS_CHECK")), wxCheckBox); show_norm_pval_check = wxDynamicCast(FindWindow(XRCID("IDC_NORM_P_VAL_CHECK")), wxCheckBox); w_row_standardize = wxDynamicCast(FindWindow(XRCID("IDC_W_ROW_STAND")), wxRadioButton); w_binary = wxDynamicCast(FindWindow(XRCID("IDC_W_BINARY")), wxRadioButton); } void GetisOrdChoiceDlg::OnOkClick( wxCommandEvent& event ) { bool gi = gi_clus_map_perm_check->GetValue() == 1; bool gi_star = gi_star_clus_map_perm_check->GetValue() == 1; bool sig_map = show_sig_map_check->GetValue() == 1; bool norm_pval = show_norm_pval_check->GetValue() == 1; Gi_ClustMap_norm = norm_pval && gi; Gi_SigMap_norm = norm_pval && gi && sig_map; GiStar_ClustMap_norm = norm_pval && gi_star; GiStar_SigMap_norm = norm_pval && gi_star && sig_map; Gi_ClustMap_perm = gi; Gi_SigMap_perm = gi && sig_map; GiStar_ClustMap_perm = gi_star; GiStar_SigMap_perm = gi_star && sig_map; row_standardize_weights = w_row_standardize->GetValue() == 1; event.Skip(); EndDialog(wxID_OK); } void GetisOrdChoiceDlg::OnRadioWStand( wxCommandEvent& event ) { } void GetisOrdChoiceDlg::OnRadioWBinary( wxCommandEvent& event ) { }
31.138298
80
0.74479
chenyoujie
da8861ca0bda2567c52addb0dd5eb903b58a28dc
1,285
cpp
C++
practice/algorithms/graph-theory/floyd-city-of-blinding-lights/floyd-city-of-blinding-lights.cpp
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
4
2017-01-18T17:51:58.000Z
2019-10-20T12:14:37.000Z
practice/algorithms/graph-theory/floyd-city-of-blinding-lights/floyd-city-of-blinding-lights.cpp
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
null
null
null
practice/algorithms/graph-theory/floyd-city-of-blinding-lights/floyd-city-of-blinding-lights.cpp
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
8
2016-03-14T17:16:59.000Z
2021-06-26T10:11:33.000Z
/* * @Author: Zeyuan Shang * @Date: 2015-12-28 01:30:58 * @Last Modified by: Zeyuan Shang * @Last Modified time: 2015-12-28 01:31:04 */ #include <iostream> #include <vector> using namespace std; vector<vector<int>> build_graph(int N, int M) { vector<vector<int>> graph(N, vector<int>(N, -1)); int x, y, r; while (M--) { scanf("%d%d%d", &x, &y, &r); graph[--x][--y] = r; } while (N--) { graph[N][N] = 0; } return graph; } void floyd_warshall(vector<vector<int>> &graph, int N) { int candidate; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { for (int k = 0; k < N; ++k) { if (graph[j][i] == -1 || graph[i][k] == -1) { continue; } candidate = graph[j][i] + graph[i][k]; if (candidate < graph[j][k] || graph[j][k] == -1) { graph[j][k] = candidate; } } } } } int main() { int N, M; scanf("%d%d", &N, &M); vector<vector<int>> graph = build_graph(N, M); floyd_warshall(graph, N); int Q, a, b; scanf("%d", &Q); while (Q--) { scanf("%d%d", &a, &b); printf("%d\n", graph[--a][--b]); } return 0; }
22.155172
67
0.435019
zeyuanxy
da893fc9e70304f1ab28d7209ee1b5c92a4589df
2,252
cpp
C++
tutorial/message/message_server.cpp
TencentOpen/Pebble
0f32f94db47b3bc1955ac2843bfa10372eeba1fb
[ "BSD-2-Clause" ]
233
2016-05-12T02:28:44.000Z
2020-08-24T18:11:49.000Z
tutorial/message/message_server.cpp
TencentOpen/Pebble
0f32f94db47b3bc1955ac2843bfa10372eeba1fb
[ "BSD-2-Clause" ]
1
2016-06-07T04:18:16.000Z
2016-06-07T06:09:08.000Z
tutorial/message/message_server.cpp
TencentOpen/Pebble
0f32f94db47b3bc1955ac2843bfa10372eeba1fb
[ "BSD-2-Clause" ]
116
2016-05-24T10:55:49.000Z
2019-11-24T06:57:08.000Z
/* * Tencent is pleased to support the open source community by making Pebble available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 <stdlib.h> #include "source/message/http_driver.h" #include "source/message/message.h" #include "source/message/tcp_driver.h" using namespace std; using namespace pebble::net; #define CHECK(e) \ if ((e) != 0) {\ printf("file:%s, line:%d, error:%s\n", __FILE__, __LINE__, Message::LastErrorMessage());\ exit(1);\ } int on_message(int handle, const char *msg, size_t msg_len, uint64_t addr) { string str(msg, msg_len); printf("server handle:%d, msg:%s, len:%d\n", handle, str.c_str(), static_cast<int>(msg_len)); char ret_msg[512]; int ret_n = snprintf(ret_msg, sizeof(ret_msg), "your msg=%s", str.c_str()); CHECK(Message::SendTo(handle, ret_msg, ret_n, addr)); return 0; } int main(int argc, char **argv) { if (argc != 2) { printf("usage:%s tbusd_address(eg.:udp://127.0.0.1:11599)\n", argv[0]); exit(1); } HttpDriver driver3; CHECK(driver3.Init()); Message::RegisterDriver(&driver3); TcpDriver driver4; CHECK(driver4.Init()); Message::RegisterDriver(&driver4); int handle4 = Message::NewHandle(); CHECK(Message::Bind(handle4, "http://0.0.0.0:8250")); int handle5 = Message::NewHandle(); CHECK(Message::Bind(handle5, "tcp://0.0.0.0:8260")); printf("handle4:%d, handle5:%d\n", handle4, handle5); NetEventCallbacks net_event_callbacks; net_event_callbacks.on_message = on_message; while (true) { Message::Poll(net_event_callbacks, 100); usleep(100); } return 0; }
30.849315
100
0.667407
TencentOpen
da89c8934244a95ce9a950cdd8a37b003bbea530
333
cpp
C++
ProjectEuler/fibonacci.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
3
2020-10-19T10:03:20.000Z
2021-12-18T20:39:31.000Z
ProjectEuler/fibonacci.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
null
null
null
ProjectEuler/fibonacci.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
null
null
null
/* Sum all even numbers of fibonacci until 4000000 */ #include <iostream> using namespace std; int main(){ int a = 0; int b = 1; int c; int sum = 0; do{ c = a + b; a = b; b = c; if(b % 2 == 0) //check if number is even sum += b; }while(b <= 4000000); cout << sum; //return sum of all even number return 0; }
12.807692
48
0.564565
MFathirIrhas
da8b2b9b1f99c12410a7203831d68d71b6fb9666
2,235
cpp
C++
scripts/matterport/render_uv/src/mesh_transformer/mesh_transformer.cpp
lukasHoel/stylemesh
a5e570d759fae0c08216154f51307b93894d2f98
[ "MIT" ]
53
2021-12-19T18:38:57.000Z
2022-03-30T16:25:34.000Z
scripts/matterport/render_uv/src/mesh_transformer/mesh_transformer.cpp
lukasHoel/stylemesh
a5e570d759fae0c08216154f51307b93894d2f98
[ "MIT" ]
null
null
null
scripts/matterport/render_uv/src/mesh_transformer/mesh_transformer.cpp
lukasHoel/stylemesh
a5e570d759fae0c08216154f51307b93894d2f98
[ "MIT" ]
null
null
null
#include "mesh_transformer.h" Mesh_Transformer::Mesh_Transformer(Mesh& mesh, Segmentation_Provider& sp): m_mesh(mesh), m_sp(sp) { } Mesh_Transformer::~Mesh_Transformer() = default; void Mesh_Transformer::splitMeshAtObject(int objectId) { std::vector<unsigned int> newIndices; // check each triangle if it is on the same object or not // If on different objects AND one of the objects is the object to split: remove this triangle for(int i=0; i< m_mesh.indices.size(); i+=3) { int ids[3]; ids[0] = m_sp.getObjectId(m_mesh.indices[i]); ids[1] = m_sp.getObjectId(m_mesh.indices[i+1]); ids[2] = m_sp.getObjectId(m_mesh.indices[i+2]); bool sameObjectIds = ids[0] == ids[1] && ids[1] == ids[2]; bool noneOfTargetObjectId = ids[0] != objectId && ids[1] != objectId && ids[2] != objectId; if(sameObjectIds || noneOfTargetObjectId){ // can keep all of these indices... the other ones are discarded because they match the above criterion newIndices.push_back(m_mesh.indices[i]); newIndices.push_back(m_mesh.indices[i+1]); newIndices.push_back(m_mesh.indices[i+2]); } } m_mesh.indices = newIndices; // TODO because we completely replace the original indices, we can only ever do one split per mesh load!! m_mesh.updateData(); } void Mesh_Transformer::moveVerticesOfObject(int objectId, glm::mat4& transformation){ std::vector<Vertex> newVertices; for(int i=0; i<m_mesh.vertices.size(); i++) { int id; id = m_sp.getObjectId(i); if(id == objectId){ Vertex v = m_mesh.vertices[i]; v.Position = transformation * glm::vec4(v.Position, 1.0f); glm::mat3 it_trans = glm::transpose(glm::inverse(transformation)); v.Normal = it_trans * v.Normal; v.Tangent = it_trans * v.Tangent; // TODO NOT SURE ABOUT THIS v.Bitangent = it_trans * v.Bitangent; // TODO NOT SURE ABOUT THIS newVertices.push_back(v); } else { newVertices.push_back(m_mesh.vertices[i]); } } m_mesh.vertices = newVertices; m_mesh.updateData(); }
37.25
138
0.624161
lukasHoel
da9851cebef7ce2a96a6a97705266be324bf4867
9,422
hpp
C++
cartesian_trajectory_controller/include/cartesian_trajectory_controller/cartesian_trajectory_controller.hpp
christianlandgraf/Universal_Robots_ROS_controllers_cartesian
987e4539af011292b5b34c7f891fe9f274e00ddd
[ "Apache-2.0" ]
12
2021-06-09T15:05:28.000Z
2022-02-16T11:14:16.000Z
cartesian_trajectory_controller/include/cartesian_trajectory_controller/cartesian_trajectory_controller.hpp
christianlandgraf/Universal_Robots_ROS_controllers_cartesian
987e4539af011292b5b34c7f891fe9f274e00ddd
[ "Apache-2.0" ]
7
2021-08-03T10:06:13.000Z
2022-03-25T22:58:28.000Z
cartesian_trajectory_controller/include/cartesian_trajectory_controller/cartesian_trajectory_controller.hpp
christianlandgraf/Universal_Robots_ROS_controllers_cartesian
987e4539af011292b5b34c7f891fe9f274e00ddd
[ "Apache-2.0" ]
5
2021-06-21T06:21:52.000Z
2022-03-02T14:52:40.000Z
// -- BEGIN LICENSE BLOCK ---------------------------------------------- // Copyright 2020 FZI Forschungszentrum Informatik // Created on behalf of Universal Robots A/S // // 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 LICENSE BLOCK ------------------------------------------------ //----------------------------------------------------------------------------- /*!\file cartesian_trajectory_controller.hpp * * \author Stefan Scherzinger <scherzin@fzi.de> * \date 2021/01/24 * */ //----------------------------------------------------------------------------- #include <cartesian_trajectory_controller/cartesian_trajectory_controller.h> #include "hardware_interface/robot_hw.h" namespace cartesian_trajectory_controller { template <class HWInterface> bool CartesianTrajectoryController<HWInterface>::init(hardware_interface::RobotHW* hw, ros::NodeHandle& nh, ros::NodeHandle& controller_nh) { if (!ControlPolicy::init(hw, nh, controller_nh)) { return false; } // Use speed scaling interface if available auto speed_scaling_interface = hw->get<scaled_controllers::SpeedScalingInterface>(); if (!speed_scaling_interface) { ROS_INFO_STREAM(controller_nh.getNamespace() << ": Your RobotHW seems not to provide speed scaling. Starting " "without this feature."); speed_scaling_ = nullptr; } else { speed_scaling_ = std::make_unique<scaled_controllers::SpeedScalingHandle>(speed_scaling_interface->getHandle("speed" "_scal" "ing_" "facto" "r")); } // Action server action_server_.reset(new actionlib::SimpleActionServer<cartesian_control_msgs::FollowCartesianTrajectoryAction>( controller_nh, "follow_cartesian_trajectory", std::bind(&CartesianTrajectoryController::executeCB, this, std::placeholders::_1), false)); action_server_->registerPreemptCallback(std::bind(&CartesianTrajectoryController::preemptCB, this)); action_server_->start(); return true; } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::starting(const ros::Time& time) { // Start where we are ControlPolicy::updateCommand(ControlPolicy::getState()); } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::stopping(const ros::Time& time) { if (action_server_->isActive()) { // Set canceled flag in the action result action_server_->setPreempted(); } } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::update(const ros::Time& time, const ros::Duration& period) { if (action_server_->isActive() && !done_.load()) { // Apply speed scaling if available. const double factor = (speed_scaling_) ? *speed_scaling_->getScalingFactor() : 1.0; trajectory_duration_.now += period * factor; // Sample the Cartesian trajectory's target state and command that to // the control policy. if (trajectory_duration_.now < trajectory_duration_.end) { std::lock_guard<std::mutex> lock_trajectory(lock_); ros_controllers_cartesian::CartesianState desired; trajectory_.sample(trajectory_duration_.now.toSec(), desired); ControlPolicy::updateCommand(desired); // Give feedback auto actual = ControlPolicy::getState(); auto error = desired - actual; cartesian_control_msgs::FollowCartesianTrajectoryFeedback f; auto now = trajectory_duration_.now.toSec(); f.desired = desired.toMsg(now); f.actual = actual.toMsg(now); f.error = error.toMsg(now); action_server_->publishFeedback(f); // Check tolerances and set terminal conditions for the // action server if special criteria are met. monitorExecution(error); } else // Time is up. Check goal tolerances and set terminal state. { timesUp(); } } } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::executeCB( const cartesian_control_msgs::FollowCartesianTrajectoryGoalConstPtr& goal) { // Upon entering this callback, the simple action server has already // preempted the previously active goal (if any) and has accepted the new goal. if (!this->isRunning()) { ROS_ERROR("Can't accept new action goals. Controller is not running."); cartesian_control_msgs::FollowCartesianTrajectoryResult result; result.error_code = cartesian_control_msgs::FollowCartesianTrajectoryResult::INVALID_GOAL; action_server_->setAborted(result); return; } path_tolerances_ = goal->path_tolerance; goal_tolerances_ = goal->goal_tolerance; // Start where we are by adding the current state as first trajectory // waypoint. auto state = ControlPolicy::getState(); { std::lock_guard<std::mutex> lock_trajectory(lock_); cartesian_control_msgs::CartesianTrajectory traj = goal->trajectory; traj.points.insert(traj.points.begin(), state.toMsg(0)); // start time zero if (!trajectory_.init(traj)) { ROS_ERROR("Action goal has invalid trajectory."); cartesian_control_msgs::FollowCartesianTrajectoryResult result; result.error_code = cartesian_control_msgs::FollowCartesianTrajectoryResult::INVALID_GOAL; action_server_->setAborted(result); return; } } // Time keeping trajectory_duration_.now = ros::Duration(0.0); trajectory_duration_.end = goal->trajectory.points.back().time_from_start + goal->goal_time_tolerance; done_ = false; while (!done_.load()) { ros::Duration(0.01).sleep(); } } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::preemptCB() { cartesian_control_msgs::FollowCartesianTrajectoryResult result; result.error_string = "preempted"; action_server_->setPreempted(result); done_ = true; } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::timesUp() { using Result = cartesian_control_msgs::FollowCartesianTrajectoryResult; Result result; // When time is over, sampling gives us the last waypoint. ros_controllers_cartesian::CartesianState goal; { std::lock_guard<std::mutex> lock_trajectory(lock_); trajectory_.sample(trajectory_duration_.now.toSec(), goal); } // TODO: What should happen when speed scaling was active? // Only check position and orientation in that case? // Address this once we know more edge cases during beta testing. // Check if goal was reached. // Abort if any of the dimensions exceeds its goal tolerance auto error = goal - ControlPolicy::getState(); if (!withinTolerances(error, goal_tolerances_)) { result.error_code = Result::GOAL_TOLERANCE_VIOLATED; action_server_->setAborted(result); } else // Succeed { result.error_code = Result::SUCCESSFUL; action_server_->setSucceeded(result); } done_ = true; } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::monitorExecution( const ros_controllers_cartesian::CartesianState& error) { if (!withinTolerances(error, path_tolerances_)) { using Result = cartesian_control_msgs::FollowCartesianTrajectoryResult; Result result; result.error_code = Result::PATH_TOLERANCE_VIOLATED; action_server_->setAborted(result); done_ = true; } } template <class HWInterface> bool CartesianTrajectoryController<HWInterface>::withinTolerances( const ros_controllers_cartesian::CartesianState& error, const cartesian_control_msgs::CartesianTolerance& tolerance) { // Uninitialized tolerances do not need checking cartesian_control_msgs::CartesianTolerance uninitialized; std::stringstream str_1; std::stringstream str_2; str_1 << tolerance; str_2 << uninitialized; if (str_1.str() == str_2.str()) { return true; } auto not_within_limits = [](const auto& a, const auto& b) { return a.x() > b.x || a.y() > b.y || a.z() > b.z; }; // Check each individual dimension separately. if (not_within_limits(error.p, tolerance.position_error) || not_within_limits(error.rot(), tolerance.orientation_error) || not_within_limits(error.v, tolerance.twist_error.linear) || not_within_limits(error.w, tolerance.twist_error.angular) || not_within_limits(error.v_dot, tolerance.acceleration_error.linear) || not_within_limits(error.w_dot, tolerance.acceleration_error.angular)) { return false; } return true; } } // namespace cartesian_trajectory_controller
34.639706
120
0.674061
christianlandgraf
da98c63af88cc4832c59e649e342539bbdde2ab3
3,285
cpp
C++
src/main.cpp
gustavosinbandera1/mongoose_os_esp32_http_server
97a491e606b0508dbee37bf0ecdb91ae46e903be
[ "Apache-2.0" ]
null
null
null
src/main.cpp
gustavosinbandera1/mongoose_os_esp32_http_server
97a491e606b0508dbee37bf0ecdb91ae46e903be
[ "Apache-2.0" ]
null
null
null
src/main.cpp
gustavosinbandera1/mongoose_os_esp32_http_server
97a491e606b0508dbee37bf0ecdb91ae46e903be
[ "Apache-2.0" ]
null
null
null
#include "mgos.h" #include "mgos_mqtt.h" #include "mgos_wifi.h" static void timer_cb(void *arg) { static bool s_tick_tock = false; LOG(LL_INFO, ("%s uptime: %.2lf, RAM: %lu, %lu free", (s_tick_tock ? "Tick" : "Tock"), mgos_uptime(), (unsigned long) mgos_get_heap_size(), (unsigned long) mgos_get_free_heap_size())); s_tick_tock = !s_tick_tock; (void) arg; } static void wifi_cb(int ev, void *evd, void *arg) { switch (ev) { case MGOS_WIFI_EV_STA_DISCONNECTED: { struct mgos_wifi_sta_disconnected_arg *da = (struct mgos_wifi_sta_disconnected_arg *) evd; LOG(LL_INFO, ("WiFi STA disconnected, reason %d", da->reason)); break; } case MGOS_WIFI_EV_STA_CONNECTING: LOG(LL_INFO, ("WiFi STA connecting %p", arg)); break; case MGOS_WIFI_EV_STA_CONNECTED: LOG(LL_INFO, ("WiFi STA connected %p", arg)); break; case MGOS_WIFI_EV_STA_IP_ACQUIRED: LOG(LL_INFO, ("WiFi STA IP acquired %p", arg)); break; case MGOS_WIFI_EV_AP_STA_CONNECTED: { struct mgos_wifi_ap_sta_connected_arg *aa = (struct mgos_wifi_ap_sta_connected_arg *) evd; LOG(LL_INFO, ("WiFi AP STA connected MAC %02x:%02x:%02x:%02x:%02x:%02x", aa->mac[0], aa->mac[1], aa->mac[2], aa->mac[3], aa->mac[4], aa->mac[5])); break; } case MGOS_WIFI_EV_AP_STA_DISCONNECTED: { struct mgos_wifi_ap_sta_disconnected_arg *aa = (struct mgos_wifi_ap_sta_disconnected_arg *) evd; LOG(LL_INFO, ("WiFi AP STA disconnected MAC %02x:%02x:%02x:%02x:%02x:%02x", aa->mac[0], aa->mac[1], aa->mac[2], aa->mac[3], aa->mac[4], aa->mac[5])); break; } } (void) arg; } static void button_cb(int pin, void *arg) { char topic[100]; snprintf(topic, sizeof(topic), "/devices/%s/events", mgos_sys_config_get_device_id()); bool res = mgos_mqtt_pubf(topic, 0, false /* retain */, "{total_ram: %lu, free_ram: %lu}", (unsigned long) mgos_get_heap_size(), (unsigned long) mgos_get_free_heap_size()); char buf[8]; LOG(LL_INFO, ("Pin: %s, published: %s", mgos_gpio_str(pin, buf), res ? "yes" : "no")); (void) arg; } extern "C" enum mgos_app_init_result mgos_app_init(void) { char buf[8]; /* Simple repeating timer */ mgos_set_timer(1000, MGOS_TIMER_REPEAT, timer_cb, NULL); /* Publish to MQTT on button press */ int btn_pin = mgos_sys_config_get_board_btn1_pin(); if (btn_pin >= 0) { enum mgos_gpio_pull_type btn_pull; enum mgos_gpio_int_mode btn_int_edge; if (mgos_sys_config_get_board_btn1_pull_up()) { btn_pull = MGOS_GPIO_PULL_UP; btn_int_edge = MGOS_GPIO_INT_EDGE_NEG; } else { btn_pull = MGOS_GPIO_PULL_DOWN; btn_int_edge = MGOS_GPIO_INT_EDGE_POS; } LOG(LL_INFO, ("Button pin %s, active %s", mgos_gpio_str(btn_pin, buf), (mgos_sys_config_get_board_btn1_pull_up() ? "low" : "high"))); mgos_gpio_set_button_handler(btn_pin, btn_pull, btn_int_edge, 20, button_cb, NULL); } mgos_event_add_group_handler(MGOS_WIFI_EV_BASE, wifi_cb, NULL); return MGOS_APP_INIT_SUCCESS; }
33.865979
80
0.625571
gustavosinbandera1
da98d8d237a88d751487f8800bd19f444849a5c6
5,066
cpp
C++
Source/SprueEngine/Libs/igl/streamlines.cpp
Qt-Widgets/TexGraph
8fe72cea1afcf5e235c810003bf4ee062bb3fc13
[ "MIT" ]
199
2018-02-26T20:56:21.000Z
2022-03-16T06:09:52.000Z
Source/SprueEngine/Libs/igl/streamlines.cpp
Qt-Widgets/TexGraph
8fe72cea1afcf5e235c810003bf4ee062bb3fc13
[ "MIT" ]
10
2018-03-20T02:49:58.000Z
2021-12-29T01:13:22.000Z
Source/SprueEngine/Libs/igl/streamlines.cpp
Qt-Widgets/TexGraph
8fe72cea1afcf5e235c810003bf4ee062bb3fc13
[ "MIT" ]
41
2018-02-28T01:33:37.000Z
2021-12-29T16:06:19.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 Francisca Gil Ureta <gilureta@cs.nyu.edu> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "edge_topology.h" #include "sort_vectors_ccw.h" #include "streamlines.h" #include "per_face_normals.h" #include "polyvector_field_matchings.h" #include "segment_segment_intersect.h" #include "triangle_triangle_adjacency.h" #include "barycenter.h" #include "slice.h" #include <Eigen/Geometry> IGL_INLINE void igl::streamlines_init( const Eigen::MatrixXd V, const Eigen::MatrixXi F, const Eigen::MatrixXd &temp_field, const bool treat_as_symmetric, StreamlineData &data, StreamlineState &state, double percentage ){ using namespace Eigen; using namespace std; igl::edge_topology(V, F, data.E, data.F2E, data.E2F); igl::triangle_triangle_adjacency(F, data.TT); // prepare vector field // -------------------------- int half_degree = temp_field.cols() / 3; int degree = treat_as_symmetric ? half_degree * 2 : half_degree; data.degree = degree; Eigen::MatrixXd FN; Eigen::VectorXi order; Eigen::RowVectorXd sorted; igl::per_face_normals(V, F, FN); data.field.setZero(F.rows(), degree * 3); for (unsigned i = 0; i < F.rows(); ++i){ const Eigen::RowVectorXd &n = FN.row(i); Eigen::RowVectorXd temp(1, degree * 3); if (treat_as_symmetric) temp << temp_field.row(i), -temp_field.row(i); else temp = temp_field.row(i); igl::sort_vectors_ccw(temp, n, order, sorted); // project vectors to tangent plane for (int j = 0; j < degree; ++j) { Eigen::RowVector3d pd = sorted.segment(j * 3, 3); pd = (pd - (n.dot(pd)) * n).normalized(); data.field.block(i, j * 3, 1, 3) = pd; } } Eigen::VectorXd curl; igl::polyvector_field_matchings(data.field, V, F, false, treat_as_symmetric, data.match_ab, data.match_ba, curl); // create seeds for tracing // -------------------------- Eigen::VectorXi samples; int nsamples; nsamples = percentage * F.rows(); Eigen::VectorXd r; r.setRandom(nsamples, 1); r = (1 + r.array()) / 2.; samples = (r.array() * F.rows()).cast<int>(); data.nsample = nsamples; Eigen::MatrixXd BC, BC_sample; igl::barycenter(V, F, BC); igl::slice(BC, samples, 1, BC_sample); // initialize state for tracing vector field state.start_point = BC_sample.replicate(degree,1); state.end_point = state.start_point; state.current_face = samples.replicate(1, degree); state.current_direction.setZero(nsamples, degree); for (int i = 0; i < nsamples; ++i) for (int j = 0; j < degree; ++j) state.current_direction(i, j) = j; } IGL_INLINE void igl::streamlines_next( const Eigen::MatrixXd V, const Eigen::MatrixXi F, const StreamlineData & data, StreamlineState & state ){ using namespace Eigen; using namespace std; int degree = data.degree; int nsample = data.nsample; state.start_point = state.end_point; for (int i = 0; i < degree; ++i) { for (int j = 0; j < nsample; ++j) { int f0 = state.current_face(j,i); if (f0 == -1) // reach boundary continue; int m0 = state.current_direction(j, i); // the starting point of the vector const Eigen::RowVector3d &p = state.start_point.row(j + nsample * i); // the direction where we are trying to go const Eigen::RowVector3d &r = data.field.block(f0, 3 * m0, 1, 3); // new state, int f1, m1; for (int k = 0; k < 3; ++k) { f1 = data.TT(f0, k); // edge vertices const Eigen::RowVector3d &q = V.row(F(f0, k)); const Eigen::RowVector3d &qs = V.row(F(f0, (k + 1) % 3)); // edge direction Eigen::RowVector3d s = qs - q; double u; double t; if (igl::segments_intersect(p, r, q, s, t, u)) { // point on next face state.end_point.row(j + nsample * i) = p + t * r; state.current_face(j,i) = f1; // matching direction on next face int e1 = data.F2E(f0, k); if (data.E2F(e1, 0) == f0) m1 = data.match_ab(e1, m0); else m1 = data.match_ba(e1, m0); state.current_direction(j, i) = m1; break; } } } } }
30.335329
115
0.543229
Qt-Widgets
da9ec50f1712432130d279a175473549476d285c
290
cpp
C++
leetcode/07-Bit/JD0501E-InsertIntoBits/InsertIntoBits.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/07-Bit/JD0501E-InsertIntoBits/InsertIntoBits.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/07-Bit/JD0501E-InsertIntoBits/InsertIntoBits.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
class Solution { public: int insertBits(int N, int M, int i, int j) { bitset<32> b_N( N ); bitset<32> b_M( M ); for ( int x = i, y = 0 ; x <= j; x++, y++ ){ b_N[x] = b_M[y]; } return b_N.to_ulong(); } };
20.714286
52
0.382759
BinRay
daa42ce41c7c0f1609cce10fa965e61ed6e45023
411
cpp
C++
Uncategorized/Summing A Sequence.cpp
andy-liuu/personal-DMOJ-Solutions
42e08a32e84ea733f2c7fb3781b9652c26d70b59
[ "MIT" ]
null
null
null
Uncategorized/Summing A Sequence.cpp
andy-liuu/personal-DMOJ-Solutions
42e08a32e84ea733f2c7fb3781b9652c26d70b59
[ "MIT" ]
null
null
null
Uncategorized/Summing A Sequence.cpp
andy-liuu/personal-DMOJ-Solutions
42e08a32e84ea733f2c7fb3781b9652c26d70b59
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; long long n; int main(){ //set up inputs and dp arrays cin>>n; long long items[n+1]; for(int i = 1;i<=n;i++){ cin>>items[i]; } long long dp[n+1] = {}; dp[1] = items[1]; for(int q = 2;q<=n;q++){ dp[q] = max(dp[q-1],max(dp[q-2]+items[q],max(dp[q-2],items[q]))); } cout<<dp[n]<<endl; }
18.681818
74
0.459854
andy-liuu
daa6251b9f3e3e75b293b7c66562ed3f62e501a7
1,049
hpp
C++
src/scenes/highscore.hpp
Pfeifenjoy/Theseus
9b427c16deaaacfff2e174e3dd133feed9724d3b
[ "MIT" ]
6
2016-10-28T15:39:09.000Z
2019-04-16T09:00:03.000Z
src/scenes/highscore.hpp
Pfeifenjoy/Theseus
9b427c16deaaacfff2e174e3dd133feed9724d3b
[ "MIT" ]
null
null
null
src/scenes/highscore.hpp
Pfeifenjoy/Theseus
9b427c16deaaacfff2e174e3dd133feed9724d3b
[ "MIT" ]
6
2017-02-22T17:25:32.000Z
2021-02-03T19:17:06.000Z
/** * @author Dominic Steinhauser */ #ifndef _THESEUS_GAME_HIGHSCORE_H #define _THESEUS_GAME_HIGHSCORE_H #include "../engine/scene.hpp" #include "../gameobjects/textfield.hpp" #include <memory> #include <vector> #include <string> namespace theseus { namespace scenes { class Highscore : public engine::Scene { private: int screenWidth; int screenHeigth; gameobjects::Textfield * textfield; std::string getHighscore(float timeLeft); public: //---- Constructor -------------------------------------------------------------------------------------- // Generates a new Intro scene Highscore(int screenWidth, int screenHeigth, float time); //---- Destructor --------------------------------------------------------------------------------------- ~Highscore(); //---- Methods ------------------------------------------------------------------------------------------ /** * Passes the key-down event to the game objects. */ void handleKeyDownEvent(sf::Keyboard::Key key); }; } } #endif
20.98
108
0.505243
Pfeifenjoy
daa652bebe679c616aa8e046a2b8f83d4b59e5f8
400
hpp
C++
src/Application.hpp
Thomas-Zorroche/Oryon
54237355055b262110346b33023d3cab63124fc0
[ "MIT" ]
null
null
null
src/Application.hpp
Thomas-Zorroche/Oryon
54237355055b262110346b33023d3cab63124fc0
[ "MIT" ]
null
null
null
src/Application.hpp
Thomas-Zorroche/Oryon
54237355055b262110346b33023d3cab63124fc0
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "Window.hpp" #include "Editor/Editor.hpp" #include "Events/Event.hpp" namespace oryon { class Application { public: Application(int argc, char** argv); Window& getWindow() { return * _window; } void run(); void onEvent(Event& e); private: std::unique_ptr<Window> _window = nullptr; std::unique_ptr<Editor> _editor = nullptr; }; }
12.5
44
0.6725
Thomas-Zorroche
daa7b48131608c28dadc74dc66c423d09fde1596
614
cpp
C++
Source.cpp
usamashafiq/print_right_triangle
78f7ae74ed2672235648793ba4ffc9f3d679a5ea
[ "MIT" ]
null
null
null
Source.cpp
usamashafiq/print_right_triangle
78f7ae74ed2672235648793ba4ffc9f3d679a5ea
[ "MIT" ]
null
null
null
Source.cpp
usamashafiq/print_right_triangle
78f7ae74ed2672235648793ba4ffc9f3d679a5ea
[ "MIT" ]
null
null
null
#include<iostream> #include<conio.h> using namespace std; void print_right_triangle(int, char = '*'); void main() { int a; char c,q; cout << "Enter a size " << endl; cin >> a; cout << "you want to enter char ans in (Y/N) " << endl; cin >> c; if (c == 'y'||c=='Y') { cout << "Enter a char '@,#,$,%' " << endl; cin >> q; print_right_triangle(a, q); } else { print_right_triangle(a); } _getch(); } void print_right_triangle(int a, char b) { for (int i = a; i >= 1; i--) { for (int j = a; j>i; j--) { cout << b; } cout << "\n"; } }
14.97561
59
0.486971
usamashafiq
daaa486a8d57cd530b323a1ffb7865177cae4357
3,168
cpp
C++
UnitTest/LibTest/sdl_test.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
UnitTest/LibTest/sdl_test.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
UnitTest/LibTest/sdl_test.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdint.h> #include <assert.h> #include <iostream> #include <iomanip> #define SDL_MAIN_HANDLED #include <SDL2/SDL.h> #include <glad/glad.h> #include <SDL2/SDL_opengl.h> //#include <GL/gl.h> typedef int32_t i32; typedef uint32_t u32; typedef int32_t b32; #define WinWidth 1280 #define WinHeight 720 int main(int argc, char* argv[]) { // int context_flags = SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG | SDL_GL_CONTEXT_DEBUG_FLAG; // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, context_flags); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); // SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); // SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); u32 WindowFlags = SDL_WINDOW_OPENGL; SDL_Window *Window = SDL_CreateWindow("OpenGL Test", 0, 0, WinWidth, WinHeight, WindowFlags); assert(Window); SDL_GLContext Context = SDL_GL_CreateContext(Window); SDL_GL_MakeCurrent(Window, Context); if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } std::cout << std::setw(34) << std::left << "OpenGL Version: " << GLVersion.major << "." << GLVersion.minor << std::endl; std::cout << std::setw(34) << std::left << "OpenGL Shading Language Version: " << (char *)glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << std::setw(34) << std::left << "OpenGL Vendor:" << (char *)glGetString(GL_VENDOR) << std::endl; std::cout << std::setw(34) << std::left << "OpenGL Renderer:" << (char *)glGetString(GL_RENDERER) << std::endl; b32 Running = 1; b32 FullScreen = 0; while (Running) { SDL_Event Event; while (SDL_PollEvent(&Event)) { if (Event.type == SDL_KEYDOWN) { switch (Event.key.keysym.sym) { case SDLK_ESCAPE: Running = 0; break; case 'f': FullScreen = !FullScreen; if (FullScreen) { SDL_SetWindowFullscreen(Window, WindowFlags | SDL_WINDOW_FULLSCREEN_DESKTOP); } else { SDL_SetWindowFullscreen(Window, WindowFlags); } break; default: break; } } else if (Event.type == SDL_QUIT) { Running = 0; } } glViewport(0, 0, WinWidth, WinHeight); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); SDL_GL_SwapWindow(Window); } return 0; }
34.064516
148
0.591856
rocketman123456
daab8cab39a6a8016de0c4dc9b727ff4756cbae1
6,616
cxx
C++
Libraries/ITK/Testing/Segmentation/MIDASIrregularVolumeEditor/itkMIDASRegionOfInterestCalculatorTest.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
Libraries/ITK/Testing/Segmentation/MIDASIrregularVolumeEditor/itkMIDASRegionOfInterestCalculatorTest.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
Libraries/ITK/Testing/Segmentation/MIDASIrregularVolumeEditor/itkMIDASRegionOfInterestCalculatorTest.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include <memory> #include <math.h> #include <itkImage.h> #include <itkMIDASHelper.h> #include <itkMIDASRegionOfInterestCalculator.h> /** * Basic tests for itkMIDASRegionOfInterestCalculator */ int itkMIDASRegionOfInterestCalculatorTest(int argc, char * argv[]) { typedef itk::Image<unsigned char, 3> ImageType; typedef itk::MIDASRegionOfInterestCalculator<unsigned char, 3> CalculatorType; typedef ImageType::RegionType RegionType; typedef ImageType::SizeType SizeType; typedef ImageType::IndexType IndexType; /********************************************************** * Normal, default ITK image, should be RAI * i.e. * 1 0 0 * 0 1 0 == RAI * 0 0 1 **********************************************************/ CalculatorType::Pointer calculator = CalculatorType::New(); //calculator->DebugOn(); ImageType::Pointer image = ImageType::New(); std::string orientation = calculator->GetOrientationString(image); if (orientation != "RAI") { std::cerr << "Expected RAI, but got:" << orientation << " from direction=\n" << image->GetDirection() << std::endl; return EXIT_FAILURE; } int axis = calculator->GetAxis(image, itk::ORIENTATION_AXIAL); if (axis != 2) { std::cerr << "Expected 2, but got:" << axis << std::endl; return EXIT_FAILURE; } axis = calculator->GetAxis(image, itk::ORIENTATION_SAGITTAL); if (axis != 0) { std::cerr << "Expected 0, but got:" << axis << std::endl; return EXIT_FAILURE; } axis = calculator->GetAxis(image, itk::ORIENTATION_CORONAL); if (axis != 1) { std::cerr << "Expected 1, but got:" << axis << std::endl; return EXIT_FAILURE; } int direction = 0; direction = calculator->GetPlusOrUpDirection(image, itk::ORIENTATION_AXIAL); if (direction != -1) { std::cerr << "Expected -1, but got:" << direction << std::endl; return EXIT_FAILURE; } direction = calculator->GetPlusOrUpDirection(image, itk::ORIENTATION_SAGITTAL); if (direction != -1) { std::cerr << "Expected -1, but got:" << direction << std::endl; return EXIT_FAILURE; } direction = calculator->GetPlusOrUpDirection(image, itk::ORIENTATION_CORONAL); if (direction != -1) { std::cerr << "Expected -1, but got:" << direction << std::endl; return EXIT_FAILURE; } SizeType size; size.Fill(256); IndexType voxelIndex; voxelIndex.Fill(0); RegionType region; region.SetSize(size); region.SetIndex(voxelIndex); image->SetRegions(region); image->Allocate(); image->FillBuffer(0); region = calculator->GetPlusOrUpRegion(image, itk::ORIENTATION_AXIAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 256 || size[2] != 10 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 256, 10, 0, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetMinusOrDownRegion(image, itk::ORIENTATION_AXIAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 256 || size[2] != 245 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 11) { std::cerr << "Expected 256, 256, 245, 0, 0, 11, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetPlusOrUpRegion(image, itk::ORIENTATION_CORONAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 10 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 10, 256, 0, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetMinusOrDownRegion(image, itk::ORIENTATION_CORONAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 245 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 11 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 245, 256, 0, 11, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetPlusOrUpRegion(image, itk::ORIENTATION_SAGITTAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 10 || size[1] != 256 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 10, 256, 256, 0, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetMinusOrDownRegion(image, itk::ORIENTATION_SAGITTAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 245 || size[1] != 256 || size[2] != 256 || voxelIndex[0] != 11 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 245, 256, 256, 11, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetSliceRegion(image, itk::ORIENTATION_AXIAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 256 || size[2] != 1 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 10) { std::cerr << "Expected 256, 256, 1, 0, 0, 10, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetSliceRegion(image, itk::ORIENTATION_CORONAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 1 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 10 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 1, 256, 0, 10, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetSliceRegion(image, itk::ORIENTATION_SAGITTAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 1 || size[1] != 256 || size[2] != 256 || voxelIndex[0] != 10 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 1, 256, 256, 10, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
32.273171
124
0.60792
NifTK
daacc621b1123920e28327f57cac176717cd58d1
48
cpp
C++
Engine.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Engine.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Engine.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
#define OLC_PGE_APPLICATION #include "Engine.h"
16
27
0.8125
KarmaiSAYIn
dab09ead5983335ab8305127b36caf33624c85fc
1,499
cc
C++
third_party/accessibility/base/string_utils_unittest.cc
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
12
2018-12-07T05:15:45.000Z
2019-12-26T01:15:34.000Z
third_party/accessibility/base/string_utils_unittest.cc
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
155
2020-11-30T09:16:59.000Z
2022-03-29T09:40:55.000Z
third_party/accessibility/base/string_utils_unittest.cc
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
22
2020-11-25T10:58:46.000Z
2022-01-25T09:45:25.000Z
// Copyright 2013 The Flutter 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 "string_utils.h" #include <cerrno> #include <cstddef> #include "base/logging.h" #include "gtest/gtest.h" namespace base { TEST(StringUtilsTest, StringPrintfEmpty) { EXPECT_EQ("", base::StringPrintf("%s", "")); } TEST(StringUtilsTest, StringPrintfMisc) { EXPECT_EQ("123hello w", StringPrintf("%3d%2s %1c", 123, "hello", 'w')); } // Test that StringPrintf and StringAppendV do not change errno. TEST(StringUtilsTest, StringPrintfErrno) { errno = 1; EXPECT_EQ("", StringPrintf("%s", "")); EXPECT_EQ(1, errno); } TEST(StringUtilsTest, canASCIIToUTF16) { std::string ascii = "abcdefg"; EXPECT_EQ(ASCIIToUTF16(ascii).compare(u"abcdefg"), 0); } TEST(StringUtilsTest, canUTF8ToUTF16) { std::string utf8 = "äåè"; EXPECT_EQ(UTF8ToUTF16(utf8).compare(u"äåè"), 0); } TEST(StringUtilsTest, canUTF16ToUTF8) { std::u16string utf16 = u"äåè"; EXPECT_EQ(UTF16ToUTF8(utf16).compare("äåè"), 0); } TEST(StringUtilsTest, canNumberToString16) { float number = 1.123; EXPECT_EQ(NumberToString16(number).compare(u"1.123000"), 0); } TEST(StringUtilsTest, canNumberToString) { float f = 1.123; EXPECT_EQ(NumberToString(f).compare("1.123000"), 0); unsigned int s = 11; EXPECT_EQ(NumberToString(s).compare("11"), 0); int32_t i = -23; EXPECT_EQ(NumberToString(i).compare("-23"), 0); } } // namespace base
25.40678
73
0.70447
onix39
dab0bfa6f03f9278a999b2e413f4be4e110e997b
384
hpp
C++
graphics/Axis.hpp
theoden8/plot
ff69782d43b45bf5f4f95ee3f79a08fd9ce0bed3
[ "WTFPL" ]
null
null
null
graphics/Axis.hpp
theoden8/plot
ff69782d43b45bf5f4f95ee3f79a08fd9ce0bed3
[ "WTFPL" ]
null
null
null
graphics/Axis.hpp
theoden8/plot
ff69782d43b45bf5f4f95ee3f79a08fd9ce0bed3
[ "WTFPL" ]
null
null
null
#pragma once #include "Types.hpp" struct axis { real_t winsize, gridsize, shift, thickness; real_t lborder, rborder; private: void reborder(); public: axis(real_t winsize, real_t thickness, real_t shift = 0.); real_t bold() const; void set_grid(real_t diff); void set_shift(real_t diff); void set_size(real_t newsize); bool in_grid(const real_t &val) const; };
16
59
0.713542
theoden8
dab460b8aaae2d1c00ac6597cc64bb2e60790632
5,273
cpp
C++
Server/Tools/Supervisor/src/SupervisorReceiver.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Tools/Supervisor/src/SupervisorReceiver.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Tools/Supervisor/src/SupervisorReceiver.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "SupervisorReceiver.h" #include "ISABThread.h" #include "DatagramSocket.h" #include "PacketReceiver.h" #include "Properties.h" #include "SupervisorStorage.h" SupervisorReceiver::SupervisorReceiver() : m_newAllowedMapSets( MAX_UINT32 ), m_allowedMapSets( MAX_UINT32 ), m_monitor( new ISABMonitor() ), m_receiver( NULL ), m_nbrReceivers( 0 ), m_packetReceiver( NULL ) {} SupervisorReceiver::~SupervisorReceiver() { cleanup(); } void SupervisorReceiver::cleanup() { delete m_packetReceiver; m_packetReceiver = NULL; if ( m_receiver != NULL ) { for( uint32 i = 0; i < m_nbrReceivers; i++) { delete m_receiver[ i ]; } } delete [] m_receiver; m_receiver = NULL; } Packet* SupervisorReceiver::receiveAndCreatePacket( uint32 timeOut, DatagramReceiver*& sock ) { if ( m_newAllowedMapSets != m_allowedMapSets ) { cleanup(); m_allowedMapSets = m_newAllowedMapSets; } if ( m_receiver == NULL ) { // Make new uint32 mapSetCount = 1; if ( Properties::getProperty( "MAP_SET_COUNT" ) != NULL ) { mapSetCount = Properties::getUint32Property( "MAP_SET_COUNT", 1 ); } uint32 nbrModules = 0; // Count module while ( SupervisorStorage::modules[nbrModules] != MODULE_TYPE_INVALID ) { nbrModules++; } // Double the number of receivers to receive from leaders and avails. m_nbrReceivers = nbrModules * mapSetCount * 2; m_receiver = new DatagramReceiver*[ m_nbrReceivers ]; // Join the groups that we want to listen to. for ( uint32 i = 0 ; i < nbrModules ; ++i ) { for ( int leader = 0; leader < 2; ++leader ) { uint32 ip = MultiCastProperties::getNumericIP( SupervisorStorage::modules[ i ], leader ); uint16 port = MultiCastProperties::getPort( SupervisorStorage::modules[i], leader ); mc2dbg4 << "[Supervisor]: ip = " << ip << " port = " << port << endl; for ( uint32 m = 0 ; m < mapSetCount ; ++m ) { if ( (1<<m) & m_allowedMapSets ) { uint32 mip = ip + (m << 8); uint16 mport = port | (m << 13); m_receiver[ (2*i + leader)*mapSetCount + m ] = new DatagramReceiver( mport, DatagramReceiver::REUSEADDR ); m_receiver[ (2*i + leader)*mapSetCount + m ] ->joinGroup( mip ); } else { m_receiver[ (2*i + leader)*mapSetCount + m ] = NULL; } } } } // Create a packetreceiver and add the receivers to it. m_packetReceiver = new PacketReceiver(); for ( uint32 i = 0 ; i < m_nbrReceivers ; i++ ) { if ( m_receiver[ i ] != NULL ) { m_packetReceiver->addDatagramSocket( m_receiver[ i ] ); } } } // End if create new Packet* packet = m_packetReceiver->receiveAndCreatePacket( timeOut ); void* received = m_packetReceiver->getSocketThatReceived(); if ( packet != NULL && (packet->getSubType() == Packet::PACKETTYPE_STATISTICS || packet->getSubType() == Packet::PACKETTYPE_HEARTBEAT) ) { uint32 i = 0; sock = m_receiver[ 0 ]; while ( i < m_nbrReceivers && sock != received ) { sock = m_receiver[ i ]; i++; } if ( sock != received ) { sock = NULL; } } // else irrelevant packet or timeout return packet; }
38.772059
755
0.617296
wayfinder
dab86dea5b681cbeba3cdc98e98de5cd25567755
682
cpp
C++
source/SexyAppFramework/FModSoundInstance.cpp
alula/CircleShootApp
6a15f2de91f0bbe3d030d8ec971e9c961275f5eb
[ "MIT" ]
8
2022-03-17T22:15:59.000Z
2022-03-23T20:59:38.000Z
source/SexyAppFramework/FModSoundInstance.cpp
alula/CircleShootApp
6a15f2de91f0bbe3d030d8ec971e9c961275f5eb
[ "MIT" ]
null
null
null
source/SexyAppFramework/FModSoundInstance.cpp
alula/CircleShootApp
6a15f2de91f0bbe3d030d8ec971e9c961275f5eb
[ "MIT" ]
null
null
null
#include "FModSoundInstance.h" #include "FModLoader.h" using namespace Sexy; FModSoundInstance::FModSoundInstance() { mStream = NULL; mChannelNum = 0; } FModSoundInstance::~FModSoundInstance() { Release(); } void FModSoundInstance::Release() { } void FModSoundInstance::SetVolume(double theVolume) { } void FModSoundInstance::SetPan(int thePosition) { } bool FModSoundInstance::Play(bool looping, bool autoRelease) { if (mStream == NULL) return false; gFMod->FSOUND_Stream_Play(FSOUND_FREE, mStream); return true; } void FModSoundInstance::Stop() { } bool FModSoundInstance::IsPlaying() { return true; } bool FModSoundInstance::IsReleased() { return false; }
13.372549
60
0.741935
alula
dab8bade4524f62efde33035a7c18b38a05d091a
1,300
cc
C++
libmat/test/src/test_reItr_all.cc
stiegerc/winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
2
2020-10-06T09:14:23.000Z
2020-11-25T06:08:54.000Z
libmat/test/src/test_reItr_all.cc
stiegerc/Winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
1
2020-12-23T04:20:33.000Z
2020-12-23T04:20:33.000Z
libmat/test/src/test_reItr_all.cc
stiegerc/Winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
1
2020-07-14T13:53:32.000Z
2020-07-14T13:53:32.000Z
// 2014-2019, ETH Zurich, Integrated Systems Laboratory // Authors: Christian Stieger #include "testTools.h" #include "test_cpxItr_all.h" #include "test_cpxItr_all.cc" using namespace lm__; // tests template<> void test_cpxItr_all<0>::test_all_dereference() { // c_reItr { // lambda to generate const random range auto gen = [](const size_t L) -> const CPX__* { CPX__* res = new CPX__ [L]; rnd(res,L); return res; }; const size_t L = genRndST(); const CPX__* rg = gen(L); c_reItr tItr(rg,1); for (size_t i=0; i!=L; ++i,++tItr) CPPUNIT_ASSERT_EQUAL(std::real(rg[i]),*tItr); delete[] rg; } // reItr { // lambda to generate const random range auto gen = [](const size_t L) -> CPX__* { CPX__* res = new CPX__ [L]; rnd(res,L); return res; }; const size_t L = genRndST(); CPX__* rg = gen(L); reItr tItr(rg,1); for (size_t i=0; i!=L; ++i,++tItr) { CPPUNIT_ASSERT_EQUAL(std::real(rg[i]),*tItr); const auto tmp = rg[i]; *tItr = RE__(1.0); CPPUNIT_ASSERT_EQUAL(std::real(rg[i]),RE__(1.0)); CPPUNIT_ASSERT_EQUAL(std::imag(rg[i]),std::imag(tmp)); } delete[] rg; } } // test id template<> const char* test_cpxItr_all<0>::test_id() noexcept { return "test_reItr_all"; } // instantiation template class test_cpxItr_all<0>;
19.402985
57
0.636154
stiegerc
dabd5194efb503198df7e08bf34029a2b7e72213
8,699
cpp
C++
addglopeningbalance.cpp
bizjust/bizjust-erp
d3291e212bf89ab6e753194127b3951afcd02548
[ "MIT" ]
1
2022-02-16T13:02:43.000Z
2022-02-16T13:02:43.000Z
addglopeningbalance.cpp
bizjust/bizjust-erp
d3291e212bf89ab6e753194127b3951afcd02548
[ "MIT" ]
null
null
null
addglopeningbalance.cpp
bizjust/bizjust-erp
d3291e212bf89ab6e753194127b3951afcd02548
[ "MIT" ]
null
null
null
#include "addglopeningbalance.h" #include "ui_addglopeningbalance.h" AddGLOpeningBalance::AddGLOpeningBalance(QWidget *parent) : QWidget(parent), ui(new Ui::AddGLOpeningBalance) { ui->setupUi(this); loadform(); } AddGLOpeningBalance::~AddGLOpeningBalance() { delete ui; } void AddGLOpeningBalance::autocompleter(QString sql, QLineEdit *name_txt, QLineEdit *id_txt) { sch.name_txt = name_txt; sch.id_txt = id_txt; QMap<int, QString> data = sch.data; //conn.connOpen(); QSqlQuery qry; qry.prepare(sql); if(qry.exec()) { while(qry.next()) { data[qry.value(0).toInt()] = qry.value(1).toString(); } } //conn.connClose(); /*data[2] = "Moscow"; data[4] = "London"; data[6] = "Paris";*/ QCompleter *completer = new QCompleter(this); QStandardItemModel *model = new QStandardItemModel(completer); QMapIterator<int, QString> it(data); while (it.hasNext()) { it.next(); int code = it.key(); QString name = it.value(); QStandardItem *item = new QStandardItem; item->setText(name); item->setData(code, Qt::UserRole); model->appendRow(item); } completer->setModel(model); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setCurrentRow(0); completer->setFilterMode(Qt::MatchContains); name_txt->setCompleter(completer); connect(completer, SIGNAL(highlighted(QModelIndex)),this,SLOT(onItemHighlighted(QModelIndex)),Qt::QueuedConnection); connect(name_txt,SIGNAL(editingFinished()),this,SLOT(editingFinished() )); } void AddGLOpeningBalance::onItemHighlighted(const QModelIndex &index) { QString code = index.data(Qt::UserRole).toString(); QString sname = index.data(0).toString(); sch.searchname = sname; sch.searchid = code; sch.id_txt->setText(code); } void AddGLOpeningBalance::editingFinished() { QString sname = sch.name_txt->text(); QString sid = sch.id_txt->text(); if(sname!=sch.searchname || sid != sch.searchid) { sch.name_txt->setText(""); sch.id_txt->setText(""); } } void AddGLOpeningBalance::on_accountname_textEdited(const QString &arg1) { QString sql = sch.glaccount_generalize(arg1); autocompleter(sql,ui->accountname, ui->accountid); } void AddGLOpeningBalance::loadform() { ui->entrydate->setDate(QDate::currentDate()); ui->detailtable->setColumnCount(5); QStringList titles; titles <<"Account"<<"Account Id"<<"Description"<<"Debit"<<"Credit"; ui->detailtable->setHorizontalHeaderLabels(titles); ui->detailtable->hideColumn(ACCOUNTID); ui->detailtable->horizontalHeader()->setSectionResizeMode(ACCOUNTNAME, QHeaderView::Stretch); ui->detailtable->horizontalHeader()->setSectionResizeMode(DESCRIPTION, QHeaderView::Stretch); ui->detailtable->setColumnWidth(DEBIT,100); ui->detailtable->setColumnWidth(CREDIT,100); ui->btn_save->setEnabled(false); } void AddGLOpeningBalance::on_btn_add_clicked() { QString accountname = ui->accountname->text(); QString accountid = ui->accountid->text(); float debit = ui->debit->value(); float credit = ui->credit->value(); float total = debit+credit; if(accountid=="") { QMessageBox::critical(this,"","Please select Account"); ui->accountname->setFocus(); return; } else if(total<=0) { QMessageBox::critical(this,"","Please enter debit or credit"); ui->debit->setFocus(); return; } else { int row = ui->detailtable->rowCount(); ui->detailtable->insertRow(row); ui->detailtable->setItem(row,ACCOUNTNAME, new QTableWidgetItem(accountname)); ui->detailtable->setItem(row,ACCOUNTID, new QTableWidgetItem(accountid)); ui->detailtable->setItem(row,DESCRIPTION, new QTableWidgetItem(ui->description->text())); ui->detailtable->setItem(row,DEBIT, new QTableWidgetItem( erp.DecimalString(debit) )); ui->detailtable->setItem(row,CREDIT, new QTableWidgetItem( erp.DecimalString(credit) )); checktotal(); ui->accountname->clear(); ui->accountid->clear(); ui->debit->setValue(0.00); ui->credit->setValue(0.00); ui->accountname->setFocus(); } } void AddGLOpeningBalance::checktotal() { float tot_debit=0; float tot_credit=0; for(int i=0; i<ui->detailtable->rowCount(); i++) { float debit = ui->detailtable->item(i,DEBIT)->text().toFloat(); float credit = ui->detailtable->item(i,CREDIT)->text().toFloat(); tot_debit += debit; tot_credit += credit; } ui->total_debit->setValue(tot_debit); ui->total_credit->setValue(tot_credit); if(ui->detailtable->rowCount()>0) { ui->btn_save->setEnabled(true); } else { ui->btn_save->setEnabled(false); } } void AddGLOpeningBalance::on_btn_delete_row_clicked() { if(ui->detailtable->currentRow()>=0) { ui->detailtable->removeRow(ui->detailtable->currentRow()); checktotal(); } } void AddGLOpeningBalance::on_btn_save_clicked() { QString entrydate = ui->entrydate->date().toString("yyyy-MM-dd"); float total = ui->total_debit->value() + ui->total_credit->value(); if(entrydate=="") { QMessageBox::critical(this,"","Transaction date is required"); ui->entrydate->setFocus(); return; } else if(total==0) { QMessageBox::critical(this,"","Total Debit or Total Credit must not be 0.00"); return; } else { QString ob_code = "OB"; QString ob_num = erp.get_num(ob_code); QString vno = ob_code+"-"+ob_num; erp.update_ids_num(ob_code); float total_debit = ui->total_debit->value(); float total_credit = ui->total_credit->value(); float total_amount = total_debit+total_credit; QString wherefrom = "3"; QString description = "gl opening balance"; QString query_transaction = "INSERT INTO `tblgltransvoucher` " " ( `voucherno` ,`description` ,`entrydate` ,`total_debit` ,`total_credit` ,`wherefrom`, `financialyearid`) " " VALUES " " ('"+vno+"' ,'"+description+"', '"+entrydate+"', '"+erp.DecimalString(total_amount)+"', '"+erp.DecimalString(total_amount)+"', '"+wherefrom+"', '"+erp._yearid+"')"; if(!conn.execQuery(query_transaction)) { QMessageBox::critical(this,"","Some problem in record insertion"); return; } QString voucherid = erp.getvoucherid(vno); QString event = "Add"; QString transtype = "GL Opening Balance"; QString transid = vno ; erp.AddToEventLog(event,transtype,transid); QString voucher = vno; for(int i=0; i<ui->detailtable->rowCount(); i++) { QString glaccountid = ui->detailtable->item(i,ACCOUNTID)->text(); int ln = 0; if(glaccountid!="") { description = ui->detailtable->item(i,DESCRIPTION)->text(); float debit = ui->detailtable->item(i,DEBIT)->text().toFloat(); float credit = ui->detailtable->item(i,CREDIT)->text().toFloat(); ln++; QString query = "insert into tblgltransaction " " ( voucherno, voucherid, glaccountid, description, debit, credit, linenumber, `entrydate`, financialyearid) " " values " " ('"+voucher+"', '"+voucherid+"', '"+glaccountid+"', '"+description+"', '"+erp.DecimalString(debit)+"', '"+erp.DecimalString(credit)+"', '"+erp.intString(ln)+"', '"+entrydate+"', '"+erp._yearid+"')"; if(!conn.execQuery(query)) { QMessageBox::critical(this,"","Some problem in record insertion"); return; } } } QMessageBox::information(this,"","Opening balance "+voucher+" inserted successfully"); ui->detailtable->setRowCount(0); ui->accountname->clear(); ui->accountid->clear(); ui->debit->setValue(0.00); ui->credit->setValue(0.00); ui->entrydate->setFocus(); checktotal(); } } void AddGLOpeningBalance::on_debit_valueChanged(double arg1) { if(arg1>0) { ui->credit->setValue(0.00); } } void AddGLOpeningBalance::on_credit_valueChanged(double arg1) { if(arg1>0) { ui->debit->setValue(0.00); } }
33.457692
232
0.604667
bizjust
dabf957435d7070c4e57a7989218521f406dc7b4
789
cpp
C++
src/apps/icon-o-matic/shape/commands/ReversePathCommand.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/icon-o-matic/shape/commands/ReversePathCommand.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/icon-o-matic/shape/commands/ReversePathCommand.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2006, Haiku. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Stephan Aßmus <superstippi@gmx.de> */ #include "ReversePathCommand.h" #include <stdio.h> #include <Catalog.h> #include <Locale.h> #include "VectorPath.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Icon-O-Matic-ReversePathCmd" // constructor ReversePathCommand::ReversePathCommand(VectorPath* path) : PathCommand(path) { } // destructor ReversePathCommand::~ReversePathCommand() { } // Perform status_t ReversePathCommand::Perform() { fPath->Reverse(); return B_OK; } // Undo status_t ReversePathCommand::Undo() { return Perform(); } // GetName void ReversePathCommand::GetName(BString& name) { name << B_TRANSLATE("Reverse Path"); }
14.089286
59
0.730038
Kirishikesan
dac0f574f5bd7dc4f5546df185453a394d9ba17e
27,800
cpp
C++
externals/source/testdog/pack/src/html_reporter.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
externals/source/testdog/pack/src/html_reporter.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
externals/source/testdog/pack/src/html_reporter.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // PROJECT : TEST-DOG // FILENAME : html_reporter.hpp // DESCRIPTION : Concrete HTML reporting class. // COPYRIGHT : Andy Thomas (C) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // LICENSE //--------------------------------------------------------------------------- // This file is part of the "TEST-DOG" program. // TEST-DOG 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. // TEST-DOG 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 TEST-DOG. If not, see <http://www.gnu.org/licenses/>. //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // INCLUDES //--------------------------------------------------------------------------- #include "html_reporter.hpp" #include "testdog/private/basic_test.hpp" #include "testdog/unit_test.hpp" #include "util.hpp" //--------------------------------------------------------------------------- // DECLARATIONS //--------------------------------------------------------------------------- using namespace testdog; namespace testdog { // Report tag names // Updating these can be used to form the basis for internationalization const char* const BASIC_TITLE = "Test Report"; const char* const PROJECT_NAME_LEADER = "PROJECT: "; const char* const PROJECT_VERSION_LEADER = "Version: "; const char* const REG_COUNT_LEADER = "Registered Tests: "; const char* const SCOPE_LEADER = "Run Scope: "; const char* const RUN_NONE_STR = "No Tests were Run"; const char* const RUN_ALL_STR = "All Tests"; const char* const RUN_SUITE_STR = "Specified Suite"; const char* const RUN_TEST_STR = "Specified Test Only"; const char* const START_TIME_LEADER = "Start Time: "; const char* const SUITE_LEADER = "TEST SUITE: "; const char* const DEF_SUITE_NAME = "[Default Suite]"; const char* const REPORT_CONTENTS = "Report Contents"; const char* const TEST_RESULTS = "Test Run Results"; const char* const TEST_STATS = "Statistical Results"; const char* const FAIL_DETAILS = "Test Failure Information"; const char* const ERROR_DETAILS = "Test Error Information"; const char* const PASS_DETAILS = "Test Pass Information"; const char* const DISABLED_TESTS = "Disabled Tests"; const char* const DISABLED_NOTES = "The following tests were skipped:"; const char* const END_TIME_LEADER = "End Time: "; const char* const DURATION_LEADER = "Run Duration: "; const char* const TAB_TEST_NAME = "Test Name"; const char* const TAB_AUTHOR = "Author"; const char* const TAB_START_TIME = "Start Time"; const char* const TAB_DURATION = "Duration"; const char* const TAB_RESULT = "Result"; const char* const STAT_TAB_METRIC = "Statistic"; const char* const STAT_TAB_VALUE = "Value"; const char* const STAT_TAB_RAN = "Tests Ran"; const char* const STAT_TAB_SKIPPED = "Skipped"; const char* const STAT_TAB_PASSED = "Passed"; const char* const STAT_TAB_FAILED = "Failed"; const char* const STAT_TAB_ERRORS = "Test Errors"; const char* const STAT_TAB_PERC = "Pass Rate"; const char* const NONE_STR = "NONE"; const char* const TEST_LEADER = "Test: "; const char* const BTS_NOT_RUN_STR = "NOT RUN"; const char* const BTS_SKIPPED_STR = "SKIPPED"; const char* const BTS_PASSED_STR = "PASSED"; const char* const BTS_FAILED_STR = "FAILED "; const char* const BTS_ERROR_STR = "TEST ERROR"; const char* const GENERATED_LEADER = "Test report generated by: "; } //--------------------------------------------------------------------------- // CLASS html_reporter : PROTECTED MEMBERS //--------------------------------------------------------------------------- std::string html_reporter::m_indent(int chrs) const { // Return indentation if (chrs < 0) chrs = m_indent_cnt; if (chrs > 0) return std::string(chrs, ' '); else return ""; } //--------------------------------------------------------------------------- std::ostream& html_reporter::m_generate_css(std::ostream& os) { // Generate interal CCS, or specify external sheet std::string temp_str = m_runner_ptr->html_report_stylesheet(); // Default styles os << m_indent() << "<style type=\"text/css\">\n"; m_indent_cnt += m_indent_step; os << m_indent() << "th {background-color:silver; font-weight:bold;"; os << " border-style:solid; border-width:thin}\n"; os << m_indent() << "td {border-style:solid; border-width:thin}\n"; os << m_indent() << ".pass-cell-col {background-color:lightgreen}\n"; os << m_indent() << ".fail-cell-col {background-color:red}\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</style>\n"; if (!temp_str.empty()) { os << m_indent() << "<link rel=\"stylesheet\" href=\""; os << temp_str; os << "\" type=\"text/css\" />\n"; } return os; } //--------------------------------------------------------------------------- std::string html_reporter::s_clean_id(const std::string& id_str) { // Clean up id_str and return result std::string rslt; std::size_t sz = id_str.size(); for(std::size_t n = 0; n < sz; ++n) { if ((id_str[n] >= 'a' && id_str[n] <= 'z') || (id_str[n] >= '0' && id_str[n] <= '9') || id_str[n] == '_' || id_str[n] == ':' || id_str[n] == '.' || id_str[n] == '-') { rslt += id_str[n]; } else if (id_str[n] == 0x20) { rslt += '_'; } else if (id_str[n] >= 'A' && id_str[n] <= 'Z') { rslt += static_cast<char>(id_str[n] + 0x20); } } return rslt; } //--------------------------------------------------------------------------- std::string html_reporter::s_page_link(const std::string& id_str, const std::string& name_str) { // Make "id_str" a link to an anchor. // Example: s_link("suite", "UCD_TESTS"); // returns: <a href=\"#anchor_suite">UCD_TESTS</a> return "<a href=\"#anchor_" + s_clean_id(id_str) + "\">" + name_str + "</a>"; } //--------------------------------------------------------------------------- std::string html_reporter::s_page_anchor(const std::string& id_str) { // Make "cat_str" an (empty) anchor. // Example: s_anchor("suite"); // returns: <span id=\"anchor_suite" /> return "<p id=\"anchor_" + s_clean_id(id_str) + "\"></p>"; } //--------------------------------------------------------------------------- std::string html_reporter::s_rslt_str(const basic_test* tc) { // Overral result of test switch(tc->state()) { case BTS_NOT_RUN: return BTS_NOT_RUN_STR; case BTS_SKIPPED: return BTS_SKIPPED_STR; case BTS_PASSED: return BTS_PASSED_STR; case BTS_FAILED: return std::string(BTS_FAILED_STR) + " (" + int_to_str(tc->fail_cnt()) + ")"; case BTS_TEST_ERROR: return BTS_ERROR_STR; default: return ""; } } //--------------------------------------------------------------------------- std::string html_reporter::s_th_str(const std::string& content, const std::string& width) { // Make table header cell if (!width.empty()) { return "<th style=\"width:" + width + "\">" + content + "</th>"; } else { return "<th>" + content + "</th>"; } } //--------------------------------------------------------------------------- std::string html_reporter::s_td_str(const std::string& content, bool bold, const std::string& class_id) { // Make table data cell std::string rslt = "<td"; if (!class_id.empty()) rslt += " class=\"" + class_id + "\""; rslt += ">"; if (bold) rslt += "<strong>" + content + "</strong>"; else rslt += content; return rslt + "</td>"; } //--------------------------------------------------------------------------- std::string html_reporter::s_cond_classid(bool passed) { // Condition color if (passed) return "pass-cell-col"; else return "fail-cell-col"; } //--------------------------------------------------------------------------- void html_reporter::m_build_trace(std::ostream& os, const std::vector<std::string>& trace_vec, const std::string& title_elem) { // During test case generation, trace output if buffered to a vector // array for adding to the report later. In this call, we take the vector // an build the trace sections of the report. Each test case is stored as // two items in the array. The first is the test name, and section is the // text formatted trace. Therefore, even numbered array indexes always // hold the test name for the trace that follows in the next item. // Start local indent - we expect 2 steps instead <html> & <body> tags std::size_t sz = trace_vec.size(); if (sz > 0 && sz % 2 == 0) { std::string t_name, t_cont; for(std::size_t n = 0; n < sz; n += 2) { // Extract test name and trace contents t_name = trace_vec[n]; t_cont = trace_vec[n+1]; if (t_cont.empty()) t_cont = NONE_STR; if (!t_name.empty()) { // Write title anchor os << m_indent() << s_page_anchor(t_name) + "\n"; // Make title, i.e. "....<h3>Suite::TestName</h3>" os << m_indent() << "<" << title_elem << ">"; os << TEST_LEADER << t_name << "</" + title_elem << ">\n"; // Stream <ul> start os << m_indent() + "<ul>\n"; m_indent_cnt += m_indent_step; // Steam trace content, replacing newlines with <li> pairs os << m_indent() + "<li>"; os << str_replace(t_cont, "\n", "</li>\n" + m_indent() + "<li>"); os << "</li>\n"; // Stream <ul> end m_indent_cnt -= m_indent_step; os << m_indent() + "</ul>\n"; } } } else { // No tests os << m_indent() << "<p>" << NONE_STR << "</p>\n"; } } //--------------------------------------------------------------------------- // CLASS html_reporter : PUBLIC MEMBERS //--------------------------------------------------------------------------- html_reporter::html_reporter(const runner* owner, html_reporter::style_t rs) : basic_reporter(owner) { // Constructor m_style = rs; m_indent_step = 2; m_html_report_author_col = true; // Create internal text reporter for test details // NB. We disable the test name leader as each output // block will have the test name as the heading. m_text_reporter_ptr = new text_reporter(m_runner_ptr, true); m_text_reporter_ptr->set_testname_leader(false); m_text_reporter_ptr->set_suite_breaks(false); // Zero clear(); } //--------------------------------------------------------------------------- html_reporter::~html_reporter() { try { // Destructor delete m_text_reporter_ptr; } catch(...) { } } //--------------------------------------------------------------------------- html_reporter::style_t html_reporter::style() const { // Accessor return m_style; } //--------------------------------------------------------------------------- void html_reporter::set_style(html_reporter::style_t s) { // Mutator m_style = s; } //--------------------------------------------------------------------------- int html_reporter::indent_step() const { // Accessor return m_indent_step; } //--------------------------------------------------------------------------- void html_reporter::set_indent_step(int is) { // Mutator if (is < 0) is = 0; m_indent_step = is; } //--------------------------------------------------------------------------- bool html_reporter::report_loc() const { // Accessor return m_text_reporter_ptr->report_loc(); } //--------------------------------------------------------------------------- void html_reporter::set_report_loc(bool rl) { // Mutator m_text_reporter_ptr->set_report_loc(rl); } //--------------------------------------------------------------------------- bool html_reporter::html_report_author_col() const { // Returns whether the HTML reports have an "author" column in // the result tables. return m_html_report_author_col; } //--------------------------------------------------------------------------- void html_reporter::set_html_report_author_col(bool a) { // Sets whether the HTML reports have an "author" column in // the result tables. m_html_report_author_col = a; } //--------------------------------------------------------------------------- void html_reporter::clear() { // Clear internal data m_suite_added = false; m_current_suite.clear(); m_indent_cnt = 0; m_text_reporter_ptr->clear(); m_pass_trace.clear(); m_fail_trace.clear(); m_error_trace.clear(); m_skipped_tests.clear(); } //--------------------------------------------------------------------------- std::ostream& html_reporter::gen_start(std::ostream& os) { // Write header to stream clear(); // DOCTYPE os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" "; os << "\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"; // HTML element os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"; m_indent_cnt += m_indent_step; // Head os << m_indent() << "<head>\n"; m_indent_cnt += m_indent_step; // Content-Type std::string temp_str = m_runner_ptr->report_charset(); os << m_indent() << "<meta http-equiv=\"Content-Type\" "; os << "content=\"text/html;"; if (!temp_str.empty()) os << " charset=" << temp_str; os << "\" />\n"; // Title temp_str = xml_esc(m_runner_ptr->project_name()); os << m_indent() << "<title>" << BASIC_TITLE; if (!temp_str.empty()) os << " | " << temp_str; os << "</title>\n"; // Stylesheet m_generate_css(os); // Head closure m_indent_cnt -= m_indent_step; os << m_indent() << "</head>\n"; // Body os << m_indent() << "<body>\n"; m_indent_cnt += m_indent_step; // Content - Title os << m_indent() << "<h1>" << BASIC_TITLE << "</h1>\n"; // Project information os << m_indent() << "<p>\n"; m_indent_cnt += m_indent_step; temp_str = xml_esc(m_runner_ptr->project_name()); if (!temp_str.empty()) { os << m_indent() << "<strong>" << PROJECT_NAME_LEADER << "</strong>"; os << temp_str << "<br/>\n"; } // Project version temp_str = xml_esc(m_runner_ptr->project_version()); if (!temp_str.empty()) { os << m_indent() << "<strong>" << PROJECT_VERSION_LEADER << "</strong>"; os << temp_str << "<br/>\n"; } // Test count os << m_indent() << "<strong>" << REG_COUNT_LEADER << "</strong>"; os << m_runner_ptr->registered_count() << "<br/>\n"; // Run scope os << m_indent() << "<strong>" << SCOPE_LEADER << "</strong>"; switch(m_runner_ptr->run_scope()) { case RUN_NONE: os << RUN_NONE_STR << "<br/>\n"; break; case RUN_ALL: os << RUN_ALL_STR << "<br/>\n"; break; case RUN_SUITE: os << RUN_SUITE_STR << "<br/>\n"; break; case RUN_TEST: os << RUN_TEST_STR << "<br/>\n"; break; default: os << "<br/>\n"; break; } // Start time os << m_indent() << "<strong>" << START_TIME_LEADER << "</strong>"; os << iso_time(m_runner_ptr->start_time()) << "<br/>\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</p>\n"; // Content - Title os << m_indent() << "<h2>" << REPORT_CONTENTS << "</h2>\n"; // Build navigation list if (m_runner_ptr->contains_suites()) { // Suite navigation // List os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<li>"; os << s_page_link("main", "<strong>" + std::string(TEST_RESULTS) + "</strong>"); os << "</li>\n"; // Get suite names std::vector<std::string> suite_array; m_runner_ptr->enum_suite_names(suite_array); std::size_t sz = suite_array.size(); for(std::size_t n = 0; n < sz; ++n) { if (suite_array[n].empty()) { // Sub default name suite_array[n] = DEF_SUITE_NAME; } // Escape suite_array[n] = xml_esc(suite_array[n]); os << m_indent() << "<li>"; os << s_page_link("suite_" + suite_array[n], suite_array[n]) << "</li>\n"; } // List closure m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; } else { // List os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<li>"; os << s_page_link("main", "<strong>" + std::string(TEST_RESULTS) + "</strong>"); os << "</li>\n"; // List closure m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; } // Additional info // List os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<li>"; os << s_page_link("test_stats", "<strong>" + std::string(TEST_STATS) + "</strong>"); os << "</li>\n"; if (m_style != HTML_SUMMARY) { // Additional content os << m_indent() << "<li>"; os << s_page_link("fail_details", FAIL_DETAILS); os << "</li>\n"; os << m_indent() << "<li>"; os << s_page_link("error_details", ERROR_DETAILS); os << "</li>\n"; if (m_style == HTML_VERBOSE) { // Verbose only content os << m_indent() << "<li>"; os << s_page_link("pass_details", PASS_DETAILS); os << "</li>\n"; os << m_indent() << "<li>"; os << s_page_link("disabled_tests", DISABLED_TESTS); os << "</li>\n"; } } // List closure m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; // Main section os << m_indent() << s_page_anchor("main") << "\n"; os << m_indent() << "<h2>" << TEST_RESULTS << "</h2>\n"; return os; } //--------------------------------------------------------------------------- std::ostream& html_reporter::gen_test(std::ostream& os, const basic_test* tc) { // Write test case to stream. tc cannot be null. if (tc->state() == BTS_SKIPPED) { if (m_style == HTML_VERBOSE) { // Record to skipped list m_skipped_tests.push_back(tc->full_name()); } } else if (tc->state() != BTS_NOT_RUN) { // Set temp_str to be suite name std::string s_name = xml_esc(tc->suite_name()); if (s_name != m_current_suite || !m_suite_added) { // New test suite if (m_suite_added) { // Close old suite m_indent_cnt -= m_indent_step; os << m_indent() << "</table>\n"; } // Add new suite m_suite_added = true; m_current_suite = s_name; // Apply default name if (m_runner_ptr->contains_suites()) { // Add suite header if (s_name.empty()) s_name = DEF_SUITE_NAME; os << m_indent() << s_page_anchor("suite_" + s_name) << "\n"; os << m_indent() << "<h3>" << SUITE_LEADER << s_name << "</h3>\n"; } // Open table (defines width properties) os << m_indent() << "<table style=\"width:75%; max-width:100em\">\n"; m_indent_cnt += m_indent_step; // Header row os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_th_str(TAB_TEST_NAME) << "\n"; if (m_html_report_author_col) { os << m_indent() << s_th_str(TAB_AUTHOR, "15%") << "\n"; } os << m_indent() << s_th_str(TAB_START_TIME, "20%") << "\n"; os << m_indent() << s_th_str(TAB_DURATION, "15%") << "\n"; os << m_indent() << s_th_str(TAB_RESULT, "15%") << "\n"; // Close row m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; } // Data row os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; // Set temp_str to be full test name std::string t_name = xml_esc(tc->full_name()); if (m_style == HTML_VERBOSE || (m_style != HTML_SUMMARY && tc->state() != BTS_PASSED)) { // Add event to corresponding vector - these // will be appended to the report later. We append // the test name, followed by the trace text, so // that even number elements always content the // test name, and trace contents will follow. std::stringstream ss; m_text_reporter_ptr->gen_test(ss, tc); std::string t_cont = xml_esc(trim_str(ss.str())); switch(tc->state()) { // Append to applicable vector case BTS_PASSED: m_pass_trace.push_back(t_name); m_pass_trace.push_back(t_cont); break; case BTS_FAILED: m_fail_trace.push_back(t_name); m_fail_trace.push_back(t_cont); break; case BTS_TEST_ERROR: m_error_trace.push_back(t_name); m_error_trace.push_back(t_cont); break; default: break; } // Linked test name t_name = s_page_link(t_name, t_name); } os << m_indent() << s_td_str(t_name) << "\n"; if (m_html_report_author_col) { os << m_indent() << s_td_str(xml_esc(tc->author())) << "\n"; } os << m_indent() << s_td_str(iso_time(tc->start_time())) << "\n"; os << m_indent() << s_td_str(duration_str(tc->test_duration())) << "\n"; // Color pass/fail value bool pass_ok = (tc->state() == BTS_PASSED); os << m_indent() << s_td_str(s_rslt_str(tc), !pass_ok, s_cond_classid(pass_ok)) << "\n"; // Close row m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; } return os; } //--------------------------------------------------------------------------- std::ostream& html_reporter::gen_end(std::ostream& os) { // Write footer to stream if (m_suite_added) { // Close last table m_indent_cnt -= m_indent_step; os << m_indent() << "</table>\n"; } else if (m_runner_ptr->stat_result(ST_RAN) == 0) { os << m_indent() << "<p>" << NONE_STR << "</p>"; } // Statistics os << m_indent() << s_page_anchor("test_stats") << "\n"; os << m_indent() << "<h2>" << TEST_STATS << "</h2>\n"; // Define colors std::string pass_id, fail_id, err_id; if (m_runner_ptr->stat_result(ST_PASSED) == m_runner_ptr->stat_result(ST_RAN)) { pass_id = s_cond_classid(true); } if (m_runner_ptr->stat_result(ST_FAILED) > 0) { fail_id = s_cond_classid(false); } if (m_runner_ptr->stat_result(ST_ERRORS) > 0) { err_id = s_cond_classid(false); } // Open table os << m_indent() << "<table style=\"width:20em\">\n"; m_indent_cnt += m_indent_step; // Header row os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_th_str(STAT_TAB_METRIC) << "\n"; os << m_indent() << s_th_str(STAT_TAB_VALUE) << "\n"; // Close row m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_RAN, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_RAN))) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_SKIPPED, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_SKIPPED))) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_PASSED, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_PASSED))) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_FAILED, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_FAILED)), false, fail_id) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_ERRORS, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_ERRORS)), false, err_id) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_PERC, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_PASS_RATE)) + "%", false, pass_id) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</table>\n"; // Test end time os << m_indent() << "<p>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<strong>" << END_TIME_LEADER << "</strong>"; os << iso_time(m_runner_ptr->end_time()) << "<br/>\n"; // Duration os << m_indent() << "<strong>" << DURATION_LEADER << "</strong>"; os << duration_str(m_runner_ptr->duration()) << " (approx.) <br/>\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</p>\n"; if (m_style != HTML_SUMMARY) { // Additional content os << m_indent() << s_page_anchor("fail_details") << "\n"; os << m_indent() << "<h2>" << FAIL_DETAILS << "</h2>\n"; m_build_trace(os, m_fail_trace, "h3"); os << m_indent() << s_page_anchor("error_details") << "\n"; os << m_indent() << "<h2>" << ERROR_DETAILS << "</h2>\n"; m_build_trace(os, m_error_trace, "h3"); if (m_style == HTML_VERBOSE) { // Verbose only content os << m_indent() << s_page_anchor("pass_details") << "\n"; os << m_indent() << "<h2>" << PASS_DETAILS << "</h2>\n"; m_build_trace(os, m_pass_trace, "h3"); // Disabled tests os << m_indent() << s_page_anchor("disabled_tests") << "\n"; os << m_indent() << "<h2>" << DISABLED_TESTS << "</h2>\n"; // Build list of disabled tests std::size_t sk_sz = m_skipped_tests.size(); if (sk_sz > 0) { os << m_indent() << "<p>" << DISABLED_NOTES << "</p>\n"; os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; for(std::size_t n = 0; n < sk_sz; ++n) { os << m_indent() << "<li>" << m_skipped_tests[n] << "</li>\n"; } m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; } else { os << m_indent() << "<p>" << NONE_STR << "</p>\n"; } } } // Generator os << m_indent() << "<p>" << GENERATED_LEADER; os << LIB_NAME << " " << LIB_VERSION; os << "</p>\n"; // Close body m_indent_cnt -= m_indent_step; os << m_indent() << "</body>\n"; // Close html m_indent_cnt -= m_indent_step; os << m_indent() << "</html>\n"; return os; } //---------------------------------------------------------------------------
31.698974
81
0.523921
skarab
dac18c98d7b653007725ef7b0622af146c8360f6
1,099
hpp
C++
include/gtfs/read_csv.hpp
mapbox/nepomuk
8771482edb9b16bb0f5a152c15681c57eb3bb6b6
[ "MIT" ]
22
2017-05-12T11:52:26.000Z
2021-12-06T06:05:08.000Z
include/gtfs/read_csv.hpp
mapbox/nepomuk
8771482edb9b16bb0f5a152c15681c57eb3bb6b6
[ "MIT" ]
49
2017-05-11T16:13:58.000Z
2017-12-13T11:19:17.000Z
include/gtfs/read_csv.hpp
mapbox/nepomuk
8771482edb9b16bb0f5a152c15681c57eb3bb6b6
[ "MIT" ]
7
2017-11-19T12:04:26.000Z
2021-12-06T06:14:25.000Z
#ifndef NEPOMUK_GTFS_READ_CSV_HPP_ #define NEPOMUK_GTFS_READ_CSV_HPP_ #include <boost/filesystem/path.hpp> #include <boost/optional.hpp> #include <string> #include "gtfs/dataset.hpp" namespace nepomuk { namespace gtfs { struct CSVDiscSource { boost::filesystem::path agency; boost::filesystem::path calendar; boost::filesystem::path routes; boost::filesystem::path stops; boost::filesystem::path stop_times; boost::filesystem::path trips; boost::optional<boost::filesystem::path> calendar_dates; boost::optional<boost::filesystem::path> fare_attributes; boost::optional<boost::filesystem::path> fare_rules; boost::optional<boost::filesystem::path> feed_info; boost::optional<boost::filesystem::path> frequencies; boost::optional<boost::filesystem::path> shapes; boost::optional<boost::filesystem::path> transfers; CSVDiscSource(boost::filesystem::path base); }; // Ingest streams from a local source on disk Dataset readCSV(CSVDiscSource const &source); } // namespace gtfs } // namespace nepomuk #endif // NEPOMUK_GTFS_READ_CSV_HPP_
26.166667
61
0.745223
mapbox
dac5c782a1224e35b42b94abfa4e19ce81d22180
1,362
cpp
C++
code/2D_misc_code/math2d.cpp
darketmaster/misc_code
46b66284e756a02ded677035a994d87b1e1cff69
[ "MIT" ]
null
null
null
code/2D_misc_code/math2d.cpp
darketmaster/misc_code
46b66284e756a02ded677035a994d87b1e1cff69
[ "MIT" ]
null
null
null
code/2D_misc_code/math2d.cpp
darketmaster/misc_code
46b66284e756a02ded677035a994d87b1e1cff69
[ "MIT" ]
null
null
null
#define ALLEGRO_INCLUDE_MATH_H #include "allegro.h" #include "math2d.h" #include "math.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif void correct_angle(float *ang) { if(*ang >= 360.0) while(*ang >= 360.0) *ang -= 360.0; else if(*ang < 0.0) while(*ang < 0.0) *ang += 360.0; } float get_angle_xz(float x,float z) { float ang; ang = RAD2DEG(atan2(x,z)); correct_angle(&ang); return (ang); } float *Sintab = NULL; float *Costab = NULL; float *Tantab = NULL; float *aTantab = NULL; /* #define floatcos(x) Costab[(int)(x*10)] //cos((x) * M_PI / 128.0) #define floatsin(x) Sintab[(int)(x*10)] //sin((x) * M_PI / 128.0) #define floattan(x) Tantab[(int)(x*10)] //tan((x) * M_PI / 128.0) */ void math_exit(void) { if(Sintab) free(Sintab); if(Costab) free(Costab); if(Tantab) free(Tantab); } int math_ini(void) { int i; Sintab = (float*)calloc(3600,sizeof(float)); Costab = (float*)calloc(3600,sizeof(float)); Tantab = (float*)calloc(3600,sizeof(float)); if(!Sintab || !Costab || !Tantab) { math_exit(); return FALSE; } for(i=0; i<3600; i++) { Sintab[i] = sin(DEG2RAD((float) i / 10.0)); Costab[i] = cos(DEG2RAD((float) i / 10.0)); Tantab[i] = tan(DEG2RAD((float) i / 10.0)); } return TRUE; }
20.636364
73
0.571219
darketmaster
dac60771e185d510189f139a26d01a41a909b797
14,725
inl
C++
image/include/storm/image/Image.inl
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
image/include/storm/image/Image.inl
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
image/include/storm/image/Image.inl
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copyright (C) 2021 Arthur LAURENT <arthur.laurent4@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution #pragma once #include "Image.hpp" namespace storm::image { ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::pixel(core::ArraySize index, core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); auto _data = data(layer, face, level); STORMKIT_EXPECTS(index < m_extent.width * m_extent.height * m_extent.depth); const auto block_size = m_channel_count * m_bytes_per_channel; return { std::data(_data) + index * block_size, block_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::pixel(core::ArraySize index, core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); auto _data = data(layer, face, level); const auto mip_extent = extent(level); STORMKIT_EXPECTS(index < mip_extent.width * mip_extent.height * mip_extent.depth); const auto block_size = m_channel_count * m_bytes_per_channel; return { std::data(_data) + index * block_size, block_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::pixel(core::Position3u position, core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { const auto mip_extent = extent(level); const auto id = position->x + (position->y * mip_extent.width) + (mip_extent.width * mip_extent.height * position->z); return pixel(id, layer, face, level); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::pixel(core::Position3u position, core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { const auto mip_extent = extent(level); const auto id = position->x + (position->y * mip_extent.width) + (mip_extent.width * mip_extent.height * position->z); return pixel(id, layer, face, level); } ///////////////////////////////////// ///////////////////////////////////// core::Extentu Image::extent(core::UInt32 level) const noexcept { STORMKIT_EXPECTS(m_mip_levels > level); return { std::max(1u, m_extent.width >> level), std::max(1u, m_extent.height >> level), std::max(1u, m_extent.depth >> level) }; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::channelCount() const noexcept { return m_channel_count; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::bytesPerChannel() const noexcept { return m_bytes_per_channel; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::layers() const noexcept { return m_layers; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::faces() const noexcept { return m_faces; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::mipLevels() const noexcept { return m_mip_levels; } ///////////////////////////////////// ///////////////////////////////////// Image::Format Image::format() const noexcept { return m_format; } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size() const noexcept { return std::size(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); const auto mip_extent = extent(level); return mip_extent.width * mip_extent.height * mip_extent.depth * m_channel_count * m_bytes_per_channel; } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size(core::UInt32 layer, core::UInt32 face) const noexcept { auto _size = core::ArraySize { 0u }; for (auto i = 0u; i < m_mip_levels; ++i) _size += size(layer, face, i); return _size; } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size(core::UInt32 layer) const noexcept { auto _size = core::ArraySize { 0u }; for (auto i = 0u; i < m_faces; ++i) _size += size(layer, i); return _size; } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::data() noexcept { return m_data; } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::data(core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { const auto mip_size = size(layer, face, level); auto offset = 0u; for (auto i = 0u; i < layer; ++i) offset += size(i); for (auto j = 0u; j < face; ++j) offset += size(layer, j); for (auto k = 0u; k < level; ++k) offset += size(layer, face, k); return { std::data(m_data) + offset, mip_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::data() const noexcept { return m_data; } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::data(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { const auto mip_size = size(layer, face, level); auto offset = 0u; for (auto i = 0u; i < layer; ++i) offset += size(i); for (auto j = 0u; j < face; ++j) offset += size(layer, j); for (auto k = 0u; k < level; ++k) offset += size(layer, face, k); return { std::data(m_data) + offset, mip_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::iterator Image::begin() noexcept { return std::begin(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan::iterator Image::begin(core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); return std::begin(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::begin() const noexcept { return std::begin(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::begin(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::begin(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::cbegin() const noexcept { return std::cbegin(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::cbegin(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::cbegin(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::iterator Image::end() noexcept { return std::end(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan::iterator Image::end(core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { return std::end(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::end() const noexcept { return std::end(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::end(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::end(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::cend() const noexcept { return std::cend(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::cend(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::cend(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// constexpr core::UInt8 getChannelCountFor(Image::Format format) noexcept { switch (format) { case Image::Format::R8_SNorm: case Image::Format::R8_UNorm: case Image::Format::R16_SNorm: case Image::Format::R16_UNorm: case Image::Format::R8I: case Image::Format::R8U: case Image::Format::R16I: case Image::Format::R16U: case Image::Format::R32I: case Image::Format::R32U: case Image::Format::R16F: case Image::Format::R32F: return 1; case Image::Format::RG8_SNorm: case Image::Format::RG8_UNorm: case Image::Format::RG16_SNorm: case Image::Format::RG16_UNorm: case Image::Format::RG8I: case Image::Format::RG8U: case Image::Format::RG16I: case Image::Format::RG16U: case Image::Format::RG32I: case Image::Format::RG32U: case Image::Format::RG16F: case Image::Format::RG32F: return 2; case Image::Format::RGB8_SNorm: case Image::Format::RGB8_UNorm: case Image::Format::RGB16_SNorm: case Image::Format::RGB16_UNorm: case Image::Format::BGR8_UNorm: case Image::Format::RGB8I: case Image::Format::RGB8U: case Image::Format::RGB16I: case Image::Format::RGB16U: case Image::Format::RGB32I: case Image::Format::RGB32U: case Image::Format::RGB16F: case Image::Format::RGB32F: case Image::Format::sRGB8: case Image::Format::sBGR8: return 3; case Image::Format::RGBA8_SNorm: case Image::Format::RGBA8_UNorm: case Image::Format::RGBA16_SNorm: case Image::Format::RGBA16_UNorm: case Image::Format::BGRA8_UNorm: case Image::Format::RGBA8I: case Image::Format::RGBA8U: case Image::Format::RGBA16I: case Image::Format::RGBA16U: case Image::Format::RGBA32I: case Image::Format::RGBA32U: case Image::Format::RGBA16F: case Image::Format::RGBA32F: case Image::Format::sRGBA8: case Image::Format::sBGRA8: return 4; default: return 0u; } return 0u; } ///////////////////////////////////// ///////////////////////////////////// constexpr core::UInt8 getArraySizeByChannelFor(Image::Format format) noexcept { switch (format) { case Image::Format::R8_SNorm: case Image::Format::R8_UNorm: case Image::Format::RG8_SNorm: case Image::Format::RG8_UNorm: case Image::Format::R8I: case Image::Format::R8U: case Image::Format::RG8I: case Image::Format::RG8U: case Image::Format::RGB8_SNorm: case Image::Format::RGB8_UNorm: case Image::Format::BGR8_UNorm: case Image::Format::RGB8I: case Image::Format::RGB8U: case Image::Format::RGBA8_SNorm: case Image::Format::RGBA8_UNorm: case Image::Format::RGBA16_SNorm: case Image::Format::BGRA8_UNorm: case Image::Format::sRGB8: case Image::Format::sBGR8: case Image::Format::sRGBA8: case Image::Format::sBGRA8: return 1u; case Image::Format::R16_SNorm: case Image::Format::R16_UNorm: case Image::Format::R16I: case Image::Format::R16U: case Image::Format::RG16_SNorm: case Image::Format::RG16_UNorm: case Image::Format::RG16I: case Image::Format::RG16U: case Image::Format::RG16F: case Image::Format::RGB16I: case Image::Format::RGB16U: case Image::Format::RGB16F: case Image::Format::RGBA16I: case Image::Format::RGBA16U: case Image::Format::RGBA16F: case Image::Format::R16F: return 2u; case Image::Format::R32I: case Image::Format::R32U: case Image::Format::R32F: case Image::Format::RG32I: case Image::Format::RG32U: case Image::Format::RG32F: case Image::Format::RGB16_SNorm: case Image::Format::RGB32I: case Image::Format::RGB32U: case Image::Format::RGB32F: case Image::Format::RGBA8I: case Image::Format::RGBA8U: case Image::Format::RGBA32I: case Image::Format::RGBA32U: case Image::Format::RGBA32F: return 4u; default: return 0u; } return 0u; } } // namespace storm::image
37.659847
100
0.469134
Arthapz
dacde3c23dc3777e5404cccc19a89b390708c63a
7,150
cxx
C++
vtr/toro/TO_Output/TO_OutputEmailMetrics.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
31
2016-02-15T02:57:28.000Z
2021-06-02T10:40:25.000Z
vtr/toro/TO_Output/TO_OutputEmailMetrics.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
null
null
null
vtr/toro/TO_Output/TO_OutputEmailMetrics.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
6
2017-02-08T21:51:51.000Z
2021-06-02T10:40:40.000Z
//===========================================================================// // Purpose : Supporting methods for the TO_Output_c post-processor class. // These methods support formatting and sending a metrics email. // // Private methods include: // - SendMetricsEmail_ // - BuildMetricsEmailSubject_ // - BuildMetricsEmailBody_ // - MailMetricsEmailMessage_ // //===========================================================================// //---------------------------------------------------------------------------// // Copyright (C) 2012 Jeff Rudolph, Texas Instruments (jrudolph@ti.com) // // // // This program is free software; you can redistribute it and/or modify it // // under the terms of the GNU General Public License as published by the // // Free Software Foundation; version 3 of the License, or any later version. // // // // This program is distributed in the hope that it will be useful, but // // WITHOUT ANY WARRANTY; without even an 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, see <http://www.gnu.org/licenses>. // //---------------------------------------------------------------------------// #include "TC_StringUtils.h" #include "TIO_StringText.h" #include "TIO_SkinHandler.h" #include "TIO_PrintHandler.h" #include "TO_Output.h" //===========================================================================// // Method : SendMetricsEmail_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// bool TO_Output_c::SendMetricsEmail_( const TOS_InputOptions_c& inputOptions, const TOS_OutputOptions_c& outputOptions ) const { bool ok = true; const string& srEmailAddress = outputOptions.srMetricsEmailAddress; TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); printHandler.Info( "Sending %s email to '%s'...\n", TIO_SZ_OUTPUT_METRICS_DEF_TYPE, TIO_SR_STR( srEmailAddress )); const char* pszOptionsFileName = inputOptions.optionsFileNameList[0]->GetName( ); string srMessageSubject; this->BuildMetricsEmailSubject_( pszOptionsFileName, &srMessageSubject ); const TCL_CommandLine_c& commandLine = *this->pcommandLine_; string srCommandLine; commandLine.ExtractArgString( &srCommandLine ); string srMessageBody; this->BuildMetricsEmailBody_( srCommandLine, &srMessageBody ); ok = this->MailMetricsEmailMessage_( srEmailAddress, srMessageSubject, srMessageBody ); return( ok ); } //===========================================================================// // Method : BuildMetricsEmailSubject_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// void TO_Output_c::BuildMetricsEmailSubject_( const char* pszFileName, string* psrSubject ) const { if( psrSubject ) { TIO_SkinHandler_c& skinHandler = TIO_SkinHandler_c::GetInstance( ); const char* pszBinaryName = skinHandler.GetBinaryName( ); *psrSubject = ""; *psrSubject += pszBinaryName; *psrSubject += " "; *psrSubject += pszFileName; } } //===========================================================================// // Method : BuildMetricsEmailBody_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// void TO_Output_c::BuildMetricsEmailBody_( const string& srCommandLine, string* psrBody ) const { if( psrBody ) { TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); char szTimeStamp[TIO_FORMAT_STRING_LEN_DATE_TIME]; size_t lenTimeStamp = sizeof( szTimeStamp ); TC_FormatStringDateTimeStamp( szTimeStamp, lenTimeStamp, "[", "]" ); TIO_SkinHandler_c& skinHandler = TIO_SkinHandler_c::GetInstance( ); const char* pszBinaryName = skinHandler.GetBinaryName( ); string srWorkingDir; printHandler.FindWorkingDir( &srWorkingDir ); string srUserName; printHandler.FindUserName( &srUserName ); string srHostName; printHandler.FindHostName( &srHostName ); const char* pszBuildVersion = TIO_SZ_BUILD_VERSION; *psrBody = ""; *psrBody += szTimeStamp; *psrBody += " "; *psrBody += pszBinaryName; *psrBody += " "; *psrBody += srCommandLine; *psrBody += ", "; *psrBody += srUserName; *psrBody += ", "; *psrBody += srHostName; *psrBody += ", "; *psrBody += srWorkingDir; *psrBody += ", "; *psrBody += pszBuildVersion; *psrBody += "\n"; } } //===========================================================================// // Method : MailMetricsEmailMessage_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// bool TO_Output_c::MailMetricsEmailMessage_( const string& srAddress, const string& srSubject, const string& srBody ) const { bool ok = true; int lenBody = static_cast< int >( srBody.length( )); int lenSubject = static_cast< int >( srSubject.length( )); int lenAddress = static_cast< int >( srAddress.length( )); const char* pszTemplate = "echo \"\" | mail -s \"\" "; size_t lenTemplate = strlen( pszTemplate ) + 1; if( lenBody + lenSubject + lenAddress + lenTemplate > TIO_FORMAT_STRING_LEN_EMAIL ) { lenBody = static_cast< int >( TIO_FORMAT_STRING_LEN_EMAIL - lenSubject - lenAddress - lenTemplate ); } char szSendCmd[TIO_FORMAT_STRING_LEN_EMAIL + TIO_FORMAT_STRING_LEN_DATA]; sprintf( szSendCmd, "echo \"%*s\" | mail -s \"%*s\" %*s", lenBody, TIO_SR_STR( srBody ), lenSubject, TIO_SR_STR( srSubject ), lenAddress, TIO_SR_STR( srAddress )); ok = ( system( szSendCmd ) >= 0 ? true : false ); return( ok ); }
38.235294
106
0.50042
haojunliu
dad1354450c609a7e177b5f64d9da1cb1be2bde3
545
cpp
C++
GeeksForGeeks/DS/1. Linked List/5.search-an-element-in-a-linked-list-iterative-and-recursive.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
GeeksForGeeks/DS/1. Linked List/5.search-an-element-in-a-linked-list-iterative-and-recursive.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
GeeksForGeeks/DS/1. Linked List/5.search-an-element-in-a-linked-list-iterative-and-recursive.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// http://geeksquiz.com/search-an-element-in-a-linked-list-iterative-and-recursive #include "linkedList.h" bool search(node *head, int x){ if(head == NULL) return 0; if(head->data == x) return true; return search(head->next, x); } int main(){ node* head = NULL; int x = 21; /* Use push() to construct below list 14->21->11->30->10 */ push(&head, 10); push(&head, 30); push(&head, 11); push(&head, 21); push(&head, 14); search(head, 21)? printf("Yes") : printf("No"); return 0; }
19.464286
82
0.572477
Ashwanigupta9125
dad4144fd8a60c44e5f8ac9649ebbfc262a21ff1
5,970
cpp
C++
IRLib/Decoder.cpp
rizwanullah/IRLib
d06bea379e62f0db7276d3be3488b5af8ce8c369
[ "Apache-2.0" ]
null
null
null
IRLib/Decoder.cpp
rizwanullah/IRLib
d06bea379e62f0db7276d3be3488b5af8ce8c369
[ "Apache-2.0" ]
null
null
null
IRLib/Decoder.cpp
rizwanullah/IRLib
d06bea379e62f0db7276d3be3488b5af8ce8c369
[ "Apache-2.0" ]
null
null
null
#include "Decoder.h" #include "json.hpp" #include "Common.h" using json = nlohmann::json; Decoder::Decoder() {} std::string Decoder::decode(std::string encodedIrJsonStr) { json encodedIrJson; REMOTE_COMMON remoteCommon; std::string encodedIrData; //memset(&remoteCommon, 0, sizeof(remoteCommon)); try { encodedIrJson = json::parse(encodedIrJsonStr); } catch (std::exception &e) { Common::logIrLib("Exception: %s", e.what()); return createResponseJson(CM_CODE_JSON_PARSE_ERROR, e.what(), "", ""); } try { remoteCommon.remoteId = encodedIrJson["remoteId"]; } catch (std::exception &e) { Common::logIrLib("Exception: %s", e.what()); return createResponseJson(CM_CODE_JSON_NO_KEY_ERROR, e.what(), "", ""); } try { encodedIrData = encodedIrJson["encodedIrData"]; } catch (std::exception &e) { Common::logIrLib("Exception: %s", e.what()); return createResponseJson(CM_CODE_JSON_NO_KEY_ERROR, e.what(), "", ""); } int32_t decodeErrorCode = DE_CODE_REMOTE_NOT_FOUND; if (remoteCommon.remoteId == 0) { // find remote if (decodeErrorCode != DE_CODE_SUCCESS) { RmtChigo1 *rmtChigo1 = new RmtChigo1(); decodeErrorCode = rmtChigo1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtChigo1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtAux1 *rmtAux1 = new RmtAux1(); decodeErrorCode = rmtAux1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtAux1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtTcl1 *rmtTcl1 = new RmtTcl1(); decodeErrorCode = rmtTcl1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtTcl1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtChigo2 *rmtChigo2 = new RmtChigo2(); decodeErrorCode = rmtChigo2->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtChigo2::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtLG1 *rmtLG1 = new RmtLG1(); decodeErrorCode = rmtLG1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtLG1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtMits1 *rmtMits1 = new RmtMits1(); decodeErrorCode = rmtMits1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtMits1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtGreeAll *rmtGreeAll = new RmtGreeAll(); decodeErrorCode = rmtGreeAll->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtGreeAll::remoteId; } } else if (remoteCommon.remoteId == RmtChigo1::remoteId) { RmtChigo1 *rmtChigo1 = new RmtChigo1(); decodeErrorCode = rmtChigo1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtAux1::remoteId) { RmtAux1 *rmtAux1 = new RmtAux1(); decodeErrorCode = rmtAux1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtTcl1::remoteId) { RmtTcl1 *rmtTcl1 = new RmtTcl1(); decodeErrorCode = rmtTcl1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtChigo2::remoteId) { RmtChigo2 *rmtChigo2 = new RmtChigo2(); decodeErrorCode = rmtChigo2->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtLG1::remoteId) { RmtLG1 *rmtLG1 = new RmtLG1(); decodeErrorCode = rmtLG1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtMits1::remoteId) { RmtMits1 *rmtMits1 = new RmtMits1(); decodeErrorCode = rmtMits1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtGreeAll::remoteId) { RmtGreeAll *rmtGreeAll = new RmtGreeAll(); decodeErrorCode = rmtGreeAll->decodeRemote(encodedIrData, &remoteCommon); } else { return createResponseJson(DE_CODE_REMOTE_NOT_FOUND, Common::getErrorString(DE_CODE_REMOTE_NOT_FOUND), "", ""); } json remoteJson; remoteJson["remoteId"] = remoteCommon.remoteId; remoteJson["remoteModel"] = remoteCommon.remoteModel; remoteJson["remoteBrand"] = remoteCommon.remoteBrand; remoteJson["powerOnOff"] = remoteCommon.powerOnOff; remoteJson["operationMode"] = remoteCommon.operationMode; remoteJson["setTemperature"] = remoteCommon.setTemperature; remoteJson["fanSpeed"] = remoteCommon.fanSpeed; remoteJson["swingVertical"] = remoteCommon.swingVertical; remoteJson["swingHorizontal"] = remoteCommon.swingHorizontal; remoteJson["turboOnOff"] = remoteCommon.turboOnOff; remoteJson["muteOnOff"] = remoteCommon.muteOnOff; remoteJson["autoEvapOnOff"] = remoteCommon.autoEvapOnOff; remoteJson["displayOnOff"] = remoteCommon.displayOnOff; if (decodeErrorCode == DE_CODE_SUCCESS) { json responseJson; responseJson["errorCode"] = DE_CODE_SUCCESS; responseJson["errorMessage"] = ""; responseJson["decodedIrPacket"] = remoteCommon.decodedPacket; responseJson["decodedIrJson"] = remoteJson; return responseJson.dump(); } else return createResponseJson(decodeErrorCode, Common::getErrorString(decodeErrorCode), "", ""); } std::string Decoder::createResponseJson(int32_t errorCode, std::string errorMessage, std::string decodedIrPacket, std::string decodedIrJsonStr) { json responseJson; responseJson["errorCode"] = errorCode; responseJson["errorMessage"] = errorMessage; responseJson["decodedIrPacket"] = decodedIrPacket; responseJson["decodedIrJson"] = decodedIrJsonStr; return responseJson.dump(); }
44.552239
145
0.672362
rizwanullah
dad944fc138dd5b3cbcdc751f6a2c80231622cde
278
cc
C++
sem3/jnp1/playlist/SequenceMode.cc
abrams27/mimuw
ad8b01b63c05d7903aab29fd145845cf97ac32d9
[ "MIT" ]
3
2021-10-07T18:19:37.000Z
2021-10-07T19:02:14.000Z
sem3/jnp1/playlist/SequenceMode.cc
abrams27/mimuw
ad8b01b63c05d7903aab29fd145845cf97ac32d9
[ "MIT" ]
null
null
null
sem3/jnp1/playlist/SequenceMode.cc
abrams27/mimuw
ad8b01b63c05d7903aab29fd145845cf97ac32d9
[ "MIT" ]
3
2021-12-02T11:09:09.000Z
2022-01-25T21:31:23.000Z
#include "SequenceMode.h" std::shared_ptr<std::vector<size_t>> SequenceMode::get_order(size_t size) { auto order = std::make_shared<std::vector<size_t>>(); for (size_t i = 0; i < size; i++) { order->push_back(i); } return order; } SequenceMode::SequenceMode() {}
21.384615
75
0.661871
abrams27
dae53245f62fea7a54ed6926505324621f29f39b
1,056
cpp
C++
roman-to-integer.cpp
isanchez-aguilar/LeetCode-Solutions
094c15b672efa6ca2581f187579303c8b94390a3
[ "MIT" ]
null
null
null
roman-to-integer.cpp
isanchez-aguilar/LeetCode-Solutions
094c15b672efa6ca2581f187579303c8b94390a3
[ "MIT" ]
null
null
null
roman-to-integer.cpp
isanchez-aguilar/LeetCode-Solutions
094c15b672efa6ca2581f187579303c8b94390a3
[ "MIT" ]
null
null
null
class Solution { public: static int getValueOfChar(char c) { if (c == 'I') return 1; if (c == 'V') return 5; if (c == 'X') return 10; if (c == 'L') return 50; if (c == 'C') return 100; if (c == 'D') return 500; return 1000; } /* ** Time complexity: O(|s|) ** Space complexity: O(1) */ int romanToInt(string s) { int answer = 0; int currentSum = getValueOfChar(s[0]); int prevVal = currentSum; const int size = s.size(); for (int i = 1; i < size; ++i) { const int symbolValue = getValueOfChar(s[i]); if (symbolValue == prevVal) { currentSum += symbolValue; } if (symbolValue < prevVal) { answer += currentSum; currentSum = symbolValue; } if (prevVal < symbolValue) { answer += symbolValue - currentSum; currentSum = 0; } prevVal = symbolValue; } answer += currentSum; return answer; } };
17.311475
51
0.482008
isanchez-aguilar
daea7fa9d026ab64bc6657d418427ad9b130ff80
1,291
cpp
C++
src/modelFactory/FindSCMain.cpp
toebs88/SCAM
0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca
[ "MIT" ]
3
2018-08-31T21:35:27.000Z
2018-10-29T04:06:46.000Z
src/modelFactory/FindSCMain.cpp
toebs88/SCAM
0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca
[ "MIT" ]
1
2018-04-20T12:38:22.000Z
2018-04-20T12:38:55.000Z
src/modelFactory/FindSCMain.cpp
toebs88/SCAM
0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca
[ "MIT" ]
null
null
null
#include <iostream> #include "FindSCMain.h" namespace SCAM { FindSCMain::FindSCMain(clang::TranslationUnitDecl *tuDecl): pass(0), scMainFound(false), _scmainFunctionDecl(NULL){ assert (!(tuDecl == NULL)); //Find sc_main TraverseDecl(tuDecl); //Is found } bool FindSCMain::VisitFunctionDecl(clang::FunctionDecl *functionDecl) { /// Find sc_main. /// There are three conditions to satisfy this: /// 1. Must have sc_main in its name. /// 2. Must have a body /// 3. Must *not* be a first declaration. (This is becuase systemc.h includes a null definition of sc_main. if ((functionDecl->getNameInfo().getAsString() == "sc_main") && (functionDecl->hasBody())) { //Pass the null definition of main if(pass == 1){ _scmainFunctionDecl = functionDecl; scMainFound = true; return false; } pass = 1; } return true; } clang::FunctionDecl *FindSCMain::getSCMainFunctionDecl() { assert (!(_scmainFunctionDecl == NULL)); return _scmainFunctionDecl; } bool FindSCMain::isScMainFound() const { return scMainFound; } }
28.688889
115
0.570875
toebs88
daf21b6cc2dad19ff68ccdb7b99cafead549e91a
8,908
cpp
C++
modules/xfeatures2d/src/pct_signatures_sqfd.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
7,158
2016-07-04T22:19:27.000Z
2022-03-31T07:54:32.000Z
modules/xfeatures2d/src/pct_signatures_sqfd.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
2,184
2016-07-05T12:04:14.000Z
2022-03-30T19:10:12.000Z
modules/xfeatures2d/src/pct_signatures_sqfd.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
5,535
2016-07-06T12:01:10.000Z
2022-03-31T03:13:24.000Z
/* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For Open Source Computer Vision Library (3-clause BSD License) Copyright (C) 2000-2016, Intel Corporation, all rights reserved. Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved. Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved. Copyright (C) 2015-2016, Itseez Inc., all rights reserved. Third party copyrights are property of their respective owners. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ /* Contributed by Gregor Kovalcik <gregor dot kovalcik at gmail dot com> based on code provided by Martin Krulis, Jakub Lokoc and Tomas Skopal. References: Martin Krulis, Jakub Lokoc, Tomas Skopal. Efficient Extraction of Clustering-Based Feature Signatures Using GPU Architectures. Multimedia tools and applications, 75(13), pp.: 8071�8103, Springer, ISSN: 1380-7501, 2016 Christian Beecks, Merih Seran Uysal, Thomas Seidl. Signature quadratic form distance. In Proceedings of the ACM International Conference on Image and Video Retrieval, pages 438-445. ACM, 2010. */ #include "precomp.hpp" #include "pct_signatures/constants.hpp" #include "pct_signatures/similarity.hpp" namespace cv { namespace xfeatures2d { namespace pct_signatures { class PCTSignaturesSQFD_Impl : public PCTSignaturesSQFD { public: PCTSignaturesSQFD_Impl( const int distanceFunction, const int similarityFunction, const float similarityParameter) : mDistanceFunction(distanceFunction), mSimilarityFunction(similarityFunction), mSimilarityParameter(similarityParameter) { } float computeQuadraticFormDistance( InputArray _signature0, InputArray _signature1) const CV_OVERRIDE; void computeQuadraticFormDistances( const Mat& sourceSignature, const std::vector<Mat>& imageSignatures, std::vector<float>& distances) const CV_OVERRIDE; private: int mDistanceFunction; int mSimilarityFunction; float mSimilarityParameter; float computePartialSQFD( const Mat& signature0, const Mat& signature1) const; }; /** * @brief Class implementing parallel computing of SQFD distance for multiple images. */ class Parallel_computeSQFDs : public ParallelLoopBody { private: const PCTSignaturesSQFD* mPctSignaturesSQFDAlgorithm; const Mat* mSourceSignature; const std::vector<Mat>* mImageSignatures; std::vector<float>* mDistances; public: Parallel_computeSQFDs( const PCTSignaturesSQFD* pctSignaturesSQFDAlgorithm, const Mat* sourceSignature, const std::vector<Mat>* imageSignatures, std::vector<float>* distances) : mPctSignaturesSQFDAlgorithm(pctSignaturesSQFDAlgorithm), mSourceSignature(sourceSignature), mImageSignatures(imageSignatures), mDistances(distances) { mDistances->resize(imageSignatures->size()); } void operator()(const Range& range) const CV_OVERRIDE { if (mSourceSignature->empty()) { CV_Error(Error::StsBadArg, "Source signature is empty!"); } for (int i = range.start; i < range.end; i++) { if (mImageSignatures[i].empty()) { CV_Error_(Error::StsBadArg, ("Signature ID: %d is empty!", i)); } (*mDistances)[i] = mPctSignaturesSQFDAlgorithm->computeQuadraticFormDistance( *mSourceSignature, (*mImageSignatures)[i]); } } }; float PCTSignaturesSQFD_Impl::computeQuadraticFormDistance( InputArray _signature0, InputArray _signature1) const { // check input if (_signature0.empty() || _signature1.empty()) { CV_Error(Error::StsBadArg, "Empty signature!"); } Mat signature0 = _signature0.getMat(); Mat signature1 = _signature1.getMat(); if (signature0.cols != SIGNATURE_DIMENSION || signature1.cols != SIGNATURE_DIMENSION) { CV_Error_(Error::StsBadArg, ("Signature dimension must be %d!", SIGNATURE_DIMENSION)); } if (signature0.rows <= 0 || signature1.rows <= 0) { CV_Error(Error::StsBadArg, "Signature count must be greater than 0!"); } // compute sqfd float result = 0; result += computePartialSQFD(signature0, signature0); result += computePartialSQFD(signature1, signature1); result -= computePartialSQFD(signature0, signature1) * 2; return sqrt(result); } void PCTSignaturesSQFD_Impl::computeQuadraticFormDistances( const Mat& sourceSignature, const std::vector<Mat>& imageSignatures, std::vector<float>& distances) const { parallel_for_(Range(0, (int)imageSignatures.size()), Parallel_computeSQFDs(this, &sourceSignature, &imageSignatures, &distances)); } float PCTSignaturesSQFD_Impl::computePartialSQFD( const Mat& signature0, const Mat& signature1) const { float result = 0; for (int i = 0; i < signature0.rows; i++) { for (int j = 0; j < signature1.rows; j++) { result += signature0.at<float>(i, WEIGHT_IDX) * signature1.at<float>(j, WEIGHT_IDX) * computeSimilarity(mDistanceFunction, mSimilarityFunction, mSimilarityParameter, signature0, i, signature1, j); } } return result; } }// end of namespace pct_signatures Ptr<PCTSignaturesSQFD> PCTSignaturesSQFD::create( const int distanceFunction, const int similarityFunction, const float similarityParameter) { return makePtr<pct_signatures::PCTSignaturesSQFD_Impl>(distanceFunction, similarityFunction, similarityParameter); } } }
39.591111
140
0.591828
Nondzu
daf3166dce0501452596e89e418449bde63c9607
5,965
cpp
C++
StartDialog.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
StartDialog.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
StartDialog.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
#include "StartDialog.h" #include "ui_StartDialog.h" #include <QStringList> #include <QFileDialog> #include <QDir> #include <QDebug> #include <QPushButton> #include <QLabel> #include <QObject> #include <QAction> #include <QMouseEvent> #include "Utils/Helper.h" using Helper::chopFileName; using Helper::openFileDialog; /** * @brief StartDialog::StartDialog * @param parent */ StartDialog::StartDialog(QWidget *parent) : QDialog(parent), ui(new Ui::StartDialog) { ui->setupUi(this); this->setWindowFlags(Qt::FramelessWindowHint); ui->stackedWidget->setCurrentIndex(0); ui->buttonRun->setDisabled(true); } /** * @brief StartDialog::~StartDialog */ StartDialog::~StartDialog() { /*REMEMBER: What should be done here?*/ } /** * @brief StartDialog::createPushButton * @return */ QPushButton * StartDialog::createPushButton() { QPushButton * button = new QPushButton(); button->setText("+"); return button; } /** * @brief StartDialog::addDatasetToLayout * @param name */ void StartDialog::addDatasetToLayout(const QString filePath) { QString fileName = chopFileName(filePath); QListWidgetItem * item = new QListWidgetItem(fileName); ui->listDatasets->addItem(item); } /** * @brief StartDialog::enableRunButtonIfReady - If every requirement is set, enable the run button */ void StartDialog::enableRunButtonIfReady() { bool isUploadedDataset = !uploadedDatasets.isEmpty(); bool isUseDefaultSelected = ui->checkBoxUseDefault->isChecked(); bool isCustomMarkerFileUploaded = !uploadedMarkerFile.isNull(); if (isUploadedDataset && (isUseDefaultSelected || isCustomMarkerFileUploaded)) { ui->buttonRun->setEnabled(true); } } /** * @brief StartDialog::disableUseDefaultButton - Disables the default button (in case no valid default file was found) */ void StartDialog::disableUseDefaultButton() { this->ui->checkBoxUseDefault->setDisabled(true); } // ++++++++++++++++++++++++++++++++ SLOTS ++++++++++++++++++++++++++++++++ // STACKED WIDGET PAGE ONE /** * @brief StartDialog::on_buttonMenuBarExit_clicked */ __attribute__((noreturn)) void StartDialog::on_buttonMenuBarExit_clicked() { exit(0); } /** * @brief StartDialog::on_buttonExit_clicked */ __attribute__((noreturn)) void StartDialog::on_buttonExit_clicked() { exit(0); } /** * @brief StartDialog::on_buttonLoadProject_clicked */ void StartDialog::on_buttonLoadProject_clicked() { QStringList csvMimeTypes = { "text/plain" }; QStringList fileNames = openFileDialog(this, csvMimeTypes, false); if (fileNames.empty()) return; qDebug() << "Sent project file name."; } /** * @brief StartDialog::on_buttonNewProject_clicked */ void StartDialog::on_buttonNewProject_clicked() { ui->stackedWidget->setCurrentIndex(1); } // STACKED WIDGET PAGE TWO /** * @brief StartDialog::on_buttonMenuBarBack_clicked */ void StartDialog::on_buttonMenuBarBack_clicked() { ui->stackedWidget->setCurrentIndex(0); } /** * @brief StartDialog::on_checkBoxUseDefault_stateChanged * @param state */ void StartDialog::on_checkBoxUseDefault_stateChanged(int state) { if (state == Qt::CheckState::Checked) { ui->buttonLoadCustom->setDisabled(true); // REMEMBER: This should be done differently uploadedMarkerFile = "nAn"; enableRunButtonIfReady(); } else { ui->buttonLoadCustom->setDisabled(false); ui->buttonRun->setDisabled(true); } } /** * @brief StartDialog::on_buttonMenuBarExit_2_clicked */ __attribute__((noreturn)) void StartDialog::on_buttonMenuBarExit_2_clicked() { exit(0); } /** * @brief StartDialog::on_buttonLoadCustom_clicked */ void StartDialog::on_buttonLoadCustom_clicked() { QStringList csvMimeTypes = { "text/csv" }; QStringList fileNames = openFileDialog(this, csvMimeTypes, false); if (fileNames.empty()) return; uploadedMarkerFile = fileNames.first(); enableRunButtonIfReady(); qDebug() << "Uploaded" << fileNames[0]; } /** * @brief StartDialog::on_buttonAddDataset_clicked */ void StartDialog::on_buttonAddDataset_clicked() { QStringList csvMimeTypes = { "text/csv" }; QStringList filePaths = openFileDialog(this, csvMimeTypes, true); if (filePaths.empty()) return; for (int i = 0; i < filePaths.length(); i++) { QString filePath = filePaths[i]; QString fileName = chopFileName(filePath); // If file has already been uploaded, skip it if (uploadedDatasets.contains(fileName)) { continue; } uploadedDatasets.insert(fileName, filePath); addDatasetToLayout(fileName); qDebug() << "Uploaded" << fileName; } enableRunButtonIfReady(); } /** * @brief StartDialog::on_buttonRemoveDataset_clicked */ void StartDialog::on_buttonRemoveDataset_clicked() { qDebug() << uploadedDatasets; for (QListWidgetItem * item : ui->listDatasets->selectedItems()) { uploadedDatasets.remove(item->text()); delete ui->listDatasets->takeItem(ui->listDatasets->row(item)); } qDebug() << uploadedDatasets; } /** * @brief StartDialog::on_buttonRun_clicked */ void StartDialog::on_buttonRun_clicked() { emit runNewProject(uploadedMarkerFile, uploadedDatasets.values()); this->close(); //REMEMBER: How to delete this the right way? // this->deleteLater(); ?! // this->~StartDialog(); } // ++++++++++++++++++++++++++++++++ SLOTS ++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++ MOUSE ++++++++++++++++++++++++++++++++ void StartDialog::mousePressEvent(QMouseEvent * mousePressEvent) { this->mouseClickXCoordinate = mousePressEvent->x(); this->mouseClickYCoordinate = mousePressEvent->y(); } void StartDialog::mouseMoveEvent(QMouseEvent * mouseMoveEvent) { this->move(mouseMoveEvent->globalX() - this->mouseClickXCoordinate, mouseMoveEvent->globalY() - this->mouseClickYCoordinate); }
25.063025
125
0.677284
KaikiasVind
daf428e5daade87c6e23122d7d74215de7f98183
719
cpp
C++
Rogue.cpp
Kahsyaj/TacticalRPGProject
689c2131e4ec0e5ccc272e630b9483880ecbafc3
[ "MIT" ]
null
null
null
Rogue.cpp
Kahsyaj/TacticalRPGProject
689c2131e4ec0e5ccc272e630b9483880ecbafc3
[ "MIT" ]
null
null
null
Rogue.cpp
Kahsyaj/TacticalRPGProject
689c2131e4ec0e5ccc272e630b9483880ecbafc3
[ "MIT" ]
null
null
null
#include "Rogue.h" #include "IronArmor.h" #include "SilverDagger.h" #include "SilverSword.h" #include "YewStick.h" #include "Inventory.h" //Constructor //No drop defined Rogue::Rogue(int lvl) : Monster("Rogue", new int[2]{HP*lvl, HP*lvl}, new int[2]{MANA*lvl, MANA*lvl}, lvl, GOLD*lvl, STRENGTH*lvl, AGILITY*lvl, WISDOM*lvl) { IronArmor *sArmor = new IronArmor(level); YewStick *yStick = new YewStick(level); SilverDagger *sDagger = new SilverDagger(level); SilverSword *sSword = new SilverSword(level); this->drop->getStock().push_back(sArmor); this->drop->getStock().push_back(yStick); this->drop->getStock().push_back(sDagger); this->drop->getStock().push_back(sSword); }
29.958333
101
0.687065
Kahsyaj
dafb238d7c9ae5709f90ff437c60dd5c5e2410bd
309
hpp
C++
firmware/VersickerungsSensor/src/Display/Pages/Elements/Mixins/FilteredDistanceMixin.hpp
Finomnis/VersickerungsSensor
90b02acc9c57b71c38a874760008780dce1abc8f
[ "MIT" ]
null
null
null
firmware/VersickerungsSensor/src/Display/Pages/Elements/Mixins/FilteredDistanceMixin.hpp
Finomnis/VersickerungsSensor
90b02acc9c57b71c38a874760008780dce1abc8f
[ "MIT" ]
null
null
null
firmware/VersickerungsSensor/src/Display/Pages/Elements/Mixins/FilteredDistanceMixin.hpp
Finomnis/VersickerungsSensor
90b02acc9c57b71c38a874760008780dce1abc8f
[ "MIT" ]
null
null
null
#pragma once #include "../../../../utils/ValueWatcher.hpp" namespace Pages::Elements::Mixins { class FilteredDistanceMixin { protected: FilteredDistanceMixin(); ValueWatcher<float> &filtered_distance(); private: ValueWatcher<float> filtered_distance_value; }; }
18.176471
52
0.653722
Finomnis
daff34c6e49f7ce10c7b45518a1edd7a3d66be09
5,256
cpp
C++
traj_visualization_plugin/src/trajectory_display.cpp
YanzhouWang/rsp_final_project
c58c3efbf507cdd54abf860f7519006bc077c9f0
[ "MIT" ]
null
null
null
traj_visualization_plugin/src/trajectory_display.cpp
YanzhouWang/rsp_final_project
c58c3efbf507cdd54abf860f7519006bc077c9f0
[ "MIT" ]
null
null
null
traj_visualization_plugin/src/trajectory_display.cpp
YanzhouWang/rsp_final_project
c58c3efbf507cdd54abf860f7519006bc077c9f0
[ "MIT" ]
null
null
null
#include <traj_visualization_plugin/trajectory_display.hpp> namespace trajectory_display_ns{ trajectory_display::trajectory_display(){ description_property_=new rviz::StringProperty("Robot Description","robot_description", "The name of the ROS parameter where the URDF for the robot is loaded", this, SLOT (updateRobotDescription())); target_property_=new rviz::StringProperty("Target link", " ", "Target link of the robot", this, SLOT (updateLinkChoice())); color_property_=new rviz::ColorProperty("Line color",QColor(204,51,204), "Color of the path", this, SLOT (updateLineColorandAlpha())); alpha_property_=new rviz::FloatProperty("Line alpha",1, "Line alpha, 1 is opaque, 0 is transparent", this, SLOT (updateLineColorandAlpha())); width_property_=new rviz::FloatProperty("Line width",0.003, "Line width", this, SLOT(updateLineWidth())); plugin_status_=new rviz::StatusProperty("Plugin status","plugin status",rviz::StatusProperty::Level(0) , this); plugin_status_->hide(); } trajectory_display::~trajectory_display(){ delete target_property_; delete description_property_; delete color_property_; delete alpha_property_; delete width_property_; delete plugin_status_; delete kdlfk_r2t_; } void trajectory_display::onInitialize(){ MFDClass::onInitialize(); std::string robot_description_string; ros::param::get(description_property_->getStdString(),robot_description_string); if(!kdl_parser::treeFromString(robot_description_string, tree_)){ ROS_ERROR("Cannot build tree."); setStatus(rviz::StatusProperty::Level(2),"Robot state","Cannot get robot model from parameter server."); plugin_status_->setLevel(rviz::StatusProperty::Level(2)); } else{ ROS_INFO("Retrieved tree from parameter server."); setStatus(rviz::StatusProperty::Level(0),"Robot state","OK"); plugin_status_->setLevel(rviz::StatusProperty::Level(0)); } path_line_=new rviz::BillboardLine(scene_manager_, scene_node_); } void trajectory_display::reset(){ MFDClass::reset(); updateLinkChoice(); path_line_->clear(); } void trajectory_display::updateLinkChoice(){ std::map<std::string, KDL::TreeElement>::const_iterator root; root=tree_.getRootSegment(); std::string root_link=root->first; std::string target_link=target_property_->getStdString(); //Setting up for chain from root to target link if(!tree_.getChain(root_link,target_link,chain_r2t_)){ ROS_ERROR("Cannot get chain from %s to %s.", root_link.c_str(),target_link.c_str()); setStatus(rviz::StatusProperty::Level(2),"Target link","Cannot get chain."); plugin_status_->setLevel(rviz::StatusProperty::Level(2)); } else { ROS_INFO("To-target chain updated from %s to %s.",root_link.c_str(),target_link.c_str()); kdlfk_r2t_=new KDL::ChainFkSolverPos_recursive(chain_r2t_); setStatus(rviz::StatusProperty::Level(0),"Target link","OK"); plugin_status_->setLevel(rviz::StatusProperty::Level(0)); } } void trajectory_display::updateRobotDescription(){ onInitialize(); } void trajectory_display::updateLineColorandAlpha(){ Ogre::ColourValue new_color=color_property_->getOgreColor(); new_color.a=alpha_property_->getFloat(); path_line_->setColor(new_color.r, new_color.g, new_color.b, new_color.a); context_->queueRender(); } void trajectory_display::updateLineWidth(){ float new_width=width_property_->getFloat(); path_line_->setLineWidth(new_width); context_->queueRender(); } void trajectory_display::processMessage(const display_trajectory_msgs::DisplayTrajectoryStamped::ConstPtr& msg){ path_line_->clear(); Ogre::Quaternion orientation; Ogre::Vector3 position; if( !context_->getFrameManager()->getTransform( msg->header.frame_id, msg->header.stamp, position, orientation )) { ROS_DEBUG( "Error transforming from frame '%s' to frame '%s'", msg->header.frame_id.c_str(), qPrintable( fixed_frame_ )); return; } path_line_->setPosition(position); path_line_->setOrientation(orientation); //Proceed only when status is OK if(plugin_status_->getLevel()==0){ int num_wayPoints=msg->moveit_display_trajectory.trajectory[0].joint_trajectory.points.size(); int num_joints_to_target=chain_r2t_.getNrOfJoints(); updateLineWidth(); updateLineColorandAlpha(); //Here is the tricky part and will need more work into this. KDL::JntArray q_in_target; q_in_target.resize(num_joints_to_target); for(size_t i=0; i<num_wayPoints; i++){ for(size_t k=0; k<num_joints_to_target; k++){ q_in_target(k)=msg->moveit_display_trajectory.trajectory[0].joint_trajectory.points[i].positions[k]; } KDL::Frame p_out_target; kdlfk_r2t_->JntToCart(q_in_target, p_out_target); KDL::Vector V=p_out_target.p; Ogre::Vector3 new_point{(double)V.x(), (double)V.y(), (double)V.z()}; path_line_->addPoint(new_point); } } } } #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(trajectory_display_ns::trajectory_display, rviz::Display)
38.364964
115
0.709285
YanzhouWang