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
545baa2e0151f63383a4a253d465912828f123a3
751
cpp
C++
Decorator/Streams/ByteEncodingTable.cpp
chosti34/ood
3d74b5253f667d3de1ee610fb7509cf3015ea79c
[ "MIT" ]
null
null
null
Decorator/Streams/ByteEncodingTable.cpp
chosti34/ood
3d74b5253f667d3de1ee610fb7509cf3015ea79c
[ "MIT" ]
9
2018-02-09T06:12:29.000Z
2018-06-06T06:26:40.000Z
Decorator/Streams/ByteEncodingTable.cpp
chosti34/ood
3d74b5253f667d3de1ee610fb7509cf3015ea79c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ByteEncodingTable.h" #include <numeric> #include <algorithm> #include <random> ByteEncodingTable::ByteEncodingTable(unsigned seed) : m_table(256u) , m_reversedTable(256u) { std::iota(m_table.begin(), m_table.end(), uint8_t(0u)); std::shuffle(m_table.begin(), m_table.end(), std::mt19937(seed)); for (size_t i = 0; i < m_table.size(); ++i) { m_reversedTable[m_table[i]] = static_cast<uint8_t>(i); } } uint8_t ByteEncodingTable::EncodeByte(uint8_t byte)const { // no need for checking index bounds since uint8_t in [0 .. 255] return m_table[byte]; } uint8_t ByteEncodingTable::DecodeByte(uint8_t byte)const { // no need for checking index bounds since uint8_t in [0 .. 255] return m_reversedTable[byte]; }
24.225806
66
0.721704
chosti34
54602498491b853a3d3a24f6a95942f3be94a9c3
886
cpp
C++
labs/HW2/labLexer/src/labLexer-3.cpp
RabbitWhite1/USTC-2020-Compilers-Principles-HWs
81f2c733ebf4f4020b5b92534a3823626c2844f1
[ "MIT" ]
5
2021-03-25T09:20:21.000Z
2021-12-14T09:44:50.000Z
labs/HW2/labLexer/src/labLexer-3.cpp
RabbitWhite1/USTC-2020-Compilers-Principles-HWs
81f2c733ebf4f4020b5b92534a3823626c2844f1
[ "MIT" ]
null
null
null
labs/HW2/labLexer/src/labLexer-3.cpp
RabbitWhite1/USTC-2020-Compilers-Principles-HWs
81f2c733ebf4f4020b5b92534a3823626c2844f1
[ "MIT" ]
1
2022-03-19T17:02:21.000Z
2022-03-19T17:02:21.000Z
#include <iostream> #include "antlr4-runtime.h" #include "rel.h" #define LINE_SIZE 1024 using namespace antlr4; using namespace std; int main(int argc, const char* argv[]) { char str_line[LINE_SIZE]; cin.getline(str_line, LINE_SIZE); ANTLRInputStream input(str_line); //ANTLRInputStream input("\n\n\n"); rel lexer(&input); CommonTokenStream tokens(&lexer); tokens.fill(); for (auto token : tokens.getTokens()) { int type = token->getType(); if (type == -1) { // EOF break; } else if (type >=1 && type <= 6) { std::cout << "(relop," << token->getText() << ")"; } else if(type == 7) { std::cout << "(other," << token->getText().length() <<")"; } } std::cout << std::endl; return 0; }
24.611111
63
0.502257
RabbitWhite1
54625f75629de7448fb5f77430590b478a8f81b1
1,469
cpp
C++
plugins/d3d9/src/vf/convert/role_visitor.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/d3d9/src/vf/convert/role_visitor.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/d3d9/src/vf/convert/role_visitor.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/d3d9/d3dinclude.hpp> #include <sge/d3d9/vf/convert/role_visitor.hpp> #include <sge/renderer/vf/dynamic/color_fwd.hpp> #include <sge/renderer/vf/dynamic/extra_fwd.hpp> #include <sge/renderer/vf/dynamic/normal_fwd.hpp> #include <sge/renderer/vf/dynamic/pos_fwd.hpp> #include <sge/renderer/vf/dynamic/texpos_fwd.hpp> sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::pos const &) const { return D3DDECLUSAGE_POSITION; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::normal const &) const { return D3DDECLUSAGE_NORMAL; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::color const &) const { return D3DDECLUSAGE_COLOR; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::texpos const &) const { return D3DDECLUSAGE_TEXCOORD; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::extra const &) const { return D3DDECLUSAGE_TEXCOORD; }
34.162791
98
0.741321
cpreh
5464f3a43593c2dabe316c95b9d88be08176250f
956
cpp
C++
NewFramework/HelitWing.cpp
lhthang1998/Megaman_X3_DirectX
2c695fefad81c37a7872cc79c78d0de3ff6db9ca
[ "MIT" ]
null
null
null
NewFramework/HelitWing.cpp
lhthang1998/Megaman_X3_DirectX
2c695fefad81c37a7872cc79c78d0de3ff6db9ca
[ "MIT" ]
null
null
null
NewFramework/HelitWing.cpp
lhthang1998/Megaman_X3_DirectX
2c695fefad81c37a7872cc79c78d0de3ff6db9ca
[ "MIT" ]
null
null
null
#include "HelitWing.h" HelitWing::HelitWing() { } HelitWing::HelitWing(MObject* _helit) { helit = _helit; dirRight = helit->dirRight; x = helit->x + OFFSET_X * dirRight; y = helit->y + OFFSET_Y; anim = new Animation(5, 0, 4, ANIM_DELAY); char s[50]; for (int i = 0; i < 5; i++) { sprintf_s(s, "sprites/helit/wing/%d.png", i); anim->sprite[i] = new Sprite(s); } } HelitWing::~HelitWing() { } void HelitWing::Update() { movex = helit->movex; movey = helit->movey; } void HelitWing::Render() { D3DXVECTOR2 translation = D3DXVECTOR2(x + movex, y + movey); D3DXVECTOR2 shift = D3DXVECTOR2(GameGlobal::wndWidth / 2 - GameGlobal::camera->position.x, GameGlobal::wndHeight / 2 - GameGlobal::camera->position.y); D3DXVECTOR2 combined = translation + shift; D3DXVECTOR2 scale = D3DXVECTOR2(1 * dirRight, 1); D3DXMatrixTransformation2D(&matrix, NULL, 0, &scale, NULL, NULL, &combined); x += movex; y += movey; anim->Animate(matrix); }
22.232558
152
0.670502
lhthang1998
546c2676acfcf8921ae40ab6ae1866e2afd2d448
2,512
cpp
C++
development/Common/Utility/source/Logger/YLog.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
development/Common/Utility/source/Logger/YLog.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
44
2018-06-28T03:01:44.000Z
2022-03-20T19:53:00.000Z
development/Common/Utility/source/Logger/YLog.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
#include "Logger/YLog.h" #include "App/AppUtilities.h" #include "StringHelpers.h" #include "Platform/Support.h" #include "Debugging/DevConfiguration.h" #include "Time/GameClock.h" #include <fstream> #include "YagetVersion.h" #if YAGET_LOG_ENABLED == 1 YAGET_COMPILE_GLOBAL_SETTINGS("Log Included") #else YAGET_COMPILE_GLOBAL_SETTINGS("Log NOT Included") #endif // YAGET_LOG_ENABLED namespace { std::set<std::string> GetTagSet() { const auto tags = yaget::ylog::GetRegisteredTags(); std::set<std::string> result(tags.begin(), tags.end());; return result; } } using namespace yaget; void ylog::Initialize(const args::Options& options) { ylog::Config::Vector configList; for (auto&& it : dev::CurrentConfiguration().mDebug.mLogging.Outputs) { ylog::Config::addOutput(configList, it.first.c_str()); for (auto&& o : it.second) { ylog::Config::setOption(configList, o.first.c_str(), o.second.c_str()); } } ylog::Logger& logObject = ylog::Get(); //DBUG, INFO, NOTE, WARN, EROR Log::Level level = ylog::Log::toLevel(dev::CurrentConfiguration().mDebug.mLogging.Level.c_str()); logObject = ylog::Logger(logObject.getName().c_str()); logObject.setLevel(level); // setup filters, which tags will be suppressed from log output Strings filters = dev::CurrentConfiguration().mDebug.mLogging.Filters; for (auto&& it: filters) { if (*it.begin() == '!') { std::string tag(it.begin() + 1, it.end()); ylog::Manager::AddOverrideFilter(Tagger(tag.c_str())); } else { ylog::Manager::AddFilter(Tagger(it.c_str())); } } // Configure the Log Manager (create Output objects) ylog::Manager::configure(configList); // dump file with all registered tags using name and hash values if (options.find<bool>("log_write_tags", false)) { std::string fileName = util::ExpendEnv("$(LogFolder)/LogTags.txt", nullptr); std::ofstream logTagsFile(fileName.c_str()); logTagsFile << "; Currently registered log tags\n"; const auto& tags = GetTagSet(); for (const auto& tag : tags) { logTagsFile << std::setw(4) << std::left << tag << " = " << std::setw(10) << std::right << LOG_TAG(tag.c_str()) << "\n"; } } } ylog::Logger& ylog::Get() { static ylog::Logger ApplicationLogger("yaget"); return ApplicationLogger; }
28.545455
132
0.620223
eglowacki
547023c8d77793cf121a27046292cbf4abc66ab6
805
cpp
C++
projects/project03/main.cpp
jaasonw/data_structures
aba43dc071eec932717141defe3bc30abc9e237e
[ "MIT" ]
null
null
null
projects/project03/main.cpp
jaasonw/data_structures
aba43dc071eec932717141defe3bc30abc9e237e
[ "MIT" ]
null
null
null
projects/project03/main.cpp
jaasonw/data_structures
aba43dc071eec932717141defe3bc30abc9e237e
[ "MIT" ]
null
null
null
/* * Author: Jason Wong * Project: String Tokenizer * Purpose: Create a string tokenizer that returns a single token from an input * string based on the rules set by the internal state machine * Notes: */ #include "STokenizer.h" #include "Token.h" #include <iomanip> #include <iostream> using namespace std; int main(int argc, char const* argv[]) { // STokenizer s1("...it...was the night of october 17th. pi was still.3.14."); STokenizer s2("What the uwu did you just uwu say about me, you little uwu? " "I'll have you know I uwu top of my class in the uwu"); while (!s2.done()) { Token t; s2 >> t; cout << setw(20) << left << t.type_string() << '|' << t << '|' << endl; } cout << endl; system("pause"); return 0; }
27.758621
82
0.597516
jaasonw
5471f48d27aadd1d69d1278ad6cb364b8864f37c
31,485
cpp
C++
SU2-Quantum/Common/src/fem/fem_gauss_jacobi_quadrature.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/src/fem/fem_gauss_jacobi_quadrature.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/src/fem/fem_gauss_jacobi_quadrature.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file fem_gauss_jacobi_quadrature.cpp * \brief Functions to compute the points and weights for the Gauss-Jacobi quadrature rules. All the functions in this file are based on the program JACOBI_RULE of John Burkardt. * \author E. van der Weide * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ /* From: "Burkardt, John" <jburkardt@fsu.edu> Subject: Re: Gauss-Jacobi Quadrature Code Date: July 6, 2016 at 4:14:17 AM PDT To: "Thomas D. Economon" <economon@stanford.edu> Cc: Edwin van der Weide <E.T.A.vanderWeide@ctw.utwente.nl> Dear Thomas Economon, Thank you for your note about jacobi_rule.cpp; I am glad you find it of use. You are welcome to use this code in any way you choose. The only reason I put a Gnu LGPL on it was because, from a number of inquiries, it became clear to me that people were hesitant to use a piece of software if there was no license information on it at all. At the time, LGPL seemed the least restrictive. I didn't pay attention to the vexing fact that now there are several versions of LGPL, because I really don't care. If this statement is not enough for you, let me know what would be better. I have no objection to you taking a copy of jacobi_rule.cpp and altering the license to agree with your preferred version of LGPL, for instance. John Burkardt ________________________________________ From: Thomas D. Economon <economon@stanford.edu> Sent: Tuesday, July 5, 2016 11:04:34 PM To: Burkardt, John Cc: Edwin van der Weide Subject: Gauss-Jacobi Quadrature Code Dear John, I am the lead developer for the open-source SU2 suite, which is primarily for computational fluid dynamics, but also for solving other PDE systems (http://su2.stanford.edu, https://github.com/su2code/SU2). Over the past few months, we have been working on a new high-order discontinuous Galerkin fluid solver within the codebase, led by Prof. Edwin van der Weide at the University of Twente (cc’d). We found your attached code to be very helpful in resolving some issues with integration for our pyramid elements, and we would really like to reuse the implementation if possible. First, we would like to check if this is ok with you personally, and ask how we can properly attribute your work in the code? Second, we are curious just what version of the GNU LGPL license you are using to make sure that we don’t have any licensing issues. For SU2, we are using GNU LGPL v2.1. Thanks for the time and take care, Tom */ #include "../../include/fem/fem_gauss_jacobi_quadrature.hpp" void CGaussJacobiQuadrature::GetQuadraturePoints(const passivedouble alpha, const passivedouble beta, const passivedouble a, const passivedouble b, vector<passivedouble> &GJPoints, vector<passivedouble> &GJWeights) { /*--- Determine the number of integration points. Check if the number makes sense. ---*/ unsigned int nIntPoints = (unsigned int)GJPoints.size(); if(nIntPoints < 1 || nIntPoints > 100) SU2_MPI::Error("Invalid number of Gauss Jacobi integration points", CURRENT_FUNCTION); /*--- Call the function cgqf to do the actual work. ---*/ int kind = 4; cgqf(nIntPoints, kind, alpha, beta, a, b, GJPoints.data(), GJWeights.data()); } //****************************************************************************80 void CGaussJacobiQuadrature::cdgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble t[], passivedouble wts[]) //****************************************************************************80 // // Purpose: // // CDGQF computes a Gauss quadrature formula with default A, B and simple knots. // // Discussion: // // This routine computes all the knots and weights of a Gauss quadrature // formula with a classical weight function with default values for A and B, // and only simple knots. // // There are no moments checks and no printing is done. // // Use routine EIQFS to evaluate a quadrature computed by CGQFS. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Output, passivedouble T[NT], the knots. // // Output, passivedouble WTS[NT], the weights. // { passivedouble *aj; passivedouble *bj; passivedouble zemu; parchk ( kind, 2 * nt, alpha, beta ); // // Get the Jacobi matrix and zero-th moment. // aj = new passivedouble[nt]; bj = new passivedouble[nt]; zemu = class_matrix ( kind, nt, alpha, beta, aj, bj ); // // Compute the knots and weights. // sgqf ( nt, aj, bj, zemu, t, wts ); delete [] aj; delete [] bj; return; } //****************************************************************************80 void CGaussJacobiQuadrature::cgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble a, passivedouble b, passivedouble t[], passivedouble wts[]) //****************************************************************************80 // // Purpose: // // CGQF computes knots and weights of a Gauss quadrature formula. // // Discussion: // // The user may specify the interval (A,B). // // Only simple knots are produced. // // Use routine EIQFS to evaluate this quadrature formula. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 16 February 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta // 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5) // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Input, passivedouble A, B, the interval endpoints, or // other parameters. // // Output, passivedouble T[NT], the knots. // // Output, passivedouble WTS[NT], the weights. // { int i; int *mlt; int *ndx; // // Compute the Gauss quadrature formula for default values of A and B. // cdgqf ( nt, kind, alpha, beta, t, wts ); // // Prepare to scale the quadrature formula to other weight function with // valid A and B. // mlt = new int[nt]; for ( i = 0; i < nt; i++ ) { mlt[i] = 1; } ndx = new int[nt]; for ( i = 0; i < nt; i++ ) { ndx[i] = i + 1; } scqf ( nt, t, mlt, wts, nt, ndx, wts, t, kind, alpha, beta, a, b ); delete [] mlt; delete [] ndx; return; } //****************************************************************************80 passivedouble CGaussJacobiQuadrature::class_matrix(int kind, int m, passivedouble alpha, passivedouble beta, passivedouble aj[], passivedouble bj[]) //****************************************************************************80 // // Purpose: // // CLASS_MATRIX computes the Jacobi matrix for a quadrature rule. // // Discussion: // // This routine computes the diagonal AJ and sub-diagonal BJ // elements of the order M tridiagonal symmetric Jacobi matrix // associated with the polynomials orthogonal with respect to // the weight function specified by KIND. // // For weight functions 1-7, M elements are defined in BJ even // though only M-1 are needed. For weight function 8, BJ(M) is // set to zero. // // The zero-th moment of the weight function is returned in ZEMU. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta // // Input, int M, the order of the Jacobi matrix. // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Output, passivedouble AJ[M], BJ[M], the diagonal and subdiagonal // of the Jacobi matrix. // // Output, passivedouble CLASS_MATRIX, the zero-th moment. // { passivedouble a2b2; passivedouble ab; passivedouble aba; passivedouble abi; passivedouble abj; passivedouble abti; passivedouble apone; int i; passivedouble pi = 3.14159265358979323846264338327950; passivedouble temp; passivedouble temp2; passivedouble zemu; temp = r8_epsilon ( ); parchk ( kind, 2 * m - 1, alpha, beta ); temp2 = 0.5; if ( 500.0 * temp < fabs ( pow ( tgamma ( temp2 ), 2 ) - pi ) ) { cout << "\n"; cout << "CLASS_MATRIX - Fatal error!\n"; cout << " Gamma function does not match machine parameters.\n"; exit ( 1 ); } if ( kind == 1 ) { ab = 0.0; zemu = 2.0 / ( ab + 1.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } for ( i = 1; i <= m; i++ ) { abi = i + ab * ( i % 2 ); abj = 2 * i + ab; bj[i-1] = sqrt ( abi * abi / ( abj * abj - 1.0 ) ); } } else if ( kind == 2 ) { zemu = pi; for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } bj[0] = sqrt ( 0.5 ); for ( i = 1; i < m; i++ ) { bj[i] = 0.5; } } else if ( kind == 3 ) { ab = alpha * 2.0; zemu = pow ( 2.0, ab + 1.0 ) * pow ( tgamma ( alpha + 1.0 ), 2 ) / tgamma ( ab + 2.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } bj[0] = sqrt ( 1.0 / ( 2.0 * alpha + 3.0 ) ); for ( i = 2; i <= m; i++ ) { bj[i-1] = sqrt ( i * ( i + ab ) / ( 4.0 * pow ( i + alpha, 2 ) - 1.0 ) ); } } else if ( kind == 4 ) { ab = alpha + beta; abi = 2.0 + ab; zemu = pow ( 2.0, ab + 1.0 ) * tgamma ( alpha + 1.0 ) * tgamma ( beta + 1.0 ) / tgamma ( abi ); aj[0] = ( beta - alpha ) / abi; bj[0] = sqrt ( 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) / ( ( abi + 1.0 ) * abi * abi ) ); a2b2 = beta * beta - alpha * alpha; for ( i = 2; i <= m; i++ ) { abi = 2.0 * i + ab; aj[i-1] = a2b2 / ( ( abi - 2.0 ) * abi ); abi = abi * abi; bj[i-1] = sqrt ( 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) / ( ( abi - 1.0 ) * abi ) ); } } else if ( kind == 5 ) { zemu = tgamma ( alpha + 1.0 ); for ( i = 1; i <= m; i++ ) { aj[i-1] = 2.0 * i - 1.0 + alpha; bj[i-1] = sqrt ( i * ( i + alpha ) ); } } else if ( kind == 6 ) { zemu = tgamma ( ( alpha + 1.0 ) / 2.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } for ( i = 1; i <= m; i++ ) { bj[i-1] = sqrt ( ( i + alpha * ( i % 2 ) ) / 2.0 ); } } else if ( kind == 7 ) { ab = alpha; zemu = 2.0 / ( ab + 1.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } for ( i = 1; i <= m; i++ ) { abi = i + ab * ( i % 2 ); abj = 2 * i + ab; bj[i-1] = sqrt ( abi * abi / ( abj * abj - 1.0 ) ); } } else // if ( kind == 8 ) { ab = alpha + beta; zemu = tgamma ( alpha + 1.0 ) * tgamma ( - ( ab + 1.0 ) ) / tgamma ( - beta ); apone = alpha + 1.0; aba = ab * apone; aj[0] = - apone / ( ab + 2.0 ); bj[0] = - aj[0] * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 ); for ( i = 2; i <= m; i++ ) { abti = ab + 2.0 * i; aj[i-1] = aba + 2.0 * ( ab + i ) * ( i - 1 ); aj[i-1] = - aj[i-1] / abti / ( abti - 2.0 ); } for ( i = 2; i <= m - 1; i++ ) { abti = ab + 2.0 * i; bj[i-1] = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) / ( abti * abti ) * ( ab + i ) / ( abti + 1.0 ); } bj[m-1] = 0.0; for ( i = 0; i < m; i++ ) { bj[i] = sqrt ( bj[i] ); } } return zemu; } //****************************************************************************80 void CGaussJacobiQuadrature::imtqlx(int n, passivedouble d[], passivedouble e[], passivedouble z[]) //****************************************************************************80 // // Purpose: // // IMTQLX diagonalizes a symmetric tridiagonal matrix. // // Discussion: // // This routine is a slightly modified version of the EISPACK routine to // perform the implicit QL algorithm on a symmetric tridiagonal matrix. // // The authors thank the authors of EISPACK for permission to use this // routine. // // It has been modified to produce the product Q' * Z, where Z is an input // vector and Q is the orthogonal matrix diagonalizing the input matrix. // The changes consist (essentialy) of applying the orthogonal transformations // directly to Z as they are generated. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Roger Martin, James Wilkinson, // The Implicit QL Algorithm, // Numerische Mathematik, // Volume 12, Number 5, December 1968, pages 377-383. // // Parameters: // // Input, int N, the order of the matrix. // // Input/output, passivedouble D(N), the diagonal entries of the matrix. // On output, the information in D has been overwritten. // // Input/output, passivedouble E(N), the subdiagonal entries of the // matrix, in entries E(1) through E(N-1). On output, the information in // E has been overwritten. // // Input/output, passivedouble Z(N). On input, a vector. On output, // the value of Q' * Z, where Q is the matrix that diagonalizes the // input symmetric tridiagonal matrix. // { passivedouble b; passivedouble c; passivedouble f; passivedouble g; int i; int ii; int itn = 30; int j; int k; int l; int m = 0; // To avoid a compiler warning. int mml; passivedouble p; passivedouble prec; passivedouble r; passivedouble s; prec = r8_epsilon ( ); if ( n == 1 ) { return; } e[n-1] = 0.0; for ( l = 1; l <= n; l++ ) { j = 0; for ( ; ; ) { for ( m = l; m <= n; m++ ) { if ( m == n ) { break; } if ( fabs ( e[m-1] ) <= prec * ( fabs ( d[m-1] ) + fabs ( d[m] ) ) ) { break; } } p = d[l-1]; if ( m == l ) { break; } if ( itn <= j ) { cout << "\n"; cout << "IMTQLX - Fatal error!\n"; cout << " Iteration limit exceeded\n"; exit ( 1 ); } j = j + 1; g = ( d[l] - p ) / ( 2.0 * e[l-1] ); r = sqrt ( g * g + 1.0 ); g = d[m-1] - p + e[l-1] / ( g + fabs ( r ) * r8_sign ( g ) ); s = 1.0; c = 1.0; p = 0.0; mml = m - l; for ( ii = 1; ii <= mml; ii++ ) { i = m - ii; f = s * e[i-1]; b = c * e[i-1]; if ( fabs ( g ) <= fabs ( f ) ) { c = g / f; r = sqrt ( c * c + 1.0 ); e[i] = f * r; s = 1.0 / r; c = c * s; } else { s = f / g; r = sqrt ( s * s + 1.0 ); e[i] = g * r; c = 1.0 / r; s = s * c; } g = d[i] - p; r = ( d[i-1] - g ) * s + 2.0 * c * b; p = s * r; d[i] = g + p; g = c * r - b; f = z[i]; z[i] = s * z[i-1] + c * f; z[i-1] = c * z[i-1] - s * f; } d[l-1] = d[l-1] - p; e[l-1] = g; e[m-1] = 0.0; } } // // Sorting. // for ( ii = 2; ii <= m; ii++ ) { i = ii - 1; k = i; p = d[i-1]; for ( j = ii; j <= n; j++ ) { if ( d[j-1] < p ) { k = j; p = d[j-1]; } } if ( k != i ) { d[k-1] = d[i-1]; d[i-1] = p; p = z[i-1]; z[i-1] = z[k-1]; z[k-1] = p; } } return; } //****************************************************************************80 void CGaussJacobiQuadrature::parchk(int kind, int m, passivedouble alpha, passivedouble beta) //****************************************************************************80 // // Purpose: // // PARCHK checks parameters ALPHA and BETA for classical weight functions. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 07 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta // // Input, int M, the order of the highest moment to // be calculated. This value is only needed when KIND = 8. // // Input, passivedouble ALPHA, BETA, the parameters, if required // by the value of KIND. // { passivedouble tmp; if ( kind <= 0 ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND <= 0.\n"; exit ( 1 ); } // // Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential. // if ( 3 <= kind && alpha <= -1.0 ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " 3 <= KIND and ALPHA <= -1.\n"; exit ( 1 ); } // // Check BETA for Jacobi. // if ( kind == 4 && beta <= -1.0 ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND == 4 and BETA <= -1.0.\n"; exit ( 1 ); } // // Check ALPHA and BETA for rational. // if ( kind == 8 ) { tmp = alpha + beta + m + 1.0; if ( 0.0 <= tmp || tmp <= beta ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND == 8 but condition on ALPHA and BETA fails.\n"; exit ( 1 ); } } return; } //****************************************************************************80 passivedouble CGaussJacobiQuadrature::r8_epsilon( ) //****************************************************************************80 // // Purpose: // // R8_EPSILON returns the R8 roundoff unit. // // Discussion: // // The roundoff unit is a number R which is a power of 2 with the // property that, to the precision of the computer's arithmetic, // 1 < 1 + R // but // 1 = ( 1 + R / 2 ) // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 01 September 2012 // // Author: // // John Burkardt // // Parameters: // // Output, passivedouble R8_EPSILON, the R8 round-off unit. // { const passivedouble value = 2.220446049250313E-016; return value; } //****************************************************************************80 passivedouble CGaussJacobiQuadrature::r8_sign(passivedouble x) //****************************************************************************80 // // Purpose: // // R8_SIGN returns the sign of an R8. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 18 October 2004 // // Author: // // John Burkardt // // Parameters: // // Input, passivedouble X, the number whose sign is desired. // // Output, passivedouble R8_SIGN, the sign of X. // { passivedouble value; if ( x < 0.0 ) { value = -1.0; } else { value = 1.0; } return value; } //****************************************************************************80 void CGaussJacobiQuadrature::scqf(int nt, const passivedouble t[], const int mlt[], const passivedouble wts[], int nwts, int ndx[], passivedouble swts[], passivedouble st[], int kind, passivedouble alpha, passivedouble beta, passivedouble a, passivedouble b) //****************************************************************************80 // // Purpose: // // SCQF scales a quadrature formula to a nonstandard interval. // // Discussion: // // The arrays WTS and SWTS may coincide. // // The arrays T and ST may coincide. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 16 February 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, passivedouble T[NT], the original knots. // // Input, int MLT[NT], the multiplicity of the knots. // // Input, passivedouble WTS[NWTS], the weights. // // Input, int NWTS, the number of weights. // // Input, int NDX[NT], used to index the array WTS. // For more details see the comments in CAWIQ. // // Output, passivedouble SWTS[NWTS], the scaled weights. // // Output, passivedouble ST[NT], the scaled knots. // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta // 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5) // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Input, passivedouble A, B, the interval endpoints. // { passivedouble al; passivedouble be; int i; int k; int l; passivedouble p; passivedouble shft; passivedouble slp; passivedouble temp; passivedouble tmp; temp = r8_epsilon ( ); parchk ( kind, 1, alpha, beta ); if ( kind == 1 ) { al = 0.0; be = 0.0; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 2 ) { al = -0.5; be = -0.5; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 3 ) { al = alpha; be = alpha; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 4 ) { al = alpha; be = beta; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 5 ) { if ( b <= 0.0 ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " B <= 0\n"; exit ( 1 ); } shft = a; slp = 1.0 / b; al = alpha; be = 0.0; } else if ( kind == 6 ) { if ( b <= 0.0 ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " B <= 0.\n"; exit ( 1 ); } shft = a; slp = 1.0 / sqrt ( b ); al = alpha; be = 0.0; } else if ( kind == 7 ) { al = alpha; be = 0.0; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 8 ) { if ( a + b <= 0.0 ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " A + B <= 0.\n"; exit ( 1 ); } shft = a; slp = a + b; al = alpha; be = beta; } else // if ( kind == 9 ) { al = 0.5; be = 0.5; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } p = pow ( slp, al + be + 1.0 ); for ( k = 0; k < nt; k++ ) { st[k] = shft + slp * t[k]; l = abs ( ndx[k] ); if ( l != 0 ) { tmp = p; for ( i = l - 1; i <= l - 1 + mlt[k] - 1; i++ ) { swts[i] = wts[i] * tmp; tmp = tmp * slp; } } } return; } //****************************************************************************80 void CGaussJacobiQuadrature::sgqf(int nt, const passivedouble aj[], passivedouble bj[], passivedouble zemu, passivedouble t[], passivedouble wts[]) //****************************************************************************80 // // Purpose: // // SGQF computes knots and weights of a Gauss Quadrature formula. // // Discussion: // // This routine computes all the knots and weights of a Gauss quadrature // formula with simple knots from the Jacobi matrix and the zero-th // moment of the weight function, using the Golub-Welsch technique. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, passivedouble AJ[NT], the diagonal of the Jacobi matrix. // // Input/output, passivedouble BJ[NT], the subdiagonal of the Jacobi // matrix, in entries 1 through NT-1. On output, BJ has been overwritten. // // Input, passivedouble ZEMU, the zero-th moment of the weight function. // // Output, passivedouble T[NT], the knots. // // Output, passivedouble WTS[NT], the weights. // { int i; // // Exit if the zero-th moment is not positive. // if ( zemu <= 0.0 ) { cout << "\n"; cout << "SGQF - Fatal error!\n"; cout << " ZEMU <= 0.\n"; exit ( 1 ); } // // Set up vectors for IMTQLX. // for ( i = 0; i < nt; i++ ) { t[i] = aj[i]; } wts[0] = sqrt ( zemu ); for ( i = 1; i < nt; i++ ) { wts[i] = 0.0; } // // Diagonalize the Jacobi matrix. // imtqlx ( nt, t, bj, wts ); for ( i = 0; i < nt; i++ ) { wts[i] = wts[i] * wts[i]; } return; }
25.934926
117
0.512307
Agony5757
547256a644e198048b62b52d9ff88db2097ccb1c
41,567
cpp
C++
src/virtualMachine/VirtualMachine.cpp
Suru-09/Compilation-Tehniques
cbfc5f5a47d786287d7a75e68814de113e3d0375
[ "MIT" ]
null
null
null
src/virtualMachine/VirtualMachine.cpp
Suru-09/Compilation-Tehniques
cbfc5f5a47d786287d7a75e68814de113e3d0375
[ "MIT" ]
null
null
null
src/virtualMachine/VirtualMachine.cpp
Suru-09/Compilation-Tehniques
cbfc5f5a47d786287d7a75e68814de113e3d0375
[ "MIT" ]
null
null
null
#include "VirtualMachine.hpp" VirtualMachine::~VirtualMachine() { // delete stack_ptr; // delete stack_ptr; } VirtualMachine::VirtualMachine() : stack_ptr(nullptr), stack_after(nullptr), n_globals(0), class_name("VirtualMachine") { logger = Logger{class_name}; } void VirtualMachine::push_d(const double& d) { if ( stack_ptr + sizeof(double) > stack_after ) { std::cout << logger << "[PUSH_D] OUT OF STACK!\n"; exit(1); } *(double *)stack_ptr = d; stack_ptr += sizeof(double); } double VirtualMachine::pop_d() { if ( stack_ptr - sizeof(double) < stack ) { std::cout << logger << "[POP_D] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(double); return *(double *)stack_ptr; } void VirtualMachine::push_i(const long& i) { if ( stack_ptr + sizeof(int) > stack_after ) { std::cout << logger << "[PUSH_I] OUT OF STACK!\n"; exit(1); } *(int *)stack_ptr = i; stack_ptr += sizeof(long); } int VirtualMachine::pop_i() { if ( stack_ptr - sizeof(long) < stack ) { std::cout << logger << "[POP_I] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(long); return *(long *)stack_ptr; } void VirtualMachine::push_c(const char& c) { if ( stack_ptr + sizeof(char) > stack_after ) { std::cout << logger << "[PUSH_C] OUT OF STACK!\n"; exit(1); } *(char *)stack_ptr = c; stack_ptr += sizeof(char); } char VirtualMachine::pop_c() { if ( stack_ptr - sizeof(char) < stack ) { std::cout << logger << "[POP_C] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(char); return *(char *)stack_ptr; } void VirtualMachine::push_a(void * a) { if ( stack_ptr + sizeof(void *) > stack_after ) { std::cout << logger << "[PUSH_A] OUT OF STACK!\n"; exit(1); } *(void **)stack_ptr = a; stack_ptr += sizeof(void *); } void * VirtualMachine::pop_a() { if ( stack_ptr - sizeof(void *) < stack ) { std::cout << logger << "[POP_A] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(void *); return *(void **)stack_ptr; } void* VirtualMachine::alloc_heap(const int& size) { if ( n_globals + size > GLOBAL_SIZE ) { std::cout << logger << "There is not enough memory on the Heap!\n"; exit(2); } void * p = globals + n_globals; n_globals += size; return p; } void VirtualMachine::set_il(const InstructionList& instr_list) { this->instr_list = instr_list; } InstructionList VirtualMachine::get_il() { return instr_list; } void VirtualMachine::run() { long int i_val_1, i_val_2; double d_val_1, d_val_2; char * a_val, * a_val_2; char * frame_ptr = 0, * old_sp; stack_ptr = stack; // we allocated continuouus memory for the stack, use it stack_after = stack + STACK_SIZE; // this should be the first address after // the stack's memory for ( std::list<Instruction>::iterator it = instr_list.instr_list.begin() ; it != instr_list.instr_list.end() ;) { // std::cout << logger << "IP: [" << (int)(*it).op_code << "] SP-stack: [" // << (stack_ptr - stack) << "]\n"; // std::cout << logger << "STACK_PTR: [" << reinterpret_cast<void*> (&stack_ptr) << "]\n"; switch ((*it).op_code) { case 0: // O_HALT std::cout << logger << "[O_HALT_INSTRUCTION]\n"; return; case 1: // O_ADD_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_ADD_C] Adding: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << i_val_1 + i_val_2 << "]\n"; push_c(i_val_1 + i_val_2); ++it; break; case 2: // O_ADD_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_ADD_D] Adding: " << d_val_1 << " + " << d_val_2 << " -> " << "[" << d_val_1 + d_val_2 << "]\n"; push_d(d_val_1 + d_val_2); break; case 3: // O_ADD_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_ADD_I] Adding: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << i_val_1 + i_val_2 << "]\n"; push_i(i_val_1 + i_val_2); ++it; break; case 4: // O_AND_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_AND_C] AND: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << (i_val_1 && i_val_2) << "]\n"; push_i(i_val_1 && i_val_2); ++it; break; case 5: // O_AND_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_AND_D] AND: " << d_val_1 << " + " << d_val_2 << " -> " << "[" << (d_val_1 && d_val_2) << "]\n"; push_i(d_val_1 && d_val_2); ++it; break; case 6: // O_AND_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_AND_I] AND: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << (i_val_1 && i_val_2) << "]\n"; push_i(i_val_1 + i_val_2); ++it; break; case 7: // O_CALL std::cout << logger << "[O_CALL_INSTRUCTION]\n"; if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void") { auto val = std::get<void *> ((*it).args[0]); auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { push_a(reinterpret_cast<void *>(&(++it))); it = itr; } else { std::cout << logger << "[O_CALL_INSTRUCTION] Given instruction was wrong!\n"; exit(3); } } else { std::cout << logger << "[O_CALL] Wrong structure called!\n"; exit(2); } break; case 8: // O_CALLEXT std::cout << logger << "[O_CALLEXT_INSTRUCTION]\n"; if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void") { auto IP = std::get<void *> ((*it).args[0]); (*(void(*)())IP)(); // This is really dangerous } else { std::cout << logger << "[O_CALLEXT] Wrong structure called!\n"; exit(2); } ++it; break; case 9: // O_CAST_C_D i_val_1 = pop_c(); d_val_1 = static_cast<double>(i_val_1); std::cout << logger << "[O_CAST_C_D] char: " << i_val_1 << "to double: " << d_val_1 << "\n"; push_d(d_val_1); it++; break; case 10: // O_CAST_C_I i_val_1 = pop_c(); i_val_2 = static_cast<long>(i_val_1); std::cout << logger << "[O_CAST_C_I] char: " << i_val_1 << "to integer: " << i_val_2 << "\n"; push_i(i_val_2); it++; break; case 11: // O_CAST_D_C d_val_1 = pop_d(); i_val_1 = static_cast<char>(d_val_1); std::cout << logger << "[O_CAST_D_C] double: " << d_val_1 << "to char: " << i_val_1 << "\n"; push_i(i_val_1); it++; break; case 12: // O_CAST_D_I d_val_1 = pop_d(); i_val_1 = static_cast<long>(d_val_1); std::cout << logger << "[O_CAST_D_I] double: " << d_val_1 << "to integer: " << i_val_1 << "\n"; push_i(i_val_1); it++; break; case 13: // O_CAST_I_C i_val_1 = pop_i(); i_val_2 = static_cast<char>(i_val_1); std::cout << logger << "[O_CAST_I_C] integer: " << i_val_1 << "to char: " << i_val_2 << "\n"; push_i(i_val_2); it++; break; case 14: // O_CAST_I_D i_val_1 = pop_i(); d_val_1 = static_cast<double>(i_val_1); std::cout << logger << "[O_CAST_I_D] int: " << i_val_1 << "to double: " << d_val_1 << "\n"; push_d(d_val_1); it++; break; case 15: // O_DIV_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_DIV_C] DIV: " << i_val_1 << " / " << i_val_2 << " -> [" << i_val_1 / i_val_2 << "]\n"; push_c(i_val_1 / i_val_2); it++; break; case 16: // O_DIV_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_DIV_D] DIV: " << d_val_1 << " / " << d_val_2 << " -> [" << d_val_1 / d_val_2 << "]\n"; push_d(d_val_1 / d_val_2); it++; break; case 17: // O_DIV_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_DIV_I] DIV: " << i_val_1 << " / " << i_val_2 << " -> [" << i_val_1 / i_val_2 << "]\n"; push_i(i_val_1 / i_val_2); it++; break; case 18: // O_DROP if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_DROP] value: " << i_val_1 << "\n"; if (stack_ptr - i_val_1 < stack) { std::cout << logger << "[O_DROP] not enough stack bytes!\n"; exit(3); } stack_ptr -= i_val_1; ++it; } else { std::cout << logger << "[O_DROP] Wrong structure calling!\n"; exit(2); } break; case 19: // O_ENTER if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_ENTER] ENTER: " << i_val_1 << "\n"; push_a(frame_ptr); frame_ptr = stack_ptr; stack_ptr += i_val_1; ++it; } else { std::cout << logger << "[O_ENTER] Wrong structure calling!\n"; exit(2); } break; case 20: // O_EQ_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char *> (pop_a()); std::cout << logger << "[O_EQ_A] [" << a_val << "] == [" << a_val_2 << "] -> " << (d_val_1 == d_val_2) << "\n"; push_i(d_val_1 == d_val_2); ++it; break; case 21: // O_EQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_EQ_C] [" << i_val_1 << "] == [" << i_val_2 << "] -> " << (i_val_1 == i_val_2) << "\n"; push_i(i_val_1 == i_val_2); ++it; break; case 22: // O_EQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_EQ_D] [" << d_val_1 << "] == [" << d_val_2 << "] -> " << (d_val_1 == d_val_2) << "\n"; push_i(d_val_1 == d_val_2); ++it; break; case 23: // O_EQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_EQ_I] [" << i_val_1 << "] == [" << i_val_2 << "] -> " << (i_val_1 == i_val_2) << "\n"; push_i(i_val_1 == i_val_2); ++it; break; case 24: // O_GREATER_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_GREATER_C] [" << i_val_1 << "] > [" << i_val_2 << "] -> " << (i_val_1 > i_val_2) << "\n"; push_i(i_val_1 > i_val_2); ++it; break; case 25: // O_GREATER_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_GREATER_D] [" << d_val_1 << "] > [" << d_val_2 << "] -> " << (d_val_1 > d_val_2) << "\n"; push_i(d_val_1 > d_val_2); ++it; break; case 26: // O_GREATER_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_GREATER_I] [" << i_val_1 << "] > [" << i_val_2 << "] -> " << (i_val_1 > i_val_2) << "\n"; push_i(i_val_1 > i_val_2); ++it; break; case 27: // O_GREATEREQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_GREATEREQ_C] [" << i_val_1 << "] >= [" << i_val_2 << "] -> " << (i_val_1 >= i_val_2) << "\n"; push_i(i_val_1 >= i_val_2); ++it; break; case 28: // O_GREATEREQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_GREATEREQ_D] [" << d_val_1 << "] >= [" << d_val_2 << "] -> " << (d_val_1 >= d_val_2) << "\n"; push_i(d_val_1 >= d_val_2); ++it; break; case 29: // O_GREATEREQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_GREATEREQ_I] [" << i_val_1 << "] >= [" << i_val_2 << "] -> " << (i_val_1 >= i_val_2) << "\n"; push_i(i_val_1 >= i_val_2); ++it; break; case 30: // O_INSERT if ( (*it).args.size() == 2 && Instruction::variant_to_type((*it).args[0]) == "long" && Instruction::variant_to_type((*it).args[1]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); // Destination i_val_2 = std::get<long> ((*it).args[1]); // No. of bytes std::cout << logger << "[O_INSERT]/t" << i_val_1 << ", " << i_val_2 << "\n"; if ( stack_ptr + i_val_2 > stack_after) { std::cout << logger << "[O_INSERT] OUT of stack!\n"; exit(2); } // make room memmove(stack_ptr - i_val_1 + i_val_2, stack_ptr - i_val_1, i_val_1); memmove(stack_ptr - i_val_1, stack_ptr + i_val_2, i_val_2); stack_ptr += i_val_2; ++it; } else { std::cout << logger << "[O_INSERT] Wrong structure calling!\n"; exit(2); } break; case 31: // O_JF_A if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { a_val = static_cast<char *> (pop_a()); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_A] " << val << " (" << a_val << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !a_val ? itr : ++it; } else { std::cout << logger << "[O_JF_A] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_A] Wrong structure calling!\n"; exit(2); } break; case 32: // O_JF_C if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_c(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_C] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JF_C] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_C] Wrong structure calling!\n"; exit(2); } break; case 33: // O_JF_D if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { d_val_1 = pop_d(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_D] " << val << " (" << d_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !d_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JF_D] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_D] Wrong structure calling!\n"; exit(2); } break; case 34: // O_JF_I if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_i(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_I] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JF_I] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_I] Wrong structure calling!\n"; exit(2); } break; case 35: // O_JMP if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JMP] " << val << "\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = itr; } else { std::cout << logger << "[O_JMP] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JMP] Wrong structure calling!\n"; exit(2); } break; case 36: // O_JT_A if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { a_val = static_cast<char *> (pop_a()); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_A] " << val << " (" << a_val << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = a_val ? itr : ++it; } else { std::cout << logger << "[O_JT_A] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_A] Wrong structure calling!\n"; exit(2); } break; case 37: // O_JT_C if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_c(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_C] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JT_C] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_C] Wrong structure calling!\n"; exit(2); } break; case 38: // O_JT_D if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { d_val_1 = pop_d(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_D] " << val << " (" << d_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = d_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JT_D] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_D] Wrong structure calling!\n"; exit(2); } break; case 39: // O_JT_I if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_i(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_I] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JT_I] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_I] Wrong structure calling!\n"; exit(2); } break; case 40: // O_LESS_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_LESS_C] [" << i_val_1 << "] < [" << i_val_2 << "] -> " << (i_val_1 < i_val_2) << "\n"; push_i(i_val_1 < i_val_2); ++it; break; case 41: // O_LESS_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_LESS_D] [" << d_val_1 << "] < [" << d_val_2 << "] -> " << (d_val_1 < d_val_2) << "\n"; push_i(d_val_1 < d_val_2); ++it; break; case 42: // O_LESS_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_LESS_I] [" << i_val_1 << "] < [" << i_val_2 << "] -> " << (i_val_1 < i_val_2) << "\n"; push_i(i_val_1 < i_val_2); ++it; break; case 43: // O_LESSEQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_LESSEQ_C] [" << i_val_1 << "] <= [" << i_val_2 << "] -> " << (i_val_1 <= i_val_2) << "\n"; push_i(i_val_1 <= i_val_2); ++it; break; case 44: // O_LESSEQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_LESSEQ_D] [" << d_val_1 << "] <= [" << d_val_2 << "] -> " << (d_val_1 <= d_val_2) << "\n"; push_i(d_val_1 <= d_val_2); ++it; break; case 45: // O_LESSEQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_LESSEQ_I] [" << i_val_1 << "] <= [" << i_val_2 << "] -> " << (i_val_1 <= i_val_2) << "\n"; push_i(i_val_1 <= i_val_2); ++it; break; case 46: // O_MUL_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_MUL_C] MUL: " << i_val_1 << " * " << i_val_2 << " -> " << "[" << i_val_1 * i_val_2 << "]\n"; push_c(i_val_1 * i_val_2); ++it; break; case 47: // O_MUL_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_MUL_D] MUL: " << d_val_1 << " * " << d_val_2 << " -> " << "[" << d_val_1 * d_val_2 << "]\n"; push_c(d_val_1 * d_val_2); ++it; break; case 48: // O_MUL_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_MUL_I] MUL: " << i_val_1 << " * " << i_val_2 << " -> " << "[" << i_val_1 * i_val_2 << "]\n"; push_c(i_val_1 * i_val_2); ++it; break; case 49: // O_NEG_C i_val_1 = pop_c(); std::cout << logger << "[O_NEG_C] [-" << i_val_1 << "]\n"; push_c(-i_val_1); ++it; break; case 50: // O_NEG_D d_val_1 = pop_d(); std::cout << logger << "[O_NEG_D] [-" << d_val_1 << "]\n"; push_c(-d_val_1); ++it; break; case 51: // O_NEG_I i_val_1 = pop_i(); std::cout << logger << "[O_NEG_I] [-" << i_val_1 << "]\n"; push_i(-i_val_1); ++it; break; case 52: // O_NOP std::cout << logger << "[O_NOP]\n"; ++it; break; case 53: // O_NOT_A a_val = static_cast<char *>(pop_a()); std::cout << logger << "[O_NOT_A] [-" << a_val << "]\n"; push_i(!a_val); ++it; break; case 54: // O_NOT_C i_val_1 = pop_c(); std::cout << logger << "[O_NOT_C] [-" << i_val_1 << "]\n"; push_i(!i_val_1); ++it; break; case 55: // O_NOT_D d_val_1 = pop_d(); std::cout << logger << "[O_NOT_D] [-" << d_val_1 << "]\n"; push_i(!d_val_1); ++it; break; case 56: // O_NOT_I i_val_1 = pop_i(); std::cout << logger << "[O_NOT_I] [-" << i_val_1 << "]\n"; push_i(!i_val_1); ++it; break; case 57: // O_NOTEQ_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char *> (pop_a()); std::cout << logger << "[O_NOTEQ_A] [" << a_val << "] != [" << a_val_2 << "] -> " << (a_val != a_val_2) << "\n"; push_i(a_val != a_val_2); it++; break; case 58: // O_NOTEQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_NOTEQ_C] [" << i_val_1 << "] != [" << i_val_2 << "] -> " << (i_val_1 != i_val_2) << "\n"; push_i(i_val_1 != i_val_2); it++; break; case 59: // O_NOTEQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_NOTEQ_D] [" << d_val_1 << "] != [" << d_val_2 << "] -> " << (d_val_1 != d_val_2) << "\n"; push_i(d_val_1 != d_val_2); it++; break; case 60: // O_NOTEQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_NOTEQ_I] [" << i_val_1 << "] != [" << i_val_2 << "] -> " << (i_val_1 != i_val_2) << "\n"; push_i(i_val_1 != i_val_2); it++; break; case 61: // O_OFFSET i_val_1 = pop_i(); a_val = static_cast<char *> (pop_a()); std::cout << logger << "[O_OFFSET] " << a_val << " + " << i_val_1 << " -> " << a_val + i_val_1 << "\n"; push_a(a_val + i_val_1); ++it; break; case 62: // O_OR_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char *> (pop_a()); std::cout << logger << "[O_OR_A] [" << a_val << "] || [" << a_val_2 << "] -> " << (a_val || a_val_2) << "\n"; push_i(a_val || a_val_2); it++; break; case 63: // O_OR_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_OR_D] [" << d_val_1 << "] || [" << d_val_2 << "] -> " << (d_val_1 || d_val_2) << "\n"; push_i(d_val_1 || d_val_2); it++; break; case 64: // O_OR_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_OR_I] [" << i_val_1 << "] || [" << i_val_2 << "] -> " << (i_val_1 || i_val_2) << "\n"; push_i(i_val_1 || i_val_2); it++; break; case 65: // O_PUSHFPADDR if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_PUSHFPADDR] " << i_val_1 << " " << i_val_1 + frame_ptr << "\n"; push_a(frame_ptr + i_val_1); ++it; } else { std::cout << logger << "[O_PUSHFPADDR] Wrong structure calling!\n"; exit(2); } break; case 66: // O_PUSHCT_A if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { a_val = static_cast<char * > (std::get<void*> ((*it).args[0])); std::cout << logger << "[O_PUSHCT_A] " << std::hex << a_val << "\n"; push_a(std::get<void*> ((*it).args[0])); ++it; } else { std::cout << logger << "[O_PUSHCT_A] Wrong structure calling!\n"; exit(2); } break; case 67: // O_PUSHCT_C if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = static_cast<char> (std::get<long> ((*it).args[0])); std::cout << logger << "[O_PUSHCT_C] " << std::hex << i_val_1 << "\n"; push_i(std::get<long> ((*it).args[0])); ++it; } else { std::cout << logger << "[O_PUSHCT_C] Wrong structure calling!\n"; exit(2); } break; case 68: // O_PUSHCT_D if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "double" ) { d_val_1 = std::get<double> ((*it).args[0]); std::cout << logger << "[O_PUSHCT_D] " << std::hex << d_val_1 << "\n"; push_i(std::get<double> ((*it).args[0])); ++it; } else { std::cout << logger << "[O_PUSHCT_D] Wrong structure calling!\n"; exit(2); } break; case 69: // O_PUSHCT_I if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_PUSHCT_I] " << i_val_1 << "\n"; push_i(i_val_1); ++it; } else { std::cout << logger << "[O_PUSHCT_I] Wrong structure calling!\n"; exit(2); } break; break; case 70: // O_RET if ( (*it).args.size() == 2 && Instruction::variant_to_type((*it).args[0]) == "long" && Instruction::variant_to_type((*it).args[1]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); // size args i_val_2 = std::get<long> ((*it).args[1]); // sizeof(retType) std::cout << logger << "[O_RET] " << i_val_1 << " " << i_val_2 << "\n"; old_sp = stack_ptr; stack_ptr = frame_ptr; frame_ptr = static_cast<char *> (pop_a()); if ( stack_ptr - i_val_1 < stack ) { std::cout << logger << "[O_RET] Not enough stack!\n"; exit(2); } stack_ptr -= i_val_1; memmove(stack_ptr, old_sp - i_val_2, i_val_2); stack_ptr+= i_val_2; } else { std::cout << logger << "[O_RET] Wrong structure calling!\n"; exit(2); } break; case 71: // O_STORE if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ){ i_val_1 = std::get<long> ((*it).args[0]); if ( stack_ptr - (sizeof(void *) + i_val_1 ) < stack ) { std::cout << logger << "[O_STORE] Not enough stack bytes for SET!\n"; exit(2); } a_val = stack_ptr - sizeof(void *) - i_val_1; std::cout << logger << "[O_STORE] storing " << i_val_1 << " at " << static_cast<void *> (&a_val) << "\n"; memcpy(a_val, stack_ptr - i_val_1, i_val_1); stack_ptr -= sizeof(void *) + i_val_1; // std::cout << logger << "Stack_ptr : " << static_cast<void *> (&stack_ptr) // << " vs " << static_cast<void *> (&stack) << "\n"; ++it; } else { std::cout << logger << "[O_STORE] Wrong structure calling!\n"; exit(2); } break; case 72: // O_SUB_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_SUB_C] " << i_val_1 << " - " << i_val_2 << " -> " << i_val_1 - i_val_2 << "\n"; push_d(i_val_1 - i_val_2); ++it; break; case 73: // O_SUB_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_SUB_D] " << d_val_2 << " - " << d_val_1 << " -> " << d_val_2 - d_val_1 << "\n"; push_d(d_val_2 - d_val_1); ++it; break; case 74: // O_SUB_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_SUB_I] " << i_val_1 << " - " << i_val_2 << " -> " << i_val_1 - i_val_2 << "\n"; push_d(i_val_1 - i_val_2); ++it; break; case 75: // O_LOAD if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); a_val = static_cast<char*> (pop_a()); std::cout << logger << "[O_LOAD]\t" << i_val_1 << " at " << static_cast<void *> (&a_val) << "\n"; if ( stack_ptr + i_val_1 > stack_after ) { std::cout << logger << "[O_LOAD] Out of stack!\n"; exit(2); } memcpy(stack_ptr, a_val, i_val_1); // loading from address a_val [i_val_1] bytes on stack stack_ptr += i_val_1; it++; } else { std::cout << logger << "[O_LOAD] Wrong structure calling!\n"; exit(2); } break; case 76: // O_AND_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char*> (pop_a()); std::cout << logger << "[O_AND_A] Adding: " << a_val << " + " << a_val_2 << " -> " << "[" << (a_val && a_val_2) << "]\n"; push_i(a_val && a_val_2); ++it; break; case 77: // O_OR_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_OR_C] [" << i_val_1 << "] || [" << i_val_2 << "] -> " << (i_val_1 || i_val_2) << "\n"; push_i(i_val_1 || i_val_2); it++; break; default: std::cout << logger << "[O_NONE] No instructionm with the given code!\n"; exit(2); } } }
45.083514
139
0.371713
Suru-09
547273f87b4a527486b33e099b397f92371445ba
901
cpp
C++
Code/AutomatedTests/HeaderBlockTokenTest.cpp
ProgramMax/maxGif
de509a1512dd56015c7f044bfc177ae662e57694
[ "BSD-3-Clause" ]
1
2016-11-13T17:50:10.000Z
2016-11-13T17:50:10.000Z
Code/AutomatedTests/HeaderBlockTokenTest.cpp
ProgramMax/maxGif
de509a1512dd56015c7f044bfc177ae662e57694
[ "BSD-3-Clause" ]
23
2016-11-13T18:41:42.000Z
2017-12-27T13:58:07.000Z
Code/AutomatedTests/HeaderBlockTokenTest.cpp
ProgramMax/maxGif
de509a1512dd56015c7f044bfc177ae662e57694
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016, The maxGif Contributors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <max/Testing/TestSuite.hpp> #include <maxGif/Parsing/Tokens.hpp> #include <vector> int main() { auto TestSuite = max::Testing::TestSuite( "HeaderBlockToken" ); TestSuite.AddTest( max::Testing::Test( "constructor sets the start offset", []( max::Testing::Test & CurrentTest ) { auto const StartOffset = size_t{ 0 }; auto const TestObject = maxGif::Parsing::HeaderBlockToken{ StartOffset }; CurrentTest.MAX_TESTING_ASSERT( TestObject.StartOffset == StartOffset ); } )); TestSuite.AddTest( max::Testing::Test( "size is 6", []( max::Testing::Test & CurrentTest ) { CurrentTest.MAX_TESTING_ASSERT( maxGif::Parsing::HeaderBlockToken::SizeInBytes() == 6 ); } )); TestSuite.RunTests(); return 0; }
30.033333
91
0.711432
ProgramMax
5479359c393138813c965364fca1b25e64bd24d8
95
cpp
C++
Fists.cpp
Kahsyaj/TacticalRPGProject
689c2131e4ec0e5ccc272e630b9483880ecbafc3
[ "MIT" ]
null
null
null
Fists.cpp
Kahsyaj/TacticalRPGProject
689c2131e4ec0e5ccc272e630b9483880ecbafc3
[ "MIT" ]
null
null
null
Fists.cpp
Kahsyaj/TacticalRPGProject
689c2131e4ec0e5ccc272e630b9483880ecbafc3
[ "MIT" ]
null
null
null
#include "Fists.h" //Constructor Fists::Fists() : Weapon("Fists", 0, 0, 0, 1) { }
9.5
36
0.515789
Kahsyaj
5479c25d42fce9a4c66824606b3f5552f1772eca
3,681
hpp
C++
src/classical/dd/zdd.hpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/dd/zdd.hpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/dd/zdd.hpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2017 EPFL * * 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. */ /** * @file zdd.hpp * * @brief ZDD package * * @author Heinz Riener * @author Mathias Soeken * @since 2.3 */ #ifndef ZDD_HPP #define ZDD_HPP #include <cassert> #include <iostream> #include <memory> #include <classical/dd/dd_manager.hpp> namespace cirkit { class zdd_manager; struct zdd { zdd() : manager( nullptr ), index( 0u ) {} zdd( zdd_manager* manager, unsigned index ) : manager( manager ), index( index ) {} zdd( const zdd& other ) : manager( other.manager ), index( other.index ) {} zdd& operator=( const zdd& other ); unsigned var() const; zdd high() const; zdd low() const; inline bool is_bot() const { return index == 0u; } inline bool is_top() const { return index == 1u; } zdd operator-( const zdd& other ) const; zdd operator||( const zdd& other ) const; zdd operator&&( const zdd& other ) const; zdd operator^( const zdd& other ) const; zdd operator+( const zdd& other ) const; zdd operator*( const zdd& other ) const; zdd delta( const zdd& other ) const; zdd nonsub( const zdd& other ) const; zdd nonsup( const zdd& other ) const; zdd minhit() const; bool equals( const zdd& other ) const; zdd_manager* manager; unsigned index; }; std::ostream& operator<<( std::ostream& os, const zdd& z ); class zdd_manager : public dd_manager { public: zdd_manager( unsigned nvars, unsigned log_max_objs, bool verbose = false ); ~zdd_manager(); inline zdd zdd_bot() { return zdd( this, 0u ); } inline zdd zdd_top() { return zdd( this, 1u ); } inline zdd zdd_var( unsigned i ) { assert( i < nvars ); return zdd( this, i + 2u ); } unsigned zdd_diff( unsigned z1, unsigned z2 ); unsigned zdd_union( unsigned z1, unsigned z2 ); unsigned zdd_intersection( unsigned z1, unsigned z2 ); unsigned zdd_symmetric_difference( unsigned z1, unsigned z2 ); unsigned zdd_join( unsigned z1, unsigned z2 ); unsigned zdd_meet( unsigned z1, unsigned z2 ); unsigned zdd_delta( unsigned z1, unsigned z2 ); unsigned zdd_nonsub( unsigned z1, unsigned z2 ); unsigned zdd_nonsup( unsigned z1, unsigned z2 ); unsigned zdd_minhit( unsigned z ); private: unsigned unique_create( unsigned var, unsigned high, unsigned low ); public: friend std::ostream& operator<<( std::ostream& os, const zdd_manager& mgr ); }; } #endif // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
29.685484
87
0.695735
eletesta
5479ccd289b973d5ace94630955cc67960d6fddd
242
cpp
C++
etc/config/src/EXPORT_KEYWORD.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
etc/config/src/EXPORT_KEYWORD.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
etc/config/src/EXPORT_KEYWORD.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
// checking for the export keyword // NOTE: test EXPORT.cpp links with EXPORT_KEYOWRD.o and expects // to find a definition of the function template below there export template <class T> T exported_function_template (T t) { return t; }
20.166667
64
0.752066
Hower91
547a53619c49fb55405d4158c828505150ce23ba
3,334
cpp
C++
middleware/xatmi/source/xatmi/server.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/xatmi/source/xatmi/server.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/xatmi/source/xatmi/server.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
1
2022-02-21T18:30:25.000Z
2022-02-21T18:30:25.000Z
//! //! Copyright (c) 2015, The casual project //! //! This software is licensed under the MIT license, https://opensource.org/licenses/MIT //! #include "casual/xatmi/server.h" #include "casual/xatmi/internal/log.h" #include "casual/xatmi/internal/code.h" #include "casual/xatmi/internal/transform.h" #include "common/server/start.h" #include "common/code/raise.h" #include "common/code/xatmi.h" #include "common/functional.h" #include "common/process.h" #include "common/event/send.h" #include "common/signal.h" #include <vector> #include <algorithm> namespace casual { namespace xatmi { namespace server { namespace local { namespace { namespace transform { template< typename A> auto services( A& value) { std::vector< common::server::argument::xatmi::Service> result; auto service = value.services; for( ; service->function_pointer != nullptr; ++service) { result.emplace_back( service->name, service->function_pointer, common::service::transaction::mode( service->transaction), service->category); } return result; } } // transform template< typename A> int start( const A& argument) { return common::exception::main::log::guard( [&argument]() { casual::xatmi::Trace trace{ "casual::xatmi::server::local::start"}; auto done = common::execute::scope( [done = argument.server_done]() { if( done) common::invoke( done); }); // We block child so users can spawn stuff without actions/errors from casual common::signal::thread::scope::Block block( { common::code::signal::child}); common::server::start( transform::services( argument), xatmi::transform::resources( argument.xa_switches), [&]() { if( argument.server_init && common::invoke( argument.server_init, argument.argc, argument.argv) == -1) { // if init is not ok, then we don't call done, symmetry with ctor/dtor done.release(); common::event::error::raise( common::code::xatmi::argument, "server initialize failed - action: exit"); } }); }); } } // <unnamed> } // local } // server } // xatmi } // casual int casual_start_server( struct casual_server_argument* arguments) { return casual::xatmi::server::local::start( *arguments); } int casual_run_server( struct casual_server_arguments* arguments) { return casual::xatmi::server::local::start( *arguments); }
28.254237
133
0.485303
casualcore
547d0f5ae0bc366ef158fb6e871d7736b6df31c5
930
cpp
C++
Vijos/1470.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
Vijos/1470.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
Vijos/1470.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <cstdio> #include <cstring> #define MAXN 100010 #define cleardp memset(dp,0,sizeof(dp)); using namespace std; int dp[MAXN][4]; int a[MAXN][4]; int ans, n; int mymax(int a, int b) { return a > b ? a : b; } inline void dpit() { for (int i = 2; i <= n; i++) { dp[i][0] = mymax(dp[i - 1][2], dp[i - 1][3]) + a[i][0]; dp[i][1] = dp[i - 1][3] + a[i][1]; dp[i][2] = dp[i - 1][0] + a[i][1]; dp[i][3] = mymax(dp[i - 1][0], dp[i - 1][1]) + a[i][2]; } return ; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d %d %d", &a[i][0], &a[i][1], &a[i][2]); cleardp dp[1][0] = a[1][0]; dpit(); ans = mymax(ans, mymax(dp[n][2], dp[n][3])); cleardp dp[1][1] = a[1][1]; dpit(); ans = mymax(ans, dp[n][3]); cleardp dp[1][2] = a[1][1]; dpit(); ans = mymax(ans, dp[n][0]); cleardp dp[1][3] = a[1][2]; dpit(); ans = mymax(ans, mymax(dp[n][0], dp[n][1])); printf("%d\n", ans); return 0; }
18.235294
57
0.484946
HeRaNO
547fd0284213cf16392ec1e92d51f510c1fed0c4
1,922
cc
C++
third_party/perfetto/src/base/metatrace.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/perfetto/src/base/metatrace.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/perfetto/src/base/metatrace.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/base/metatrace.h" #include <fcntl.h> #include <stdlib.h> #include "perfetto/base/build_config.h" #include "perfetto/base/time.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <corecrt_io.h> #endif namespace perfetto { namespace base { int MaybeOpenTraceFile() { static const char* tracing_path = getenv("PERFETTO_METATRACE_FILE"); if (tracing_path == nullptr) return -1; static int fd = open(tracing_path, O_WRONLY | O_CREAT | O_TRUNC, 0755); return fd; } template <> std::string FormatJSON<std::string>(std::string value) { return "\"" + value + "\""; } template <> std::string FormatJSON<const char*>(const char* value) { return std::string("\"") + value + "\""; } void MetaTrace::WriteEvent(std::string type) { int fd = MaybeOpenTraceFile(); if (fd == -1) return; std::string data = "{"; data.reserve(128); for (size_t i = 0; i < trace_.size(); ++i) { const std::pair<std::string, std::string>& p = trace_[i]; data += p.first; data += ": "; data += p.second; data += ", "; } data += "\"ts\": " + std::to_string(GetWallTimeNs().count() / 1000.) + ", \"cat\": \"PERF\", \"ph\": \"" + type + "\"},\n"; ignore_result(write(fd, data.c_str(), data.size())); } } // namespace base } // namespace perfetto
27.070423
75
0.656608
zipated
548055c5c726bfd5487e71523b054ca6fe96ffb4
768
hpp
C++
libs/gui/impl/include/sge/gui/impl/style/spacing.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/gui/impl/include/sge/gui/impl/style/spacing.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/gui/impl/include/sge/gui/impl/style/spacing.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_GUI_IMPL_STYLE_SPACING_HPP_INCLUDED #define SGE_GUI_IMPL_STYLE_SPACING_HPP_INCLUDED #include <sge/gui/impl/style/inner_border.hpp> #include <sge/gui/impl/style/outer_border.hpp> #include <sge/rucksack/scalar.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace sge::gui::impl::style { using spacing = std::integral_constant< sge::rucksack::scalar, (sge::gui::impl::style::inner_border::value + sge::gui::impl::style::outer_border::value) * 2>; } #endif
29.538462
99
0.740885
cpreh
5488bd7ac166194fe649d8d2c8ea1c34a77f01ea
4,163
cpp
C++
libspace/plugins/craq/PluginInterface.cpp
sirikata/sirikata
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
[ "BSD-3-Clause" ]
31
2015-01-28T17:01:10.000Z
2021-11-04T08:30:37.000Z
libspace/plugins/craq/PluginInterface.cpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
null
null
null
libspace/plugins/craq/PluginInterface.cpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
9
2015-08-02T18:39:49.000Z
2019-10-11T10:32:30.000Z
/* Sirikata * PluginInterface.cpp * * Copyright (c) 2010, Ewen Cheslack-Postava * 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 Sirikata nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sirikata/core/util/Platform.hpp> #include <sirikata/core/options/Options.hpp> #include <sirikata/space/ObjectSegmentation.hpp> #include "CraqObjectSegmentation.hpp" static int space_craq_plugin_refcount = 0; #define OSEG_UNIQUE_CRAQ_PREFIX "oseg_unique_craq_prefix" namespace Sirikata { static void InitPluginOptions() { Sirikata::InitializeClassOptions ico("space_craq", NULL, new OptionValue(OSEG_UNIQUE_CRAQ_PREFIX,"G",Sirikata::OptionValueType<String>(),"Specifies a unique character prepended to Craq lookup calls. Note: takes in type string. Will only select the first character in the string. Also note that it acceptable values range from g to z, and are case sensitive."), NULL); } static ObjectSegmentation* createCraqOSeg(SpaceContext* ctx, Network::IOStrand* oseg_strand, CoordinateSegmentation* cseg, OSegCache* cache, const String& args) { OptionSet* optionsSet = OptionSet::getOptions("space_craq",NULL); optionsSet->parse(args); String oseg_craq_prefix = optionsSet->referenceOption(OSEG_UNIQUE_CRAQ_PREFIX)->as<String>(); if (oseg_craq_prefix.size() ==0) { std::cout<<"\n\nERROR: Incorrect craq prefix for oseg. String must be at least one letter long. (And be between G and Z.) Please try again.\n\n"; assert(false); } return new CraqObjectSegmentation(ctx, oseg_strand, cseg, cache, oseg_craq_prefix[0]); } } // namespace Sirikata SIRIKATA_PLUGIN_EXPORT_C void init() { using namespace Sirikata; if (space_craq_plugin_refcount==0) { InitPluginOptions(); using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; using std::tr1::placeholders::_4; using std::tr1::placeholders::_5; OSegFactory::getSingleton() .registerConstructor("craq", std::tr1::bind(&createCraqOSeg, _1, _2, _3, _4, _5)); } space_craq_plugin_refcount++; } SIRIKATA_PLUGIN_EXPORT_C int increfcount() { return ++space_craq_plugin_refcount; } SIRIKATA_PLUGIN_EXPORT_C int decrefcount() { assert(space_craq_plugin_refcount>0); return --space_craq_plugin_refcount; } SIRIKATA_PLUGIN_EXPORT_C void destroy() { using namespace Sirikata; if (space_craq_plugin_refcount==0) { OSegFactory::getSingleton().unregisterConstructor("craq"); } } SIRIKATA_PLUGIN_EXPORT_C const char* name() { return "craq"; } SIRIKATA_PLUGIN_EXPORT_C int refcount() { return space_craq_plugin_refcount; }
40.028846
314
0.735767
sirikata
5489d19cb30ac996d5676e3db61db24e56aff326
7,037
cpp
C++
src/add-ons/kernel/drivers/audio/echo/generic/CIndigoIO.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/add-ons/kernel/drivers/audio/echo/generic/CIndigoIO.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/add-ons/kernel/drivers/audio/echo/generic/CIndigoIO.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
// **************************************************************************** // // CIndigoIO.cpp // // Implementation file for the CIndigoIO driver class. // Set editor tabs to 3 for your viewing pleasure. // // ---------------------------------------------------------------------------- // // This file is part of Echo Digital Audio's generic driver library. // Copyright Echo Digital Audio Corporation (c) 1998 - 2005 // All rights reserved // www.echoaudio.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // **************************************************************************** #include "CIndigoIO.h" #include "CIndigoDJ.h" #define INDIGO_IO_OUTPUT_LATENCY_SINGLE_SPEED 44 #define INDIGO_IO_OUTPUT_LATENCY_DOUBLE_SPEED 37 #define INDIGO_IO_INPUT_LATENCY_SINGLE_SPEED 44 #define INDIGO_IO_INPUT_LATENCY_DOUBLE_SPEED 41 /**************************************************************************** Construction and destruction ****************************************************************************/ //=========================================================================== // // Overload new & delete so memory for this object is allocated // from non-paged memory. // //=========================================================================== PVOID CIndigoIO::operator new( size_t Size ) { PVOID pMemory; ECHOSTATUS Status; Status = OsAllocateNonPaged(Size,&pMemory); if ( (ECHOSTATUS_OK != Status) || (NULL == pMemory )) { ECHO_DEBUGPRINTF(("CIndigoIO::operator new - memory allocation failed\n")); pMemory = NULL; } else { memset( pMemory, 0, Size ); } return pMemory; } // PVOID CIndigoIO::operator new( size_t Size ) VOID CIndigoIO::operator delete( PVOID pVoid ) { if ( ECHOSTATUS_OK != OsFreeNonPaged( pVoid ) ) { ECHO_DEBUGPRINTF(("CIndigoIO::operator delete memory free failed\n")); } } // VOID CIndigoIO::operator delete( PVOID pVoid ) //=========================================================================== // // Constructor and destructor // //=========================================================================== CIndigoIO::CIndigoIO( PCOsSupport pOsSupport ) : CEchoGalsVmixer( pOsSupport ) { ECHO_DEBUGPRINTF( ( "CIndigoIO::CIndigoIO() is born!\n" ) ); } CIndigoIO::~CIndigoIO() { ECHO_DEBUGPRINTF( ( "CIndigoIO::~CIndigoIO() is toast!\n" ) ); } /**************************************************************************** Setup and hardware initialization ****************************************************************************/ //=========================================================================== // // Every card has an InitHw method // //=========================================================================== ECHOSTATUS CIndigoIO::InitHw() { ECHOSTATUS Status; // // Call the base method // if ( ECHOSTATUS_OK != ( Status = CEchoGals::InitHw() ) ) return Status; // // Create the DSP comm object // ECHO_ASSERT(NULL == m_pDspCommObject ); m_pDspCommObject = new CIndigoIODspCommObject( (PDWORD) m_pvSharedMemory, m_pOsSupport ); if (NULL == m_pDspCommObject) { ECHO_DEBUGPRINTF(("CIndigoIO::InitHw - could not create DSP comm object\n")); return ECHOSTATUS_NO_MEM; } // // Load the DSP // GetDspCommObject()->LoadFirmware(); if ( GetDspCommObject()->IsBoardBad() ) return ECHOSTATUS_DSP_DEAD; // // Do flags // m_wFlags &= ~ECHOGALS_FLAG_BADBOARD; m_wFlags |= ECHOGALS_ROFLAG_SUPER_INTERLEAVE_OK; // // Must call this here after DSP is init to // init gains and mutes // Status = InitLineLevels(); if ( ECHOSTATUS_OK != Status ) return Status; // // Get default sample rate from DSP // m_dwSampleRate = GetDspCommObject()->GetSampleRate(); ECHO_DEBUGPRINTF( ( "CIndigoIO::InitHw() complete\n" ) ); return Status; } // ECHOSTATUS CIndigoIO::InitHw() /**************************************************************************** Informational methods ****************************************************************************/ //=========================================================================== // // Override GetCapabilities to enumerate unique capabilties for this card // //=========================================================================== ECHOSTATUS CIndigoIO::GetCapabilities ( PECHOGALS_CAPS pCapabilities ) { ECHOSTATUS Status; Status = GetBaseCapabilities(pCapabilities); if ( ECHOSTATUS_OK != Status ) return Status; pCapabilities->dwOutClockTypes = 0; return Status; } // ECHOSTATUS CIndigoIO::GetCapabilities //=========================================================================== // // QueryAudioSampleRate is used to find out if this card can handle a // given sample rate. // //=========================================================================== ECHOSTATUS CIndigoIO::QueryAudioSampleRate ( DWORD dwSampleRate ) { if ( dwSampleRate != 32000 && dwSampleRate != 44100 && dwSampleRate != 48000 && dwSampleRate != 64000 && dwSampleRate != 88200 && dwSampleRate != 96000 ) { ECHO_DEBUGPRINTF( ("CIndigoIO::QueryAudioSampleRate() - rate %ld invalid\n",dwSampleRate) ); return ECHOSTATUS_BAD_FORMAT; } ECHO_DEBUGPRINTF( ( "CIndigoIO::QueryAudioSampleRate()\n" ) ); return ECHOSTATUS_OK; } // ECHOSTATUS CIndigoIO::QueryAudioSampleRate void CIndigoIO::QuerySampleRateRange(DWORD &dwMinRate,DWORD &dwMaxRate) { dwMinRate = 32000; dwMaxRate = 96000; } //=========================================================================== // // GetAudioLatency - returns the latency for a single pipe // //=========================================================================== void CIndigoIO::GetAudioLatency(ECHO_AUDIO_LATENCY *pLatency) { DWORD dwLatency; DWORD dwSampleRate; // // The latency depends on the current sample rate // dwSampleRate = GetDspCommObject()->GetSampleRate(); if (FALSE == pLatency->wIsInput) { if (dwSampleRate < 50000) dwLatency = INDIGO_IO_OUTPUT_LATENCY_SINGLE_SPEED; else dwLatency = INDIGO_IO_OUTPUT_LATENCY_DOUBLE_SPEED; } else { if (dwSampleRate < 50000) dwLatency = INDIGO_IO_INPUT_LATENCY_SINGLE_SPEED; else dwLatency = INDIGO_IO_INPUT_LATENCY_DOUBLE_SPEED; } pLatency->dwLatency = dwLatency; } // GetAudioLatency // *** CIndigoIO.cpp ***
25.404332
79
0.549666
Kirishikesan
548a79c421b09c5cdcc9aa9c505d904cc625f10e
2,795
cpp
C++
OneCodeTeam/How to create a SDI with Multi-Views in MFC/[C++]-How to create a SDI with Multi-Views in MFC/C++/MFCSDIAppln/MFCSDIApplnView.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
OneCodeTeam/How to create a SDI with Multi-Views in MFC/[C++]-How to create a SDI with Multi-Views in MFC/C++/MFCSDIAppln/MFCSDIApplnView.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
OneCodeTeam/How to create a SDI with Multi-Views in MFC/[C++]-How to create a SDI with Multi-Views in MFC/C++/MFCSDIAppln/MFCSDIApplnView.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
null
null
null
/****************************** Module Header ******************************\ * Module Name: MFCSDIApplnView.cpp * Project: MFCSDIAppln * Copyright (c) Microsoft Corporation. * * This is Main View. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ #include "stdafx.h" // SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail // and search filter handlers and allows sharing of document code with that project. #ifndef SHARED_HANDLERS #include "MFCSDIAppln.h" #endif #include "MFCSDIApplnDoc.h" #include "MFCSDIApplnView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCSDIApplnView IMPLEMENT_DYNCREATE(CMFCSDIApplnView, CView) BEGIN_MESSAGE_MAP(CMFCSDIApplnView, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview) END_MESSAGE_MAP() // CMFCSDIApplnView construction/destruction CMFCSDIApplnView::CMFCSDIApplnView() { // TODO: add construction code here } CMFCSDIApplnView::~CMFCSDIApplnView() { } BOOL CMFCSDIApplnView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CMFCSDIApplnView drawing void CMFCSDIApplnView::OnDraw(CDC* pDC) { CMFCSDIApplnDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; CString str = _T("Displaying MainView"); pDC->DrawText(str, CRect(100, 100, 500, 500), DT_CENTER); } // CMFCSDIApplnView printing BOOL CMFCSDIApplnView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CMFCSDIApplnView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CMFCSDIApplnView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } // CMFCSDIApplnView diagnostics #ifdef _DEBUG void CMFCSDIApplnView::AssertValid() const { CView::AssertValid(); } void CMFCSDIApplnView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMFCSDIApplnDoc* CMFCSDIApplnView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMFCSDIApplnDoc))); return (CMFCSDIApplnDoc*)m_pDocument; } #endif //_DEBUG // CMFCSDIApplnView message handlers
23.487395
85
0.729159
zzgchina888
548dd46e2289357b2682171fe2f3d589bbdefe1c
1,295
cpp
C++
Deitel/Chapter12/exercises/12.09/ex_1209.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter12/exercises/12.09/ex_1209.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter12/exercises/12.09/ex_1209.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include <iostream> #include "OvernightPackage.hpp" #include "TwoDayPackage.hpp" #include "Utility.hpp" int main(int argc, const char *argv[]) { OvernightPackage op(Person("Bob", "Bobson", "12 Bob Street", "BobVille", "Bobzone", "B0B-50N"), Person("Sue", "Sueson", "12 Sue Street", "SueVille", "Suezona", "5U3-50N"), 12.0f, 5.0f, 1.0f); TwoDayPackage tdp( Person("Send", "er", "Sender Street", "Send Place", "Snd", "53N-D3R"), Person("Reci", "pient", "Receipient Lane", "Recip Town", "Rpt", "R3C-3NT"), 12.0f, 5.0f, 1.0f); std::cout << "Overnight Package:\n"; op.printDetails(); std::cout << "\n\nTwo day Package:\n"; tdp.printDetails(); std::cout << std::endl; return 0; }
27.553191
88
0.433977
SebastianTirado
548e37bb640ef1a19cddda474c9951b077bbb54f
3,015
hpp
C++
external/mapnik/include/mapnik/group/group_layout_manager.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/group/group_layout_manager.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/group/group_layout_manager.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GROUP_LAYOUT_MANAGER_HPP #define MAPNIK_GROUP_LAYOUT_MANAGER_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/pixel_position.hpp> #include <mapnik/group/group_layout.hpp> // stl #include <vector> namespace mapnik { struct group_layout_manager { using bound_box = box2d<double>; group_layout_manager() : update_layout_(false) {} explicit group_layout_manager(group_layout const& layout) : layout_(layout), update_layout_(false) { } group_layout_manager(group_layout const& layout, pixel_position const& input_origin) : layout_(layout), input_origin_(input_origin), update_layout_(false) { } group_layout_manager(group_layout const& layout, pixel_position const& input_origin, std::vector<bound_box> const& item_boxes) : layout_(layout), input_origin_(input_origin), member_boxes_(item_boxes), update_layout_(true) { } void set_input_origin(double x, double y) { input_origin_.set(x, y); update_layout_ = true; } void set_input_origin(pixel_position const& input_origin) { input_origin_ = input_origin; update_layout_ = true; } inline void set_layout(group_layout const& layout) { layout_ = layout; update_layout_ = true; } inline void add_member_bound_box(bound_box const& member_box) { member_boxes_.push_back(member_box); update_layout_ = true; } inline pixel_position const& offset_at(size_t i) { handle_update(); return member_offsets_.at(i); } bound_box offset_box_at(size_t i); private: void handle_update(); group_layout layout_; pixel_position input_origin_; std::vector<bound_box> member_boxes_; std::vector<pixel_position> member_offsets_; bool update_layout_; }; } // namespace mapnik #endif // MAPNIK_GROUP_LAYOUT_MANAGER_HPP
26.681416
88
0.65141
baiyicanggou
5490715eab05b16a29adef8834ad61db35612d76
635
cpp
C++
VC2010Samples/ComTypeLibfor7/dcom/atldraw/preatldr.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/ComTypeLibfor7/dcom/atldraw/preatldr.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/ComTypeLibfor7/dcom/atldraw/preatldr.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// preatldr.cpp : source file that includes just the standard includes // ATLDraw.pch will be the pre-compiled header // preatldr.obj will contain the pre-compiled type information #include "preatldr.h" LONG g_cObjCnt; void dump_com_error(_com_error &e) { _tprintf(_T("Oops - hit an error!\n")); _tprintf(_T("\a\tCode = %08lx\n"), e.Error()); _tprintf(_T("\a\tCode meaning = %s\n"), e.ErrorMessage()); _bstr_t bstrSource(e.Source()); _bstr_t bstrDescription(e.Description()); _tprintf(_T("\a\tSource = %s\n"), (LPCTSTR) bstrSource); _tprintf(_T("\a\tDescription = %s\n"), (LPCTSTR) bstrDescription); }
33.421053
70
0.68189
alonmm
549382a8825cf8cd8e0f2d62c6c0c15a4542fbcc
318
inl
C++
node_modules/lzz-gyp/lzz-source/smtc_CreateDtorBaseName.inl
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_CreateDtorBaseName.inl
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_CreateDtorBaseName.inl
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_CreateDtorBaseName.inl // #ifdef LZZ_ENABLE_INLINE #define LZZ_INLINE inline #else #define LZZ_INLINE #endif namespace smtc { LZZ_INLINE BaseNamePtr createDtorBaseName (util::Loc const & loc, util::Ident const & ident) { return createDtorBaseName (loc, util::Ident (), ident); } } #undef LZZ_INLINE
18.705882
94
0.745283
SuperDizor
5499e32fbdb9383297eb7f760eb6759ed6f686f9
881
cpp
C++
console/src/boost_1_78_0/libs/type_traits/test/is_unscoped_enum_test.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
106
2015-08-07T04:23:50.000Z
2020-12-27T18:25:15.000Z
console/src/boost_1_78_0/libs/type_traits/test/is_unscoped_enum_test.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
130
2016-06-22T22:11:25.000Z
2020-11-29T20:24:09.000Z
Libs/boost_1_76_0/libs/type_traits/test/is_unscoped_enum_test.cpp
Antd23rus/S2DE
47cc7151c2934cd8f0399a9856c1e54894571553
[ "MIT" ]
41
2015-07-08T19:18:35.000Z
2021-01-14T16:39:56.000Z
/* Copyright 2020 Glen Joseph Fernandes (glenjofe@gmail.com) Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifdef TEST_STD #include <type_traits> #else #include <boost/type_traits/is_unscoped_enum.hpp> #endif #include "check_integral_constant.hpp" enum Unscoped { Constant = 1 }; #if !defined(BOOST_NO_CXX11_SCOPED_ENUMS) enum class Scoped { Constant = 2 }; #endif TT_TEST_BEGIN(is_unscoped_enum) BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_unscoped_enum<void>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_unscoped_enum<int>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_unscoped_enum<Unscoped>::value, true); #if !defined(BOOST_NO_CXX11_SCOPED_ENUMS) BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_unscoped_enum<Scoped>::value, false); #endif TT_TEST_END
23.810811
77
0.790011
vany152
5499fe18223882ee1792d4083a10b2eac2be9b94
3,521
hpp
C++
argholder.hpp
degarashi/spinner
6c0d5dbdcde962a36de28cdc867478e2a715b689
[ "MIT" ]
null
null
null
argholder.hpp
degarashi/spinner
6c0d5dbdcde962a36de28cdc867478e2a715b689
[ "MIT" ]
null
null
null
argholder.hpp
degarashi/spinner
6c0d5dbdcde962a36de28cdc867478e2a715b689
[ "MIT" ]
null
null
null
#pragma once #include <type_traits> #include <cassert> namespace spn { struct none_t{}; //! rvalue-reference wrapper template <class T> struct _RRef { T& value; _RRef(T& v): value(v) {} _RRef(const _RRef& r): value(r.value) {} int get() { return 0; } operator T& () { return value; } }; template <class T> struct _RRef<T&&> { T&& value; _RRef(const _RRef& r): value(std::move(r.value)) {} _RRef(T&& v): value(std::forward<T>(v)) {} operator T&& () { return std::move(value); } int get() { return 1; } }; template <class T> auto RRef(T&& t) -> _RRef<decltype(std::forward<T>(t))> { return _RRef<T&&>(std::forward<T>(t)); } template <class... Ts> struct ArgHolder { ArgHolder() = default; ArgHolder(ArgHolder&& /*a*/) {} template <class CB, class... TsA> auto reverse(CB cb, TsA&&... tsa) -> decltype(cb(std::forward<TsA>(tsa)...)) { return cb(std::forward<TsA>(tsa)...); } template <class CB, class... TsA> auto inorder(CB cb, TsA&&... tsa) -> decltype(cb(std::forward<TsA>(tsa)...)) { return cb(std::forward<TsA>(tsa)...); } }; //! 引数を一旦とっておいて後で関数に渡す /*! not reference, not pointerな型はrvalue_referenceで渡されるので2回以上呼べない */ template <class T0, class... Ts> struct ArgHolder<T0,Ts...> { T0 _value; using Lower = ArgHolder<Ts...>; Lower _other; // 2度呼び出しチェック #ifdef DEBUG bool _bCall = false; void _check() { if(_bCall) assert(!"Invalid ArgHolder call (called twice)"); _bCall = true; } #else void _check() {} #endif template <class T2> ArgHolder(ArgHolder<T2,Ts...>&& a): _value(std::move(a._value)), _other(std::move(a._other)) #ifdef DEBUG , _bCall(a._bCall) #endif {} template <class T0A, class... TsA> ArgHolder(T0A&& t0, TsA&&... tsa): _value(std::forward<T0A>(t0)), _other(std::forward<TsA>(tsa)...) {} // T0がnot reference, not pointerな時はrvalue referenceで渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<std::is_object<TT0>::value>::type> auto reverse(CB cb, TsA&&... tsa) -> decltype(_other.reverse(cb, std::move(_value), std::forward<TsA>(tsa)...)) { _check(); return _other.reverse(cb, std::move(_value), std::forward<TsA>(tsa)...); } // それ以外はそのまま渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<!std::is_object<TT0>::value>::type> auto reverse(CB cb, TsA&&... tsa) -> decltype(_other.reverse(cb, _value, std::forward<TsA>(tsa)...)) { return _other.reverse(cb, _value, std::forward<TsA>(tsa)...); } // T0がnot reference, not pointerな時はrvalue referenceで渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<std::is_object<TT0>::value>::type> auto inorder(CB cb, TsA&&... tsa) -> decltype(_other.inorder(cb, std::forward<TsA>(tsa)..., std::move(_value))) { _check(); return _other.inorder(cb, std::forward<TsA>(tsa)..., std::move(_value)); } // それ以外はそのまま渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<!std::is_object<TT0>::value>::type> auto inorder(CB cb, TsA&&... tsa) -> decltype(_other.inorder(cb, std::forward<TsA>(tsa)..., _value)) { return _other.inorder(cb, std::forward<TsA>(tsa)..., _value); } }; //! 引数の順序を逆にしてコール template <class CB, class... Ts> auto ReversedArg(CB cb, Ts&&... ts) -> decltype(ArgHolder<decltype(std::forward<Ts>(ts))...>(std::forward<Ts>(ts)...).reverse(cb)) { return ArgHolder<decltype(std::forward<Ts>(ts))...>(std::forward<Ts>(ts)...).reverse(cb); } }
33.216981
133
0.628515
degarashi
549a54abf8eeb4332bb9fbaae6cf0ae119c5b8a5
532
cpp
C++
src/js_array.cpp
bygreencn/libj
e77b2f4466962f3d020418b043a3c693fde0b0d1
[ "BSD-2-Clause", "BSD-3-Clause" ]
1
2019-05-07T15:01:23.000Z
2019-05-07T15:01:23.000Z
src/js_array.cpp
bygreencn/libj
e77b2f4466962f3d020418b043a3c693fde0b0d1
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/js_array.cpp
bygreencn/libj
e77b2f4466962f3d020418b043a3c693fde0b0d1
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012-2013 Plenluno All rights reserved. #include <libj/js_array.h> #include <libj/detail/js_array.h> namespace libj { JsArray::Ptr JsArray::create(Size length) { detail::JsArray<JsArray>* a = new detail::JsArray<JsArray>(); for (Size i = 0; i < length; i++) { a->add(UNDEFINED); } return Ptr(a); } JsArray::Ptr JsArray::create(ArrayList::CPtr list) { if (!list) return null(); JsArray::Ptr ary = JsArray::create(); ary->addAll(list); return ary; } } // namespace libj
21.28
65
0.631579
bygreencn
549ae70a1a5bbcb1f02f57e430fb0f25622111ba
224
cpp
C++
Source/FSD/Private/DistanceToTargetDamageCondition.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/DistanceToTargetDamageCondition.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/DistanceToTargetDamageCondition.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
#include "DistanceToTargetDamageCondition.h" UDistanceToTargetDamageCondition::UDistanceToTargetDamageCondition() { this->TestMaxDistance = true; this->MaxDistance = 100.00f; this->MinimumDistance = 100.00f; }
24.888889
70
0.767857
trumank
549b05c7f97acd0d48578db2fee40efd3401dc63
5,660
cpp
C++
csl/cslbase/utf8check.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/utf8check.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/utf8check.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
// utfcheck.cpp Copyright (C) 2016-2020 Codemist // // This is a pretty silly program! It looks at Unicode characters and tests // when case-folding can change the number of utf-8 bytes needed to encode // them. At least in the default locales I have set up on my own Mac and // Linux systems there is never a change of encoded length, but on Windows // there sometimes is. For instance towlower when applied to a capital letter // "I" with a dot over it gives back a simple lower case "i". A consequence // of this is of course that folding case backwards and forwards can be // lossy. The code here lists the cases I came across on my Windows // system when running under cygwin. A windows version compiled using // i686-w64-mingw32-gcc seems to behave like Linux with no discrepancies // shown. // // There is a real prospect that the concept of "case" and folding will be // locale sensitive and so running this in different locales may be // instructive. // /************************************************************************** * Copyright (C) 2020, Codemist. A C Norman * * * * 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 relevant * * 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. * * * * 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 OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * * DAMAGE. * *************************************************************************/ // $Id: utf8check.cpp 5433 2020-10-15 21:09:02Z arthurcnorman $ #include <cstdio> #include <cwchar> #include <cctype> #include <cwctype> int encode(char *s, int c) { char *s1 = s; if (c <= 0x7f) *s++ = c; else if (c <= 0x7ff) { *s++ = 0xc0 + ((c>>6) & 0x1f); *s++ = 0x80 + (c & 0x3f); } else if (c <= 0xffff) { *s++ = 0xe0 + ((c>>12) & 0x0f); *s++ = 0x80 + ((c>>6) & 0x3f); *s++ = 0x80 + (c & 0x3f); } else { *s++ = 0xf0 + ((c>>16) & 0x07); *s++ = 0x80 + ((c>>12) & 0x3f); *s++ = 0x80 + ((c>>6) & 0x3f); *s++ = 0x80 + (c & 0x3f); } *s = 0; return (s - s1); } int main(int argc, char *argv[]) { int c1, c2, c3, n1, n2, n3, status, flag; char s1[8], s2[8], s3[8]; std::printf(" base upper lower\n"); for (c1 = 0; c1<=0xffff; c1++) { // Skip the surrogate range if (0xd800 <= c1 && c1 <= 0xdfff) continue; c2 = std::towupper(c1); c3 = std::towlower(c1); n1 = encode(s1, c1); n2 = encode(s2, c2); n3 = encode(s3, c3); flag = 1; switch (c1) { // Here are cases I know are sometimes at issue... // about them! case 0x0130: // LATIN CAPITAL I WITH DOT case 0x0131: // LATIN SMALL LETTER DOTLESS I case 0x017f: // LATIN SMALL LETTER LONG S case 0x023a: // LATIN CAPITAL A WITH STROKE case 0x023e: case 0x023f: case 0x0240: case 0x0250: case 0x0251: case 0x0252: case 0x026b: case 0x0271: case 0x027d: case 0x1e9e: case 0x1fbe: case 0x2126: case 0x212a: case 0x212b: case 0x2c62: case 0x2c64: case 0x2c65: case 0x2c66: case 0x2c6d: case 0x2c6e: case 0x2c6f: case 0x2c70: // LATIN CAPITRAL LETTER TURNED ALPHA case 0x2c7e: // LATIN CAPITAL S WITH SWASH TAIL case 0x2c7f: // LATIN CAPITAL Z WITH SWASH TAIL flag = 0; default: break; } status = (n1 == n2 && n1 == n3); // are utf-8 lengths unchanged? if (status && flag) continue; std::printf("%#.4x(%d) %#.4x(%d) %#.4x(%d) %s %s %s %s\n", c1, n1, c2, n2, c3, n3, (status ? "OK " : "bad"), s1, s2, s3); } return 0; } // end of utf8check.cpp
40.428571
82
0.514664
arthurcnorman
549b3ed789af7653d7eadacb42cd9ff98e5605be
4,034
hpp
C++
rmvmath/matrix/affinematrix3x3/operator/TAffineMatrix3x3_operator_mul.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
rmvmath/matrix/affinematrix3x3/operator/TAffineMatrix3x3_operator_mul.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
rmvmath/matrix/affinematrix3x3/operator/TAffineMatrix3x3_operator_mul.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
// // Created by Vitali Kurlovich on 1/13/16. // #ifndef RMVECTORMATH_TAFFINEMATRIX3X3_OPERATOR_MUL_HPP #define RMVECTORMATH_TAFFINEMATRIX3X3_OPERATOR_MUL_HPP #include "../TAffineMatrix3x3_def.hpp" #include "../func/TAffineMatrix3x3_func_mul.hpp" #include "../func/TAffineMatrix3x3_func_mulvec.hpp" namespace rmmath { namespace matrix { // Mul template<typename T> inline TAffineMatrix3x3 <T> operator*(const TAffineMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x4 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x4 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix4x3 <T> operator*(const TMatrix4x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x3 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x3 <T> operator*(const TMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x2 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x2 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix2x3 <T> operator*(const TMatrix2x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x1 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x1 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix1x3 <T> operator*(const TMatrix1x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TAffineMatrix3x3 <T> &operator*=(TAffineMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix4x3 <T> &operator*=(TMatrix4x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix3x3 <T> &operator*=(TMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix2x3 <T> &operator*=(TMatrix2x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix1x3 <T> &operator*=(TMatrix1x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } } template<typename T> inline vector::TVector3 <T> operator * (const matrix::TAffineMatrix3x3 <T> &a, const vector::TVector3<T> &b) { return mul(a, b); } template<typename T> inline vector::TVector3 <T> operator * (const vector::TVector3<T> &a, const matrix::TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline vector::TVector3 <T> &operator *= (vector::TVector3 <T> &a, const matrix::TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a,b); return a; } template<typename T> inline vector::TVector3 <T> operator * (const matrix::TAffineMatrix3x3 <T> &a, const vector::TAffineVector3<T> &b) { return mul(a, b); } template<typename T> inline vector::TAffineVector3 <T> operator * (const vector::TAffineVector3<T> &a, const matrix::TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline vector::TAffineVector3 <T> &operator *= (vector::TAffineVector3 <T> &a, const matrix::TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a,b); return a; } } #endif //RMVECTORMATH_TAFFINEMATRIX3X3_OPERATOR_MUL_HPP
29.021583
126
0.587506
vitali-kurlovich
549b6040ee5d3c7bd70398800ba99e8c830d7bf3
254
cpp
C++
CodeForces/4A - Watermelon.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
CodeForces/4A - Watermelon.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
CodeForces/4A - Watermelon.cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
// http://codeforces.com/problemset/problem/4/A #include <iostream> using namespace std; int main(){ int x; cin >> x; if(x == 2) cout<<"NO"; else if(x % 2 == 0) cout<<"YES"; else cout<<"NO"; return 0; }
14.111111
47
0.496063
tanishq1g
549f7add891c354e05c87513df8fcd43a6c06037
1,957
cpp
C++
algorithms/graph/kruskals_mst_algorithm.cpp
sureshmangs/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
algorithms/graph/kruskals_mst_algorithm.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
algorithms/graph/kruskals_mst_algorithm.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
#include<bits/stdc++.h> using namespace std; struct Edge { int src, dst, weight; }; class DisjointSet { unordered_map<int, int> parent; public: void makeSet(int V){ // create V disjoint sets (one for each vertex) for(int i = 0; i < V; i++) parent[i] = i; } // Find the root of the set in which element k belongs int Find(int k){ // if k is root if (parent[k] == k) return k; // recur for parent until we find root return Find(parent[k]); } void Union(int a, int b){ // find root of the sets in which elements x and y belongs int x = Find(a); int y = Find(b); parent[x] = y; } }; vector<Edge> Kruskals(vector<Edge> edges, int V){ // stores edges present in MST vector<Edge> MST; // initialize DisjointSet class DisjointSet ds; // create singleton set for each element of universe ds.makeSet(V); // MST contains exactly V-1 edges while (MST.size() != V - 1){ // consider next edge with minimum weight from the graph Edge next_edge = edges.back(); edges.pop_back(); // find root of the sets to which two endpoint // vertices of next_edge belongs int x = ds.Find(next_edge.src); int y = ds.Find(next_edge.dst); // if both endpoints have different parents, they belong to // different connected components and can be included in MST if (x != y) { MST.push_back(next_edge); ds.Union(x, y); } } return MST; } bool comp(Edge a, Edge b){ return (a.weight > b.weight); } int main(){ vector<Edge> edges {{ 0, 1, 4 }, { 0, 7, 8 }, { 1, 2, 8 }, { 1, 7, 11 }, { 2, 3, 7 }, { 2, 8, 2 }, { 2, 5, 4 }, { 3, 4, 9 }, { 3, 5, 14 }, { 4, 5, 10 }, { 5, 6, 2 }, {6, 7, 1}, {6, 8, 6}, {7, 8, 7} }; // sort edges by increasing weight sort(edges.begin(), edges.end(), comp); int V = 9; // vertices // construct graph vector<Edge> e = Kruskals(edges, V); for (auto &edge: e) cout << "(" << edge.src << ", " << edge.dst << ", " << edge.weight << ")" << endl; return 0; }
20.819149
201
0.599387
sureshmangs
54a1523fda2e54a274eeb38d617b589861a732e0
1,740
cpp
C++
OJ/LeetCode/leetcode/problems/938.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
null
null
null
OJ/LeetCode/leetcode/problems/938.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
2
2021-10-31T10:05:45.000Z
2022-02-12T15:17:53.000Z
OJ/LeetCode/leetcode/938.cpp
ONGOING-Z/Learn-Algorithm-and-DataStructure
3a512bd83cc6ed5035ac4550da2f511298b947c0
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> using namespace std; /* Leetcode */ /* 题目信息 */ /* *938. Range Sum of BST Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. Example 1: Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32 Example 2: Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 Output: 23 Note: The number of nodes in the tree is at most 10000. The final answer is guaranteed to be less than 2^31. */ 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) {} }; /* my solution */ // none /* better solution */ /** * 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 sum = 0; void inorder(TreeNode *root, int L, int R) { if (root->left) inorder(root->left, L, R); if (root->val >= L && root->val <= R) sum += root->val; if (root->right) inorder(root->right, L, R); } int rangeSumBST(TreeNode *root, int L, int R) { inorder(root, L, R); return sum; } }; /* 一些总结 */ // 1. 使用的是中序遍历,这样看来并不难。
23.513514
123
0.584483
ONGOING-Z
54a35c9edb4161389804c450a775aac3e2d47cc9
7,762
cpp
C++
esp32/libraries/TouchLib-master/src/TLSampleMethodResistive.cpp
zvikapika/HanukiyaIOT
6f54e3d2d945962e9c1ff65d282269ae60898246
[ "MIT" ]
null
null
null
esp32/libraries/TouchLib-master/src/TLSampleMethodResistive.cpp
zvikapika/HanukiyaIOT
6f54e3d2d945962e9c1ff65d282269ae60898246
[ "MIT" ]
null
null
null
esp32/libraries/TouchLib-master/src/TLSampleMethodResistive.cpp
zvikapika/HanukiyaIOT
6f54e3d2d945962e9c1ff65d282269ae60898246
[ "MIT" ]
null
null
null
/* * TLSampleMethodResistive.cpp - Resistive sensing implementation for * TouchLibrary for Arduino Teensy 3.x * * https://github.com/AdmarSchoonen/TLSensor * Copyright (c) 2016 - 2017 Admar Schoonen * * 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 <organization> 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 <COPYRIGHT HOLDER> 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 "TouchLib.h" #include "TLSampleMethodResistive.h" #define USE_CORRECT_TRANSFER_FUNCTION 0 #define TL_SAMPLE_METHOD_RESISTIVE_GND_PIN 2 #define TL_SAMPLE_METHOD_RESISTIVE_USE_INTERNAL_PULLUP true /* ATmega2560 has internal pull-ups of 20 - 50 kOhm. Assume it is 35 kOhm */ #define TL_REFERENCE_VALUE_DEFAULT ((int32_t) 35000) /* 32 kOhm */ #define TL_SCALE_FACTOR_DEFAULT ((int32_t) 1) #define TL_VALUE_MAX_DEFAULT ((int32_t) 8000000) /* 8 MOhm */ #define TL_OFFSET_VALUE_DEFAULT ((int32_t) 0) /* Ohm */ #define TL_SET_OFFSET_VALUE_MANUALLY_DEFAULT false #if IS_PARTICLE #define TL_ADC_RESOLUTION_BIT 12 #elif IS_ESP32 #define TL_ADC_RESOLUTION_BIT 12 #elif IS_ATMEGA #define TL_ADC_RESOLUTION_BIT 10 #else #define TL_ADC_RESOLUTION_BIT 10 #endif #define TL_ADC_MAX ((1 << TL_ADC_RESOLUTION_BIT) - 1) #if (USE_CORRECT_TRANSFER_FUNCTION == 1) #define TL_RELEASED_TO_APPROACHED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 4500) #define TL_APPROACHED_TO_RELEASED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 5500) #define TL_APPROACHED_TO_PRESSED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 800) #define TL_PRESSED_TO_APPROACHED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 1000) #else #define TL_RELEASED_TO_APPROACHED_THRESHOLD_DEFAULT 0.5 #define TL_APPROACHED_TO_RELEASED_THRESHOLD_DEFAULT 0.25 #define TL_APPROACHED_TO_PRESSED_THRESHOLD_DEFAULT 5 #define TL_PRESSED_TO_APPROACHED_THRESHOLD_DEFAULT 4 #endif int TLSampleMethodResistivePreSample(struct TLStruct * data, uint8_t nSensors, uint8_t ch) { return 0; } int32_t TLSampleMethodResistiveSample(struct TLStruct * data, uint8_t nSensors, uint8_t ch, bool inv) { struct TLStruct * dCh; int ch_pin, gnd_pin; int32_t sample; bool useInternalPullup; if (inv) { /* Pseudo differential measurements are not supported */ sample = 0; } else { dCh = &(data[ch]); ch_pin = dCh->tlStructSampleMethod.resistive.pin; gnd_pin = dCh->tlStructSampleMethod.resistive.gndPin; useInternalPullup = dCh->tlStructSampleMethod.resistive.useInternalPullup; if (ch_pin < 0) { return 0; /* An error occurred */ } if (useInternalPullup) { /* Enable internal pull-up on analog input */ pinMode(ch_pin, INPUT_PULLUP); } else { /* Disable internal pull-up on analog input */ pinMode(ch_pin, INPUT); } if (gnd_pin >= 0) { /* Configure gnd_pin as digital output, low (gnd) */ pinMode(gnd_pin, OUTPUT); digitalWrite(gnd_pin, LOW); } /* Read */ sample = analogRead(ch_pin); /* Disable internal pull-up on analog input */ pinMode(ch_pin, INPUT); if (gnd_pin >= 0) { /* Leave gnd_pin floating */ pinMode(gnd_pin, INPUT); digitalWrite(gnd_pin, LOW); } } return sample; } int TLSampleMethodResistivePostSample(struct TLStruct * data, uint8_t nSensors, uint8_t ch) { TLStruct * d; int32_t tmp, scale; d = &(data[ch]); switch (d->filterType) { case TLStruct::filterTypeAverage: scale = (((int32_t) d->nMeasurementsPerSensor) << 1) * (TL_ADC_MAX + 1); break; case TLStruct::filterTypeSlewrateLimiter: scale = ((TL_ADC_MAX + 1) << 2); break; case TLStruct::filterTypeMedian: scale = ((TL_ADC_MAX + 1) << 2); break; default: /* Error! */ scale = ((TL_ADC_MAX + 1) << 2); } #if (USE_CORRECT_TRANSFER_FUNCTION == 1) /* * Actual transfer function is * (d->raw / scale) / (1 - (d->raw / scale)), but this is very * sensitive to noise when sensor is not pressed (since tmp will then * be very close to 1). Instead, clip the value to a predefined * maximum. */ if (d->raw > scale) { d->raw = scale; } denum = scale - d->raw; tmp = (d->scaleFactor * d->referenceValue * d->raw + (denum >> 1)) / denum; if (tmp > d->tlStructSampleMethod.resistive.valueMax) { tmp = d->tlStructSampleMethod.resistive.valueMax; } #else tmp = d->scaleFactor * d->referenceValue * d->raw / scale; #endif d->value = tmp; /* Resistance can be negative due to noise! */ return 0; } int32_t TLSampleMethodResistiveMapDelta(struct TLStruct * data, uint8_t nSensors, uint8_t ch, int length) { int32_t n = -1; struct TLStruct * d; int32_t delta; d = &(data[ch]); delta = d->delta - d->releasedToApproachedThreshold / 2; n = map(100 * delta, 0, 100 * d->calibratedMaxDelta, 0, length); n = (n < 0) ? 0 : n; n = (n > length) ? length : n; return n; } int TLSampleMethodResistive(struct TLStruct * data, uint8_t nSensors, uint8_t ch) { struct TLStruct * d; d = &(data[ch]); d->sampleMethodPreSample = TLSampleMethodResistivePreSample; d->sampleMethodSample = TLSampleMethodResistiveSample; d->sampleMethodPostSample = TLSampleMethodResistivePostSample; d->sampleMethodMapDelta = TLSampleMethodResistiveMapDelta; d->tlStructSampleMethod.resistive.pin = A0 + ch; d->tlStructSampleMethod.resistive.gndPin = ch + TL_SAMPLE_METHOD_RESISTIVE_GND_PIN; d->tlStructSampleMethod.resistive.useInternalPullup = TL_SAMPLE_METHOD_RESISTIVE_USE_INTERNAL_PULLUP; d->referenceValue = TL_REFERENCE_VALUE_DEFAULT; d->offsetValue = TL_OFFSET_VALUE_DEFAULT; d->scaleFactor = TL_SCALE_FACTOR_DEFAULT; d->setOffsetValueManually = TL_SET_OFFSET_VALUE_MANUALLY_DEFAULT; d->tlStructSampleMethod.resistive.valueMax = TL_VALUE_MAX_DEFAULT; d->releasedToApproachedThreshold = TL_RELEASED_TO_APPROACHED_THRESHOLD_DEFAULT; d->approachedToReleasedThreshold = TL_APPROACHED_TO_RELEASED_THRESHOLD_DEFAULT; d->approachedToPressedThreshold = TL_APPROACHED_TO_PRESSED_THRESHOLD_DEFAULT; d->pressedToApproachedThreshold = TL_PRESSED_TO_APPROACHED_THRESHOLD_DEFAULT; d->direction = TLStruct::directionNegative; d->sampleType = TLStruct::sampleTypeNormal; d->filterType = TLStruct::filterTypeAverage; d->waterRejectPin = -1; d->waterRejectMode = TLStruct::waterRejectModeFloat; d->pin = &(d->tlStructSampleMethod.resistive.pin); return 0; }
30.439216
98
0.725457
zvikapika
54a443e2c8ec66c132e17f3cf36b936fba077140
2,224
cc
C++
src/LockManagerTest.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/LockManagerTest.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/LockManagerTest.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
/* * LockManagerTest.cc * * Created on: Dec 8, 2016 * Author: theo */ #include <cassert> #include <iostream> #include "AVLTreeLockManager.h" #include "LockManager.h" #include "LockManagerTest.h" #include "TestEvent.h" LockManagerTest::LockManagerTest(LockManager *lock_manager) { _lock_manager = lock_manager; } void LockManagerTest::run() { uint64_t last = 1; // Unit tests for tryBackwardLock. assert(_lock_manager->tryBackwardLock(0, 0, 3, false, new TestEvent(1), &last)); assert(last == 0); assert(!_lock_manager->tryBackwardLock(0, 1, 4, true, new TestEvent(2), &last)); assert(last == 3); // Unit tests for tryLock. assert(_lock_manager->tryLock(1, 0, 5, 15, false)); assert(!_lock_manager->tryLock(1, 1, 1, 5, true)); // Unit tests for freeze. _lock_manager->freeze(0); assert(_lock_manager->tryBackwardLock(0, 1, 3, true, new TestEvent(2), &last)); assert(last == 3); // Unit tests for unlock. _lock_manager->unlock(1); assert(_lock_manager->tryBackwardLock(0, 2, 5, false, new TestEvent(3), &last)); assert(last == 3); _lock_manager->unlock(2); // More sophisticated test. assert(_lock_manager->tryBackwardLock(2, 3, 15, true, new TestEvent(3), &last)); assert(last == 0); assert(_lock_manager->tryBackwardLock(2, 4, 30, true, new TestEvent(4), &last)); assert(last == 0); assert(_lock_manager->tryLock(2, 4, 31, 35, false)); assert(!_lock_manager->tryLock(2, 5, 5, 5, false)); assert(!_lock_manager->tryBackwardLock(2, 6, 40, true, new TestEvent(6), &last)); assert(last == 35); _lock_manager->freeze(3); _lock_manager->freeze(4); assert(_lock_manager->tryBackwardLock(2, 6, 35, true, new TestEvent(6), &last)); assert(last == 35); assert(_lock_manager->tryBackwardLock(2, 7, 50, true, new TestEvent(7), &last)); assert(_lock_manager->tryLock(2, 7, 51, 55, false)); assert(!_lock_manager->tryBackwardLock(2, 8, 70, true, new TestEvent(8), &last)); assert(last == 55); _lock_manager->unlock(6); _lock_manager->unlock(7); assert(_lock_manager->tryBackwardLock(2, 8, 55, true, new TestEvent(8), &last)); assert(last == 35); _lock_manager->freeze(8); std::cout << "Lock Manager Test Successful." << std::endl; }
32.231884
83
0.680306
mkaguilera
54ac1b1efbf79f072467343fcf1c14cad3983c15
1,803
cpp
C++
code/cheonsa/cheonsa_platform_icon.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa_platform_icon.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa_platform_icon.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
#include "cheonsa_platform_icon.h" #include "cheonsa_engine.h" #if defined( cheonsa_platform_windows ) #define WIN32_LEAN_AND_MEAN #include <Windows.h> #undef LoadIcon #endif namespace cheonsa { platform_icon_c::platform_icon_c() : icon_handle( nullptr ) { } platform_icon_c::~platform_icon_c() { unload(); } boolean_c platform_icon_c::load_from_exe( string8_c const & resource_name ) { icon_handle = static_cast< void_c * >( LoadImageA( GetModuleHandleA( NULL ), resource_name.character_list.get_internal_array(), IMAGE_ICON, 0, 0, 0 ) ); return icon_handle != 0; } boolean_c platform_icon_c::load_from_exe( string16_c const & resource_name ) { icon_handle = static_cast< void_c * >( LoadImageW( GetModuleHandleW( NULL ), resource_name.character_list.get_internal_array(), IMAGE_ICON, 0, 0, 0 ) ); return icon_handle != 0; } boolean_c platform_icon_c::load_from_absolute_file_path( string16_c const & file_path_absolute ) { icon_handle = static_cast< void_c * >( LoadImageW( NULL, file_path_absolute.character_list.get_internal_array(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE ) ); return icon_handle != 0; } boolean_c platform_icon_c::load_from_relative_file_path( string16_c const & file_path_relative ) { unload(); #if defined( cheonsa_platform_windows ) string16_c file_path_absolute; if ( engine.get_content_manager()->resolve_absolute_file_path( file_path_relative, file_path_absolute, true, true ) ) { icon_handle = static_cast< void_c * >( LoadImageW( NULL, file_path_absolute.character_list.get_internal_array(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE ) ); } #endif return icon_handle != 0; } void_c platform_icon_c::unload() { if ( icon_handle ) { DestroyIcon( static_cast< HICON >( icon_handle ) ); icon_handle = nullptr; } } }
28.171875
154
0.747643
Olaedaria
54ad6c6a42ce99c193006d256a63da90fefecfa5
1,005
cc
C++
leveldb/cloud/db_cloud_impl.cc
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
leveldb/cloud/db_cloud_impl.cc
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
leveldb/cloud/db_cloud_impl.cc
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2017 Rockset. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "cloud/db_cloud_impl.h" #include "db/file_util.h" #include <inttypes.h> #include "leveldb/db.h" #include "leveldb/env.h" #include "leveldb/options.h" #include "leveldb/status.h" #include "leveldb/table.h" #include "util/xxhash.h" #include "cloud/aws/aws_env.h" #include "cloud/filename.h" #include "cloud/manifest_reader.h" namespace leveldb { DBCloudImpl::DBCloudImpl(DB* db) : DBCloud(db), cenv_(nullptr) {} DBCloudImpl::~DBCloudImpl() {} Status DBCloud::Open(const Options& options, const std::string& name, DBCloud** dbptr) { Status st; DB* db = nullptr; st = DB::Open(options, name, &db); if (st.ok()) { DBCloudImpl* cloud = new DBCloudImpl(db); *dbptr = cloud; } Log(InfoLogLevel::INFO_LEVEL, options.info_log, "Opened cloud db with local dir %s. %s", name.c_str(), st.ToString().c_str()); return st; } } // namespace leveldb
21.382979
69
0.677612
naivewong
2a6150c024f6de94d3415ca38faf869bf06cf2ba
2,776
cpp
C++
source/sprites/AnchorSprite.cpp
xzrunner/sprite2
2d5d8c6b79a63871bdd6cfdcd4805946fde95921
[ "MIT" ]
null
null
null
source/sprites/AnchorSprite.cpp
xzrunner/sprite2
2d5d8c6b79a63871bdd6cfdcd4805946fde95921
[ "MIT" ]
null
null
null
source/sprites/AnchorSprite.cpp
xzrunner/sprite2
2d5d8c6b79a63871bdd6cfdcd4805946fde95921
[ "MIT" ]
null
null
null
#include "sprite2/AnchorSprite.h" #include "sprite2/AnchorActor.h" #include "sprite2/SprVisitorParams.h" #include "sprite2/ActorFactory.h" #include "sprite2/UpdateParams.h" #include "sprite2/SpriteVisitor.h" namespace s2 { void AnchorSprite::OnMessage(const UpdateParams& up, Message msg) { auto actor = up.GetActor(); auto anchor = QueryAnchor(actor); if (!anchor) { return; } UpdateParams up_child(up); up_child.Push(this); auto anchor_spr = anchor->GetSprRaw(); up_child.SetActor(anchor_spr->QueryActor(actor)); const_cast<Sprite*>(anchor_spr)->OnMessage(up_child, msg); } bool AnchorSprite::Update(const UpdateParams& up) { auto actor = up.GetActor(); auto anchor = QueryAnchor(actor); if (!anchor) { return false; } auto spr_real = anchor->GetSprRaw(); // update inherit if (!up.IsForce() && !spr_real->IsInheritUpdate()) { return false; } auto actor_real = spr_real->QueryActor(actor); // visible bool visible = actor_real ? actor_real->IsVisible() : spr_real->IsVisible(); if (!visible) { return false; } UpdateParams up_child(up); up_child.Push(this); up_child.SetActor(actor_real); bool ret = const_cast<Sprite*>(spr_real)->Update(up_child); return ret; } SprPtr AnchorSprite::FetchChildByName(int name, const ActorConstPtr& actor) const { auto anchor = QueryAnchor(actor.get()); if (anchor) { auto anchor_spr = anchor->GetSprRaw(); return anchor_spr->FetchChildByName(name, anchor_spr->QueryActorRef(actor.get())); } else { return nullptr; } } SprPtr AnchorSprite::FetchChildByIdx(int idx, const ActorPtr& actor) const { auto anchor = QueryAnchor(actor.get()); if (anchor) { auto anchor_spr = anchor->GetSprRaw(); return anchor_spr->FetchChildByIdx(idx, anchor_spr->QueryActorRef(actor.get())); } else { return nullptr; } } VisitResult AnchorSprite::TraverseChildren(SpriteVisitor& visitor, const SprVisitorParams& params) const { VisitResult ret = VISIT_OVER; auto& actor = params.actor; auto anchor = actor ? static_cast<const AnchorActor*>(actor)->GetAnchorPtr() : nullptr; if (anchor) { SprVisitorParams cp = params; cp.actor = anchor.get(); SpriteVisitor::VisitChild(visitor, cp, anchor->GetSpr(), ret); } return ret; } VisitResult AnchorSprite::TraverseChildren2(SpriteVisitor2& visitor, const SprVisitorParams2& params) const { auto& actor = params.actor; auto anchor = actor ? S2_VI_PTR_DOWN_CAST<const AnchorActor>(actor)->GetAnchorPtr() : nullptr; if (anchor) { SprVisitorParams2 cp = params; cp.actor = anchor; return anchor->GetSprRaw()->TraverseChildren2(visitor, cp); } else { return VISIT_OVER; } } const Actor* AnchorSprite::QueryAnchor(const Actor* actor) const { return actor ? S2_VI_DOWN_CAST<const AnchorActor*>(actor)->GetAnchor() : nullptr; } }
24.785714
107
0.729107
xzrunner
2a627c41c871456a988c75e915226c7cc75efd87
338
hpp
C++
Phoenix3D/Tools/MaxToPX2/PX2Mtls.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
36
2016-04-24T01:40:38.000Z
2022-01-18T07:32:26.000Z
Phoenix3D/Tools/MaxToPX2/PX2Mtls.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
null
null
null
Phoenix3D/Tools/MaxToPX2/PX2Mtls.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
16
2016-06-13T08:43:51.000Z
2020-09-15T13:25:58.000Z
// PX2Mtls.hpp #ifndef PX2MTLS_HPP #define PX2MTLS_HPP #include "PX2MaxToPX2PluginPre.hpp" class Mtl; class Mtls { public: Mtls (); bool Add (Mtl *mtl); void SetQuantity (int quantity); int GetQuantity () const; int GetIndex (Mtl *mtl) const; Mtl *GetMtl (int mtlIndex) const; private: std::vector<Mtl*> mMaterial; }; #endif
13.52
35
0.707101
PheonixFoundation
2a654d6baafef17060e8aabe64bc0de8e7fa9c7e
2,831
hpp
C++
include/trainer/GradientDescent.hpp
YSZhuoyang/CudaNeuralNetwork
1c7d5d6ae8e8bb622e7fcbbac2e3db487a202157
[ "MIT" ]
null
null
null
include/trainer/GradientDescent.hpp
YSZhuoyang/CudaNeuralNetwork
1c7d5d6ae8e8bb622e7fcbbac2e3db487a202157
[ "MIT" ]
null
null
null
include/trainer/GradientDescent.hpp
YSZhuoyang/CudaNeuralNetwork
1c7d5d6ae8e8bb622e7fcbbac2e3db487a202157
[ "MIT" ]
null
null
null
#include "model/MiniNeuralNets.hpp" #ifndef GRADIENT_DESCENT_HPP #define GRADIENT_DESCENT_HPP namespace MiniNeuralNetwork { using namespace MyHelper; class Trainer { public: Trainer( std::shared_ptr<MiniNeuralNets> neuralNets, cublasHandle_t cublasHandle ); ~Trainer(); void train( const float* featureMat, const unsigned short* classIndexMat, const unsigned int numInstances, const unsigned int maxIter, const float learningRate, const float regularParam, const float costThreshold ); void test( const float* featureMat, const unsigned short* classIndexMat, const unsigned int numInstances ); private: inline void forwardProp( Layer* layers, const unsigned int numInstances, cudaStream_t stream1 ); inline void backwardProp( Layer* layers, const unsigned short* dClassIndexMat, const unsigned int numInstances, const float learningParam, const float regularParam, cudaStream_t stream1, cudaStream_t stream2 ); inline void forwardOutput( const Layer& sourceLayer, const Layer& targetLayer, const Connection& connection, const unsigned int numInstances, const std::shared_ptr<ActivationFunction> actFunction, cublasHandle_t cublasHandle, cudaStream_t stream ); inline void backPropError( const Layer& sourceLayer, const Layer& targetLayer, const Connection& connection, const unsigned int numInstances, const std::shared_ptr<ActivationFunction> actFunction, cublasHandle_t cublasHandle, cudaStream_t stream ); inline void updateWeights( const Layer& sourceLayer, const Layer& targetLayer, const Connection& connection, const unsigned int numInstances, const float learningParam, const float regularParam, cublasHandle_t cublasHandle, cudaStream_t stream ); std::shared_ptr<MiniNeuralNets> neuralNets = nullptr; cudaEvent_t* backPropCompletes = nullptr; cudaEvent_t forwardPropComplete; cudaEvent_t trainingComplete; cudaEvent_t testComplete; cublasHandle_t cublasHandle; }; } #endif
34.52439
70
0.553161
YSZhuoyang
2a6942c1f475a9950905d0b87a438fcefc38bc2e
415
hpp
C++
player/include/api/oauth.hpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
36
2018-03-09T08:05:32.000Z
2021-09-09T19:06:39.000Z
player/include/api/oauth.hpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
35
2018-03-15T06:43:49.000Z
2021-04-14T00:07:00.000Z
player/include/api/oauth.hpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
3
2018-05-18T21:17:05.000Z
2021-09-09T19:06:42.000Z
#pragma once #include <QObject> #include <QtPromise> class QTcpServer; class QNetworkRequest; using QtPromise::QPromise; class OAuth: public QObject { Q_OBJECT public: OAuth(QObject * = nullptr); QPromise<QString> query_token(); signals: void token_ready(QString); private: QTcpServer *_local_server; void fetch_token(const QUrl &); void save_token_data(const QByteArray &); };
14.821429
45
0.713253
Globidev
2a6a6bf76801e28205566b223c22881582591332
2,303
cpp
C++
src/configuration/CallCost.cpp
Governikus/AusweisApp2-Omapi
0d563e61cb385492cef96c2542d50a467e003259
[ "Apache-2.0" ]
1
2019-06-06T11:58:51.000Z
2019-06-06T11:58:51.000Z
src/configuration/CallCost.cpp
ckahlo/AusweisApp2-Omapi
5141b82599f9f11ae32ff7221b6de3b885e6e5f9
[ "Apache-2.0" ]
1
2022-01-28T11:08:59.000Z
2022-01-28T12:05:33.000Z
src/configuration/CallCost.cpp
ckahlo/AusweisApp2-Omapi
5141b82599f9f11ae32ff7221b6de3b885e6e5f9
[ "Apache-2.0" ]
3
2019-06-06T11:58:14.000Z
2021-11-15T23:32:04.000Z
/*! * \copyright Copyright (c) 2016-2019 Governikus GmbH & Co. KG, Germany */ #include "CallCost.h" #include <QDebugStateSaver> #include <QJsonObject> using namespace governikus; namespace { inline double getValue(const QJsonValue& pJson, const char* pSection, const char* pSubSection) { return pJson.toObject()[QLatin1String(pSection)].toObject()[QLatin1String(pSubSection)].toDouble(); } } // namespace CallCost::CallCost(int pFreeSeconds, double pLandlineCentsPerMinute, double pLandlineCentsPerCall, double pMobileCentsPerMinute, double pMobileCentsPerCall) : mFreeSeconds(pFreeSeconds) , mLandlineCentsPerMinute(pLandlineCentsPerMinute) , mLandlineCentsPerCall(pLandlineCentsPerCall) , mMobileCentsPerMinute(pMobileCentsPerMinute) , mMobileCentsPerCall(pMobileCentsPerCall) { } CallCost::CallCost(const QJsonValue& pJson) : mFreeSeconds(pJson.toObject()[QLatin1String("free-seconds")].toInt()) , mLandlineCentsPerMinute(getValue(pJson, "landline", "per-minute")) , mLandlineCentsPerCall(getValue(pJson, "landline", "per-call")) , mMobileCentsPerMinute(getValue(pJson, "mobile", "per-minute")) , mMobileCentsPerCall(getValue(pJson, "mobile", "per-call")) { } bool CallCost::isNull() const { return mFreeSeconds == 0 && mLandlineCentsPerMinute == 0.0 && mLandlineCentsPerCall == 0.0 && mMobileCentsPerMinute == 0.0 && mMobileCentsPerCall == 0.0; } int CallCost::getFreeSeconds() const { return mFreeSeconds; } double CallCost::getLandlineCentsPerMinute() const { return mLandlineCentsPerMinute; } double CallCost::getLandlineCentsPerCall() const { return mLandlineCentsPerCall; } double CallCost::getMobileCentsPerMinute() const { return mMobileCentsPerMinute; } double CallCost::getMobileCentsPerCall() const { return mMobileCentsPerCall; } QDebug operator<<(QDebug pDbg, const CallCost& pCallCost) { QDebugStateSaver saver(pDbg); if (pCallCost.isNull()) { pDbg.nospace() << "CallCost(null)"; } else { pDbg.nospace() << "CallCost(free=" << pCallCost.getFreeSeconds() << ", ll-call=" << pCallCost.getLandlineCentsPerCall() << ", ll-min=" << pCallCost.getLandlineCentsPerMinute() << ", mob-call=" << pCallCost.getMobileCentsPerCall() << ", mob-min=" << pCallCost.getMobileCentsPerMinute() << ")"; } return pDbg; }
23.989583
156
0.740773
Governikus
2a6d4c7bbd84e16ea24743ee7c718f2fb44bb50f
26,375
cpp
C++
test/Account_Test.cpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
1
2021-04-24T06:01:57.000Z
2021-04-24T06:01:57.000Z
test/Account_Test.cpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
null
null
null
test/Account_Test.cpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************* * Author: Keith Adkins * Date Created: 2/12/2017 * Last Modified: 2/14/2017 * Course: CS467, Winter 2017 * Filename: Account_Test.cpp * * Overview: * Unit test for the Account class. ************************************************************************/ #include <Account.hpp> #include <string> #include <iostream> #include <stdio.h> #include <gtest/gtest.h> namespace { std::string fileName = "legacy_mud_accounts.txt"; // txt file for account data /* Testing with no accounts in the account system. */ TEST(AccountTest, NoAccounts) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Save the account to disk. Clearing any account data stored in the file. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are no accounts."; /* Check if a username is unique. */ EXPECT_TRUE(acc.uniqueUsername("Steve") ) << "Expect true since this username is not the account system."; /* Verify an account. */ EXPECT_FALSE(acc.verifyAccount("Linda", "somepassword") ) << "Expect false since this account is not in the system. "; /* Verify admin status of a user. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false since this user is not in the system."; /* Set the admin of a user. */ EXPECT_FALSE(acc.setAdmin("Linda", false ) ) << "Expect false since this user is not in the system."; /* Changing password. */ EXPECT_FALSE(acc.changePassword("China", "newPassword" ) ) << "Expect false since this user is not in the system."; /* Get UserId. */ EXPECT_EQ(0, acc.getUserId("China" ) ) << "Expect 0 since this user is not in the system."; /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are no accounts."; remove(fileName.c_str()); // delete the account system file } /* Testing with one created account in the account system. */ TEST(AccountTest, OneAccount) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Linda", "validpassword", true, 1 ) ) << "Expect true since this is a valid account creation."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is one account."; /* Save the account to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is one account."; /* Try to create second account with the same username. */ EXPECT_FALSE(acc.createAccount("Linda", "1234", false, 2 ) ) << "Expect false since this username is not unique."; /* Check if a username is unique. Testing with a username this is already in the account system. */ EXPECT_FALSE(acc.uniqueUsername("Linda") ) << "Expect false since this username is in the account system."; /* Check if a username is unique. Testing with a username not in the account system.*/ EXPECT_TRUE(acc.uniqueUsername("George") ) << "Expect true since this username is not in the account system."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "1234") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.verifyAccount("Sally", "password4") ) << "Expect false since this username is invalid."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true this user is an admin."; /* Verify admin status of a user. Testing with invalid username. */ EXPECT_FALSE(acc.verifyAdmin("Mike" ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Linda", false ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false Linda is not an admin."; /* Set the admin of a user. Testing with an invalid username. */ EXPECT_FALSE(acc.setAdmin("George", false ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to true. */ EXPECT_TRUE(acc.setAdmin("Linda", true ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true since this user is now an admin."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(1, acc.getUserId("Linda" ) ) << "Expect 1 since this is the correct user id."; /* Get userId. Testing with invalid username. */ EXPECT_EQ(0, acc.getUserId("Mike" ) ) << "Expect 0 since this username is invalid."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Linda", "newPassword" ) ) << "Expect true since this user a valid account."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "newPassword") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "validpassword") ) << "Expect false since the password is invalid."; /* Changing password. Testing with invalid username. */ EXPECT_FALSE(acc.changePassword("George", "newPassword" ) ) << "Expect false since George is an invalid username."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is only one account."; /* Delete an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.deleteAccount("Betty") ) << "Expect false since the username is valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Linda") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there is are no longer any accounts."; remove(fileName.c_str()); // delete the account system file } /* Testing with two created accounts in the account system. */ TEST(AccountTest, TwoAccounts) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Linda", "validpassword1", true, 1 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Kris", "validpassword2", false, 2 ) ) << "Expect true since this is a valid account creation."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Save the account to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Try to create second account with the same username. */ EXPECT_FALSE(acc.createAccount("Kris", "1234", false, 2 ) ) << "Expect false since this username is not unique."; /* Check if a username is unique. Testing with a username this is already in the account system. */ EXPECT_FALSE(acc.uniqueUsername("Kris") ) << "Expect false since this username is in the account system."; /* Check if a username is unique. Testing with a username not in the account system.*/ EXPECT_TRUE(acc.uniqueUsername("George") ) << "Expect true since this username is not in the account system."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "1234") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Kris", "invalidpassword") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.verifyAccount("Sally", "password4") ) << "Expect false since this username is invalid."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true this user is an admin."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_FALSE(acc.verifyAdmin("Kris" ) ) << "Expect false since this user is not an admin."; /* Verify admin status of a user. Testing with invalid username. */ EXPECT_FALSE(acc.verifyAdmin("Mike" ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Linda", false ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false since this user is not an admin."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Kris", true ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_TRUE(acc.verifyAdmin("Kris" ) ) << "Expect true since this user is now an admin."; /* Set the admin of a user. Testing with an invalid username. */ EXPECT_FALSE(acc.setAdmin("George", false ) ) << "Expect false since this username is invalid."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(1, acc.getUserId("Linda" ) ) << "Expect 1 since this is the correct user id."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(2, acc.getUserId("Kris" ) ) << "Expect 2 since this is the correct user id."; /* Get userId. Testing with invalid username. */ EXPECT_EQ(0, acc.getUserId("Mike" ) ) << "Expect 0 since this username is invalid."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Linda", "newPassword1" ) ) << "Expect true since this user a valid account."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Kris", "newPassword2" ) ) << "Expect true since this user a valid account."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "newPassword1") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Kris", "newPassword2") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect false since the password is invalid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect false since the password is invalid."; /* Changing password. Testing with invalid username. */ EXPECT_FALSE(acc.changePassword("George", "newPassword" ) ) << "Expect false since George is an invalid username."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Delete an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.deleteAccount("Betty") ) << "Expect false since the username is valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Linda") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is now one account."; /* Verify account of deleted user. */ EXPECT_FALSE(acc.verifyAccount("Linda", "newPassword1") ) << "Expect false since this username is deleted from the system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Kris", "newPassword2") ) << "Expect true since the username and password are valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Kris") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there no accounts."; remove(fileName.c_str()); // delete the account system file } /* Testing with Mutliple accounts in the account system. */ TEST(AccountTest, MultipleAccounts) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Linda", "validpassword1", true, 1 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Kris", "validpassword2", false, 2 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Sue", "validpassword3", false, 3 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Mike", "validpassword4", false, 4 ) ) << "Expect true since this is a valid account creation."; /* Get the number of accounts in the account system. */ EXPECT_EQ(4, acc.getNumberOfAccounts() ) << "Expect 4 since there are four accounts."; /* Save the account to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(4, acc.getNumberOfAccounts() ) << "Expect 4 since there are four accounts."; /* Try to create second account with the same username. */ EXPECT_FALSE(acc.createAccount("Mike", "1234", false, 2 ) ) << "Expect false since this username is not unique."; /* Check if a username is unique. Testing with a username this is already in the account system. */ EXPECT_FALSE(acc.uniqueUsername("Kris") ) << "Expect false since this username is in the account system."; /* Check if a username is unique. Testing with a username not in the account system.*/ EXPECT_TRUE(acc.uniqueUsername("George") ) << "Expect true since this username is not in the account system."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Mike", "validpassword4") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Mike", "1234") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Sue", "validpassword3") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Sue", "invalidpassword") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.verifyAccount("Sally", "password4") ) << "Expect false since this username is invalid."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true this user is an admin."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_FALSE(acc.verifyAdmin("Mike" ) ) << "Expect false since this user is not an admin."; /* Verify admin status of a user. Testing with invalid username. */ EXPECT_FALSE(acc.verifyAdmin("Larry" ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Linda", false ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false since this user is not an admin."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Mike", true ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_TRUE(acc.verifyAdmin("Mike" ) ) << "Expect true since this user is now an admin."; /* Set the admin of a user. Testing with an invalid username. */ EXPECT_FALSE(acc.setAdmin("Larry", false ) ) << "Expect false since this username is invalid."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(4, acc.getUserId("Mike" ) ) << "Expect 4 since this is the correct user id."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(3, acc.getUserId("Sue" ) ) << "Expect 3 since this is the correct user id."; /* Get userId. Testing with invalid username. */ EXPECT_EQ(0, acc.getUserId("Larry" ) ) << "Expect -1 since this username is invalid."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Mike", "newPassword4" ) ) << "Expect true since this user a valid account."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Sue", "newPassword3" ) ) << "Expect true since this user a valid account."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Mike", "newPassword4") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Sue", "newPassword3") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Mike", "validpassword4") ) << "Expect false since the password is invalid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Sue", "validpassword3") ) << "Expect false since the password is invalid."; /* Changing password. Testing with invalid username. */ EXPECT_FALSE(acc.changePassword("George", "newPassword" ) ) << "Expect false since George is an invalid username."; /* Get the number of accounts in the account system. */ EXPECT_EQ(4, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Delete an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.deleteAccount("Betty") ) << "Expect false since the username is valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Mike") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(3, acc.getNumberOfAccounts() ) << "Expect 3 since there are three accounts."; /* Verify account of deleted user. */ EXPECT_FALSE(acc.verifyAccount("Mike", "newPassword4") ) << "Expect false since this username is deleted from the system."; /* Verify account of other user. */ EXPECT_TRUE(acc.verifyAccount("Sue", "newPassword3") ) << "Expect true since the username and password are valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Sue") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are no accounts."; /* Verify account of deleted user. */ EXPECT_FALSE(acc.verifyAccount("Sue", "newPassword3") ) << "Expect false since this user is no longer in the account system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect true since since this user is still in the account system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect true since since this user is still in the account system."; /* Save the account data to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect true since since this user is still in the account system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect true since since this user is still in the account system."; remove(fileName.c_str()); // delete the account system file } }
45.317869
105
0.619905
rigertd
2a6e71a05d077b451507fa23f69677e01d76050b
5,351
cxx
C++
BidirectionalQueue.cxx
jackytck/topcoder
5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3
[ "MIT" ]
null
null
null
BidirectionalQueue.cxx
jackytck/topcoder
5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3
[ "MIT" ]
null
null
null
BidirectionalQueue.cxx
jackytck/topcoder
5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3
[ "MIT" ]
null
null
null
// BEGIN CUT HERE /* // PROBLEM STATEMENT // You are given a bidirectional cyclical queue which contains N elements. You need to extract several elements from this queue. You can do 3 kinds of operations with this queue: Extract first element. After applying this operation, queue a1, ..., aK becomes a2, ..., aK. Shift queue elements left. After applying this operation, queue a1, ..., aK becomes a2, ..., aK, a1. Shift queue elements right. After applying this operation, queue a1, ..., aK becomes aK, a1, ..., aK-1. You are given the initial number of elements in the queue N and a vector <int> indices which contains the initial (1-based) positions of wanted elements in the queue. Return the minimal number of left and right shifts you'll have to perform to extract the wanted elements in the given order. DEFINITION Class:BidirectionalQueue Method:extractElements Parameters:int, vector <int> Returns:int Method signature:int extractElements(int N, vector <int> indices) CONSTRAINTS -N will be between 1 and 50, inclusive. -indices will contain between 1 and N elements, inclusive. -Each element of indices will be between 1 and N, inclusive. -All elements of indices will be distinct. EXAMPLES 0) 10 {1, 2, 3} Returns: 0 The elements are extracted in the same order as they appear in the queue, so no shifts are required. 1) 10 {2, 9, 5} Returns: 8 To extract the first wanted element, 1 left shift is required. After this the next wanted element will be 7th in a queue with 9 elements, so to extract it 3 right shifts are required. Finally, the last wanted element will be 5th in a queue with 8 elements, so either 4 left shifts or 4 right shifts are required. 2) 32 {27, 16, 30, 11, 6, 23} Returns: 59 3) 10 {1, 6, 3, 2, 7, 9, 8, 4, 10, 5} Returns: 14 */ // END CUT HERE #line 68 "BidirectionalQueue.cxx" #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #define sz size() #define PB push_back #define clr(x) memset(x, 0, sizeof(x)) #define forn(i,n) for(__typeof(n) i = 0; i < (n); i++) #define ford(i,n) for(int i = (n) - 1; i >= 0; i--) #define forv(i,v) forn(i, v.sz) #define For(i, st, en) for(__typeof(en) i = (st); i < (en); i++) using namespace std; class BidirectionalQueue { public: int extractElements(int N, vector <int> indices) { int cnt = 0; forv(i, indices) { int left = indices[i]-1, right = N-indices[i]+1; if(left-right<=0) { leftShift(N, indices, left); cnt += left; } else { rightShift(N, indices, right); cnt += right; } extractMin(N, indices); } return cnt; } void extractMin(int& N, vector <int>& indices) { N--; forv(i, indices) indices[i]--; } void leftShift(const int N, vector <int>& indices, int steps) { forv(i, indices) indices[i] -= steps; forv(i, indices) if(indices[i] < 1) indices[i] += N; } void rightShift(const int N, vector <int>& indices, int steps) { forv(i, indices) indices[i] += steps; forv(i, indices) if(indices[i] > N) indices[i] -= N; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 10; int Arr1[] = {1, 2, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(0, Arg2, extractElements(Arg0, Arg1)); } void test_case_1() { int Arg0 = 10; int Arr1[] = {2, 9, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 8; verify_case(1, Arg2, extractElements(Arg0, Arg1)); } void test_case_2() { int Arg0 = 32; int Arr1[] = {27, 16, 30, 11, 6, 23}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 59; verify_case(2, Arg2, extractElements(Arg0, Arg1)); } void test_case_3() { int Arg0 = 10; int Arr1[] = {1, 6, 3, 2, 7, 9, 8, 4, 10, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 14; verify_case(3, Arg2, extractElements(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { BidirectionalQueue ___test; ___test.run_test(-1); } // END CUT HERE
32.041916
312
0.615025
jackytck
2a70b687eb4b63c4533ccc654dccafd36d769adb
800
cpp
C++
example/DetectPortsUDP/detectports.cpp
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
6
2017-08-07T09:22:34.000Z
2019-05-11T09:11:45.000Z
example/DetectPortsUDP/detectports.cpp
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
null
null
null
example/DetectPortsUDP/detectports.cpp
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
2
2018-05-15T23:28:43.000Z
2021-11-13T09:53:40.000Z
#include "detectports.h" #include <iostream> #include <pcapwrapper/helpers/common.h> #include <string.h> #include <string> using namespace PCAP; DetectPorts::DetectPorts(PCAP::IpAddress desiredIp) : m_expectedip{desiredIp} { reset(); } void DetectPorts::receive_package(PCAP::ICMPPackage package) { if (package.get_src_ip() == m_expectedip) { const PCAP::uchar *data = package.get_package(); ushort port = (((ushort)data[64]) << 0x08) | ((ushort)data[65]); m_ports[port] = true; } } std::vector<int> DetectPorts::get_ports() { std::vector<int> result; for (int i = 0; i < MAX_PORT; ++i) { if (!m_ports[i]) result.push_back(i); } reset(); return result; } void DetectPorts::reset() { memset(m_ports, '\0', MAX_PORT); }
24.242424
79
0.6325
jef42
2a716ef7969657991a8e8b2e6e7488473d4b5c4c
7,652
cpp
C++
LookAndFeels/foleys_LookAndFeel.cpp
kant/foleys_gui_magic
1f3da46e497c24ba66cae2ddd7f9cd52fe16b169
[ "BSD-3-Clause" ]
null
null
null
LookAndFeels/foleys_LookAndFeel.cpp
kant/foleys_gui_magic
1f3da46e497c24ba66cae2ddd7f9cd52fe16b169
[ "BSD-3-Clause" ]
null
null
null
LookAndFeels/foleys_LookAndFeel.cpp
kant/foleys_gui_magic
1f3da46e497c24ba66cae2ddd7f9cd52fe16b169
[ "BSD-3-Clause" ]
null
null
null
/* ============================================================================== Copyright (c) 2019 Foleys Finest Audio Ltd. - Daniel Walz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== */ namespace foleys { void LookAndFeel::drawRotarySlider (juce::Graphics& g, int x, int y, int width, int height, float sliderPos, const float rotaryStartAngle, const float rotaryEndAngle, juce::Slider& slider) { const auto outline = slider.findColour (juce::Slider::rotarySliderOutlineColourId); const auto fill = slider.findColour (juce::Slider::rotarySliderFillColourId); const auto text = slider.findColour (juce::Slider::textBoxTextColourId); auto bounds = juce::Rectangle<int> (x, y, width, height).toFloat().reduced (10); auto centre = bounds.getCentre(); const auto tickHeight = 6; const auto tickWidth = 40; auto radius = juce::jmin (bounds.getWidth() / 2.0f, bounds.getHeight() / 2.0f); g.setColour (text); if (radius > tickWidth * 2.0f + 10.0f) { const auto xLeft = int (bounds.getX()); const auto xRight = int (bounds.getRight() - tickWidth); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.5f)), int (centre.getX() - tickWidth / 2), int (bounds.getY()), tickWidth, tickHeight, juce::Justification::centred, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.375f)), xLeft, int (bounds.getY()), tickWidth, tickHeight, juce::Justification::left, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.25f)), xLeft, int (juce::jmap (0.33f, float (bounds.getY()), bounds.getBottom() - tickHeight)), tickWidth, tickHeight, juce::Justification::left, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.125f)), xLeft, int (juce::jmap (0.66f, float (bounds.getY()), bounds.getBottom() - tickHeight)), tickWidth, tickHeight, juce::Justification::left, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.0f)), xLeft, int (bounds.getBottom() - tickHeight), tickWidth, tickHeight, juce::Justification::left, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.625f)), xRight, int (bounds.getY()), tickWidth, tickHeight, juce::Justification::right, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.75f)), xRight, int (juce::jmap (0.33f, float (bounds.getY()), bounds.getBottom() - tickHeight)), tickWidth, tickHeight, juce::Justification::right, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (0.875f)), xRight, int (juce::jmap (0.66f, float (bounds.getY()), bounds.getBottom() - tickHeight)), tickWidth, tickHeight, juce::Justification::right, 1); g.drawFittedText (slider.getTextFromValue (slider.proportionOfLengthToValue (1.0f)), xRight, int (bounds.getBottom() - tickHeight), tickWidth, tickHeight, juce::Justification::right, 1); bounds.removeFromTop (tickHeight + 4.0f); bounds.reduce (tickWidth, 0.0f); } radius = juce::jmin (bounds.getWidth() / 2.0f, bounds.getHeight() / 2.0f); centre = bounds.getCentre(); if (radius > 50.0f) { for (int i = 0; i < 9; ++i) { const auto angle = juce::jmap (i / 8.0f, rotaryStartAngle, rotaryEndAngle); const auto point = centre.getPointOnCircumference (radius - 2.0f, angle); g.fillEllipse (point.getX() - 3, point.getY() - 3, 6, 6); } radius -= 10.0f; } auto toAngle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle); auto lineW = juce::jmin (4.0f, radius * 0.5f); auto arcRadius = radius - lineW; juce::Path backgroundArc; backgroundArc.addCentredArc (bounds.getCentreX(), bounds.getCentreY(), arcRadius, arcRadius, 0.0f, rotaryStartAngle, rotaryEndAngle, true); g.setColour (outline); g.strokePath (backgroundArc, juce::PathStrokeType (lineW, juce::PathStrokeType::curved, juce::PathStrokeType::butt)); auto knobRadius = std:: max (radius - 3.0f * lineW, 10.0f); { juce::Graphics::ScopedSaveState saved (g); if (slider.isEnabled()) { juce::ColourGradient fillGradient (outline.brighter(), centre.getX() + lineW * 2.0f, centre.getY() - lineW * 4.0f, outline, centre.getX() + knobRadius, centre.getY() + knobRadius, true); g.setGradientFill (fillGradient); } g.fillEllipse (centre.getX() - knobRadius, centre.getY() - knobRadius, knobRadius * 2.0f, knobRadius * 2.0f); } knobRadius = std:: max (knobRadius - 4.0f, 10.0f); g.setColour (outline.brighter()); g.drawEllipse (centre.getX() - knobRadius, centre.getY() - knobRadius, knobRadius * 2.0f, knobRadius * 2.0f, 2.0f); if (slider.isEnabled() && arcRadius > 10.0f) { juce::Path valueArc; valueArc.addCentredArc (bounds.getCentreX(), bounds.getCentreY(), arcRadius, arcRadius, 0.0f, rotaryStartAngle, toAngle, true); g.setColour (fill); g.strokePath (valueArc, juce::PathStrokeType (lineW, juce::PathStrokeType::curved, juce::PathStrokeType::butt)); } juce::Path p; p.startNewSubPath (centre.getPointOnCircumference (knobRadius - lineW, toAngle)); p.lineTo (centre.getPointOnCircumference ((knobRadius - lineW) * 0.6f, toAngle)); g.strokePath (p, juce::PathStrokeType (lineW, juce::PathStrokeType::curved, juce::PathStrokeType::rounded)); } } // namespace foleys
56.264706
240
0.639049
kant
2a7430b597e42f3c2664caf971798c9abf0d953d
261
cpp
C++
Demo_03/main.cpp
vitahlin/VitahCmake
a5360ca9ce548fa16f40e98e2a7985d5fd6978cf
[ "MIT" ]
null
null
null
Demo_03/main.cpp
vitahlin/VitahCmake
a5360ca9ce548fa16f40e98e2a7985d5fd6978cf
[ "MIT" ]
null
null
null
Demo_03/main.cpp
vitahlin/VitahCmake
a5360ca9ce548fa16f40e98e2a7985d5fd6978cf
[ "MIT" ]
null
null
null
#include <iostream> #include "demo3.h" using namespace std; int main(int argc, char *argv[]) { cout << "This is Demo_3 " << endl; cout << "Max Num is " << MAX_NUM << endl; cout << "Double Max num is " << doubleNum(MAX_NUM) << endl; return 0; }
23.727273
63
0.59387
vitahlin
2a76a31ba0ab047a5f2ea5ec719e10c36b35931b
4,220
cpp
C++
DSP/extensions/WindowFunctionLib/tests/TTTukeyWindow.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
31
2015-02-28T23:51:10.000Z
2021-12-25T04:16:01.000Z
DSP/extensions/WindowFunctionLib/tests/TTTukeyWindow.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
126
2015-01-01T13:42:05.000Z
2021-07-13T14:11:42.000Z
DSP/extensions/WindowFunctionLib/tests/TTTukeyWindow.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
14
2015-02-10T15:08:32.000Z
2019-09-17T01:21:25.000Z
/** @file * * @ingroup dspWindowFunctionLib * * @brief Unit tests for the Tukey Window Function Unit * * @details * * @authors Nathan Wolek, Tim Place, Trond Lossius * * @copyright Copyright © 2011 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTWindowFunction.h" #include "TTTukeyWindow.h" /* * coefficients calculated using Octave using these variables and commands: * alpha = 0.5 * alphaOverTwo = alpha / 2 * twoOverAlpha = 2 / alpha * x = 0.0:1/127:1.0 * n = 1:length(x) * y = * if x(n) < alphaOverTwo * y(n) = 0.5 * (1 + cos ( pi * ((twoOverAlpha * x(n) ) - 1))); * else * if x(n) > (1 - alphaOverTwo) * y(n) = 0.5 * (1 + cos ( pi * ((twoOverAlpha * x(n) ) - twoOverAlpha + 1))); * else * y(n) = 1; * end * end */ static TTFloat64 sTukeyWindowCoefficients128[128] = { 0, 0.002445670414196688, 0.009758756441687333, 0.0218677164899363, 0.03865409245759671, 0.0599536685724058, 0.08555807786180814, 0.1152168405407152, 0.148639814375505, 0.1855000330531288, 0.2254369047884639, 0.2680597398789554, 0.3129515726976034, 0.3596732407349534, 0.4077676807861221, 0.4567644002546273, 0.5061840798316815, 0.5555432625244022, 0.6043590831616676, 0.6521539921103681, 0.6984604269914436, 0.7428253866937918, 0.7848148629399286, 0.8240180860508026, 0.8600515433748003, 0.8925627310699273, 0.9212336025366787, 0.9457836797666722, 0.9659727971697173, 0.9816034510373285, 0.9925227316586316, 0.9986238191873873, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9986238191873873, 0.9925227316586317, 0.9816034510373286, 0.9659727971697174, 0.9457836797666723, 0.9212336025366786, 0.8925627310699273, 0.8600515433748003, 0.8240180860508026, 0.7848148629399287, 0.7428253866937922, 0.698460426991444, 0.6521539921103678, 0.6043590831616674, 0.5555432625244022, 0.5061840798316815, 0.4567644002546273, 0.4077676807861222, 0.3596732407349537, 0.3129515726976038, 0.2680597398789558, 0.2254369047884637, 0.1855000330531288, 0.148639814375505, 0.1152168405407152, 0.08555807786180825, 0.05995366857240592, 0.03865409245759677, 0.02186771648993618, 0.009758756441687333, 0.002445670414196688, 0 }; TTErr TukeyWindow::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; int badSampleCount = 0; TTAudioObjectBasePtr windowObject = NULL; TTAudioSignalPtr input = NULL; TTAudioSignalPtr output = NULL; int N = 128; TTValue v; TTFloat64 testAlpha = 0.5; // setup windowObject TTObjectBaseInstantiate(TT("WindowFunction"), &windowObject, TTValue(1)); windowObject->setAttributeValue(TT("function"), TT("tukey")); windowObject->setAttributeValue(TT("mode"), TT("apply")); // set the value for alpha windowObject->setAttributeValue(TT("alpha"), testAlpha); TTTestLog("alpha was set to %.10f for test", testAlpha); // create 1 channel audio signal objects TTObjectBaseInstantiate(kTTSym_audiosignal, &input, 1); TTObjectBaseInstantiate(kTTSym_audiosignal, &output, 1); input->allocWithVectorSize(N); output->allocWithVectorSize(N); // create a signal to be transformed and then process it) input->fill(1.0); windowObject->process(input, output); // now test the output for (int n=0; n<N; n++) { TTBoolean result = !TTTestFloatEquivalence(output->mSampleVectors[0][n], sTukeyWindowCoefficients128[n]); badSampleCount += result; if (result) TTTestLog("BAD SAMPLE @ n=%i ( value=%.10f expected=%.10f )", n, output->mSampleVectors[0][n], sTukeyWindowCoefficients128[n]); } TTTestAssertion("Produces correct window coefficients", badSampleCount == 0, testAssertionCount, errorCount); if (badSampleCount) TTTestLog("badSampleCount is %i", badSampleCount); TTObjectBaseRelease(&input); TTObjectBaseRelease(&output); TTObjectBaseRelease(&windowObject); // wrap up test results and pass back to whoever called test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); }
37.017544
161
0.714455
avilleret
2a78d8daff5be631583e25777900db0800f3ef00
5,293
hpp
C++
src/evaluate.hpp
CristianCin/randMathFunction
9394d039b2c42df70f96479ba95bada3b6257b4e
[ "MIT" ]
null
null
null
src/evaluate.hpp
CristianCin/randMathFunction
9394d039b2c42df70f96479ba95bada3b6257b4e
[ "MIT" ]
null
null
null
src/evaluate.hpp
CristianCin/randMathFunction
9394d039b2c42df70f96479ba95bada3b6257b4e
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define PI 3.14159265 bool dbg = false; bool isF(string op){ if(op == "sin") return true; if(op == "cos") return true; if(op == "tan") return true; if(op == "cotan") return true; if(op == "arcsin") return true; if(op == "arccos") return true; if(op == "arctan") return true; if(op == "arccotan") return true; if(op == "sqrt") return true; if(op == "log_2") return true; if(op == "ln") return true; if(op == "log_3") return true; if(op == "log_4") return true; if(op == "log_5") return true; if(op == "log_6") return true; if(op == "log_7") return true; if(op == "log_8") return true; if(op == "log_9") return true; if(op == "log") return true; return false; } int prec(string c) { if(isF(c)) return 4; if(c == "^") return 3; if(c == "*" || c == "/") return 2; if(c == "+" || c == "-") return 1; return -1; } bool isO(string op){ return (prec(op) > 0 || isF(op))? true : false; } vector<string> infixToPostfix(vector<string> s) { stack<string> st; int l = s.size(); vector<string> ns; for(int i = 0; i < l; i++) { if(isO(s[i]) == false && isF(s[i]) == false && s[i] != "(" && s[i] != ")") ns.push_back(s[i]); else if(s[i] == "(") st.push("("); else if(s[i] == ")") { while(!st.empty() && st.top() != "(") { ns.push_back(st.top()); st.pop(); } if(st.top() == "(") st.pop(); } else{ while(!st.empty() && prec(s[i]) < prec(st.top())) { ns.push_back(st.top()); st.pop(); } st.push(s[i]); } } while(!st.empty()) { ns.push_back(st.top()); st.pop(); } return ns; } bool is_number(string number_string) { string::size_type sz; bool is_valid; double parsed_number = 0.0; try { parsed_number = std::stod(number_string, &sz); is_valid = true; } catch(std::exception& ia) { is_valid = false; } return is_valid; } vector<string> tokenization(string token){ string tmp = ""; vector<string> ret; for(int i = 0; i < token.size(); i++){ string x = string(1, token[i]) ; if(x != " "){ if(isO(x) || x == "(" || x == ")" ){ ret.push_back(tmp); ret.push_back(x); tmp = ""; } else tmp += x; }else continue; } if(tmp.size() > 0) ret.push_back(tmp); vector<string> retret; for(auto x : ret) if(x != "") retret.push_back(x); vector<string> newretret; bool flag = false; for(int i = 0; i < retret.size(); i++) if(i > 0 && i + 1 < retret.size() && (isO(retret[i-1]) || retret[i-1] == "(") && retret[i] == "-" && is_number(retret[i+1])) newretret.push_back("-" + retret[i+1]), i++; else newretret.push_back(retret[i]); return newretret; } double apply(double a, double b, string op){ if(op == "+") return a + b; if(op == "-") return a - b; if(op == "*") return a * b; if(op == "/") return a / b; if(op == "^") return pow(a,b); return 0; } double cbl(double base, double arg){ return (double)log10(arg)/(double)log10(base); } double applyF(double a, string op){ if(op == "sin") return sin((a/180)*PI); if(op == "cos") return cos((a/180)*PI); if(op == "tan") return tan((a/180)*PI); if(op == "cotan") return 1/tan((a/180)*PI); if(op == "arcsin") return asin(a) * 180.0 / PI; if(op == "arccos") return acos(a) * 180.0 / PI; if(op == "arctan") return atan(a) * 180.0 / PI; if(op == "arccotan") return PI/2 - atan(a); if(op == "sqrt") return sqrt(a); if(op == "log_2") return log2(a); if(op == "ln") return log(a); if(op == "log_3") return cbl(3,a); if(op == "log_4") return cbl(4,a); if(op == "log_5") return cbl(5,a); if(op == "log_6") return cbl(6,a); if(op == "log_7") return cbl(7,a); if(op == "log_8") return cbl(8,a); if(op == "log_9") return cbl(9,a); if(op == "log") return log10(a); return 0; } double evaluate(string expr){ vector<string> tokens = tokenization(expr); vector<string> post = infixToPostfix(tokens); if(dbg){ for(int i = 0; i < post.size(); i++) cout<<"["<<post[i]<<"]"; cout<<endl; } stack<double> values; for(int i = 0; i < post.size(); i++){ if(isF(post[i]) || isO(post[i])){ if(isF(post[i])){ double value = values.top(); values.pop(); values.push(applyF(value, post[i])); }else{ double value1 = values.top(); values.pop(); double value2 = values.top(); values.pop(); values.push(apply(value2, value1, post[i])); } }else values.push(stold(post[i])); if(dbg){ for(stack<double> tmp = values; !tmp.empty(); tmp.pop()) cout<<tmp.top()<<" "; cout<<endl; } } return values.top(); }
23.317181
132
0.472889
CristianCin
2a7967b87098788b53c5b4a6e9126910d3b5bc77
11,638
cpp
C++
re_vision/src/changeReferenceSystem.cpp
mattjr/structured
0cb4635af7602f2a243a9b739e5ed757424ab2a7
[ "Apache-2.0" ]
14
2015-01-11T02:53:04.000Z
2021-11-25T17:31:22.000Z
re_vision/src/changeReferenceSystem.cpp
skair39/structured
0cb4635af7602f2a243a9b739e5ed757424ab2a7
[ "Apache-2.0" ]
null
null
null
re_vision/src/changeReferenceSystem.cpp
skair39/structured
0cb4635af7602f2a243a9b739e5ed757424ab2a7
[ "Apache-2.0" ]
14
2015-07-21T04:47:52.000Z
2020-03-12T12:31:25.000Z
/** \file changeReferenceSystem.cpp * \brief Changes reference system of points and cameras * * Standalone application for changing the reference system of a point cloud * and a set of cameras * * This file is part of the RoboEarth ROS WP1 package. * * It file was originally created for <a href="http://www.roboearth.org/">RoboEarth</a>. * The research leading to these results has received funding from the European Union Seventh Framework Programme FP7/2007-2013 under grant agreement no248942 RoboEarth. * * Copyright (C) 2011 by <a href="mailto:dorian@unizar.es">Dorian Galvez-Lopez</a>, University of Zaragoza * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * \author Dorian Galvez-Lopez * \version 1.0 * \date 2011 * \image html http://www.roboearth.org/sites/default/files/RoboEarth.org_logo.gif * \image latex http://www.roboearth.org/sites/default/files/RoboEarth.org_logo.gif ***********************************************/ #include <iostream> #include <fstream> #include <opencv/cv.h> #include <opencv/highgui.h> #include <string> #include <vector> #include "DUtils.h" #include "DUtilsCV.h" #include "DVision.h" typedef DVision::PixelPointFile::PixelPoint PixelPoint; typedef DVision::PMVS::PatchFile PatchFile; typedef DVision::PMVS::PatchFile::Patch Patch; typedef DVision::PMVS::CameraFile CameraFile; typedef DVision::PMVS::CameraFile::Camera Camera; typedef DVision::PMVS::PLYFile PLYFile; typedef DVision::PMVS::PLYFile::PLYPoint PLYPoint; using namespace std; using namespace DUtils; // ---------------------------------------------------------------------------- /** * Calculates the transformation needed to describe the points in the * object reference system * @param plypoints * @return a 4x4 transformation matrix */ cv::Mat calculateTransformation(const vector<PLYPoint> &plypoints); /** * Applys a transformation to the points to move them to the object * reference system * @param plypoints * @param oTw transformation from (w)orld to (o)bject */ void transformPoints(vector<PLYPoint> &plypoints, vector<Patch> &sparse_points, const cv::Mat &oTw); /** * Applies the given transformation to the given 3d point * @param x * @param y * @param z * @param s scale (homogeneous coordinates) * @param oTw transformation from (w)orld to (o)bject */ void transformPoint(double &x, double &y, double &z, double s, const cv::Mat &oTw); /** * Applys a transformation to the cameras so that the projection of the new * 3D points be the same as before * @param cameras * @param oTw */ void transformCameras(vector<Camera> &cameras, const cv::Mat &oTw); // ---------------------------------------------------------------------------- void test(const Camera &camera, const PLYPoint &p) { cv::Mat X = (cv::Mat_<double>(4,1) << p.x, p.y, p.z, 1.); cv::Mat x = camera.P * X; x.at<double>(0,0) /= x.at<double>(2,0); x.at<double>(1,0) /= x.at<double>(2,0); cout << "(" << p.x << " " << p.y << " " << p.z << ") --> "; cout << x.at<double>(0,0) << ", " << x.at<double>(1,0) << endl; } // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { if(argc < 7) { cout << "Usage: " << argv[0] << " <camera file> <ply file> <patch file>" " <camera out dir> <out ply file> <out patch file>" << endl; return 1; } string camera_file = argv[1]; string ply_file = argv[2]; string patch_file = argv[3]; string camera_out_dir = argv[4]; string ply_out_file = argv[5]; string patch_out_file = argv[6]; try { cout << "Reading data..." << endl; vector<PLYPoint> plypoints; PLYFile::readFile(ply_file, plypoints); cout << "-- " << plypoints.size() << " PLY points read" << endl; vector<Patch> patches; PatchFile::readFile(patch_file, patches); cout << "-- " << patches.size() << " patches read" << endl; vector<Camera> cameras; CameraFile::readFile(camera_file, cameras); cout << "-- " << cameras.size() << " cameras read" << endl; cout << "Changing reference system..." << endl; #if 0 test(cameras[0], plypoints[10]); test(cameras[0], plypoints[20]); test(cameras[0], plypoints[30]); #endif cv::Mat oTw = calculateTransformation(plypoints); cout << "." << flush; transformPoints(plypoints, patches, oTw); cout << "." << flush; transformCameras(cameras, oTw); cout << "." << endl; #if 0 test(cameras[0], plypoints[10]); test(cameras[0], plypoints[20]); test(cameras[0], plypoints[30]); #endif cout << "Saving..." << endl; PLYFile::saveFile(ply_out_file, plypoints); PatchFile::saveFile(patch_out_file, patches); CameraFile::saveFile(camera_out_dir, cameras); }catch(std::string ex) { std::cout << ex << std::endl; return 1; } return 0; } // ---------------------------------------------------------------------------- cv::Mat calculateTransformation(const vector<PLYPoint> &plypoints) { // the object reference will be the centroid of the point cloud. // the new axes will be oriented according to the principal axis of the cloud if(plypoints.empty()) return cv::Mat::eye(4, 4, CV_64F); cv::Mat samples(plypoints.size(), 3, CV_64FC1); cv::Mat centroid(1, 3, CV_64FC1); centroid = 0.0; /* double minx, maxx, miny, maxy, minz, maxz; minx = maxx = plypoints[0].x; miny = maxy = plypoints[0].y; minz = maxz = plypoints[0].z; */ for(unsigned int i = 0; i < plypoints.size(); ++i) { samples.at<double>(i, 0) = plypoints[i].x; samples.at<double>(i, 1) = plypoints[i].y; samples.at<double>(i, 2) = plypoints[i].z; /* if(plypoints[i].x < minx) minx = plypoints[i].x; else if(plypoints[i].x > maxx) maxx = plypoints[i].x; if(plypoints[i].y < miny) miny = plypoints[i].y; else if(plypoints[i].y > maxy) maxy = plypoints[i].y; if(plypoints[i].z < minz) minz = plypoints[i].z; else if(plypoints[i].z > maxz) maxz = plypoints[i].z; */ centroid += samples.rowRange(i,i+1); } centroid /= plypoints.size(); /* centroid.ptr<double>()[0] = (maxx + minx)/2.0; centroid.ptr<double>()[1] = (maxy + miny)/2.0; centroid.ptr<double>()[2] = (maxz + minz)/2.0; */ cv::Mat cov, mean; cv::calcCovarMatrix(samples, cov, mean, CV_COVAR_NORMAL | CV_COVAR_ROWS); cv::Mat eigenvalues, eigenvectors; cv::eigen(cov, eigenvalues, eigenvectors); // descending order // eigenvectors are normalized // rotation to set old x, y, z axes to new principal directions, in // descending order // 1) rotation to align old X with new X // oX = [1 0 0 0]'; const cv::Mat xX = eigenvectors.colRange(0,1); // first eigenvector == new X axis // rotation vector cv::Mat V = (cv::Mat_<double>(3,1) << 0.0, -xX.at<double>(2,0), xX.at<double>(1,0) ); // V = cross(oX, xX) V /= cv::norm(V); // rotation angle double alpha = acos(xX.at<double>(0,0)); // xX[0] == dot(oX, xX) / norm(oX) / norm(xX) // rotate the old system with RotV and get the intermediate Y axis // oY = [0 1 0 0]'; cv::Mat RotV = DUtilsCV::Transformations::rotvec(V, alpha); cv::Mat auxY = RotV.colRange(1,2).rowRange(0,3); // == RotV * oY // 2) rotation to align auxY with new Y const cv::Mat xY = eigenvectors.colRange(1,2); double beta = acos( auxY.dot(xY) ); // calculate beta sign V = auxY.cross(xY); V /= norm(V); if(V.dot(xX) < 0) beta = -beta; cv::Mat RotX = DUtilsCV::Transformations::rotx(beta); // 3) get final transformation cv::Mat wTo = RotV * RotX; // 4) merge with the translation to the centroid (or some center) wTo.at<double>(0, 3) = centroid.ptr<double>()[0]; wTo.at<double>(1, 3) = centroid.ptr<double>()[1]; wTo.at<double>(2, 3) = centroid.ptr<double>()[2]; return DUtilsCV::Transformations::inv(wTo); // == oTw } // ---------------------------------------------------------------------------- void transformPoints(vector<PLYPoint> &plypoints, vector<Patch> &patches, const cv::Mat &oTw) { vector<PLYPoint>::iterator pit; for(pit = plypoints.begin(); pit != plypoints.end(); ++pit) { transformPoint(pit->x, pit->y, pit->z, 1., oTw); transformPoint(pit->nx, pit->ny, pit->nz, 0., oTw); } vector<Patch>::iterator bit; for(bit = patches.begin(); bit != patches.end(); ++bit) { transformPoint(bit->x, bit->y, bit->z, bit->s, oTw); transformPoint(bit->nx, bit->ny, bit->nz, bit->ns, oTw); } } // --------------------------------------------------------------------------- void transformPoint(double &x, double &y, double &z, double s, const cv::Mat &oTw) { cv::Mat wP = (cv::Mat_<double>(4,1) << x, y, z, s); cv::Mat oP = oTw * wP; if(s != 0.) { x = oP.at<double>(0,0) / oP.at<double>(3,0); y = oP.at<double>(1,0) / oP.at<double>(3,0); z = oP.at<double>(2,0) / oP.at<double>(3,0); }else { x = oP.at<double>(0,0); y = oP.at<double>(1,0); z = oP.at<double>(2,0); } } // --------------------------------------------------------------------------- void transformCameras(vector<Camera> &cameras, const cv::Mat &oTw) { const cv::Mat wTo = DUtilsCV::Transformations::inv(oTw); for(unsigned int i = 0; i < cameras.size(); ++i) { // For PMVS Cameras cv::Mat K, R, t; // 3x3, 3x3, 4x1 cv::decomposeProjectionMatrix(cameras[i].P, K, R, t); // opencv 2.1: t is not correct assert(R.type() == CV_64F); assert(t.type() == CV_64F); cv::Mat Rt = K.inv() * cameras[i].P; cv::Mat cvTw = (cv::Mat_<double>(4,4) << Rt.at<double>(0,0), Rt.at<double>(0,1), Rt.at<double>(0,2), Rt.at<double>(0,3), Rt.at<double>(1,0), Rt.at<double>(1,1), Rt.at<double>(1,2), Rt.at<double>(1,3), Rt.at<double>(2,0), Rt.at<double>(2,1), Rt.at<double>(2,2), Rt.at<double>(2,3), 0, 0, 0, 1); cv::Mat cvTo = cvTw * wTo; cvTo.at<double>(0,3) /= cvTo.at<double>(3,3); cvTo.at<double>(1,3) /= cvTo.at<double>(3,3); cvTo.at<double>(2,3) /= cvTo.at<double>(3,3); cameras[i].P = K * cvTo.rowRange(0,3); /* // For Bundle Cameras cv::Mat R, t; R = cameras[i].R; t = cameras[i].t; cv::Mat cvTw = ( cv::Mat_<double>(4, 4) << R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2), t.at<double>(0,0), R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2), t.at<double>(1,0), R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2), t.at<double>(2,0), 0.0, 0.0, 0.0, t.at<double>(3,0)); cv::Mat cvTo = cvTw * wTo; cvTo.at<double>(0,3) /= cvTo.at<double>(3,3); cvTo.at<double>(1,3) /= cvTo.at<double>(3,3); cvTo.at<double>(2,3) /= cvTo.at<double>(3,3); cameras[i].R = cvTo.rowRange(0, 3).colRange(0, 3); cameras[i].t = cvTo.rowRange(0, 3).colRange(3, 4); */ } } // ---------------------------------------------------------------------------
30.952128
169
0.583605
mattjr
2a7cb726963da0dd2ae1d8cda7ffb780bc1302f7
3,763
cpp
C++
PrismAPI/PrismCore/Enum.cpp
DigitalQR/Prism
e67965040ec9f7375a73a6924051e4962228eecd
[ "MIT" ]
1
2021-06-30T07:13:20.000Z
2021-06-30T07:13:20.000Z
PrismAPI/PrismCore/Enum.cpp
DigitalQR/Prism
e67965040ec9f7375a73a6924051e4962228eecd
[ "MIT" ]
null
null
null
PrismAPI/PrismCore/Enum.cpp
DigitalQR/Prism
e67965040ec9f7375a73a6924051e4962228eecd
[ "MIT" ]
null
null
null
#include "Include\Prism\Enum.h" namespace Prism { Enum::Value::Value() : Name() , NumberValue() { } Enum::Value::Value(const String& name, size_t value) : Name(name) , NumberValue(value) { } Enum::Enum(long uniqueId, const String& space, const String& name, const String& documentation, size_t size, const TemplateInfo* templateInfo, const std::vector<const Attribute*>& attributes, const std::vector<Value>& values) : Type(uniqueId, space, name, documentation, size, templateInfo, attributes, false, true) , m_Values(values) { } Prism::Object Enum::CreateNew(const std::vector<Prism::Object>& params) const { if (params.size() != 0) return nullptr; switch (m_Size) { case 1: { if (params.size() == 0) return new __int8; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int8(params[0].GetAs<__int8>()); else return nullptr; } case 2: { if (params.size() == 0) return new __int16; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int16(params[0].GetAs<__int16>()); else return nullptr; } case 4: { if (params.size() == 0) return new __int32; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int32(params[0].GetAs<__int32>()); else return nullptr; } case 8: { if (params.size() == 0) return new __int64; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int64(params[0].GetAs<__int64>()); else return nullptr; } default: return nullptr; } } Prism::String Enum::ToString(Prism::Object inStorage) const { switch (m_Size) { case 1: { __int8& inValue = *inStorage.GetPtrAs<__int8>(); for (const auto& value : m_Values) { if ((__int8)value.NumberValue == inValue) { return value.Name; } } break; } case 2: { __int16& inValue = *inStorage.GetPtrAs<__int16>(); for (const auto& value : m_Values) { if ((__int16)value.NumberValue == inValue) { return value.Name; } } break; } case 4: { __int32& inValue = *inStorage.GetPtrAs<__int32>(); for (const auto& value : m_Values) { if ((__int32)value.NumberValue == inValue) { return value.Name; } } break; } case 8: { __int64& inValue = *inStorage.GetPtrAs<__int64>(); for (const auto& value : m_Values) { if ((__int64)value.NumberValue == inValue) { return value.Name; } } break; } } return Prism::Type::ToString(inStorage); } bool Enum::ParseFromString(const String& str, Prism::Object outStorage) const { switch (m_Size) { case 1: { __int8& outValue = *outStorage.GetPtrAs<__int8>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int8)value.NumberValue; return true; } } return false; } case 2: { __int16& outValue = *outStorage.GetPtrAs<__int16>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int16)value.NumberValue; return true; } } return false; } case 4: { __int32& outValue = *outStorage.GetPtrAs<__int32>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int32)value.NumberValue; return true; } } return false; } case 8: { __int64& outValue = *outStorage.GetPtrAs<__int64>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int64)value.NumberValue; return true; } } return false; } default: return false; } } }
17.834123
227
0.599787
DigitalQR
2a7d73c1cbd1eb116a8ae9b4af582b990052501a
15,611
hpp
C++
src/iterators/row.hpp
oraqlle/cortex-iterators
425f71efdc654103458795440752f6804722fc12
[ "MIT" ]
null
null
null
src/iterators/row.hpp
oraqlle/cortex-iterators
425f71efdc654103458795440752f6804722fc12
[ "MIT" ]
null
null
null
src/iterators/row.hpp
oraqlle/cortex-iterators
425f71efdc654103458795440752f6804722fc12
[ "MIT" ]
null
null
null
/// -*- C++ -*- Header compatibility <row.hpp> /// @file row.hpp /// @author Tyler Swann (oraqlle@github.com) /// @brief Row Iterator /// @version 1.0.1 /// @date 2022-05-20 /// /// @ingroup %iterators /// /// @copyright Copyright (c) 2022 /// #ifndef CORTEX_ROW_ITERATOR_HPP # define CORTEX_ROW_ITERATOR_HPP 1 #include <utility> #include <type_traits> #include <iterator> #include <iterators/two_dim.hpp> #if __cpp_lib_three_way_comparison # include <compare> #endif /// __cpp_lib_three_way_comparison #if __cpp_concepts >= 201907L # include <concepts> #endif /// __cpp_concepts >= 201907L # if __cplusplus >= 201402L namespace cortex { /// @brief Row Iterator /// /// @details A row iterator is a iterator that iterates a /// given two dimensional space in row order. Incrementing /// moves the iterator to the next item in that row and /// vice versa for decrementing. Incrementing from the last item /// in a row causes the iterator to jump to the first item in /// the next row. Like wise, decrementing from the first item /// in a row causes the iterator to jump to the last item in /// the previous row. A column iterator is derived from the base /// %cortex::two_dim_iterator. /// /// @tparam _Iterator template<typename _Iterator> class row_iterator : public two_dim_iterator<_Iterator> { protected: using _Base = two_dim_iterator<_Iterator>; using __traits_type = typename _Base::__traits_type; public: using iterator_type = typename _Base::iterator_type; using iterator_category = typename _Base::iterator_category; // #if __cpp_concepts >= 201907L // using iterator_concept = typename _Base::iterator_concept; // #endif /// __cpp_concepts >= 201907L using size_type = typename _Base::size_type; using value_type = typename __traits_type::value_type; using difference_type = typename __traits_type::difference_type; using pointer = typename __traits_type::pointer; using reference = typename __traits_type::reference; public: /// @brief Default Constructor /// /// @details Constructs a row iterator with /// the two_dim_iterators default constrcutor. constexpr row_iterator() noexcept : _Base() { } /// @brief Explicit Value Constrcutor /// /// @details Constructs a column iterator from a reference to /// an iterator of the underlying iterator type, the dimensions /// the column iterator can move through and the current point /// index the iterator points to. Calls the base class constructor. /// /// @param ptr type: iterator_type | qualifier: [const, ref] constexpr row_iterator(const iterator_type& ptr , size_type ridx, size_type cidx , size_type row, size_type col) noexcept : _Base(ptr, ridx, cidx, row, col) {} /// @brief Pre Increment Operator /// /// @details Increments the iterator to the next item in the /// row. If the iterator is at the end of the row, the iterator /// jumps to the first item in the next row. /// /// @return constexpr row_iterator& constexpr row_iterator& operator++ () noexcept { auto old_ridx { this->m_ridx }; auto old_cidx { this->m_cidx }; if (this->m_cidx == this->m_columns - 1) { this->m_cidx = size_type(); this->m_ridx++; } else this->m_cidx++; this->m_current += this->_M_index((this->m_ridx - old_ridx) , (this->m_cidx - old_cidx)); return *this; } /// @brief Post Increment Operator /// /// @details Increments the iterator to the next item in the /// row. If the iterator is at the end of the row, the iterator /// jumps to the first item in the next row. Returns the iterator /// before the increment. /// /// @return constexpr row_iterator constexpr row_iterator operator++ (int) noexcept { auto old { row_iterator(*this) }; if (this->m_cidx == this->m_columns - 1) { this->m_cidx = size_type(); this->m_ridx++; } else this->m_cidx++; this->m_current += this->_M_index((this->m_ridx - old.row_index()) , (this->m_cidx - old.column_index())); return old; } /// @brief Pre Decrement Operator /// /// @details Decrements the iterator to the previous item in the /// row. If the iterator is at the first item in the row, the /// iterator jumps to the last item in the previous row. /// /// @return constexpr row_iterator& constexpr row_iterator& operator-- () noexcept { auto old_ridx { this->m_ridx }; auto old_cidx { this->m_cidx }; if (this->m_cidx == size_type()) { this->m_cidx = this->m_columns; this->m_ridx--; } this->m_cidx--; this->m_current += this->_M_index((this->m_ridx - old_ridx) , (this->m_cidx - old_cidx)); return *this; } /// @brief Post Decrement Operator /// /// @details Decrements the iterator to the previous item in the /// row. If the iterator is at the first item in the row, the /// iterator jumps to the last item in the previous row. Returns /// the iterator before the decrement. /// /// @return constexpr row_iterator constexpr row_iterator operator-- (int) noexcept { auto old { row_iterator(*this) }; if (this->m_cidx == size_type()) { this->m_cidx = this->m_columns; this->m_ridx--; } this->m_cidx--; this->m_current += this->_M_index((this->m_ridx - old.row_index()) , (this->m_cidx - old.column_index())); return old; } /// constexpr reference operator[] (difference_type __n) noexcept /// { /// size_type cols { __n / this->m_columns }; /// auto rows { __n % this->m_columns }; /// return *(this->m_current + this->_M_access(rows, cols)); /// } /// constexpr row_iterator& operator+= (difference_type __step) noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// this->m_current += this->_M_access(rows, cols); /// return *this; /// } /// constexpr row_iterator& operator-= (difference_type __step) noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// this->m_current -= this->_M_access(rows, cols); /// return *this; /// } /// constexpr row_iterator operator+ (difference_type __step) const noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// return row_iterator(this->m_current + this->_M_access(rows, cols), this->m_ridx + rows, this->m_cidx + cols, this->m_rows, this->m_columns); /// } /// constexpr row_iterator operator- (difference_type __step) const noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// return row_iterator(this->m_current - this->_M_access(rows, cols), this->m_ridx + rows, this->m_cidx + cols, this->m_rows, this->m_columns); /// } }; /// class row_iterator /// @brief Addition Operator Overload. /// /// @details Takes an offset @param __n and a %row_iterator /// @param __i. Constructs a new %row_iterator by adding /// @param __n to @param __i.base(). /// /// @tparam _Iterator /// @tparam _Container /// @param __n /// @param __i /// @return constexpr inline row_iterator<_Iterator, _Container> /// /// [constexpr] /// [noexcept] /// template<typename _Iterator> /// constexpr inline row_iterator<_Iterator> /// operator+ (typename row_iterator<_Iterator>::difference_type __n, /// const row_iterator<_Iterator>& __i) /// noexcept /// { /// std::size_t cols { __n / __i.columns() }; /// auto rows { __n % __i.columns() }; /// auto offset { __i.columns()/// rows + cols }; /// return row_iterator(__i.base() + offset /// , __i.row_index() + rows, __i.column_index() + cols /// , __i.rows(), __i.columns()); /// } /// @brief Less Than Operator /// /// @details Performs less-than comparison of two row /// iterators. A row iterator is considered less than another /// firstly, if it is at a lower row index. If the row indices /// are equal, the row iterator is considered less than another /// if it is at a lower column index. /// /// @tparam _Iterator /// @param __lhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @param __rhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator< (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs.row_index() < __rhs.row_index() ? true : __lhs.row_index() == __rhs.row_index() and __lhs.column_index() < __rhs.column_index() ? true : false; } /// @brief Greater Than Operator /// /// @details Performs greater-than comparison of two row /// iterators. A row iterator is considered greater than /// another firstly, if it is at a higher row index. If the /// row indices are equal, the row iterator is considered /// greater than another if it is at a higher column index. /// /// @tparam _Iterator /// @param __lhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @param __rhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator> (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs.row_index() > __rhs.row_index() ? true : __lhs.row_index() == __rhs.row_index() and __lhs.column_index() > __rhs.column_index() ? true : false; } /// @brief Less Than or Equal Operator /// /// @details Performs less-than-or-equal comparison of two row /// iterators. A row iterator is considered less than or equal /// to another firstly, if they compare equal, secondly if they /// compare less than. /// /// @tparam _Iterator /// @param __lhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @param __rhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator<= (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs == __rhs ? true : __lhs < __rhs ? true : false; } /// @brief Greater Than or Equal Operator /// /// @details Performs greater-than-or-equal comparison of two row /// iterators. A row iterator is considered greater than or equal /// to another firstly, if they compare equal, secondly if they /// compare greater than. /// /// @tparam _Iterator /// @param __lhs /// @param __rhs /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator>= (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs == __rhs ? true : __lhs > __rhs ? true : false; } // // /// @brief Makes a new %row_iterator. // /// // /// @details An adaptor for turning STL container iterators // /// into %row_iterators. // /// // /// @code {.cpp} // /// auto it = make_row_iterator<std::container>(c.begin()); // /// @endcode // /// // /// @tparam _Container // /// @param __i // /// @return constexpr auto -> row_iterator<typename _Container::iterator, _Container> // /// // /// [constexpr] // /// [noexcept] // // template<typename _Container> // constexpr auto // make_column(typename _Container::iterator __i) // noexcept // -> row_iterator<typename _Container::iterator> // { return row_iterator<typename _Container::iterator, _Container>(__i); } // // /// @brief Makes a new %row_iterator. // /// // /// @details An adaptor for making C-style array pointers // /// into %row_iterators. // /// // /// @code {.cpp} // /// auto it = make_normal<int*, int[]>(arr); // /// @endcode // /// // /// @tparam _Iterator // /// @tparam _Container // /// @param __i // /// @return constexpr auto -> row_iterator<_Iterator, _Container> // /// // /// [constexpr] // /// [noexcept] // // template<typename _Iterator, typename _Container> // constexpr auto // make_column(_Iterator __i) // noexcept // -> row_iterator<_Iterator, _Container> // { return row_iterator<_Iterator, _Container>(__i); } // # if __cplusplus >= 201703L /// C++17 // // /// @brief Makes a new %row_iterator. // /// // /// @details An adaptor for making STL container iterators // /// into %row_iterators using C++17 type deduction. // /// // /// @code {.cpp} // /// auto it = make_normal(c, c.begin()); // /// @endcode // /// // /// @note @param __c has the attribute [[maybe_unused]] // /// // /// @tparam _Container // /// @tparam _Iterator // /// @param __c // /// @param __i // /// @return constexpr auto -> row_iterator<_Iterator, _Container> // /// // /// [constexpr] // /// [noexcept] // // template<typename _Container, typename _Iterator> // constexpr auto // make_column([[maybe_unused]] const _Container& __c, _Iterator __i) // noexcept // -> row_iterator<_Iterator, _Container> // { return row_iterator<_Iterator, _Container>(__i); } // // # endif /// __cplusplus >= 201703L } /// namespace cortex # endif /// __cplusplus >= 201402L #endif /// CORTEX_ROW_ITERATOR_HPP
32.796218
156
0.556403
oraqlle
2a7efb999e50a381c8c93e69cc93ae13bc444898
1,205
cpp
C++
Sorting Algorithms/Merge_Sorting.cpp
forkkr/Data-Structure-Lab-CSE---2111-
6d1d3e1853083311971d0191630fc9a2afff7b38
[ "MIT" ]
null
null
null
Sorting Algorithms/Merge_Sorting.cpp
forkkr/Data-Structure-Lab-CSE---2111-
6d1d3e1853083311971d0191630fc9a2afff7b38
[ "MIT" ]
null
null
null
Sorting Algorithms/Merge_Sorting.cpp
forkkr/Data-Structure-Lab-CSE---2111-
6d1d3e1853083311971d0191630fc9a2afff7b38
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int Merging(int ar[] , int start , int last , int mid) { int p = mid; int q = last ; int i = start ; int j = mid + 1 ; int tmp[last - start +5]; int k = 0; while(i<=p||j<=q) { if(i>p) tmp[k++] = ar[j++]; else if(j>q) tmp[k++] = ar[i++]; else if(ar[j]>ar[i]) tmp[k++] = ar[j++]; else { tmp[k++] = ar[i++]; } } i = start ; j = 0; while( j < k) { ar[start++]= tmp[j++]; } return 0; } Merge_sort(int ar[], int start , int last) { if(start >= last) return 0; int mid = ( start + last )/2; Merge_sort(ar , start , mid); Merge_sort(ar , mid+1 , last); return Merging(ar , start , last , mid); } int main() { int n; cin>>n; int ar[n+1]; for(int i = 0 ; i < n ; i++) { cin>>ar[i]; } /* for(int i = 0 ; i < n ; i++) { cout<<ar[i]<<" "; } cout<<endl;*/ Merge_sort(ar , 0 , n-1); for(int i = 0 ; i < n ; i++) { cout<<ar[i]<<" "; } }
18.538462
55
0.372614
forkkr
2a80b8091662c687ea08b13ca979cd51ccb4cc5c
44
hh
C++
RAVL2/MSVC/include/Ravl/DP/OffsetScale.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/DP/OffsetScale.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/DP/OffsetScale.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#include "../.././Core/IO/OffsetScale.hh"
11
41
0.590909
isuhao
2a8135c21c7c6950f36a3fb3b828ee6664543f03
14,037
cpp
C++
test/storage/log_test.cpp
advanced-database-group/terrier
60c86afd9c9f2a2d030dd9852903e91b0e4db48d
[ "MIT" ]
null
null
null
test/storage/log_test.cpp
advanced-database-group/terrier
60c86afd9c9f2a2d030dd9852903e91b0e4db48d
[ "MIT" ]
null
null
null
test/storage/log_test.cpp
advanced-database-group/terrier
60c86afd9c9f2a2d030dd9852903e91b0e4db48d
[ "MIT" ]
null
null
null
#include <unordered_map> #include <vector> #include "gtest/gtest.h" #include "storage/checkpoint_manager.h" #include "storage/data_table.h" #include "storage/garbage_collector.h" #include "storage/write_ahead_log/log_manager.h" #include "transaction/transaction_manager.h" #include "util/sql_transaction_test_util.h" #include "util/storage_test_util.h" #include "util/test_harness.h" #define LOG_FILE_NAME "test.log" #define CHECKPOINT_FILE_PREFIX "checkpoint_file_" // Note: make sure to clear log files before testing. Because logging's file operation is append. namespace terrier { class WriteAheadLoggingTests : public TerrierTest { public: void StartLogging(uint32_t log_period_milli) { logging_ = true; log_thread_ = std::thread([log_period_milli, this] { LogThreadLoop(log_period_milli); }); } void EndLogging() { logging_ = false; log_thread_.join(); log_manager_.Shutdown(); } void StartGC(transaction::TransactionManager *txn_manager, uint32_t gc_period_milli) { gc_ = new storage::GarbageCollector(txn_manager); run_gc_ = true; gc_thread_ = std::thread([gc_period_milli, this] { GCThreadLoop(gc_period_milli); }); } void EndGC() { run_gc_ = false; gc_thread_.join(); // Make sure all garbage is collected. This take 2 runs for unlink and deallocate gc_->PerformGarbageCollection(); gc_->PerformGarbageCollection(); delete gc_; } std::default_random_engine generator_; storage::RecordBufferSegmentPool pool_{2000, 100}; storage::BlockStore block_store_{100, 100}; storage::LogManager log_manager_{LOG_FILE_NAME, &pool_}; // Members related to running gc / logging. std::thread log_thread_; bool logging_; volatile bool run_gc_ = false; std::thread gc_thread_; storage::GarbageCollector *gc_; storage::CheckpointManager checkpoint_manager_{CHECKPOINT_FILE_PREFIX}; private: void LogThreadLoop(uint32_t log_period_milli) { while (logging_) { std::this_thread::sleep_for(std::chrono::milliseconds(log_period_milli)); log_manager_.Process(); } } void GCThreadLoop(uint32_t gc_period_milli) { while (run_gc_) { std::this_thread::sleep_for(std::chrono::milliseconds(gc_period_milli)); gc_->PerformGarbageCollection(); } } }; // This test uses the LargeTransactionTestObject to simulate some number of transactions with logging turned on, and // then reads the logged out content to make sure they are correct // NOLINTNEXTLINE TEST_F(WriteAheadLoggingTests, LargeLogTest) { // There are 5 columns. The table has 10 rows. Each transaction does 5 operations. The update-select ratio of // operations is 50%-50%. SqlLargeTransactionTestObject tested = SqlLargeTransactionTestObject::Builder() .SetMaxColumns(10) .SetInitialTableSize(50) .SetTxnLength(5) .SetUpdateSelectRatio({0.5, 0.5}) .SetBlockStore(&block_store_) .SetBufferPool(&pool_) .SetGenerator(&generator_) .SetGcOn(true) .SetBookkeeping(true) .SetLogManager(&log_manager_) .build(); StartLogging(10); StartGC(tested.GetTxnManager(), 10); auto result = tested.SimulateOltp(100, 4); EndLogging(); EndGC(); checkpoint_manager_.RegisterTable(tested.GetTable()); std::unordered_map<transaction::timestamp_t, SqlRandomWorkloadTransaction *> txns_map; for (auto *txn : result.first) txns_map[txn->BeginTimestamp()] = txn; // At this point all the log records should have been written out, we can start reading stuff back in. storage::BufferedLogReader in(LOG_FILE_NAME); while (in.HasMore()) { std::vector<byte *> dummy_varlen_contents; storage::LogRecord *log_record = checkpoint_manager_.ReadNextLogRecord(&in, &dummy_varlen_contents); if (log_record->TxnBegin() == transaction::timestamp_t(0)) { // TODO(Tianyu): This is hacky, but it will be a pain to extract the initial transaction. The LargeTransactionTest // harness probably needs some refactor (later after wal is in). // This the initial setup transaction. delete[] reinterpret_cast<byte *>(log_record); continue; } auto it = txns_map.find(log_record->TxnBegin()); if (it == txns_map.end()) { // Okay to write out aborted transaction's redos, just cannot be a commit EXPECT_NE(log_record->RecordType(), storage::LogRecordType::COMMIT); delete[] reinterpret_cast<byte *>(log_record); continue; } if (log_record->RecordType() == storage::LogRecordType::COMMIT) { EXPECT_EQ(log_record->GetUnderlyingRecordBodyAs<storage::CommitRecord>()->CommitTime(), it->second->CommitTimestamp()); EXPECT_TRUE(it->second->Updates()->empty()); // All previous updates have been logged out previously txns_map.erase(it); } else { // This is leveraging the fact that we don't update the same tuple twice in a transaction with // bookkeeping turned on auto *redo = log_record->GetUnderlyingRecordBodyAs<storage::RedoRecord>(); // TODO(Tianyu): The DataTable field cannot be recreated from oid_t yet (we also don't really have oids), // so we are not checking it. auto update_it = it->second->Updates()->find(redo->GetTupleSlot()); EXPECT_NE(it->second->Updates()->end(), update_it); EXPECT_TRUE(StorageTestUtil::ProjectionListEqualShallow(tested.Layout(), update_it->second, redo->Delta())); delete[] reinterpret_cast<byte *>(update_it->second); it->second->Updates()->erase(update_it); } delete[] reinterpret_cast<byte *>(log_record); } // Ensure that the only committed transactions which remain in txns_map are read-only, because any other committing // transaction will generate a commit record and will be erased from txns_map in the checks above, if log records are // properly being written out. If at this point, there is exists any transaction in txns_map which made updates, then // something went wrong with logging. Read-only transactions do not generate commit records, so they will remain in // txns_map. for (const auto &kv_pair : txns_map) { EXPECT_TRUE(kv_pair.second->Updates()->empty()); } unlink(LOG_FILE_NAME); for (auto *txn : result.first) delete txn; for (auto *txn : result.second) delete txn; } // This test uses the LargeTransactionTestObject to simulate some number of transactions with logging turned on, and // then reads the logged out content to make sure they are correct. Varlens allowed. // NOLINTNEXTLINE TEST_F(WriteAheadLoggingTests, LargeLogTestWithVarlen) { // There are 5 columns. The table has 10 rows. Each transaction does 5 operations. The update-select ratio of // operations is 50%-50%. SqlLargeTransactionTestObject tested = SqlLargeTransactionTestObject::Builder() .SetMaxColumns(10) .SetInitialTableSize(50) .SetTxnLength(5) .SetUpdateSelectRatio({0.5, 0.5}) .SetBlockStore(&block_store_) .SetBufferPool(&pool_) .SetGenerator(&generator_) .SetGcOn(true) .SetBookkeeping(true) .SetLogManager(&log_manager_) .SetVarlenAllowed(true) .build(); StartLogging(10); auto result = tested.SimulateOltp(100, 4); EndLogging(); checkpoint_manager_.RegisterTable(tested.GetTable()); std::unordered_map<transaction::timestamp_t, SqlRandomWorkloadTransaction *> txns_map; for (auto *txn : result.first) txns_map[txn->BeginTimestamp()] = txn; // At this point all the log records should have been written out, we can start reading stuff back in. storage::BufferedLogReader in(LOG_FILE_NAME); while (in.HasMore()) { std::vector<byte *> varlen_contents; storage::LogRecord *log_record = checkpoint_manager_.ReadNextLogRecord(&in, &varlen_contents); if (log_record->TxnBegin() == transaction::timestamp_t(0)) { // TODO(Tianyu): This is hacky, but it will be a pain to extract the initial transaction. The LargeTransactionTest // harness probably needs some refactor (later after wal is in). // This the initial setup transaction. for (auto varlen_content : varlen_contents) { delete[] varlen_content; } delete[] reinterpret_cast<byte *>(log_record); continue; } auto it = txns_map.find(log_record->TxnBegin()); if (it == txns_map.end()) { // Okay to write out aborted transaction's redos, just cannot be a commit EXPECT_NE(log_record->RecordType(), storage::LogRecordType::COMMIT); for (auto varlen_content : varlen_contents) { delete[] varlen_content; } delete[] reinterpret_cast<byte *>(log_record); continue; } if (log_record->RecordType() == storage::LogRecordType::COMMIT) { EXPECT_EQ(log_record->GetUnderlyingRecordBodyAs<storage::CommitRecord>()->CommitTime(), it->second->CommitTimestamp()); EXPECT_TRUE(it->second->Updates()->empty()); // All previous updates have been logged out previously txns_map.erase(it); } else { // This is leveraging the fact that we don't update the same tuple twice in a transaction with // bookkeeping turned on auto *redo = log_record->GetUnderlyingRecordBodyAs<storage::RedoRecord>(); // TODO(Tianyu): The DataTable field cannot be recreated from oid_t yet (we also don't really have oids), // so we are not checking it. auto update_it = it->second->Updates()->find(redo->GetTupleSlot()); EXPECT_NE(it->second->Updates()->end(), update_it); EXPECT_TRUE(StorageTestUtil::ProjectionListEqualDeep(tested.Layout(), update_it->second, redo->Delta())); delete[] reinterpret_cast<byte *>(update_it->second); it->second->Updates()->erase(update_it); } for (auto varlen_content : varlen_contents) { delete[] varlen_content; } delete[] reinterpret_cast<byte *>(log_record); } // Ensure that the only committed transactions which remain in txns_map are read-only, because any other committing // transaction will generate a commit record and will be erased from txns_map in the checks above, if log records are // properly being written out. If at this point, there is exists any transaction in txns_map which made updates, then // something went wrong with logging. Read-only transactions do not generate commit records, so they will remain in // txns_map. for (const auto &kv_pair : txns_map) { EXPECT_TRUE(kv_pair.second->Updates()->empty()); } // Cannot open GC earlier, because it would free transaction workload's varlen contents. Bookkeeping does not // copy an entire varlen out. StartGC(tested.GetTxnManager(), 10); EndGC(); unlink(LOG_FILE_NAME); for (auto *txn : result.first) delete txn; for (auto *txn : result.second) delete txn; } // This test simulates a series of read-only transactions, and then reads the generated log file back in to ensure that // read-only transactions do not generate any log records, as they are not necessary for recovery. // NOLINTNEXTLINE TEST_F(WriteAheadLoggingTests, ReadOnlyTransactionsGenerateNoLogTest) { // Each transaction is read-only (update-select ratio of 0-100). Also, no need for bookkeeping. SqlLargeTransactionTestObject tested = SqlLargeTransactionTestObject::Builder() .SetMaxColumns(5) .SetInitialTableSize(10) .SetTxnLength(5) .SetUpdateSelectRatio({0.0, 1.0}) .SetBlockStore(&block_store_) .SetBufferPool(&pool_) .SetGenerator(&generator_) .SetGcOn(true) .SetBookkeeping(false) .SetLogManager(&log_manager_) .build(); StartLogging(10); StartGC(tested.GetTxnManager(), 10); auto result = tested.SimulateOltp(100, 4); EndLogging(); EndGC(); // Read-only workload has completed. Read the log file back in to check that no records were produced for these // transactions. checkpoint_manager_.RegisterTable(tested.GetTable()); int log_records_count = 0; storage::BufferedLogReader in(LOG_FILE_NAME); while (in.HasMore()) { std::vector<byte *> dummy_varlen_contents; storage::LogRecord *log_record = checkpoint_manager_.ReadNextLogRecord(&in, &dummy_varlen_contents); if (log_record->TxnBegin() == transaction::timestamp_t(0)) { // (TODO) Currently following pattern from LargeLogTest of skipping the initial transaction. When the transaction // testing framework changes, fix this. delete[] reinterpret_cast<byte *>(log_record); continue; } log_records_count += 1; delete[] reinterpret_cast<byte *>(log_record); } EXPECT_EQ(log_records_count, 0); unlink(LOG_FILE_NAME); for (auto *txn : result.first) delete txn; for (auto *txn : result.second) delete txn; } } // namespace terrier
46.946488
120
0.647218
advanced-database-group
2a8527bd81e57dbb2bad07046fdb6138dc58b2ce
2,340
cpp
C++
Immortal/Framework/Vector.cpp
QSXW/Immortal
32adcc8609b318752dd97f1c14dc7368b47d47d1
[ "Apache-2.0" ]
6
2021-09-15T08:56:28.000Z
2022-03-29T15:55:02.000Z
Immortal/Framework/Vector.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
null
null
null
Immortal/Framework/Vector.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
4
2021-12-05T17:28:57.000Z
2022-03-29T15:55:05.000Z
#include "impch.h" #include "Vector.h" namespace Immortal { namespace Vector { bool DecomposeTransform(const mat4& transform, Vector3& position, Vector3& rotation, Vector3& scale) { using T = float; mat4 localMatrix(transform); // Normalize the matrix. if (EpsilonEqual(localMatrix[3][3], static_cast<float>(0), Epsilon<T>())) return false; // First, isolate perspective. This is the messiest. if ( EpsilonNotEqual(localMatrix[0][3], static_cast<T>(0), Epsilon<T>()) || EpsilonNotEqual(localMatrix[1][3], static_cast<T>(0), Epsilon<T>()) || EpsilonNotEqual(localMatrix[2][3], static_cast<T>(0), Epsilon<T>())) { // Clear the perspective partition localMatrix[0][3] = localMatrix[1][3] = localMatrix[2][3] = static_cast<T>(0); localMatrix[3][3] = static_cast<T>(1); } // Next take care of translation (easy). position = Vector3(localMatrix[3]); localMatrix[3] = Vector4(0, 0, 0, localMatrix[3].w); Vector3 Row[3] = { Vector3(0.0f), Vector3(0.0f), Vector3(0.0f) }; // Now get scale and shear. for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Row[i][j] = localMatrix[i][j]; } } // Compute X scale factor and normalize first row. scale.x = Length(Row[0]); Row[0] = Detail::scale(Row[0], static_cast<T>(1)); scale.y = Length(Row[1]); Row[1] = Detail::scale(Row[1], static_cast<T>(1)); scale.z = Length(Row[2]); Row[2] = Detail::scale(Row[2], static_cast<T>(1)); // At this point, the matrix (in rows[]) is orthonormal. // Check for a coordinate system flip. If the determinant // is -1, then negate the matrix and the scaling factors. #if 0 Vector3 Pdum3; Pdum3 = cross(Row[1], Row[2]); // v3Cross(row[1], row[2], Pdum3); if (dot(Row[0], Pdum3) < 0) { for (length_t i = 0; i < 3; i++) { scale[i] *= static_cast<T>(-1); Row[i] *= static_cast<T>(-1); } } #endif rotation.y = asin(-Row[0][2]); if (cos(rotation.y) != 0) { rotation.x = atan2(Row[1][2], Row[2][2]); rotation.z = atan2(Row[0][1], Row[0][0]); } else { rotation.x = atan2(-Row[2][0], Row[1][1]); rotation.z = 0; } return true; } } }
27.529412
100
0.55812
QSXW
2a854127875e581e1f908a89e6d3d3348ec3b4fa
3,184
cpp
C++
code_library/2SAT_kosaraju.cpp
zxc123qwe456asd789/algovault
0ba0b3eb0d2e31e78de05da188f13d8d7d0365ae
[ "MIT" ]
60
2020-05-29T15:07:51.000Z
2022-03-29T05:36:28.000Z
code_library/2SAT_kosaraju.cpp
sgtlaugh/algorhythm
0ba0b3eb0d2e31e78de05da188f13d8d7d0365ae
[ "MIT" ]
2
2020-04-24T14:32:27.000Z
2021-05-23T22:22:45.000Z
code_library/2SAT_kosaraju.cpp
sgtlaugh/algorhythm
0ba0b3eb0d2e31e78de05da188f13d8d7d0365ae
[ "MIT" ]
13
2020-05-16T09:10:32.000Z
2022-01-05T08:55:22.000Z
/*** * * 2SAT with Kosaraju's algorithm (1 based index for variables) * Each variable can have two possible values: true or false * Variables must satisfy a system of constraints on pairs of variables * * Complexity: O(n + m), n = number of nodes and m = number of edges or constraints * ***/ #include <bits/stdc++.h> using namespace std; struct Graph{ int n, t; vector<vector<int>> adj, rev; vector<int> visited, parent, order, dfs_t; Graph(int n): n(n){ int m = 2 * n + 2; adj.resize(m, vector<int>()); rev.resize(m, vector<int>()); visited.resize(m, 0), dfs_t.resize(m, 0), order.resize(m, 0), parent.resize(m, 0); } inline int neg(int x){ return ((x) <= n ? (x + n) : (x - n)); } /// Add implication, if a then b inline void add_implication(int a, int b){ if (a < 0) a = n - a; if (b < 0) b = n - b; assert(a >= 1 && a <= 2 * n && b >= 1 && b <= 2 * n); adj[a].push_back(b); rev[b].push_back(a); } inline void add_or(int a, int b){ add_implication(-a, b); add_implication(-b, a); } inline void add_xor(int a, int b){ add_or(a, b); add_or(-a, -b); } inline void add_and(int a, int b){ add_or(a, b); add_or(a, -b); add_or(-a, b); } /// Force variable x to be true (if x is negative, force !x to be true) inline void force_true(int x){ if (x < 0) x = n - x; add_implication(neg(x), x); } /// Force variable x to be false (if x is negative, force !x to be false) inline void force_false(int x){ if (x < 0) x = n - x; add_implication(x, neg(x)); } inline void topsort(int i){ visited[i] = true; for (auto x: rev[i]){ if (!visited[x]) topsort(x); } dfs_t[i] = ++t; } inline void dfs(int i, int p){ parent[i] = p, visited[i] = true; for (auto x: adj[i]){ if (!visited[x]) dfs(x, p); } } void build(){ int i, x; for (i = 0; i <= 2 * n; i++) visited[i] = 0; for (i = 2 * n, t = 0; i >= 1; i--){ if (!visited[i]) topsort(i); order[dfs_t[i]] = i; } for (i = 0; i <= 2 * n; i++) visited[i] = 0; for (i = 2 * n; i >= 1; i--){ x = order[i]; if (!visited[x]) dfs(x, x); } } /// Returns whether the system is 2-satisfiable bool is_satisfiable(){ build(); for (int i = 0; i <= 2 * n; i++) visited[i] = 0; for (int i = 1; i <= 2 * n; i++){ int x = order[i]; if (parent[x] == parent[neg(x)]) return false; } return true; } }; int main(){ auto g = Graph(4); g.add_implication(1, 2); /// if 1 is true then 2 is true g.add_implication(-2, -3); /// if 2 is false then 3 is false g.force_false(2); /// 2 must be false g.add_xor(2, 4); /// exactly one of 2 or 4 must be true g.add_or(1, 4); /// either 1 or 4 must be true assert(g.is_satisfiable()); return 0; }
25.472
90
0.48147
zxc123qwe456asd789
2a8bc871386aa8324ed470aad365372e19b28bca
2,575
cpp
C++
src/use_mmap/mmapUT.cpp
unihykes/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
2
2018-03-27T02:46:03.000Z
2018-05-24T02:49:17.000Z
src/use_mmap/mmapUT.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
src/use_mmap/mmapUT.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** LICENSE: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author:liu.hao(33852613@163.com) Time:2017-6 info: 共享内存文件 shm_open:创建内存文件,路径要求类似/filename,以/起头,然后文件名,中间不能带/ 可以使用cat查看该内存文件的内容 cat /dev/shm/xxxxx ***************************************************************************************************/ #include <mkheaders.h> #include <gtest/gtest.h> //#include<stdio.h> //#include<stdlib.h> //#include<string.h> //#include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<sys/stat.h> #include<sys/mman.h> //////////////////////////////////////////////////////////////////////////////// // mmapUT // class mmapUT : public testing::Test { protected: static void SetUpTestCase(){} static void TearDownTestCase(){} virtual void SetUp(){} virtual void TearDown(){} protected: }; /*封装打印出错函数*/ void sys_err(const char *str,int num){ perror(str); exit(num); } TEST_F(mmapUT, Write) { int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777); //O_EXCL|O_CREAT,若文件已经存在,则报错 if(fd < 0){ /*直接打开文件读写*/ fd = shm_open("/hello.txt",O_RDWR,0777); } else { //若为自己创建的文件,则为文件分配内存空间大小 //ftruncate会将参数fd指定的文件大小改为参数length指定的大小。 ftruncate(fd,4096); } //mmap将一个文件或者其它对象映射进内存。 //void* mmap ( void * addr , size_t len , int prot , int flags , int fd , off_t offset ) void *ptr = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); //写文件 printf("start writeing data....\n"); strcpy((char*)ptr,"mmap:do something!"); printf("write over\n"); //阻塞进程 getchar(); //删除内存映射文件 shm_unlink("/hello.txt"); close(fd); } TEST_F(mmapUT, Read) { int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777); if(fd < 0){ fd = shm_open("/hello.txt",O_RDWR,0777); } else { ftruncate(fd,4096); } void *ptr = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); //读文件 printf("start reading data....\n"); printf("%s\n", (char*)ptr); printf("read over\n"); //删除内存映射文件 shm_unlink("/hello.txt"); close(fd); }
22.991071
101
0.611262
unihykes
2a8bd543dd5a49d4f19b179e519805f196d02405
1,021
cc
C++
src/motif/main.cc
chenxuhao/GraphMiner
493a16990238648ed4f8af263b2bf06aabb0758a
[ "MIT" ]
25
2021-07-31T15:29:30.000Z
2022-03-30T02:50:33.000Z
src/motif/main.cc
chenxuhao/GraphMiner
493a16990238648ed4f8af263b2bf06aabb0758a
[ "MIT" ]
1
2022-03-27T20:43:23.000Z
2022-03-27T20:43:23.000Z
src/motif/main.cc
chenxuhao/GraphMiner
493a16990238648ed4f8af263b2bf06aabb0758a
[ "MIT" ]
2
2021-12-06T17:59:48.000Z
2022-01-26T22:58:16.000Z
// Copyright 2020 Massachusetts Institute of Technology // Contact: Xuhao Chen <cxh@mit.edu> #include "motif.h" int main(int argc, char *argv[]) { if (argc < 3) { std::cout << "Usage: " << argv[0] << "<graph> <k> [ngpu(0)] [chunk_size(1024)]\n"; std::cout << "Example: " << argv[0] << " /graph_inputs/mico/graph 4\n"; exit(1); } Graph g(argv[1]); int k = atoi(argv[2]); int n_devices = 1; int chunk_size = 1024; if (argc > 3) n_devices = atoi(argv[3]); if (argc > 4) chunk_size = atoi(argv[4]); std::cout << k << "-motif counting (only for undirected graphs)\n"; auto m = g.size(); auto nnz = g.sizeEdges(); std::cout << "|V| " << m << " |E| " << nnz << "\n"; int num_patterns = num_possible_patterns[k]; std::cout << "num_patterns: " << num_patterns << "\n"; std::vector<uint64_t> total(num_patterns, 0); MotifSolver(g, k, total, n_devices, chunk_size); for (int i = 0; i < num_patterns; i++) std::cout << "pattern " << i << ": " << total[i] << "\n"; return 0; }
31.90625
86
0.574927
chenxuhao
2a8d54132f8e4e2e9b1b61d5b03a3d9d061f9142
790
cpp
C++
Module 1/Lecture 3/3d_distance.cpp
bhattigurjot/cpp-exercises
9ae770fec1b2bcdc9811b2901e62f883d3e6ed2c
[ "MIT" ]
null
null
null
Module 1/Lecture 3/3d_distance.cpp
bhattigurjot/cpp-exercises
9ae770fec1b2bcdc9811b2901e62f883d3e6ed2c
[ "MIT" ]
null
null
null
Module 1/Lecture 3/3d_distance.cpp
bhattigurjot/cpp-exercises
9ae770fec1b2bcdc9811b2901e62f883d3e6ed2c
[ "MIT" ]
null
null
null
#include<iostream> #include<cmath> using namespace std; void print(float ux, float uy, float uz, float vx, float vy, float vz); float dist3(float ux, float uy, float uz, float vx, float vy, float vz); int main() { print(1,2,3,0,0,0); print(1,2,3,1,2,3); print(1,2,3,7,-4,5); } float dist3(float ux, float uy, float uz, float vx, float vy, float vz) { /* 3D Distance Calculation Function */ float dist = 0.0f; float res = pow(vx-ux, 2) + pow(vy-uy, 2) + pow(vz-uz, 2); dist = sqrt(res); return dist; } void print(float ux, float uy, float uz, float vx, float vy, float vz) { /* Print Function */ cout << "Distance between (" << ux << "," << uy << "," << uz << ") and (" << vx << "," << vy << "," << vz << ") = " << dist3(ux,uy,uz,vx,vy,vz) << endl; }
19.75
78
0.572152
bhattigurjot
2a8dfafc28d1d865f90be0619e75dbedba4e4be4
11,631
cpp
C++
core/common/str.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
28
2017-04-30T13:56:13.000Z
2022-03-20T06:54:37.000Z
core/common/str.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
72
2017-04-25T03:42:58.000Z
2021-12-04T06:35:28.000Z
core/common/str.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
12
2017-04-16T06:25:24.000Z
2021-07-07T13:28:27.000Z
#include "str.h" #include <string> #include <algorithm> #include <cstring> #include <vector> #include <cctype> #include <stdexcept> namespace str { using namespace std; std::string hexdump(const std::string& in) { std::string res; for (size_t i = 0; i < in.size(); i++) { if (i != 0) res += ' '; char buf[3]; snprintf(buf, 3, "%02hhX", in[i]); res += buf; } return res; } static std::string inspect(char c, bool utf8) { int d = static_cast<unsigned char>(c); if (utf8 && d >= 0x80) return string() + (char) d; if (isprint(d)) { switch (d) { case '\'': return "\\\'"; case '\"': return "\\\""; case '\?': return "\\?"; case '\\': return "\\\\"; default: return string() + (char) d; } } switch (d) { case '\a': return "\\a"; case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; default: return string("\\x") + "0123456789abcdef"[d>>4] + "0123456789abcdef"[d&0xf]; } } std::string inspect(const std::string str) { bool utf8 = validate_utf8(str); std::string res = "\""; for (auto c : str) { res += inspect(c, utf8); } res += "\""; return res; } std::string repeat(const std::string& in, int n) { std::string res; for (int i = 0; i < n; i++) { res += in; } return res; } std::string group_digits(const std::string& in, const std::string& separator) { std::string tail; auto end = in.find('.'); // end of integral part if (end != string::npos) tail = in.substr(end); else end = in.size(); std::string res; std::string integer = in.substr(0, end); std::reverse(integer.begin(), integer.end()); std::string delim = separator; std::reverse(delim.begin(), delim.end()); for (size_t i = 0; i < end; i++) { if (i != 0 && i%3 == 0) res += delim; res += integer[i]; } std::reverse(res.begin(), res.end()); return res + tail; } std::vector<std::string> split(const std::string& in, const std::string& separator) { std::vector<std::string> res; const char *p = in.c_str(); const char *sep = separator.c_str(); const char *q; while (true) { q = strstr(p, sep); if (q) { res.push_back(std::string(p, q)); p = q + std::strlen(sep); } else { res.push_back(std::string(p)); return res; } } } std::vector<std::string> split(const std::string& in, const std::string& separator, int limit) { if (limit <= 0) throw std::domain_error("limit <= 0"); std::vector<std::string> res; const char *p = in.c_str(); const char *sep = separator.c_str(); const char *q; while (true) { q = strstr(p, sep); if ((int)res.size() < limit-1 && q != nullptr) { res.push_back(std::string(p, q)); p = q + std::strlen(sep); } else { res.push_back(std::string(p)); return res; } } } std::string codepoint_to_utf8(uint32_t codepoint) { std::string res; if (/* codepoint >= 0 && */ codepoint <= 0x7f) { res += (char) codepoint; } else if (codepoint >= 0x80 && codepoint <= 0x7ff) { res += (char) (0xb0 | (codepoint >> 6)); res += (char) (0x80 | (codepoint & 0x3f)); } else if (codepoint >= 0x800 && codepoint <= 0xffff) { res += (char) (0xe0 | (codepoint >> 12)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } else if (codepoint >= 0x10000 && codepoint <= 0x1fffff) { res += (char) (0xf0 | (codepoint >> 18)); res += (char) (0x80 | ((codepoint >> 12) & 0x3f)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } else if (codepoint >= 0x200000 && codepoint <= 0x3ffffff) { res += (char) (0xf8 | (codepoint >> 24)); res += (char) (0x80 | ((codepoint >> 18) & 0x3f)); res += (char) (0x80 | ((codepoint >> 12) & 0x3f)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } else { // [0x4000000, 0x7fffffff] res += (char) (0xfb | (codepoint >> 30)); res += (char) (0x80 | ((codepoint >> 24) & 0x3f)); res += (char) (0x80 | ((codepoint >> 18) & 0x3f)); res += (char) (0x80 | ((codepoint >> 12) & 0x3f)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } return res; } #include <stdarg.h> std::string format(const char* fmt, ...) { // 必要なバイト数の計算のために vsnprintf を呼び出し、実際に文字列 // を作るためにもう一度 vsnprintf を呼び出す。 // 1度目の vsnprintf の呼び出しのあと ap の値は未定義になるので、 // 2度目の呼び出しのために aq にコピーしておく。 va_list ap, aq; std::string res; va_start(ap, fmt); va_copy(aq, ap); int size = vsnprintf(NULL, 0, fmt, ap); char *data = new char[size + 1]; vsnprintf(data, size + 1, fmt, aq); va_end(aq); va_end(ap); res = data; delete[] data; return res; } bool contains(const std::string& haystack, const std::string& needle) { return haystack.find(needle) != std::string::npos; } std::string replace_prefix(const std::string& s, const std::string& prefix, const std::string& replacement) { if (s.size() < prefix.size()) return s; if (s.substr(0, prefix.size()) == prefix) return replacement + s.substr(prefix.size()); else return s; } std::string replace_suffix(const std::string& s, const std::string& suffix, const std::string& replacement) { if (s.size() < suffix.size()) return s; if (s.substr(s.size() - suffix.size(), suffix.size()) == suffix) return s.substr(0, s.size() - suffix.size()) + replacement; else return s; } std::string upcase(const std::string& input) { std::string res; for (auto c : input) { if (isalpha(c)) res += toupper(c); else res += c; } return res; } std::string downcase(const std::string& input) { std::string res; for (auto c : input) { if (isalpha(c)) res += tolower(c); else res += c; } return res; } std::string capitalize(const std::string& input) { std::string res; bool prevWasAlpha = false; for (auto c : input) { if (isalpha(c)) { if (prevWasAlpha) res += tolower(c); else { res += toupper(c); prevWasAlpha = true; } }else { res += c; prevWasAlpha = false; } } return res; } bool is_prefix_of(const std::string& prefix, const std::string& string) { if (string.size() < prefix.size()) return false; return string.substr(0, prefix.size()) == prefix; } bool has_prefix(const std::string& subject, const std::string& prefix) { return is_prefix_of(prefix, subject); } bool has_suffix(const std::string& subject, const std::string& suffix) { if (subject.size() < suffix.size()) return false; return subject.substr(subject.size() - suffix.size(), suffix.size()) == suffix; } std::string join(const std::string& delimiter, const std::vector<std::string>& vec) { std::string res; for (auto it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) res += delimiter; res += *it; } return res; } std::string ascii_dump(const std::string& in, const std::string& replacement) { std::string res; for (auto c : in) { if (std::isprint(c)) res += c; else res += replacement; } return res; } std::string extension_without_dot(const std::string& filename) { auto i = filename.rfind('.'); if (i == std::string::npos) return ""; else return filename.substr(i + 1); } int count(const std::string& haystack, const std::string& needle) { if (needle.empty()) throw std::domain_error("cannot count empty strings"); size_t start = 0; int n = 0; while ((start = haystack.find(needle, start)) != std::string::npos) { n++; start++; } return n; } std::string rstrip(const std::string& str) { std::string res = str; while (!res.empty()) { auto c = res.back(); if (c == ' ' || (c >= 0x09 && c <= 0x0d) || c == '\0') res.pop_back(); else break; } return res; } std::string strip(const std::string& str) { auto it = str.begin(); while (it != str.end()) { auto c = *it; if (c == ' ' || (c >= 0x09 && c <= 0x0d) || c == '\0') it++; else break; } std::string res(it, str.end()); while (!res.empty()) { auto c = res.back(); if (c == ' ' || (c >= 0x09 && c <= 0x0d) || c == '\0') res.pop_back(); else break; } return res; } std::string escapeshellarg_unix(const std::string& str) { std::string buf = "\'"; for (char c : str) { if (c == '\'') buf += "\'\"\'\"\'"; else buf += c; } buf += "\'"; return buf; } std::string STR() { return ""; } std::vector<std::string> to_lines(const std::string& text) { std::vector<std::string> res; std::string line; for (auto it = text.begin(); it != text.end(); ++it) { if (*it == '\n') { line += *it; res.push_back(line); line.clear(); }else { line.push_back(*it); } } res.push_back(line); if (res.back() == "") res.pop_back(); return res; } std::string indent_tab(const std::string& text, int n) { if (n < 0) throw std::domain_error("domain error"); auto lines = to_lines(text); auto space = repeat("\t", n); for (size_t i = 0; i < lines.size(); ++i) lines[i] = space + lines[i]; return join("", lines); } bool validate_utf8(const std::string& str) { auto it = str.begin(); while (it != str.end()) { if ((*it & 0x80) == 0) // 0xxx xxxx { it++; continue; }else if ((*it & 0xE0) == 0xC0) // 110x xxxx { it++; if (it == str.end()) return false; if ((*it & 0xC0) == 0x80) it++; else return false; }else if ((*it & 0xF0) == 0xE0) // 1110 xxxx { it++; for (int i = 0; i < 2; ++i) { if (it == str.end()) return false; if ((*it & 0xC0) == 0x80) it++; else return false; } }else if ((*it & 0xF8) == 0xF0) // 1111 0xxx { it++; for (int i = 0; i < 3; ++i) { if (it == str.end()) return false; if ((*it & 0xC0) == 0x80) it++; else return false; } }else return false; } return true; } } // namespace str
22.716797
107
0.481472
plonk
2a934e187eac742774b117f4215ffab5b9ac9ab0
1,963
cpp
C++
src/publisher.cpp
DeadBlasoul/oop_exercise_08
1177b1324fd1728346d9e08157e21ef3a78f0f15
[ "MIT" ]
null
null
null
src/publisher.cpp
DeadBlasoul/oop_exercise_08
1177b1324fd1728346d9e08157e21ef3a78f0f15
[ "MIT" ]
null
null
null
src/publisher.cpp
DeadBlasoul/oop_exercise_08
1177b1324fd1728346d9e08157e21ef3a78f0f15
[ "MIT" ]
null
null
null
#include "publisher.hpp" #include <cassert> #include <stdexcept> #include <subscriber.hpp> using namespace oop; /*! * @brief * Initializes new routine (sub-thread), sets events_done_ to false. */ publisher::publisher() try : events_done_{ false } { std::unique_lock publisher_lock(routine_mu_); routine_ = std::thread(&publisher::routine_proc, this); publisher_cv_.wait(publisher_lock); } catch (...) { throw std::runtime_error("publisher: can not create thread"); } publisher::~publisher() { stop_routine(); } void publisher::push(const std::shared_ptr<const event>& e) { std::lock_guard lock(routine_mu_); events_.push_back(e); } void publisher::commit() { std::unique_lock publisher_lock(publisher_mu_); { std::lock_guard routine_lock(routine_mu_); routine_cv_.notify_all(); } publisher_cv_.wait(publisher_lock); } void publisher::subscribe(subscriber* s) { std::lock_guard lock(routine_mu_); subscribers_.push_back(s); } void publisher::routine_proc() { std::unique_lock lock(routine_mu_); publisher_cv_.notify_one(); while (!events_done_) { // Wait for next events routine_cv_.wait(lock); // Lock publisher to force it to wait till loop end std::lock_guard publisher_lock(publisher_mu_); // Process events while(!events_.empty()) { auto& e = *events_.back(); for (auto s : subscribers_) { if (s->is_suitable(e)) { s->handle(e); } } events_.pop_back(); } // Unlock publisher publisher_cv_.notify_one(); } } void publisher::stop_routine() { // Signal thread to stop { std::lock_guard lock(routine_mu_); if (!events_.empty()) { std::terminate(); } events_done_ = true; routine_cv_.notify_one(); } routine_.join(); }
22.825581
68
0.609272
DeadBlasoul
2a96b2476316dd4bcbd57d3969ec3742e17882be
2,738
cpp
C++
samples/03_advances/05_convert_to_wscene/src/main.cpp
SiminBadri/Wolf.Engine
3da04471ec26e162e1cbb7cc88c7ce37ee32c954
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
1
2020-07-15T13:14:26.000Z
2020-07-15T13:14:26.000Z
samples/03_advances/05_convert_to_wscene/src/main.cpp
foroughmajidi/Wolf.Engine
f08a8cbd519ca2c70b1c8325250dc9af7ac4c498
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
null
null
null
samples/03_advances/05_convert_to_wscene/src/main.cpp
foroughmajidi/Wolf.Engine
f08a8cbd519ca2c70b1c8325250dc9af7ac4c498
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
null
null
null
/* Project : Wolf Engine. Copyright(c) Pooya Eimandar (http://PooyaEimandar.com) . All rights reserved. Source : Please direct any bug to https://github.com/PooyaEimandar/Wolf.Engine/issues Website : http://WolfSource.io Name : main.cpp Description : This sample shows how to convert collada file to Wolf Scene Pack Comment : Read more information about this sample on http://wolfsource.io/gpunotes/ */ #include <pch.h> #include <w_io.h> #include <w_content_manager.h> #include <stdio.h> using namespace std; using namespace wolf; using namespace wolf::system; using namespace wolf::content_pipeline; int main() { //set content path directory auto _current_path_dir = wolf::system::io::get_current_directoryW(); #ifdef WIN32 auto _content_path_dir = _current_path_dir + L"/../../../../content/"; #elif defined(__APPLE__) auto _content_path_dir = _current_path_dir + L"/../../../../../content/"; #endif // WIN32 wolf::system::w_logger_config _log_config; _log_config.app_name = L"05_convert_to_wscene.Win32"; _log_config.log_path = _current_path_dir; _log_config.log_to_std_out = true; logger.initialize(_log_config); //log to output file logger.write(L"wolf initialized"); //++++++++++++++++++++++++++++++++++++++++++++++++++++ //The following codes have been added for this project //++++++++++++++++++++++++++++++++++++++++++++++++++++ //load all models from following folder "content/models/sponza/" auto _parent_dir = _content_path_dir + L"models/sponza/"; std::vector<std::wstring> _file_names; wolf::system::io::get_files_folders_in_directoryW(_parent_dir, _file_names); for (auto& _file_name : _file_names) { auto _ext = wolf::system::io::get_file_extentionW(_file_name); auto _base_name = wolf::system::io::get_base_file_nameW(_file_name); if (_ext.empty() || _ext == L"." || _ext == L".wscene") continue; auto _scene = w_content_manager::load<w_cpipeline_scene>(_parent_dir + _file_name); if (_scene) { logger.write(L"start converting: {}", _file_name); std::vector<w_cpipeline_scene> _scene_packs = { *_scene }; auto _out_path = _parent_dir + _base_name + L".wscene"; if (w_content_manager::save_wolf_scenes_to_file(_scene_packs, _out_path) == W_PASSED) { logger.write(L"scene {} converted", _file_name); } else { logger.write(L"error on converting {}", _file_name); } _scene->release(); } else { logger.write(L"file {} not exists or not supported", _file_name); } } w_content_manager::release(); //++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++ release_heap_data(); return EXIT_SUCCESS; }
32.595238
104
0.647918
SiminBadri
2a9743b2207d0b7a8f2eed317a8d3ff32b895839
3,479
cpp
C++
windz/log/LogStream.cpp
Crystalwindz/windz
f13ea10187eb1706d1c7b31b34ce1bf458d721bd
[ "MIT" ]
null
null
null
windz/log/LogStream.cpp
Crystalwindz/windz
f13ea10187eb1706d1c7b31b34ce1bf458d721bd
[ "MIT" ]
null
null
null
windz/log/LogStream.cpp
Crystalwindz/windz
f13ea10187eb1706d1c7b31b34ce1bf458d721bd
[ "MIT" ]
null
null
null
#include "windz/log/LogStream.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <strings.h> #include <algorithm> #include <limits> namespace windz { namespace { const char digits[] = "9876543210123456789"; const char *zero = digits + 9; const char digitsHex[] = "0123456789abcdef"; // From muduo // Efficient Integer to String Conversions, by Matthew Wilson. template <typename T> size_t Convert(char buf[], T value) { T i = value; char *p = buf; do { int lsd = static_cast<int>(i % 10); i /= 10; *p++ = zero[lsd]; } while (i != 0); if (value < 0) { *p++ = '-'; } *p = '\0'; std::reverse(buf, p); return p - buf; } size_t ConvertHex(char buf[], uintptr_t value) { uintptr_t i = value; char *p = buf; do { int lsd = static_cast<int>(i % 16); i /= 16; *p++ = digitsHex[lsd]; } while (i != 0); *p = '\0'; std::reverse(buf, p); return p - buf; } } // namespace template <typename T> void LogStream::FormatInteger(T v) { if (buffer_.Avail() >= kMaxNumericSize) { size_t len = Convert(buffer_.cur(), v); buffer_.Add(len); } } LogStream &LogStream::operator<<(bool v) { buffer_.Append(v ? "1" : "0", 1); return *this; } LogStream &LogStream::operator<<(short v) { *this << static_cast<int>(v); return *this; } LogStream &LogStream::operator<<(unsigned short v) { *this << static_cast<unsigned int>(v); return *this; } LogStream &LogStream::operator<<(int v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(unsigned int v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(unsigned long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(long long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(unsigned long long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(float v) { *this << static_cast<double>(v); return *this; } LogStream &LogStream::operator<<(double v) { if (buffer_.Avail() >= kMaxNumericSize) { int len = snprintf(buffer_.cur(), kMaxNumericSize, "%.12g", v); buffer_.Add(len); } return *this; } LogStream &LogStream::operator<<(long double v) { if (buffer_.Avail() >= kMaxNumericSize) { int len = snprintf(buffer_.cur(), kMaxNumericSize, "%.12Lg", v); buffer_.Add(len); } return *this; } LogStream &LogStream::operator<<(char v) { buffer_.Append(&v, 1); return *this; } LogStream &LogStream::operator<<(const char *v) { if (v) { buffer_.Append(v, strlen(v)); } else { buffer_.Append("(null)", 6); } return *this; } LogStream &LogStream::operator<<(const unsigned char *v) { *this << reinterpret_cast<const char *>(v); return *this; } LogStream &LogStream::operator<<(const std::string &v) { buffer_.Append(v.c_str(), v.length()); return *this; } LogStream &LogStream::operator<<(const void *p) { uintptr_t v = reinterpret_cast<uintptr_t>(p); if (buffer_.Avail() >= kMaxNumericSize) { char *buf = buffer_.cur(); buf[0] = '0'; buf[1] = 'x'; size_t len = ConvertHex(buf + 2, v); buffer_.Add(len + 2); } return *this; } } // namespace windz
20.345029
72
0.590112
Crystalwindz
2a9c0caa50e3d3f36694ac5b2c1ea0bd37257366
7,680
cpp
C++
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/textinput_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2020-10-04T18:50:01.000Z
2020-10-04T18:50:01.000Z
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/textinput_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
null
null
null
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/textinput_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2018-09-18T08:03:33.000Z
2018-09-18T08:03:33.000Z
#include "horus.h" #include "types.h" #include "ui_theme.h" #include "renderer.h" #include "unicode_text_cache.h" #include "ui_font.h" #include "ui_context.h" #include "util.h" #include <math.h> #include <string.h> #include <algorithm> namespace hui { bool textInput( char* text, u32 maxLength, TextInputValueMode valueMode, const char* defaultText, Image icon, bool password, const char* passwordChar) { auto bodyElem = &ctx->theme->getElement(WidgetElementId::TextInputBody); auto bodyTextCaretElemState = ctx->theme->getElement(WidgetElementId::TextInputCaret).normalState(); auto bodyTextSelectionElemState = ctx->theme->getElement(WidgetElementId::TextInputSelection).normalState(); auto bodyTextDefaultElemState = ctx->theme->getElement(WidgetElementId::TextInputDefaultText).normalState(); addWidgetItem(fmaxf(bodyElem->normalState().height * ctx->globalScale, bodyElem->normalState().font->getMetrics().height)); if (!ctx->focusChanged) buttonBehavior(); if (ctx->focusChanged && ctx->currentWidgetId != ctx->widget.focusedWidgetId) { ctx->widget.changeEnded = true; } auto bodyElemState = &bodyElem->normalState(); bool isEditingThis = ctx->currentWidgetId == ctx->textInput.widgetId && ctx->widget.focused && ctx->isActiveLayer(); ctx->textInput.themeElement = bodyElem; if (ctx->widget.focused) { bodyElemState = &bodyElem->getState(WidgetStateType::Focused); } auto clipRect = Rect( ctx->widget.rect.x + bodyElemState->border, ctx->widget.rect.y + bodyElemState->border, ctx->widget.rect.width - bodyElemState->border * 2, ctx->widget.rect.height - bodyElemState->border * 2); const u32 maxHiddenCharLen = 1024; static char hiddenPwdText[maxHiddenCharLen] = ""; bool isEmptyText = false; char* textToDraw = (char*)text; UnicodeString pwdStr; utf8ToUtf32(passwordChar, pwdStr); ctx->textInput.editNow = false; ctx->textInput.password = password; ctx->textInput.passwordCharUnicode = pwdStr; if (ctx->event.type == InputEvent::Type::Key && ctx->event.key.code == KeyCode::Enter && ctx->event.key.down && ctx->widget.focused) { if (!ctx->textInput.widgetId) { ctx->textInput.widgetId = ctx->currentWidgetId; isEditingThis = true; ctx->textInput.editNow = true; ctx->textInput.selectAllOnFocus = true; } else { ctx->textInput.widgetId = 0; ctx->textInput.editNow = false; isEditingThis = false; ctx->widget.focusedWidgetId = 0; ctx->widget.changeEnded = true; } } if (ctx->focusChanged && ctx->currentWidgetId == ctx->widget.focusedWidgetId) { ctx->textInput.editNow = true; isEditingThis = 0 != ctx->textInput.widgetId; ctx->textInput.selectAllOnFocus = true; if (isEditingThis) { ctx->textInput.widgetId = ctx->currentWidgetId; } } if (ctx->widget.pressed && ctx->currentWidgetId != ctx->textInput.widgetId) { ctx->textInput.widgetId = ctx->currentWidgetId; ctx->textInput.editNow = true; isEditingThis = true; ctx->textInput.selectAllOnFocus = true; ctx->textInput.firstMouseDown = true; ctx->widget.pressed = false; ctx->widget.focusedWidgetPressed = false; } if (ctx->textInput.editNow) { ctx->textInput.rect = ctx->widget.rect; ctx->textInput.clipRect = clipRect; ctx->textInput.maxTextLength = maxLength; ctx->textInput.selectionActive = false; ctx->textInput.valueType = valueMode; ctx->textInput.scrollOffset = 0; utf8ToUtf32(text, ctx->textInput.text); utf8ToUtf32(defaultText, ctx->textInput.defaultText); if (ctx->textInput.selectAllOnFocus) { ctx->textInput.selectAll(); } // this must be called to handle the event in the text input ways // otherwise it needs a second click to do stuff for the edit box ctx->textInput.processEvent(ctx->event); Rect rc; rc.x = ctx->widget.rect.x; rc.y = ctx->widget.rect.y; rc.width = ctx->widget.rect.width; rc.height = ctx->widget.rect.height; ctx->inputProvider->startTextInput(0, rc); bodyElemState = &bodyElem->getState(WidgetStateType::Focused); forceRepaint(); } ctx->renderer->cmdSetColor(bodyElemState->color); ctx->renderer->cmdDrawImageBordered(bodyElemState->image, bodyElemState->border, ctx->widget.rect, ctx->globalScale); ctx->renderer->cmdSetColor(bodyElemState->textColor); ctx->renderer->cmdSetFont(bodyElemState->font); ctx->renderer->pushClipRect(clipRect); if (isEditingThis) { int offs = ctx->textInput.caretPosition; if (ctx->textInput.caretPosition > ctx->textInput.text.size()) offs = ctx->textInput.text.size() - 1; FontTextSize textToCursorSize; UnicodeString textToCursor; textToCursor = UnicodeString( ctx->textInput.text.begin(), ctx->textInput.text.begin() + offs); if (!password) { textToCursorSize = bodyElemState->font->computeTextSize(textToCursor); } else { textToCursorSize = bodyElemState->font->computeTextSize(pwdStr); textToCursorSize.width *= textToCursor.size(); } const f32 cursorWidth = bodyTextCaretElemState.width; const f32 cursorBorder = bodyTextCaretElemState.border; Rect cursorRect( clipRect.x + textToCursorSize.width - ctx->textInput.scrollOffset, clipRect.y + cursorBorder, cursorWidth, clipRect.height - cursorBorder * 2); if (ctx->textInput.selectionActive) { int startSel = ctx->textInput.selectionBegin, endSel = ctx->textInput.selectionEnd, tmpSel; if (startSel > endSel) { tmpSel = startSel; startSel = endSel; endSel = tmpSel; } FontTextSize selectedTextSize; FontTextSize textToSelectionStartSize; UnicodeString selectedText = UnicodeString(ctx->textInput.text.begin() + startSel, ctx->textInput.text.begin() + endSel); UnicodeString textToSelectionStart = UnicodeString(ctx->textInput.text.begin(), ctx->textInput.text.begin() + startSel); if (!password) { selectedTextSize = bodyElemState->font->computeTextSize(selectedText); textToSelectionStartSize = bodyElemState->font->computeTextSize(textToSelectionStart); } else { selectedTextSize = bodyElemState->font->computeTextSize(pwdStr); textToSelectionStartSize = selectedTextSize; selectedTextSize.width *= selectedText.size(); textToSelectionStartSize.width *= textToSelectionStart.size(); } Rect selRect( clipRect.x + textToSelectionStartSize.width - ctx->textInput.scrollOffset, clipRect.y, selectedTextSize.width, clipRect.height); // draw selection rect ctx->renderer->cmdSetColor(bodyTextSelectionElemState.color); ctx->renderer->cmdDrawSolidRectangle(selRect); } // draw cursor ctx->renderer->cmdSetColor(bodyTextCaretElemState.color); ctx->renderer->cmdDrawSolidRectangle(cursorRect); } if (isEditingThis) { memset((char*)text, 0, maxLength); utf32ToUtf8NoAlloc(ctx->textInput.text, text, maxLength); } if (password && defaultText != textToDraw) { u32 len = std::min(utf8Len(textToDraw), maxHiddenCharLen); hiddenPwdText[0] = 0; for (int i = 0; i < len; i++) { strcat(hiddenPwdText, passwordChar); } textToDraw = hiddenPwdText; } isEmptyText = !strcmp(textToDraw, ""); if (isEmptyText && defaultText) { textToDraw = (char*)defaultText; ctx->renderer->cmdSetColor(bodyTextDefaultElemState.color); } else { ctx->renderer->cmdSetColor(bodyElemState->color); } auto textRect = Rect( clipRect.x - (isEditingThis ? ctx->textInput.scrollOffset : 0), clipRect.y, clipRect.width, clipRect.height); // draw the actual text ctx->renderer->cmdDrawTextInBox( textToDraw, textRect, HAlignType::Left, VAlignType::Bottom); ctx->renderer->popClipRect(); setAsFocusable(); ctx->currentWidgetId++; return ctx->textInput.textChanged; } }
26.947368
124
0.721875
nyaki-HUN
2aa0326817c91a36bb82f5bcc874487e3f3939ea
1,036
cpp
C++
src/old/class/http.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
src/old/class/http.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
src/old/class/http.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
#include <curl/curl.h> #include "http.class.h" size_t Http::WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } // Cosa fa : Esegue una richiesta di tipo get ad una pagina web ed estrapola il risultato // sUrl : stringa, url al quale effettuare la richiesta // Ritorna : sRet -> stringa, valore di ritorno estratto dalla pagina string Http::get(string sUrl){ // Converto il tipo dell'url perchè "curl_easy_setopt(curl, CURLOPT_URL,sUrl" si aspetta che sUrl sia di tipo const char* const char *sUrlRequest = sUrl.c_str(); CURL *curl; CURLcode res; string sRet; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, sUrlRequest); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, this->WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &sRet); res = curl_easy_perform(curl); curl_easy_cleanup(curl); } return sRet; }
29.6
122
0.724903
lucabertoni
2aa0a0cc4ba30910b307ed8d5550b2226091fa99
824
cpp
C++
Scripts/239.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
17
2018-08-23T08:53:56.000Z
2021-04-17T00:06:13.000Z
Scripts/239.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
Scripts/239.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { deque<int> value; deque<int> index; vector<int> res; for (int i = 0; i < nums.size(); i++) { if (i < k - 1){ while (!value.empty() && value.back() < nums[i]) {value.pop_back();index.pop_back();} value.push_back(nums[i]); index.push_back(i); }else{ while (!value.empty() && index.front() < i - k + 1) {value.pop_front();index.pop_front();} while (!value.empty() && value.back() < nums[i]) {value.pop_back();index.pop_back();} value.push_back(nums[i]); index.push_back(i); res.push_back(value.front()); } } return res; } };
37.454545
107
0.474515
zzz0906
2aa0fcb1b601ea1731d0fce78a8f068cfa6ef5be
379
hpp
C++
src/libs/prediction.hpp
ronaldpereira/content-based-movie-recommendation
4113e262ea85be0210373000ec7d2692d92f834b
[ "MIT" ]
null
null
null
src/libs/prediction.hpp
ronaldpereira/content-based-movie-recommendation
4113e262ea85be0210373000ec7d2692d92f834b
[ "MIT" ]
null
null
null
src/libs/prediction.hpp
ronaldpereira/content-based-movie-recommendation
4113e262ea85be0210373000ec7d2692d92f834b
[ "MIT" ]
null
null
null
#ifndef PREDICTION #define PREDICTION #include <cmath> #include <iostream> #include <iomanip> #include <fstream> #include <cstring> #include "useritem.hpp" #include "content.hpp" #include "rocchio.hpp" class Prediction { private: double makePrediction(int, int, UserItem *, Content *, Rocchio *); public: void GetPredictions(char *, UserItem *, Content *); }; #endif
16.478261
70
0.71504
ronaldpereira
2aa12a9c615984dc57b097c466acb91aa6df2cf4
578
hpp
C++
pyhelpers/vector_list_conversion.hpp
debyos/omim
2d0df9c530a91a8931b0f8986ece5f1102a1ba7b
[ "Apache-2.0" ]
null
null
null
pyhelpers/vector_list_conversion.hpp
debyos/omim
2d0df9c530a91a8931b0f8986ece5f1102a1ba7b
[ "Apache-2.0" ]
null
null
null
pyhelpers/vector_list_conversion.hpp
debyos/omim
2d0df9c530a91a8931b0f8986ece5f1102a1ba7b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "std/vector.hpp" #include <boost/python.hpp> #include <boost/python/stl_iterator.hpp> namespace { template <typename T> vector<T> python_list_to_std_vector(boost::python::object const & iterable) { return vector<T>(boost::python::stl_input_iterator<T>(iterable), boost::python::stl_input_iterator<T>()); } template <typename T> boost::python::list std_vector_to_python_list(vector<T> const & v) { boost::python::object get_iter = boost::python::iterator<vector<T>>(); return boost::python::list(get_iter(v)); } } // namespace
24.083333
75
0.712803
debyos
2aa75ada35be8dcfb6fd3f6ffe5de5992bddd731
448
cc
C++
1rQuatri/2.First Loops/12.Counting a's (1)/P97969.cc
ulidev/UPC2015
8b3b44ce204fcb0faced227d32ba85f882a510d7
[ "MIT" ]
null
null
null
1rQuatri/2.First Loops/12.Counting a's (1)/P97969.cc
ulidev/UPC2015
8b3b44ce204fcb0faced227d32ba85f882a510d7
[ "MIT" ]
null
null
null
1rQuatri/2.First Loops/12.Counting a's (1)/P97969.cc
ulidev/UPC2015
8b3b44ce204fcb0faced227d32ba85f882a510d7
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; const char CARACTER = 'a'; int main() { //Pre: Input consists of a sequence of characters ended in a period. //Post: Print the number of times that ‘a’ appears in the sequence. string texto; getline(cin, texto); int nAs = 0; for (int i = 0; i < texto.length(); i++) { if(texto[i] == CARACTER) { nAs++; } } cout<<nAs<<endl; return 0; }
17.230769
72
0.560268
ulidev
2aa83d470fab739e88fab56e773028da8bfa15ba
2,743
cpp
C++
bacs/problem/src/single/test/matcher.cpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
null
null
null
bacs/problem/src/single/test/matcher.cpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
10
2018-02-06T14:46:36.000Z
2018-03-20T13:37:20.000Z
bacs/problem/src/single/test/matcher.cpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
1
2021-11-26T10:59:09.000Z
2021-11-26T10:59:09.000Z
#include <bacs/problem/single/test/matcher.hpp> #include <bunsan/fnmatch.hpp> #include <boost/regex.hpp> namespace bacs::problem::single::test { class matcher::impl { public: virtual ~impl() {} virtual bool match(const std::string &test_id) const = 0; }; class matcher::id : public matcher::impl { public: explicit id(const std::string &test_id) : m_test_id(test_id) {} bool match(const std::string &test_id) const override { return test_id == m_test_id; } private: const std::string m_test_id; }; class matcher::wildcard : public matcher::impl { public: explicit wildcard(const TestQuery::Wildcard &query) : m_wildcard(query.value(), flags(query)) {} bool match(const std::string &test_id) const override { return m_wildcard(test_id); } private: bunsan::fnmatcher::flag flags(const TestQuery::Wildcard &query) { bunsan::fnmatcher::flag flags_ = bunsan::fnmatcher::defaults; for (const int flag : query.flag()) { switch (static_cast<TestQuery::Wildcard::Flag>(flag)) { case problem::single::TestQuery::Wildcard::IGNORE_CASE: flags_ |= bunsan::fnmatcher::icase; break; } } return flags_; } private: const bunsan::fnmatcher m_wildcard; }; class matcher::regex : public matcher::impl { public: explicit regex(const TestQuery::Regex &query) : m_regex(query.value(), flags(query)) {} bool match(const std::string &test_id) const override { return boost::regex_match(test_id, m_regex); } private: boost::regex_constants::syntax_option_type flags( const problem::single::TestQuery::Regex &query) { boost::regex_constants::syntax_option_type flags_ = boost::regex_constants::normal; for (const int flag : query.flag()) { switch (static_cast<TestQuery::Regex::Flag>(flag)) { case TestQuery::Regex::IGNORE_CASE: flags_ |= boost::regex_constants::icase; break; } } return flags_; } private: const boost::regex m_regex; }; matcher::matcher(const TestQuery &query) : m_impl(make_query(query)) {} matcher::~matcher() {} bool matcher::operator()(const std::string &test_id) const { BOOST_ASSERT(m_impl); return m_impl->match(test_id); } std::shared_ptr<const matcher::impl> matcher::make_query( const TestQuery &query) { switch (query.query_case()) { case TestQuery::kId: return std::make_shared<id>(query.id()); case TestQuery::kWildcard: return std::make_shared<wildcard>(query.wildcard()); case TestQuery::kRegex: return std::make_shared<regex>(query.regex()); default: BOOST_THROW_EXCEPTION(matcher_not_set_error()); return nullptr; } } } // namespace bacs::problem::single::test
25.877358
71
0.674079
bacsorg
2aa947d6289a79fd27d4741ffda9fb3545cc9d82
3,422
cpp
C++
07_Project/KnightFighter/Source/Loader/XMStageLoader.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
07_Project/KnightFighter/Source/Loader/XMStageLoader.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
07_Project/KnightFighter/Source/Loader/XMStageLoader.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* -------------------------------------------------------------------------- * * File XMStageLoader.cpp * Description XMStageLoader * Author J.S Park * Contact pparkppark84@gmail.com * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. All rights reserved. * * -------------------------------------------------------------------------- * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "XMStageLoader.h" XMStageLoader::XMStageLoader ( KDvoid ) { m_pLoadArray = KD_NULL; m_pObject = KD_NULL; m_nSequence = 0; m_nLoaderState = LOADERSTATE_NONE; m_nStageState = STAGESTATE_NONE; } XMStageLoader::~XMStageLoader ( KDvoid ) { //m_pLoadArray->removeAllObjects ( ); CC_SAFE_RELEASE ( m_pLoadArray ); } KDvoid XMStageLoader::loadStage ( KDint nStage ) { CC_SAFE_RELEASE ( m_pLoadArray ); const KDchar* sFileName = ccszf ( "Stage/Stage_%d.plist", nStage ); m_pLoadArray = Array::createWithContentsOfFile ( sFileName ); m_pLoadArray->retain ( ); } KDvoid XMStageLoader::update ( KDvoid ) { if ( m_pLoadArray == KD_NULL ) { return; } if ( m_nLoaderState == LOADERSTATE_NONE ) { m_nSequence = 0; m_nLoaderState = LOADERSTATE_ROLL; } else if ( m_nLoaderState == LOADERSTATE_ROLL ) { Dictionary* pDict = (Dictionary*) m_pLoadArray->getObjectAtIndex ( m_nSequence++ ); String* pTodo = (String*) pDict->objectForKey ( "TODO" ); if ( pTodo->isEqual ( String::create ( "START" ) ) ) { m_nStageState = STAGESTATE_START; } else if ( pTodo->isEqual ( String::create ( "ADD ENEMY" ) ) ) { m_nStageState = STAGESTATE_ADDENEMY; m_pObject = (Dictionary*) pDict->objectForKey ( "OBJECT" ); } else if ( pTodo->isEqual ( String::create ( "END" ) ) ) { m_nStageState = STAGESTATE_END; } } else if ( m_nLoaderState == LOADERSTATE_WAIT ) { m_nStageState = STAGESTATE_WAIT; } } KDvoid XMStageLoader::setSequence ( KDint nSequence ) { m_nSequence = nSequence; } KDint XMStageLoader::getSequence ( KDvoid ) { return m_nSequence; } KDvoid XMStageLoader::setLoaderState ( KDint nLoaderState ) { m_nLoaderState = nLoaderState; } KDint XMStageLoader::getLoaderState ( KDvoid ) { return m_nLoaderState; } KDvoid XMStageLoader::setStageState ( KDint nStageState ) { m_nStageState = nStageState; } KDint XMStageLoader::getStageState ( KDvoid ) { return m_nStageState; } Object* XMStageLoader::getObject ( KDvoid ) { return m_pObject; }
26.122137
85
0.624781
mcodegeeks
2aa9d383dc18661fc0511cb6e579547e3671f107
2,072
cpp
C++
test/Matuna.OCLLayerKernelTest/OCLLayerKernelTest.cpp
mihed/ATML
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
test/Matuna.OCLLayerKernelTest/OCLLayerKernelTest.cpp
mihed/ATML
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
[ "BSL-1.0", "BSD-3-Clause" ]
3
2015-06-08T19:51:53.000Z
2015-07-01T10:15:06.000Z
test/Matuna.OCLLayerKernelTest/OCLLayerKernelTest.cpp
mihed/ATML
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch/catch.hpp" #include "Matuna.OCLHelper/OCLHelper.h" #include "Matuna.OCLHelper/OCLProgram.h" #include "Matuna.OCLConvNet/LayerKernel.h" #include <memory> using namespace Matuna::Helper; using namespace Matuna::MachineLearning; SCENARIO("Testing and executing a layer kernel") { auto platformInfos = OCLHelper::GetPlatformInfos(); for (auto& platformInfo : platformInfos) { auto context = OCLHelper::GetContext(platformInfo); auto program = new OCLProgram(); program->SetName("Testprogram"); LayerKernel<cl_float>* kernel = new LayerKernel<cl_float>(); int memoryCount = 100; cl_float scalar = 10; auto memory = context->CreateMemory(CL_MEM_READ_WRITE, memoryCount * sizeof(cl_float)); kernel->SetKernelName("DivideByScalarKernel"); string path = OCLProgram::DefaultSourceLocation + "LayerTestKernel.cl"; kernel->AddSourcePath(path); kernel->AddIncludePath(OCLProgram::DefaultSourceLocation); kernel->AddGlobalSize(memoryCount); kernel->AddDefineSubsitute(path, "OFFSET_SCALAR", 10); program->AttachKernel(unique_ptr<OCLKernel>(kernel)); context->AttachProgram(unique_ptr<OCLProgram>(program), context->GetDevices()); kernel->SetMemoryArg(memory.get(), 0); kernel->SetRealArg(scalar, 1); for(auto device: context->GetDevices()) device->ExecuteKernel(kernel); auto program2 = new OCLProgram(); program->SetName("Testprogram2"); LayerKernel<cl_float>* kernel2 = new LayerKernel<cl_float>(); kernel2->SetKernelName("DivideByScalarKernel"); kernel2->AddSourcePath(path); kernel2->AddIncludePath(OCLProgram::DefaultSourceLocation); kernel2->AddGlobalSize(memoryCount); kernel2->AddDefineSubsitute(path, "OFFSET_SCALAR", 10); kernel2->AddDefine(path, "USE_OFFSET"); program2->AttachKernel(unique_ptr<OCLKernel>(kernel2)); context->AttachProgram(unique_ptr<OCLProgram>(program2), context->GetDevices()); kernel2->SetMemoryArg(memory.get(), 0); kernel2->SetRealArg(scalar, 1); for(auto device: context->GetDevices()) device->ExecuteKernel(kernel2); } }
33.419355
89
0.757722
mihed
2aaaee190366f7e846efc88b533958e8dbb41b87
419
cpp
C++
source/aufgabe-1-12.cpp
GottaGoGitHub/programmiersprachen-abgabe-1
f1707ef3fecd84105f754c206497a4fb350b1c86
[ "MIT" ]
null
null
null
source/aufgabe-1-12.cpp
GottaGoGitHub/programmiersprachen-abgabe-1
f1707ef3fecd84105f754c206497a4fb350b1c86
[ "MIT" ]
null
null
null
source/aufgabe-1-12.cpp
GottaGoGitHub/programmiersprachen-abgabe-1
f1707ef3fecd84105f754c206497a4fb350b1c86
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> float volumen(float radius, float hoehe){ float vol = M_PI * radius * radius * hoehe; return vol; } float oberflaeche(float radius, float hoehe){ float of = 2 * M_PI * radius * (radius + hoehe); return of; } int main(){ int r = 4; int h = 5; std::cout << "Fuer Radius = 4 und Hoehe = 5: " << volumen(4, 5) << " und " << oberflaeche(4, 5) << "\n"; }
19.952381
108
0.577566
GottaGoGitHub
2aab6d842ea8086fb480de41f15260e5b33646fb
2,282
cc
C++
cvmfs/ingestion/task_write.cc
chrisburr/cvmfs
74691036341e6010c83e9dff093f0bcad6fd08e1
[ "BSD-3-Clause" ]
2
2021-05-15T05:22:23.000Z
2021-05-15T05:23:00.000Z
cvmfs/ingestion/task_write.cc
chrisburr/cvmfs
74691036341e6010c83e9dff093f0bcad6fd08e1
[ "BSD-3-Clause" ]
2
2018-05-04T13:43:45.000Z
2018-08-27T13:53:45.000Z
cvmfs/ingestion/task_write.cc
chrisburr/cvmfs
74691036341e6010c83e9dff093f0bcad6fd08e1
[ "BSD-3-Clause" ]
1
2021-12-13T00:20:14.000Z
2021-12-13T00:20:14.000Z
/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "task_write.h" #include <cstdlib> #include "logging.h" #include "upload_facility.h" #include "util/exception.h" void TaskWrite::OnBlockComplete( const upload::UploaderResults &results, BlockItem *block_item) { if (results.return_code != 0) { PANIC(kLogStderr, "block upload failed (code: %d)", results.return_code); } delete block_item; } void TaskWrite::OnChunkComplete( const upload::UploaderResults &results, ChunkItem *chunk_item) { if (results.return_code != 0) { PANIC(kLogStderr, "chunk upload failed (code: %d)", results.return_code); } FileItem *file_item = chunk_item->file_item(); file_item->RegisterChunk(FileChunk(*chunk_item->hash_ptr(), chunk_item->offset(), chunk_item->size())); delete chunk_item; if (file_item->IsProcessed()) { tubes_out_->DispatchAny(file_item); } } void TaskWrite::Process(BlockItem *input_block) { ChunkItem *chunk_item = input_block->chunk_item(); upload::UploadStreamHandle *handle = chunk_item->upload_handle(); if (handle == NULL) { // The closure passed here, is called by the AbstractUploader as soon as // it successfully committed the complete chunk handle = uploader_->InitStreamedUpload( upload::AbstractUploader::MakeClosure( &TaskWrite::OnChunkComplete, this, chunk_item)); assert(handle != NULL); chunk_item->set_upload_handle(handle); } switch (input_block->type()) { case BlockItem::kBlockData: uploader_->ScheduleUpload( handle, upload::AbstractUploader::UploadBuffer( input_block->size(), input_block->data()), upload::AbstractUploader::MakeClosure( &TaskWrite::OnBlockComplete, this, input_block)); break; case BlockItem::kBlockStop: // If there is a sole piece and a legacy bulk chunk, two times the same // chunk is being uploaded. Well. It doesn't hurt. if (chunk_item->IsSolePiece()) { chunk_item->MakeBulkChunk(); } uploader_->ScheduleCommit(handle, *chunk_item->hash_ptr()); delete input_block; break; default: PANIC(NULL); } }
27.493976
77
0.660824
chrisburr
2aac0fe3b3cd7a84b3fdeaa5168daa3e924ae1f7
12,898
cc
C++
src/base/WCSimDataCleaner.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
src/base/WCSimDataCleaner.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
src/base/WCSimDataCleaner.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
#include "WCSimDataCleaner.hh" #include "WCSimRecoDigit.hh" #include "WCSimRecoCluster.hh" #include "WCSimRecoClusterDigit.hh" #include <cmath> #include <iostream> #include <cassert> ClassImp(WCSimDataCleaner) static WCSimDataCleaner *fgDataCleaner = 0; WCSimDataCleaner *WCSimDataCleaner::Instance() { if (!fgDataCleaner) { fgDataCleaner = new WCSimDataCleaner(); } if (!fgDataCleaner) { assert(fgDataCleaner); } if (fgDataCleaner) { } return fgDataCleaner; } void WCSimDataCleaner::Config(Int_t config) { WCSimDataCleaner::Instance()->SetConfig(config); } void WCSimDataCleaner::MinPulseHeight(Double_t min) { WCSimDataCleaner::Instance()->SetMinPulseHeight(min); } void WCSimDataCleaner::NeighbourRadius(Double_t radius) { WCSimDataCleaner::Instance()->SetNeighbourRadius(radius); } void WCSimDataCleaner::NeighbourDigits(Int_t digits) { WCSimDataCleaner::Instance()->SetNeighbourDigits(digits); } void WCSimDataCleaner::ClusterRadius(Double_t radius) { WCSimDataCleaner::Instance()->SetClusterRadius(radius); } void WCSimDataCleaner::ClusterDigits(Int_t digits) { WCSimDataCleaner::Instance()->SetClusterDigits(digits); } void WCSimDataCleaner::TimeWindow(Double_t window) { WCSimDataCleaner::Instance()->SetTimeWindow(window); } void WCSimDataCleaner::PrintParameters() { WCSimDataCleaner::Instance()->RunPrintParameters(); } WCSimDataCleaner::WCSimDataCleaner() { // cleaning mode fConfig = WCSimDataCleaner::kPulseHeightAndClusters; // default cleaning parameters fMinPulseHeight = 0.0; // minimum pulse height (PEs) fNeighbourRadius = 200.0; // clustering window (cm) fMinNeighbourDigits = 2; // minimum neighbouring digits fClusterRadius = 200.0; // clustering window (cm) fMinClusterDigits = 50; // minimum clustered digits fTimeWindow = 25.0; // timing window (ns) // vector of filtered digits fFilterAll = new std::vector<WCSimRecoDigit *>; fFilterByPulseHeight = new std::vector<WCSimRecoDigit *>; fFilterByNeighbours = new std::vector<WCSimRecoDigit *>; fFilterByClusters = new std::vector<WCSimRecoDigit *>; // vector of clusters fClusterList = new std::vector<WCSimRecoCluster *>; } WCSimDataCleaner::~WCSimDataCleaner() { delete fFilterAll; delete fFilterByPulseHeight; delete fFilterByNeighbours; delete fFilterByClusters; delete fClusterList; } void WCSimDataCleaner::RunPrintParameters() { std::cout << " *** WCSimDataCleaner::PrintParameters() *** " << std::endl; std::cout << " Data Cleaner Parameters: " << std::endl << " Config = " << fConfig << std::endl << " MinPulseHeight = " << fMinPulseHeight << std::endl << " NeighbourRadius = " << fNeighbourRadius << std::endl << " MinNeighbourDigits = " << fMinNeighbourDigits << std::endl << " ClusterRadius = " << fClusterRadius << std::endl << " MinClusterDigits = " << fMinClusterDigits << std::endl << " TimeWindow = " << fTimeWindow << std::endl; return; } void WCSimDataCleaner::Reset() { return; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::Run(std::vector<WCSimRecoDigit *> *myDigitList) { std::cout << " *** WCSimDataCleaner::Run(...) *** " << std::endl; // input digit list // ================ std::vector<WCSimRecoDigit *> *myInputList = myDigitList; std::vector<WCSimRecoDigit *> *myOutputList = myDigitList; // filter all digits // ================= myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterAll(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kNone) return myOutputList; // filter by pulse height // ====================== myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterByPulseHeight(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kPulseHeight) return myOutputList; // filter using neighbouring digits // ================================ myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterByNeighbours(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kPulseHeightAndNeighbours) return myOutputList; // filter using clustered digits // ============================= myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterByClusters(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kPulseHeightAndClusters) return myOutputList; // return vector of filtered digits // ================================ return myOutputList; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::ResetDigits(std::vector<WCSimRecoDigit *> *myDigitList) { for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); recoDigit->ResetFilter(); } return myDigitList; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterDigits(std::vector<WCSimRecoDigit *> *myDigitList) { for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); recoDigit->PassFilter(); } return myDigitList; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterAll(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // ============================== fFilterAll->clear(); // filter all digits // ================= for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); fFilterAll->push_back(recoDigit); } // return vector of filtered digits // ================================ std::cout << " filter all: " << fFilterAll->size() << std::endl; return fFilterAll; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterByPulseHeight(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // =============================== fFilterByPulseHeight->clear(); // filter by pulse height // ====================== for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); if (recoDigit->GetQPEs() > fMinPulseHeight) { fFilterByPulseHeight->push_back(recoDigit); } } // return vector of filtered digits // ================================ std::cout << " filter by pulse height: " << fFilterByPulseHeight->size() << std::endl; return fFilterByPulseHeight; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterByNeighbours(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // =============================== fFilterByNeighbours->clear(); // create array of neighbours // ========================== Int_t Ndigits = myDigitList->size(); if (Ndigits <= 0) { return fFilterByNeighbours; } Int_t *numNeighbours = new Int_t[Ndigits]; for (Int_t idigit = 0; idigit < Ndigits; idigit++) { numNeighbours[idigit] = 0; } // count number of neighbours // ========================== for (UInt_t idigit1 = 0; idigit1 < myDigitList->size(); idigit1++) { for (UInt_t idigit2 = idigit1 + 1; idigit2 < myDigitList->size(); idigit2++) { WCSimRecoDigit *fdigit1 = (WCSimRecoDigit *)(myDigitList->at(idigit1)); WCSimRecoDigit *fdigit2 = (WCSimRecoDigit *)(myDigitList->at(idigit2)); Double_t dx = fdigit1->GetX() - fdigit2->GetX(); Double_t dy = fdigit1->GetY() - fdigit2->GetY(); Double_t dz = fdigit1->GetZ() - fdigit2->GetZ(); Double_t dt = fdigit1->GetTime() - fdigit2->GetTime(); Double_t drsq = dx * dx + dy * dy + dz * dz; if (drsq > 0.0 && drsq < fNeighbourRadius * fNeighbourRadius && fabs(dt) < fTimeWindow) { numNeighbours[idigit1]++; numNeighbours[idigit2]++; } } } // filter by number of neighbours // ============================== for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *fdigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); if (numNeighbours[idigit] >= fMinNeighbourDigits) { fFilterByNeighbours->push_back(fdigit); } } // delete array of neighbours // ========================== delete[] numNeighbours; // return vector of filtered digits // ================================ std::cout << " filter by neighbours: " << fFilterByNeighbours->size() << std::endl; return fFilterByNeighbours; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterByClusters(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // =============================== fFilterByClusters->clear(); // run clustering algorithm // ======================== std::vector<WCSimRecoCluster *> *myClusterList = (std::vector<WCSimRecoCluster *> *)(this->RecoClusters(myDigitList)); for (UInt_t icluster = 0; icluster < myClusterList->size(); icluster++) { WCSimRecoCluster *myCluster = (WCSimRecoCluster *)(myClusterList->at(icluster)); for (Int_t idigit = 0; idigit < myCluster->GetNDigits(); idigit++) { WCSimRecoDigit *myDigit = (WCSimRecoDigit *)(myCluster->GetDigit(idigit)); fFilterByClusters->push_back(myDigit); } } // return vector of filtered digits // ================================ std::cout << " filter by clusters: " << fFilterByClusters->size() << std::endl; return fFilterByClusters; } std::vector<WCSimRecoCluster *> *WCSimDataCleaner::RecoClusters(std::vector<WCSimRecoDigit *> *myDigitList) { // delete cluster digits // ===================== for (UInt_t i = 0; i < vClusterDigitList.size(); i++) { delete (WCSimRecoClusterDigit *)(vClusterDigitList.at(i)); } vClusterDigitList.clear(); // delete clusters // =============== for (UInt_t i = 0; i < vClusterList.size(); i++) { delete (WCSimRecoCluster *)(vClusterList.at(i)); } vClusterList.clear(); // clear vector clusters // ===================== fClusterList->clear(); // make cluster digits // =================== for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); WCSimRecoClusterDigit *clusterDigit = new WCSimRecoClusterDigit(recoDigit); vClusterDigitList.push_back(clusterDigit); } // run clustering algorithm // ======================== for (UInt_t idigit1 = 0; idigit1 < vClusterDigitList.size(); idigit1++) { for (UInt_t idigit2 = idigit1 + 1; idigit2 < vClusterDigitList.size(); idigit2++) { WCSimRecoClusterDigit *fdigit1 = (WCSimRecoClusterDigit *)(vClusterDigitList.at(idigit1)); WCSimRecoClusterDigit *fdigit2 = (WCSimRecoClusterDigit *)(vClusterDigitList.at(idigit2)); Double_t dx = fdigit1->GetX() - fdigit2->GetX(); Double_t dy = fdigit1->GetY() - fdigit2->GetY(); Double_t dz = fdigit1->GetZ() - fdigit2->GetZ(); Double_t dt = fdigit1->GetTime() - fdigit2->GetTime(); Double_t drsq = dx * dx + dy * dy + dz * dz; if (drsq > 0.0 && drsq < fClusterRadius * fClusterRadius && fabs(dt) < fTimeWindow) { fdigit1->AddClusterDigit(fdigit2); fdigit2->AddClusterDigit(fdigit1); } } } // collect up clusters // =================== Bool_t carryon = 0; for (UInt_t idigit = 0; idigit < vClusterDigitList.size(); idigit++) { WCSimRecoClusterDigit *fdigit = (WCSimRecoClusterDigit *)(vClusterDigitList.at(idigit)); if (fdigit->IsClustered() == 0 && fdigit->GetNClusterDigits() > 0) { vClusterDigitCollection.clear(); vClusterDigitCollection.push_back(fdigit); fdigit->SetClustered(); carryon = 1; while (carryon) { carryon = 0; for (UInt_t jdigit = 0; jdigit < vClusterDigitCollection.size(); jdigit++) { WCSimRecoClusterDigit *cdigit = (WCSimRecoClusterDigit *)(vClusterDigitCollection.at(jdigit)); if (cdigit->IsAllClustered() == 0) { for (Int_t kdigit = 0; kdigit < cdigit->GetNClusterDigits(); kdigit++) { WCSimRecoClusterDigit *cdigitnew = (WCSimRecoClusterDigit *)(cdigit->GetClusterDigit(kdigit)); if (cdigitnew->IsClustered() == 0) { vClusterDigitCollection.push_back(cdigitnew); cdigitnew->SetClustered(); carryon = 1; } } } } } if ((Int_t)vClusterDigitCollection.size() >= fMinClusterDigits) { WCSimRecoCluster *cluster = new WCSimRecoCluster(); fClusterList->push_back(cluster); vClusterList.push_back(cluster); for (UInt_t jdigit = 0; jdigit < vClusterDigitCollection.size(); jdigit++) { WCSimRecoClusterDigit *cdigit = (WCSimRecoClusterDigit *)(vClusterDigitCollection.at(jdigit)); WCSimRecoDigit *recodigit = (WCSimRecoDigit *)(cdigit->GetRecoDigit()); cluster->AddDigit(recodigit); } } } } // return vector of clusters // ========================= return fClusterList; }
28.347253
119
0.65956
chipsneutrino
2aac6f5726f8bc77c01f641e97502a437b825245
23,676
cpp
C++
svc_kube_vision_opencvplus/extras/ctis/ccHKmeans.cpp
lucmichalski/kube-vproxy
c7cc0edbcbcd07a48f0fc48b9457eae693b76688
[ "Apache-2.0" ]
3
2018-06-22T07:55:51.000Z
2021-06-21T19:18:16.000Z
svc_kube_vision_opencvplus/extras/ctis/ccHKmeans.cpp
lucmichalski/kube-vproxy
c7cc0edbcbcd07a48f0fc48b9457eae693b76688
[ "Apache-2.0" ]
null
null
null
svc_kube_vision_opencvplus/extras/ctis/ccHKmeans.cpp
lucmichalski/kube-vproxy
c7cc0edbcbcd07a48f0fc48b9457eae693b76688
[ "Apache-2.0" ]
1
2020-11-04T04:56:50.000Z
2020-11-04T04:56:50.000Z
// Author: Mohamed Aly <malaa@vision.caltech.edu> // Date: October 6, 2010 //#include <stdlib.h> #include <cstdlib> #include <cmath> #include <iostream> #include <fstream> #include <ctime> #include <string> #include <algorithm> #include "ccCommon.hpp" #include "ccHKmeans.hpp" //random number function to use with random_shuffle ptrdiff_t hkm_random_shuffle_rand(ptrdiff_t s) { return rand() % s; } #define MIN(A,B) (A)<(B) ? (A) : (B) #define URAND ((double)rand() / ((double)RAND_MAX + 1.)) //get a random number between [M1, M2) #define RAND(M1, M2) (URAND * ((M2)-(M1)) + (M1)) //random number between [M1, M2-1] #define IRAND(M1, M2) floor(RAND(M1,M2)) //----------------------------------------------------------------------- // get the nearest mean to the input point template <class T> HkmClassId HkmNode<T>::getNearMean1(Data<T> &point, HkmOptions &opt, uint* cids, float* dists) { // uint cid; // float dist; //use kdtree? if (opt.usekdt) { // cout << "creating kdt: " << this->kdf << endl; //create kdf if doesn't exist if (!this->kdf) { //create the kdtree for the means this->kdf = new Kdf(opt.kdtopt); if (!this->kdf) cout << "Memory error"; create(*this->kdf, this->means); } //get nearest neighbor getKnn(*this->kdf, this->means, point, this->means.size(), cids, dists); // getKnn(*this->kdf, this->means, point, 1, &cid, &dist); // //## change this!! // this->clearKdf(); } //just use exhaustive search else { knn(dists, cids, this->means.size(), point, this->means, opt.dist); // knn(&dist, &cid, 1, point, this->means, opt.dist); } // cout << " near class: " << cid << " & dist: " << dist << endl; //return return (HkmClassId) cids[0]; } //----------------------------------------------------------------------- /// gets the nearest mean for the input data template <class T> bool HkmNode<T>::getNearMean(Data<T> &data, HkmOptions &opt, uint* ids, float* dists) { //same ids like last iteration bool same = true; //number of points uint npoints = data.size(); uint nmeans = this->means.size(); // cout << "getNearMean:npoints " << data.size() << endl; //allocate ids and dists arrays // uint *ids = new uint[npoints]; // float *dists = new float[npoints]; //use kdtree? if (opt.usekdt) { //build the tree this->buildKdf(opt.kdtopt); //get the nearest means using the kdtree getKnn(*this->kdf, this->means, data, 1, ids, dists); //clear kdf this->clearKdf(); // cout << "cleared kdf: " << this->kdf << endl; } else { knn(dists, ids, 1, data, this->means, opt.dist); } //put back ids and check for (uint i=0; i<npoints; ++i) if (this->classIds[i] != ids[i] && ids[i]<nmeans) { same = false; this->classIds[i] = ids[i]; } // if (data.filterId(0) == 0) // cout << " point 0 -> dist:" << dists[0] << " id:" << ids[0] << endl; // cout << endl; // for (uint i=0; i<classIds.size(); ++i) // cout << " " << classIds[i]; cout << endl; // cout << " finished" << endl; //clear // delete [] ids; // delete [] dists; //return return same; } //----------------------------------------------------------------------- /// gets the means template <class T> void HkmNode<T>::getMeans(Data<T> &data, Data<double>& tmeans, HkmOptions &opt, uint* meanpoints) { // cout << "getMeans:npoints " << data.size() << endl; //now loop and compute uint npoints = data.size(); uint nmeans = this->means.size(); //array to hold number of points of every mean // uint *meanpoints = new uint[nmeans]; fill(meanpoints, meanpoints + nmeans, 0); //reset means to zero fill(tmeans.getFixed(), tmeans.getFixed() + tmeans.ndims*tmeans.npoints, 0.); //loop on the points in data for (uint i=0; i<npoints; ++i) { //get point pair<T*, uint> p = data.getPoint(i); //update count meanpoints[this->classIds[i]]++; //update its mean // pair<T*, uint> pm = this->means.getPoint(this->classIds[i]); pair<double*, uint> pm = tmeans.getPoint(this->classIds[i]); for (uint j=0; j<pm.second; ++j) pm.first[j] += (double)p.first[j]; } //for i //divide every mean by its number for (uint k=0; k<nmeans; ++k) { //get mean pair<T*, uint> pm = this->means.getPoint(k); pair<double*, uint> ptm = tmeans.getPoint(k); //check if its points > 0 if (meanpoints[k]) { for (uint j=0; j<pm.second; ++j) pm.first[j] = (T) (ptm.first[j] / meanpoints[k]); } //this mean had no points else { //grab a random point uint rid = (uint) IRAND(0, npoints); //rand() % npoints pair<T*, uint> p = data.getPoint(rid); // cout << " empty mean: " << k << " id: " << rid << endl; //copy copy(p.first, p.first + p.second, pm.first); } } //clear // delete [] meanpoints; } //----------------------------------------------------------------------- /// performs kmeans on the data in this node template <class T> void HkmNode<T>::initMeans(Data<T> &data, HkmOptions &opt) { //number of points uint npoints = data.size(); // cout << "initMeans:npoints " << data.size() << endl; //init means with random points this->means.clear(); this->means.init(DATA_FIXED, MIN(opt.nbranches, npoints), data.ndims); this->means.allocate(); //mean stds this->meanStds.resize(opt.nbranches); // this->means.type = DATA_FIXED; // this->means.npoints = MIN(opt.nbranches, npoints); // this->means.ndims = data.ndims; // //loop // for (uint i=0; i<opt.nbranches; ++i) // { // //get a random point // uint rid = (uint) IRAND(0, npoints); //rand() % npoints; // pair<T*, uint> p = data.getPoint(rid); // //put it into means // pair<T*, uint> pm = this->means.getPoint(i); // copy(p.first, p.first + p.second, pm.first); // //// cout << " random id: " << rid << endl; // } //init the classIds and fill randomly // cout << "npoints:" << npoints << endl; this->classIds.resize(npoints); // fill(this->classIds.begin(), this->classIds.end(), 0); for (uint i=0; i<npoints; ++i) this->classIds[i] = (HkmClassId) IRAND(0, opt.nbranches); //set to visited this->visited = true; } //----------------------------------------------------------------------- /// performs kmeans on the data in this node template <class T> void HkmNode<T>::kmeans(Data<T> &data, Data<double>& tmeans, HkmOptions &opt) { // //check if we need to do something? // if (data.size() < opt.nbranches) return; //init means with random class memberships this->initMeans(data, opt); if (data.size() <= opt.nbranches) { //copy data to means for (uint i=0, s=data.size(); i<s; ++i) { pair<T*, uint> p = data.getPoint(i); pair<T*, uint> pm = this->means.getPoint(i); copy(p.first, p.first + p.second, pm.first); this->classIds[i] = i; //set std to 0 this->meanStds[i] = 0; } //resize means this->means.npoints = data.size(); this->meanStds.resize(data.size()); return; } uint nmeans = means.size(); uint npoints = data.size(); //mean points used inside getMeans uint *meanpoints = new uint[nmeans]; //ids and dists used inside getNearMean uint *ids = new uint[npoints]; float *dists = new float[npoints]; // cout << "kmeans:npoints " << data.size() << endl; //main loop for (int iter=0; iter<opt.niters; ++iter) { //compute the current means this->getMeans(data, tmeans, opt, meanpoints); //get new class memberships, and break if the same ids like last iteration if (this->getNearMean(data, opt, ids, dists)) break; } //sum & sum2 to collect stats float* sum = new float[nmeans]; float* sum2 = new float[nmeans]; fill(sum, sum+nmeans, 0); fill(sum2, sum2+nmeans, 0); //compute std deviation of distances fill(meanpoints, meanpoints+nmeans, 0); //loop on points for (uint i=0; i<npoints; ++i) { HkmClassId mid = this->classIds[i]; //update meanpoints meanpoints[mid]++; //update sum & sum2 float t = dists[i]; sum[mid] += t; sum2[mid] += t*t; } //compute std for (uint i=0; i<nmeans; ++i) { this->meanStds[i] = meanpoints[i]>0 ? sqrt((sum2[i] - sum[i]*sum[i]/meanpoints[i]) / meanpoints[i]) : 0; } //// cout << "iter: " << iter << endl; // //compute distance to nearest mean // bool same = this->getNearMean(data, opt); //// cout << " same:" << same ; // // //check if same means as in last iteration // if (!same) // //re-compute means // this->getMeans(data, tmeans, opt); // else // //exit // break; //clear delete [] meanpoints; delete [] ids; delete [] dists; delete [] sum; delete [] sum2; } //----------------------------------------------------------------------- /// create the HKM forest template <class T> void Hkms<T>::create(Data<T> &data) { //initialize random number generator srand(0x1234); //loop on hkms and create this->resize(this->opt.ntrees); for (uint i=0; i<this->opt.ntrees; ++i) { this->hkms[i].opt = this->opt; this->hkms[i].create(data, this->opt); } } //----------------------------------------------------------------------- /// create the HKM tree template <class T> void Hkm<T>::create(Data<T> &data, HkmOptions& opt) { //allocate node list uint npoints = data.size(); double nnodes = 1; for (int l=1; l<opt.nlevels; l++) nnodes+=pow((double)opt.nbranches, l); this->resize((uint)nnodes); // cout << "nlevels:" << opt.nlevels << endl; // cout << "nbranches:" << opt.nbranches << endl; // cout << "nnodes:" << nnodes << endl; // cout << "npoints:" << npoints << endl; //initialize root with full list HkmNode<T>& root = this->at(1); root.resize(npoints); for (uint i=0; i<npoints; ++i) root.plist[i] = i; //make a temp means data to compute means Data<double> tmeans(DATA_FIXED, opt.nbranches, data.ndims); tmeans.allocate(); //loop on the tree starting at the root for (HkmNodeId n=1; n<=nnodes; ++n) { // cout << "node: " << n << endl; //get the node HkmNode<T>& node = this->at(n); //if empty plist, just skip if (node.size() == 0) continue; //set the data filter data.setFilter(& node.plist); // cout << "node:" << n << " has data " << data.size() << // " and plist: " << node.plist.size() << endl; //do kmeans at this node node.kmeans(data, tmeans, opt); // if (data.filterId(0) == 0) // cout << "node: " << n << " point 0: id: " << data.filterId(0) << " classid: " << // node.classIds[0] << endl; //clear data filter data.clearFilter(); //get node depth int depth = this->getDepth(n); // cout << " finished kmeans with depth " << depth << endl; // cout << "node:" << n << " has means " << node.means.size() << // " and plist " << node.size() << endl; //not last level, then put ids onto children if have enough if (depth+1 < opt.nlevels) // && node.size() > this->opt.nbranches*this->opt.nbranches) { //get id of first child HkmNodeId childId = this->getChildId(n); //fill in the point list for the children // cout << "childId:" << childId + node.classIds[i] << "size:" << this->size() << endl; for (uint i=0; i<node.size(); ++i) { // cout << "childId:" << childId + node.classIds[i] << "size:" << this->size() << endl; // cout << "plist size="<< this->at(childId + node.classIds[i]).plist.size() << endl; this->at(childId + node.classIds[i]).plist.push_back(node.plist[i]); } // for (uint i=0; i<node.size(); ++i) // cout << " " << node.classIds[i]; cout << endl; //clear lists: plist and classIds node.clearLists(); } // //display first mean // cout << endl; // for (uint j=0; j<node.means.size(); ++j) // { // cout << "point: " << j << endl; // for (uint i=0; i<data.ndims; ++i) // cout << " " << node.means.getPointVal(j, i); // cout << endl; // } } //for n //clear tmeans tmeans.clear(); } //----------------------------------------------------------------------- /// descend down the tree starting from a given node template <class T> HkmNodeId Hkm<T>::descend(HkmNodeId start, Data<T>& data, uint pid, HkmClassId &meanid, HkmBranchQ* pq, HkmOptions& opt, uint tid) { HkmNodeId end = start; meanid = 0; //return if not a valid id if (!this->validId(end)) return end; //get the data point as a data object pair<T*, uint> p = data.getPoint(pid); Data<T> point(DATA_FIXED, 1, p.second); point.setFixed(p.first, false); //arrays to hold list of ids and dists to means // uint* cids = new uint[opt.nbranches]; // float* dists = new float[opt.nbranches]; //loop through starting at this node while (true) { //get the node HkmNode<T>& node = this->at(end); //get dists to means fill(this->cids, this->cids+opt.nbranches, opt.nbranches+10); fill(this->dists, this->dists+opt.nbranches, numeric_limits<float>::infinity()); meanid =node.getNearMean1(point, opt, this->cids, this->dists); //make nearest mean 1-based // meanid++; //first child id HkmNodeId fcid = this->getChildId(end); //add other branches to pq if (pq != 0) for (uint i=1; i<node.means.size(); ++i) { //get child id HkmNodeId cid = fcid + cids[i]; //add branch // HkmBranch b(cid, tid, fabs(dists[i]), meanid); // pq->push_back(b); //#malaa: try not using the distance, make it zero and see if that will //improve, branches are just explored based on their order // HkmBranch b(cid, tid, 0, meanid); // pq->push_back(b); //#malaa: try using distance divided by std dev HkmBranch b(cid, tid, node.meanStds[cids[i]] > 0 ? dists[i] / node.meanStds[cids[i]] : numeric_limits<float>::infinity(), meanid); pq->push_back(b); } // meanid = node.getNearMean1(point, opt) + 1; //check if to stop now HkmNodeId childId = fcid + meanid; // cout << "pid: " << pid << " node: " << end << " has meanid " << meanid << // " & child " << childId << endl; // if (this->validId(childId)) // cout << " child visited: " << this->at(childId).visited; // cout << endl; if (!this->validId(childId) || !this->at(childId).visited) break; //put the right child as the next node to check end = childId; } //clear point.clear(); // delete [] cids; // delete [] dists; //return the current valid node return end; } //----------------------------------------------------------------------- /// get leaf ids for input data template <class T> void Hkms<T>::getLeafIds(Data<T> &data, HkmClassId *cids) { // initialize for descend this->initDescend(); //number of points uint npoints = data.size(); //get the starting id of the first leaf (first nodedid outside the current //tree), where leaf means it's not in the tree HkmNodeId sleaf = this->hkms[0].getLeafId() + 1; //get the id of the first node in the last level HkmNodeId pleaf = this->hkms[0].getParentId(sleaf); //loop on the points for (uint i=0; i<npoints; ++i) { //get the class id for this point HkmClassId cid; //loop on the trees for (uint t=0; t<this->opt.ntrees; ++t) { cid = this->hkms[t].getLeafId(data, i, sleaf, pleaf, this->opt); //put back cids[t+this->opt.ntrees*i] = cid; } } // initialize for descend this->finishDescend(); } //----------------------------------------------------------------------- /// get leaf ids for input data template <class T> HkmClassId Hkm<T>::getLeafId(Data<T> &data, uint pid, HkmNodeId sleaf, HkmNodeId pleaf, HkmOptions& opt) { //get the class id for this point HkmClassId cid; HkmNodeId nodeId = this->descend(this->getRootId(), data, pid, cid, 0, opt, 0); int depth = this->getDepth(nodeId); // cout << "nodeId:" << nodeId << ", depth:" << depth << ", levels:" << this->opt.nlevels << ","; //get the deepest child for nodeId on the last level if (depth+1 < this->opt.nlevels) { nodeId = this->getDeepChildId(this->getChildId(nodeId) + cid - 1); cid = 0; } //check its value // if (cid > 0) // { cid += (nodeId - pleaf) * opt.nbranches; // cout << "nodeId:" << nodeId << ", pleaf:" << pleaf << ", cid: " << cid << endl; // cid = this->getChildId(nodeId) + cid - 1; // } return cid; } //----------------------------------------------------------------------- /// get Ids of points close to a given point template <class T> void Hkms<T>::getIds(Data<T>& data, uint pid, HkmPointList& plist) { //create the priority queue HkmBranchQ pq; //initialize it with the root nodes in all the trees for (uint t=0; t<this->opt.ntrees; ++t) { HkmBranch b(1, t, 0.); pq.push_back(b); } //now loop on pq and process uint bins = this->opt.nchecks; while (bins && pq.size()>0) { //sort the queue // sort(pq.begin(), pq.end()); pq.sort(); //truncate if too large if (pq.size() > this->opt.nchecks) pq.resize(this->opt.nchecks); //get the top branch HkmBranch branch = pq.front(); pq.pop_front(); // cout << "branch -> tid: " << branch.treeId << " nodeid: " << branch.nodeId << // " dist: " << branch.dist << " mid: " << branch.meanId << endl; //go down the respective tree Hkm<T>& hkm = this->hkms[branch.treeId]; HkmClassId meanid; HkmNodeId nid = hkm.descend(branch.nodeId, data, pid, meanid, &pq, this->opt, branch.treeId); // HkmNodeId nid = hkm.descend(branch.nodeId, data, pid, branch.treeId, pq, kdf.opt); //if not valid id, then this was a branch at the lowest level of the tree //so we need to get back to its parent and get points with meanid in the //branch if (!hkm.validId(nid)) { //get parent and make sure its valid nid = hkm.getParentId(nid); //meanid is the meanId in the branch meanid = branch.meanId; } //check if valid (again if getting the parent if (hkm.validId(nid)) { //add the list of ids with the same meanid HkmNode<T>& node = hkm.at(nid); for (uint i=0, s=node.size(); i<s; ++i) if (node.classIds[i] == meanid) plist.push_back(node.plist[i]); // plist.insert(plist.end(), node.plist.begin(), node.plist.end()); // //show now // cout << " nodeid: " << nid << " visited:" << node.visited << " split.dim: " << node.split.dim << // " split.val: " << node.split.val << " ids: "; // for (uint i=0; i<node.plist.size(); ++i) cout << " " << node.plist[i]; // cout << endl; } //decrement bins--; } //clear pq pq.clear(); } // //----------------------------------------------------------------------- // /// get Ids of points close to a given point // template <class T> // void Hkm<T>::getIds(Data<T>& data, uint pid, HkmPointList& plist) // { // //descend through the tree // HkmClassId meanId; // HkmNodeId nodeId = this->descend(this->getRootId(), data, pid, meanId); // // // cout << "point " << pid << " found node " << nodeId << " & meanid " << meanId << endl; // // //check if a valid meanId // if (meanId>0) // { // //get node // HkmNode<T> &node = this->at(nodeId); // // //subtract to make 0-based // meanId--; // // //loop on the points that have this class and add their ids // for (uint i=0, s=node.size(); i<s; ++i) // if (node.classIds[i] == meanId) // plist.push_back(node.plist[i]); // } // } //----------------------------------------------------------------------- /// lookup the trees and return nearest neighbors template <class T> template <class Tret> void Hkms<T>::hkmKnn(Data<T>& hkmData, Data<T>& sdata, int k, uint* ids, Tret* dists) { // initialize for descend this->initDescend(); //loop on the points DataFilter sfilter(1); for (uint i=0; i<sdata.size(); ++i) { //get list of points close to that point HkmPointList pl; this->getIds(sdata, i, pl); // cout << "point " << i << " has points:" << endl; // for (uint kk=0; kk<pl.size(); ++kk) // cout << " " << pl[kk]; // cout << endl; //remove duplicates sort(pl.begin(), pl.end()); HkmPointIt it = unique(pl.begin(), pl.end()); pl.resize(it - pl.begin()); //random shuffle random_shuffle(pl.begin(), pl.end(), hkm_random_shuffle_rand); //set the filter for kdtData hkmData.setFilter(&pl); //set filter for sdata sfilter[0] = i; sdata.setFilter(&sfilter); //get Knn knn(dists+(i*k), ids+(i*k), k, sdata, hkmData, this->opt.dist); //update ids to get the real ones for (uint f=0, fs=pl.size(), j=i*k; f<fs && f<k; ++f, ++j) ids[j] = pl[ids[j]]; //reset filter hkmData.clearFilter(); sdata.clearFilter(); pl.clear(); } //for i // fnish for descend this->finishDescend(); } //----------------------------------------------------------------------- template <class T> void Hkm<T>::initDescend(HkmOptions& opt) { //if we are using kd-trees, then init all of them if (opt.usekdt) for (uint i=this->getRootId(); i<=this->getLeafId(); ++i) this->at(i).buildKdf(opt.kdtopt); //allocate buffers for descend cids = new uint[opt.nbranches]; dists = new float[opt.nbranches]; } //----------------------------------------------------------------------- template <class T> void Hkms<T>::initDescend() { //loop on trees for (uint i=0; i<this->opt.ntrees; ++i) this->hkms[i].initDescend(this->opt); } //----------------------------------------------------------------------- /// clear kdfs template <class T> void Hkm<T>::finishDescend() { //if we are using kd-trees, then init all of them if (this->opt.usekdt) for (uint i=this->getRootId(); i<=this->getLeafId(); ++i) this->at(i).clearKdf(); //deallocate cids & dists if (cids != 0) delete [] cids; if (dists != 0) delete [] dists; } //----------------------------------------------------------------------- template <class T> void Hkms<T>::finishDescend() { //loop on trees for (uint i=0; i<this->opt.ntrees; ++i) this->hkms[i].finishDescend(); } // //----------------------------------------------------------------------- // #define TEMPLATE(F) \ // F(int) \ // F(double) \ // F(float) \ // F(char) \ // F(unsigned char) \ // F(unsigned int) #define GETKNN_F(T) \ template void Hkms<T>::hkmKnn(Data<T>&, Data<T>&, int, uint*, float*); #define GETKNN_D(T) \ template void Hkms<T>::hkmKnn(Data<T>&, Data<T>&, int, uint*, double*); #define CREATE(T) \ template void Hkms<T>::create(Data<T> &); #define LEAFIDS(T) \ template void Hkms<T>::getLeafIds(Data<T> &, HkmClassId*); TEMPLATE(GETKNN_F) TEMPLATE(GETKNN_D) TEMPLATE(CREATE) TEMPLATE(LEAFIDS)
28.219309
105
0.538689
lucmichalski
2aaf1ce7e07a34f2a1b48e2bd95754af25855fbd
3,027
cc
C++
voicenavigator/src/model/DescribeRedirectionResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
voicenavigator/src/model/DescribeRedirectionResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
voicenavigator/src/model/DescribeRedirectionResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/voicenavigator/model/DescribeRedirectionResult.h> #include <json/json.h> using namespace AlibabaCloud::VoiceNavigator; using namespace AlibabaCloud::VoiceNavigator::Model; DescribeRedirectionResult::DescribeRedirectionResult() : ServiceResult() {} DescribeRedirectionResult::DescribeRedirectionResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeRedirectionResult::~DescribeRedirectionResult() {} void DescribeRedirectionResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allSimilarUtterances = value["SimilarUtterances"]["SimilarUtterance"]; for (const auto &item : allSimilarUtterances) similarUtterances_.push_back(item.asString()); if(!value["InstanceId"].isNull()) instanceId_ = value["InstanceId"].asString(); if(!value["CategoryId"].isNull()) categoryId_ = value["CategoryId"].asString(); if(!value["NavigationScriptId"].isNull()) navigationScriptId_ = value["NavigationScriptId"].asString(); if(!value["UserUtterance"].isNull()) userUtterance_ = value["UserUtterance"].asString(); if(!value["Prompt"].isNull()) prompt_ = value["Prompt"].asString(); if(!value["Interruptible"].isNull()) interruptible_ = value["Interruptible"].asString() == "true"; if(!value["RedirectionType"].isNull()) redirectionType_ = value["RedirectionType"].asString(); if(!value["RedirectionTarget"].isNull()) redirectionTarget_ = value["RedirectionTarget"].asString(); } std::string DescribeRedirectionResult::getCategoryId()const { return categoryId_; } bool DescribeRedirectionResult::getInterruptible()const { return interruptible_; } std::string DescribeRedirectionResult::getRedirectionTarget()const { return redirectionTarget_; } std::vector<std::string> DescribeRedirectionResult::getSimilarUtterances()const { return similarUtterances_; } std::string DescribeRedirectionResult::getRedirectionType()const { return redirectionType_; } std::string DescribeRedirectionResult::getInstanceId()const { return instanceId_; } std::string DescribeRedirectionResult::getUserUtterance()const { return userUtterance_; } std::string DescribeRedirectionResult::getPrompt()const { return prompt_; } std::string DescribeRedirectionResult::getNavigationScriptId()const { return navigationScriptId_; }
27.770642
82
0.767757
iamzken
2ab139ec223782022e5b03681888693d49ab0918
39,723
cc
C++
supersonic/cursor/core/hybrid_aggregate_test.cc
IssamElbaytam/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
201
2015-03-18T21:55:00.000Z
2022-03-03T01:48:26.000Z
supersonic/cursor/core/hybrid_aggregate_test.cc
edisona/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
6
2015-03-19T16:47:19.000Z
2020-10-05T09:38:26.000Z
supersonic/cursor/core/hybrid_aggregate_test.cc
edisona/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
54
2015-03-19T16:31:57.000Z
2021-12-31T10:14:57.000Z
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <memory> #include "supersonic/base/infrastructure/projector.h" #include "supersonic/cursor/base/cursor.h" #include "supersonic/cursor/base/cursor_transformer.h" #include "supersonic/cursor/core/aggregate.h" #include "supersonic/cursor/core/hybrid_group_utils.h" #include "supersonic/cursor/core/sort.h" #include "supersonic/cursor/core/spy.h" #include "supersonic/cursor/infrastructure/ordering.h" #include "supersonic/testing/block_builder.h" #include "supersonic/testing/comparators.h" #include "supersonic/testing/operation_testing.h" #include "supersonic/testing/repeating_block.h" #include "gtest/gtest.h" #include "gtest/gtest.h" #include "supersonic/utils/container_literal.h" namespace supersonic { namespace { class HybridAggregateTest : public testing::Test { protected: CompoundSingleSourceProjector empty_projector_; }; class HybridAggregateSpyTest : public testing::TestWithParam<bool> {}; // A lot of tests just copied from aggregate_groups_test.cc. Maybe it would be // better to share this code somehow and avoid "copy & paste". FailureOrOwned<Cursor> CreateGroupAggregate( const SingleSourceProjector& group_by, const AggregationSpecification& aggregation, Cursor* input) { std::unique_ptr<Cursor> input_owner(input); return BoundHybridGroupAggregate( group_by.Clone(), aggregation, "", HeapBufferAllocator::Get(), 16, NULL, input_owner.release()); } // Sorts cursor according to all columns in an ascending order. This function is // needed because group provides no guarantees over the order of returned rows, // so output needs to be sorted before it is compared against expected output. static Cursor* Sort(Cursor* input) { SortOrder sort_order; sort_order.add(ProjectAllAttributes(), ASCENDING); std::unique_ptr<const BoundSortOrder> bound_sort_order( SucceedOrDie(sort_order.Bind(input->schema()))); std::unique_ptr<const SingleSourceProjector> result_projector( ProjectAllAttributes()); std::unique_ptr<const BoundSingleSourceProjector> bound_result_projector( SucceedOrDie(result_projector->Bind(input->schema()))); return SucceedOrDie(BoundSort( bound_sort_order.release(), bound_result_projector.release(), std::numeric_limits<size_t>::max(), "", HeapBufferAllocator::Get(), input)); } TEST_F(HybridAggregateTest, SimpleAggregation) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(4).BuildCursor()); EXPECT_EQ("sum", aggregate->schema().attribute(0).name()); EXPECT_TRUE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountWithInputColumn) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().AddRow(2).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountWithDefinedOutputType) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregationWithDefinedOutputType(COUNT, "col0", "count", INT32); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(2).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountWithNullableInputColumn) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().AddRow(1).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountAll) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().AddRow(2).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Three kinds of COUNT. TEST_F(HybridAggregateTest, CountAllColumnDistinct) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(1) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "", "count_all"); aggregation.AddAggregation(COUNT, "col0", "count_column"); aggregation.AddDistinctAggregation(COUNT, "col0", "count_distinct"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64, UINT64, UINT64>().AddRow(3, 2, 1).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_FALSE(aggregate->schema().attribute(1).is_nullable()); EXPECT_FALSE(aggregate->schema().attribute(2).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationWithOnlyNullInputs) { Cursor* input = TestDataBuilder<INT32>() .AddRow(__) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(__).BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationWithOutputTypeDifferentFromInputType) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregationWithDefinedOutputType(SUM, "col0", "sum", INT64); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT64>().AddRow(4).BuildCursor()); EXPECT_EQ("sum", aggregate->schema().attribute(0).name()); EXPECT_TRUE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, MultipleAggregations) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(2) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); aggregation.AddAggregation(MAX, "col0", "max"); aggregation.AddAggregation(MIN, "col0", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32>().AddRow(6, 3, 1).BuildCursor()); EXPECT_EQ("sum", aggregate->schema().attribute(0).name()); EXPECT_EQ("max", aggregate->schema().attribute(1).name()); EXPECT_EQ("min", aggregate->schema().attribute(2).name()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, DistinctAggregation) { Cursor* input = TestDataBuilder<INT32>() .AddRow(3) .AddRow(4) .AddRow(4) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddDistinctAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); // Only distinct values are summed (3 + 4). std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(7).BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, DistinctCountAggregation) { Cursor* input = TestDataBuilder<INT32>() .AddRow(3) .AddRow(4) .AddRow(4) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddDistinctAggregationWithDefinedOutputType( COUNT, "col0", "count", INT32); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(0).name()); // There are two distinct values (3, 4). std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(2).BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, DistinctCountAggregationNeedsInputColumn) { Cursor* input = TestDataBuilder<INT32>() .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; // This should not work, there is no way to find distinct values if input // column is not specified. aggregation.AddDistinctAggregationWithDefinedOutputType( COUNT, "", "count", INT32); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); EXPECT_TRUE(result.is_failure()); } TEST_F(HybridAggregateTest, AggregationWithGroupBy) { Cursor* input = TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(3, -3) .AddRow(1, 4) .AddRow(3, -5) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col1", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32>().AddRow(1, 7).AddRow(3, -8).BuildCursor()); EXPECT_EQ("col0", aggregate->schema().attribute(0).name()); EXPECT_EQ("sum", aggregate->schema().attribute(1).name()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_TRUE(aggregate->schema().attribute(1).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationWithGroupByNullableColumn) { Cursor* input = TestDataBuilder<INT32, INT32>() .AddRow(3, -3) .AddRow(__, 4) .AddRow(3, -5) .AddRow(__, 1) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col1", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); std::unique_ptr<Cursor> expected_output(TestDataBuilder<INT32, INT32>() .AddRow(3, -8) .AddRow(__, 5) .BuildCursor()); EXPECT_EQ("col0", aggregate->schema().attribute(0).name()); EXPECT_EQ("sum", aggregate->schema().attribute(1).name()); EXPECT_TRUE(aggregate->schema().attribute(0).is_nullable()); EXPECT_TRUE(aggregate->schema().attribute(1).is_nullable()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } INSTANTIATE_TEST_CASE_P(SpyUse, HybridAggregateSpyTest, testing::Bool()); TEST_P(HybridAggregateSpyTest, GroupBySecondColumn) { Cursor* input = TestDataBuilder<INT32, STRING>() .AddRow(-3, "foo") .AddRow(2, "bar") .AddRow(3, "bar") .AddRow(-2, "foo") .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col1")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); if (GetParam()) { std::unique_ptr<CursorTransformerWithSimpleHistory> spy_transformer( PrintingSpyTransformer()); aggregate->ApplyToChildren(spy_transformer.get()); aggregate.reset(spy_transformer->Transform(aggregate.release())); } std::unique_ptr<Cursor> expected_output(TestDataBuilder<STRING, INT32>() .AddRow("foo", -5) .AddRow("bar", 5) .BuildCursor()); EXPECT_EQ("col1", aggregate->schema().attribute(0).name()); EXPECT_EQ("sum", aggregate->schema().attribute(1).name()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, GroupByTwoColumns) { Cursor* input = TestDataBuilder<STRING, INT32, INT32>() .AddRow("foo", 1, 3) .AddRow("bar", 2, -3) .AddRow("foo", 1, 4) .AddRow("bar", 3, -5) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttributes(util::gtl::Container("col0", "col1"))); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col2", "sum"); std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_columns, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, INT32, INT32>() .AddRow("foo", 1, 7) .AddRow("bar", 2, -3) .AddRow("bar", 3, -5) .BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, GroupByTwoColumnsWithMultipleAggregations) { Cursor* input = TestDataBuilder<STRING, INT32, INT32>() .AddRow("foo", 1, 3) .AddRow("bar", 2, -3) .AddRow("foo", 1, 4) .AddRow("bar", 3, -5) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttributes(util::gtl::Container("col0", "col1"))); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col2", "sum"); aggregation.AddAggregation(MIN, "col2", "min"); aggregation.AddAggregation(COUNT, "", "count"); std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_columns, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(4).name()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, INT32, INT32, INT32, UINT64>() // Group by col, group by col, SUM col, MIN col, COUNT col .AddRow("foo", 1, 7, 3, 2) .AddRow("bar", 2, -3, -3, 1) .AddRow("bar", 3, -5, -5, 1) .BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, GroupByWithoutAggregateFunctions) { Cursor* input = TestDataBuilder<STRING>() .AddRow("foo") .AddRow("bar") .AddRow("foo") .AddRow("bar") .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification empty_aggregator; std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_column, empty_aggregator, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING>().AddRow("foo").AddRow("bar").BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } // Aggregation on empty input with empty key should return empty result. TEST_F(HybridAggregateTest, AggregationOnEmptyInput) { Cursor* input = TestDataBuilder<DATETIME>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(MIN, "col0", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<DATETIME>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Aggregation on empty input with group by columns should return empty result. TEST_F(HybridAggregateTest, AggregationOnEmptyInputWithGroupByColumn) { Cursor* input = TestDataBuilder<STRING, DATETIME>().BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(MIN, "col1", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, DATETIME>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Count on empty input with empty key should return empty result. TEST_F(HybridAggregateTest, CountOnEmptyInput) { Cursor* input = TestDataBuilder<DATETIME>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(0).name()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Count on empty input with group by columns should return empty result. TEST_F(HybridAggregateTest, CountOnEmptyInputWithGroupByColumn) { Cursor* input = TestDataBuilder<STRING, DATETIME>() .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col1", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(1).name()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, UINT64>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationInputColumnMissingError) { Cursor* input = TestDataBuilder<INT32>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "NotExistingCol", "sum"); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_ATTRIBUTE_MISSING, result.exception().return_code()); } TEST_F(HybridAggregateTest, AggregationResultColumnExistsError) { Cursor* input = TestDataBuilder<INT32, INT32>().BuildCursor(); AggregationSpecification aggregation; // Two results can not be stored in the same column. aggregation.AddAggregation(SUM, "col0", "result_col"); aggregation.AddAggregation(MIN, "col1", "result_col"); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_ATTRIBUTE_EXISTS, result.exception().return_code()); } TEST_F(HybridAggregateTest, NotSupportedAggregationError) { Cursor* input = TestDataBuilder<BINARY>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_INVALID_ARGUMENT_TYPE, result.exception().return_code()); } TEST_F(HybridAggregateTest, ExceptionFromInputPropagated) { Cursor* input = TestDataBuilder<INT32>() .ReturnException(ERROR_GENERAL_IO_ERROR) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); FailureOrOwned<Cursor> cursor( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(cursor.is_success()); ResultView result = cursor.get()->Next(100); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_GENERAL_IO_ERROR, result.exception().return_code()); } TEST_F(HybridAggregateTest, LargeInput) { TestDataBuilder<INT64, STRING> cursor_builder; for (int i = 0; i < 3 * Cursor::kDefaultRowCount + 1; ++i) { cursor_builder.AddRow(13, "foo") .AddRow(17, "bar") .AddRow(13, "foo"); } Cursor* input = cursor_builder.BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttributes(util::gtl::Container("col0", "col1"))); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_columns, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT64, STRING, INT64>() .AddRow(13, "foo", 2 * 13 * (3 * Cursor::kDefaultRowCount + 1)) .AddRow(17, "bar", 17 * (3 * Cursor::kDefaultRowCount + 1)) .BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, TransformTest) { Cursor* input = TestDataBuilder<DATETIME>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(MIN, "col0", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<CursorTransformerWithSimpleHistory> spy_transformer( PrintingSpyTransformer()); aggregate->ApplyToChildren(spy_transformer.get()); // Spy transformer should add one child, it will be a transformed version of // the input cursor. ASSERT_EQ(1, spy_transformer->GetHistoryLength()); } // Some new tests. To be removed if the duplicated the tests above. TEST_F(HybridAggregateTest, NoGroupByColumns) { OperationTest test; test.SetInput(TestDataBuilder<INT32>() .AddRow(1) .AddRow(1) .AddRow(3) .AddRow(3) .AddRow(2) .AddRow(3) .AddRow(1) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, UINT64, UINT64>() .AddRow(14, 7, 3) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( empty_projector_.Clone(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, Simple1) { OperationTest test; test.SetIgnoreRowOrder(true); test.SetInput( TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(1, 4) .AddRow(3, -3) .AddRow(2, 4) .AddRow(3, -5) .Build()); test.SetExpectedResult( TestDataBuilder<INT32, INT32, INT32, UINT64, UINT64>() .AddRow(1, 7, 2, 2, 1) .AddRow(2, 4, 2, 1, 1) .AddRow(3, -8, 6, 2, 1) .Build()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col1", "sum"); aggregation->AddAggregation(SUM, "col0", "sum2"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( group_by_columns.release(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, DistinctAggregations) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(1, 4) .AddRow(3, -1) .AddRow(3, -2) .AddRow(2, 4) .AddRow(3, -3) .AddRow(1, 3) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(1, 7, 2, 1) .AddRow(2, 4, 1, 1) .AddRow(3, -6, 3, 1) .Build()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddDistinctAggregation(SUM, "col1", "sum"); aggregation->AddDistinctAggregation(COUNT, "col1", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "cnt2"); test.Execute(HybridGroupAggregate( group_by_columns.release(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, NonDistinctAndDistinctAggregations) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(1, 4) .AddRow(3, -1) .AddRow(3, -2) .AddRow(2, 4) .AddRow(3, -3) .AddRow(1, 3) .AddRow(1, __) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, INT32, UINT64, UINT64>() .AddRow(1, 7, 2, 10, 3, 4) .AddRow(2, 4, 1, 4, 1, 1) .AddRow(3, -6, 3, -6, 3, 3) .Build()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddDistinctAggregation(SUM, "col1", "sum"); aggregation->AddDistinctAggregation(COUNT, "col1", "cnt"); aggregation->AddAggregation(SUM, "col1", "sum2"); aggregation->AddAggregation(COUNT, "col1", "cnt2"); aggregation->AddAggregation(COUNT, "", "cnt3"); test.Execute(HybridGroupAggregate( group_by_columns.release(), aggregation.release(), 16, "", test.input())); } // Test hybrid group transform for two distinct aggregations some non-distinct // aggregations including COUNT(*). Each distinct aggregation should get its // copy of data. All non-distinct aggregation share one copy of the data. // COUNT(*) gets a new column in the non-distinct data. TEST_F(HybridAggregateTest, HybridGroupTransformTest) { std::unique_ptr<Cursor> input(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, 1) .AddRow(1, 4, 2) .AddRow(3, -3, 3) .AddRow(2, 4, 4) .AddRow(3, -5, 5) .BuildCursor()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32, INT32, INT32, INT32>() .AddRow(1, 3, __, __, __, __) .AddRow(1, 4, __, __, __, __) .AddRow(3, -3, __, __, __, __) .AddRow(2, 4, __, __, __, __) .AddRow(3, -5, __, __, __, __) .AddRow(1, __, 1, __, __, __) .AddRow(1, __, 2, __, __, __) .AddRow(3, __, 3, __, __, __) .AddRow(2, __, 4, __, __, __) .AddRow(3, __, 5, __, __, __) .AddRow(1, __, __, 3, 1, 0) .AddRow(1, __, __, 4, 1, 0) .AddRow(3, __, __, -3, 3, 0) .AddRow(2, __, __, 4, 2, 0) .AddRow(3, __, __, -5, 3, 0) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col1", "sum"); aggregation.AddAggregation(SUM, "col0", "sum2"); aggregation.AddAggregation(COUNT, "col0", "cnt"); aggregation.AddAggregation(COUNT, "", "cnt_star"); aggregation.AddAggregation(COUNT, "", "cnt_star2"); aggregation.AddDistinctAggregation(COUNT, "col1", "dcnt1"); aggregation.AddDistinctAggregation(SUM, "col2", "dsum2"); aggregation.AddDistinctAggregation(COUNT, "col2", "dcnt2"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_FALSE(transformed->schema().attribute(0).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(1).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(2).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(3).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(4).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(5).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } TEST_F(HybridAggregateTest, HybridGroupTransformOnlyDistinct) { std::unique_ptr<Cursor> input(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, 10) .AddRow(1, 4, 11) .AddRow(3, -3, 10) .AddRow(2, 4, 11) .AddRow(3, -5, 10) .BuildCursor()); std::unique_ptr<Cursor> expected_output(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, __) .AddRow(1, 4, __) .AddRow(3, -3, __) .AddRow(2, 4, __) .AddRow(3, -5, __) .AddRow(1, __, 10) .AddRow(1, __, 11) .AddRow(3, __, 10) .AddRow(2, __, 11) .AddRow(3, __, 10) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1"); aggregation.AddDistinctAggregation(COUNT, "col2", "distinct2"); aggregation.AddDistinctAggregation(SUM, "col1", "distinct1b"); aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1c"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } TEST_F(HybridAggregateTest, HybridGroupTransformDistinctAndCountAll) { std::unique_ptr<Cursor> input(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, 10) .AddRow(1, 4, 11) .AddRow(3, -3, 10) .AddRow(2, 4, 11) .AddRow(3, -5, 10) .BuildCursor()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32, INT32>() .AddRow(1, 3, __, __) .AddRow(1, 4, __, __) .AddRow(3, -3, __, __) .AddRow(2, 4, __, __) .AddRow(3, -5, __, __) .AddRow(1, __, 10, __) .AddRow(1, __, 11, __) .AddRow(3, __, 10, __) .AddRow(2, __, 11, __) .AddRow(3, __, 10, __) .AddRow(1, __, __, 0) .AddRow(1, __, __, 0) .AddRow(3, __, __, 0) .AddRow(2, __, __, 0) .AddRow(3, __, __, 0) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1"); aggregation.AddDistinctAggregation(COUNT, "col2", "distinct2"); aggregation.AddDistinctAggregation(SUM, "col1", "distinct1b"); aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1c"); aggregation.AddAggregation(COUNT, "", "count_all"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } // The example from implementation comment. TEST_F(HybridAggregateTest, HybridGroupTransformExampleTest) { std::unique_ptr<Cursor> input( TestDataBuilder<INT32, INT32, INT32, INT32, INT32>() .AddRow(1, 2, 3, 4, 5) .AddRow(6, 7, 8, 9, 0) .BuildCursor()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32, INT32, INT32>() .AddRow(1, 2, __, __, __) .AddRow(6, 7, __, __, __) .AddRow(1, __, 3, __, __) .AddRow(6, __, 8, __, __) .AddRow(1, __, __, 4, 2) .AddRow(6, __, __, 9, 7) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col3", "sum2"); aggregation.AddAggregation(SUM, "col1", "sum"); aggregation.AddDistinctAggregation(COUNT, "col1", "dcnt1"); aggregation.AddDistinctAggregation(COUNT, "col2", "dcnt2"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_FALSE(transformed->schema().attribute(0).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(1).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(2).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(3).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(4).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } // Several tests that check that hybrid group's group by columns can be // specified by various kinds of projectors (by position, all columns, renaming // projectors). // TODO(user): It would be useful to be able to assert which branch of the // hybrid group algorithm was chosen (three branches that differ in the number // of projections applied), so we could make sure we are testing them all... TEST_F(HybridAggregateTest, GroupByColumnPosition1) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 0) .AddRow(1, 0) .AddRow(3, 0) .AddRow(3, 0) .AddRow(2, 0) .AddRow(3, 0) .AddRow(1, 0) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(0, 14, 7, 3) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( ProjectAttributeAt(1), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, GroupByAllColumns) { OperationTest test; test.SetInput(TestDataBuilder<INT32>() .AddRow(1) .AddRow(1) .AddRow(3) .AddRow(3) .AddRow(2) .AddRow(3) .AddRow(1) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(1, 3, 3, 1) .AddRow(2, 2, 1, 1) .AddRow(3, 9, 3, 1) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( ProjectAllAttributes(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, GroupByColumnRenamed) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 0) .AddRow(1, 0) .AddRow(3, 0) .AddRow(3, 0) .AddRow(2, 0) .AddRow(3, 0) .AddRow(1, 0) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(0, 14, 7, 3) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( ProjectNamedAttributeAs("col1", "key"), aggregation.release(), 16, "", test.input())); } } // namespace } // namespace supersonic
40.533673
80
0.65914
IssamElbaytam
2ab2159a71517dd0975685e2e25b44949e6497a3
6,289
hxx
C++
admin/netui/common/h/bitfield.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/netui/common/h/bitfield.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/netui/common/h/bitfield.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**********************************************************************/ /** Microsoft LAN Manager **/ /** Copyright(c) Microsoft Corp., 1990, 1991 **/ /**********************************************************************/ /* Bitfield.hxx This file contains the class definition for the bitfield class. FILE HISTORY: Johnl 13-Jul-1991 Created */ #ifndef _BITFIELD_HXX_ #define _BITFIELD_HXX_ #include "base.hxx" #include "uibuffer.hxx" enum BITVALUES { OFF = 0 , ON = 1 } ; /************************************************************************* NAME: BITFIELD SYNOPSIS: This class provides a variable size bitfield class INTERFACE: Fill in after comments PARENT: BASE CAVEATS: It is assumed that the last byte of the bitvector extends to a byte boundary. This allows multi-byte settings without having to worry about the half byte case at the end. Any unused bits should always be set to 0. NOTES: HISTORY: Johnl 13-Jul-1991 Created **************************************************************************/ DLL_CLASS BITFIELD : public BASE { public: /* All bits are initialized to 0 during construction */ BITFIELD( unsigned cBitsInBitfield, enum BITVALUES bitInit ) ; /* Initializes the bitfield to the chunk of memory pointed at by * pbInitValue of size cInitBytes. If cTotalBytes is 0, then the * size of the bitfield is assumed to be 8*cInitBytes bits long, otherwise * the bitfield is cTotalBits long. */ BITFIELD( const BYTE * pbInitValue, unsigned cInitBytes, unsigned cTotalBits = 0 ) ; BITFIELD( const BITFIELD & bitfieldSrc ) ; /* Provide easy ways to initialize the bitfield with standard types * which will generally be manifests. * The size is assumed to be the size of the data type. */ BITFIELD( USHORT usInit ) ; BITFIELD( ULONG ulInit ) ; ~BITFIELD() ; /* Resizes the bitfield to the specified count of bits. */ APIERR Resize( unsigned cBitsInBitfield ) ; /* Clear or set all of the bits in the bitfield */ void SetAllBits( enum BITVALUES bit = ON ) ; /* Set the bit at bit offset iBitPos to the value of bBit (defaults to 1). */ void SetBit( unsigned iBitPos, enum BITVALUES bitVal = ON ) ; BOOL IsBitSet( unsigned iBitPos ) const ; // // Does a bitwise complement of the bitfield // void Not( void ) ; /* Given two bitfields, ANDs the contents and returns TRUE if any of the * same positioned bits are set. * Example: if ( bitOldBits & bitMaskBits ) ... ; * * For an equivalent OR operation, simply check if any bits are set */ BOOL operator&( const BITFIELD & bitfieldSrc ) ; /* ORs or ANDs or Assigns the bitfield on the right with the target bitfield on the * left. * Example: bitMyBits |= bitMaskBits ; * * The bitfields must be of the same size. */ BITFIELD & operator=( const BITFIELD & bitfieldSrc ) ; BITFIELD & operator=( ULONG ulMask ) ; BITFIELD & operator=( USHORT usMask ) ; void operator&=( const BITFIELD & bitfieldSrc ) ; void operator|=( const BITFIELD & bitfieldSrc ) ; BOOL operator==( BITFIELD & bitfieldSrc ) ; BOOL operator==( ULONG ulMask ) const ; BOOL operator==( USHORT usMask ) const ; BOOL operator!=( BITFIELD & bitfieldSrc ) { return !operator==( bitfieldSrc ) ; } /* Provide easy way to do masks with common types, the bitfield does not * have to be the same size as the operand type, must be at least as big * however. */ //void operator&=( BYTE bSrc ) ; void operator&=( USHORT usSrc ) ; void operator&=( ULONG ulSrc ) ; //void operator|=( BYTE bSrc ) ; void operator|=( USHORT usSrc ) ; void operator|=( ULONG ulSrc ) ; /* Conversion operators: * * The size must match the size of the bitfield. */ operator ULONG() ; operator USHORT() ; //operator BYTE() ; /* Returns the number of bits in this bitfield */ unsigned QueryCount( void ) const { return _cBitsInBitfield ; } /* Returns the number of BYTEs it takes to represent this bitfield. * * Need to add one if a bit overhangs a BYTE boundary. * * BUGBUG - Misleading name, is really Byte count of bitfield */ unsigned QueryAllocSize( void ) const { return ( QueryCount()/8 + ( QueryCount() % 8 ? 1 : 0 ) ) ; } /* Return the number of bits into the byte the requested bit is at */ unsigned QueryOffset( unsigned iBitPos ) const { return iBitPos % 8 ; } protected: /* Get a pointer to the BYTE which contains the requested bit (for * multi-byte setting, should occur on a BYTE boundary). * iBitOffset - index of the requested bit (0 = 1st bit, 1 = 2nd bit etc.) * cbitsTargetOpSize - number of bits that will be used in the * operation, used for bounds checking */ BYTE * QueryBitPos( unsigned iBitOffset, unsigned cbitsTargetOpSize ) const ; /* Returns TRUE if the bitfield had to be allocated in _pbBitVector, * returns FALSE if the bitfield is wholly contained in _ulBitfield. */ BOOL IsAllocated( void ) const { return ( _cBitsInBitfield > QueryMaxNonAllocBitCount() ) ; } /* Returns the number of bits that a BITFIELD object can hold without * allocating any memory. */ unsigned QueryMaxNonAllocBitCount( void ) const { return (8 * sizeof(ULONG)) ; } /* Allocates the memory required by the bitfield class if the size * is greater then what can fit inline. */ APIERR AllocBitfield( unsigned cBitsInBitfield ) ; private: /* The actual bitfield. */ union { BYTE * _pbBitVector ; // Pointer to allocated bitfield ULONG _ulBitfield ; // ULONG bitfield if bitfield < 32 bits } ; /* Count of bits that are in this bitfield. */ unsigned _cBitsInBitfield ; } ; #endif // _BITFIELD_HXX_
30.090909
88
0.594212
npocmaka
2ab509d027a430f7d149af45caa410bed541eb1d
3,644
cpp
C++
src/Shared.cpp
IWantedToBeATranslator/2D-Strip-Packing
4ee9a220f2e9debf775b020d961f0ba547f32636
[ "MIT" ]
1
2017-12-12T19:23:44.000Z
2017-12-12T19:23:44.000Z
src/Shared.cpp
IWantedToBeATranslator/2D-Strip-Packing
4ee9a220f2e9debf775b020d961f0ba547f32636
[ "MIT" ]
1
2016-04-20T18:47:05.000Z
2016-05-04T08:05:45.000Z
src/Shared.cpp
IWantedToBeATranslator/2D-Strip-Packing
4ee9a220f2e9debf775b020d961f0ba547f32636
[ "MIT" ]
1
2019-07-14T15:39:27.000Z
2019-07-14T15:39:27.000Z
#include "Shared.h" Resources algosResources; int eCount = 120; spColorRectSprite* _bloxArray = new spColorRectSprite[eCount]; spClipRectActor _blockClip; spTextField _mainInfo; int* bloxHeights = new int[eCount]; int* bloxWidths = new int[eCount]; int algosHeights = 0; int algosSpaces = 0; int spaceUsed = 0; int screenWidth = 700; int screenHeight = 1000; float clipHeight; float clipWidth; spColorRectSprite spawnRandomBlock(float stageWidth, float stageHeight, float buttonWidth, float buttonHeight, int Xmod, int Ymod) { Color randColor((int)(rand() % 215 + 20), (int)(rand() % 215 + 20), (int)(rand() % 215 + 20), (int)(rand() % 215 + 20)); int bloxWidth = (int)rand() % (int)(stageWidth) / Xmod + 20; int bloxHeight = (int)rand() % (int)(stageWidth) / Ymod + 20; int posX = (int)rand() % (int)(stageWidth - buttonWidth - bloxWidth); int posY = (int)rand() % (int)(stageHeight - buttonHeight - bloxHeight); spColorRectSprite blox = initActor( new ColorRectSprite, arg_color = randColor, arg_x = posX, arg_y = posY, arg_w = bloxWidth, arg_h = bloxHeight, arg_blend = blend_disabled ); _blockClip->addChild(blox); spColorRectSprite left = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = 0, arg_y = 0, arg_w = 1, arg_h = bloxHeight, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(left); spColorRectSprite right = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = bloxWidth, arg_y = 0, arg_w = 1, arg_h = bloxHeight + 1, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(right); spColorRectSprite top = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = 0, arg_y = 0, arg_w = bloxWidth, arg_h = 1, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(top); spColorRectSprite bottom = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = 0, arg_y = bloxHeight, arg_w = bloxWidth + 1, arg_h = 1, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(bottom); spTextField bloxWidthText = initActor( new TextField, arg_color = Color(0, 0, 0), arg_y = bloxHeight - 15, arg_anchor = Vector2(1, 1), arg_text = (std::string)std::to_string(bloxWidth), arg_attachTo = blox, arg_input = false ); Rect tempRect = bloxWidthText->getTextRect(); bloxWidthText->setX(bloxWidth / 2 - tempRect.getWidth() / 2); blox->addChild(bloxWidthText); spTextField bloxHeightText = initActor( new TextField, arg_color = Color(0, 0, 0), arg_x = bloxWidth - 15, arg_rotation = -MATH_PI / 2, arg_anchor = Vector2(1, 1), arg_text = (std::string)std::to_string(bloxHeight), arg_attachTo = blox, arg_input = false ); tempRect = bloxHeightText->getTextRect(); bloxHeightText->setY(bloxHeight / 2 + tempRect.getHeight() / 2); blox->addChild(bloxHeightText); return blox; } void sortNonDecr(spColorRectSprite * blocks, int * blockHeights, int * blockWidths) { spColorRectSprite bloxBuffer; int tempbuf; FOR(m, 0, eCount) { FOR(n, 0, eCount - 1) { if (blockHeights[n] < blockHeights[n + 1]) { tempbuf = blockWidths[n]; blockWidths[n] = blockWidths[n + 1]; blockWidths[n + 1] = tempbuf; tempbuf = blockHeights[n]; blockHeights[n] = blockHeights[n + 1]; blockHeights[n + 1] = tempbuf; bloxBuffer = blocks[n]; blocks[n] = blocks[n + 1]; blocks[n + 1] = bloxBuffer; } } } }
26.028571
131
0.649012
IWantedToBeATranslator
2ab8fbf2535cfcac80e64bd88f1c8ffc46090fac
3,005
cc
C++
src/QGenderSelector.cc
png85/QGenderSelector
e4df122b582c9c9861416c4dad11d2a24daf44c0
[ "BSD-3-Clause" ]
null
null
null
src/QGenderSelector.cc
png85/QGenderSelector
e4df122b582c9c9861416c4dad11d2a24daf44c0
[ "BSD-3-Clause" ]
null
null
null
src/QGenderSelector.cc
png85/QGenderSelector
e4df122b582c9c9861416c4dad11d2a24daf44c0
[ "BSD-3-Clause" ]
null
null
null
#include <QDebug> #ifndef HAS_CXX11_NULLPTR #define nullptr 0 #endif #include "QGenderSelector.h" QGenderSelector::QGenderSelector(QWidget* parent) : QFrame(parent) , m_layout(nullptr) , m_radioMale(nullptr) , m_radioFemale(nullptr) , m_radioOther(nullptr) , m_selectedGender(Other) { qRegisterMetaType<Gender>("QGenderSelector::Gender"); setupUi(); setSelectedGender(m_selectedGender); } void QGenderSelector::setupUi() { try { m_layout = new QHBoxLayout(this); } catch (std::bad_alloc& ex) { QString msg = tr("Failed to allocate memory for new QBoxLayout in %1: %2").arg(Q_FUNC_INFO, ex.what()); qCritical() << msg; throw; } try { m_buttonGroup = new QButtonGroup(m_layout); } catch (std::bad_alloc& ex) { QString msg = tr("Failed to allocate memory for new QButtonGroup in %1: %2").arg(Q_FUNC_INFO, ex.what()); qCritical() << msg; throw; } QList<QRadioButton*> radioButtons; try { m_radioMale = new QRadioButton(tr("Male"), this); m_radioMale->setIcon(QIcon(":/icons/genders/male.png")); m_layout->addWidget(m_radioMale); m_buttonGroup->addButton(m_radioMale, static_cast<int>(Male)); m_radioFemale = new QRadioButton(tr("Female"), this); m_radioFemale->setIcon(QIcon(":/icons/genders/female.png")); m_layout->addWidget(m_radioFemale); m_buttonGroup->addButton(m_radioFemale, static_cast<int>(Female)); m_radioOther = new QRadioButton(tr("Other"), this); m_radioOther->setIcon(QIcon(":/icons/genders/other.png")); m_layout->addWidget(m_radioOther); m_buttonGroup->addButton(m_radioOther, static_cast<int>(Other)); } catch (std::bad_alloc& ex) { QString msg = tr("Failed to allocate memory for new QRadioButton in %1: %2").arg(Q_FUNC_INFO, ex.what()); qCritical() << msg; throw; } connect(m_buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(buttonGroup_buttonClicked(int))); QFrame::setLayout(m_layout); } void QGenderSelector::buttonGroup_buttonClicked(int id) { m_selectedGender = static_cast<Gender>(id); emit selectedGenderChanged(m_selectedGender); emit selectedGenderChanged(genderToDicomVR(m_selectedGender)); } void QGenderSelector::setSelectedGender(QGenderSelector::Gender g) { m_selectedGender = g; switch (g) { case Male: m_radioMale->setChecked(true); m_radioFemale->setChecked(false); m_radioOther->setChecked(false); break; case Female: m_radioMale->setChecked(false); m_radioFemale->setChecked(true); m_radioOther->setChecked(false); break; case Other: default: m_radioMale->setChecked(false); m_radioFemale->setChecked(false); m_radioOther->setChecked(true); break; } } void QGenderSelector_initResources() { Q_INIT_RESOURCE(QGenderSelector); }
27.318182
113
0.658236
png85
2abcb0a402576a40db36efcd62d48c7ae939fbac
2,198
cpp
C++
src/Game/Tile.cpp
warzes/RPGInBox
3d8ccbb38711cf6a1b2542113fa4d9a9e53c9e31
[ "MIT" ]
3
2021-07-12T14:54:01.000Z
2021-09-06T07:45:40.000Z
src/Game/Tile.cpp
warzes/RPGInBox
3d8ccbb38711cf6a1b2542113fa4d9a9e53c9e31
[ "MIT" ]
null
null
null
src/Game/Tile.cpp
warzes/RPGInBox
3d8ccbb38711cf6a1b2542113fa4d9a9e53c9e31
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Tile.h" #include "IGameCamera.h" #include "ResourceManager.h" #include "DebugNew.h" //----------------------------------------------------------------------------- const std::map<TileType, std::string> textureFloorName = { {TileType::Grass, "../data/temp/textures/map/outdoor/plains-ground2.png"}, {TileType::Road, "../data/temp/textures/map/outdoor/road.png"}, }; //----------------------------------------------------------------------------- const std::map<TileDecorType, std::string> textureDecorName = { {TileDecorType::None, ""}, {TileDecorType::Tree, "../data/temp/textures/map/outdoor/plains-tree2.png"}, {TileDecorType::Tree2, "../data/temp/textures/map/outdoor/plains-tree3.png"}, }; //----------------------------------------------------------------------------- Tile Tile::Create(ResourceManager& resource, TileType type, TileDecorType decor) { Tile tile; tile.type = type; tile.decor = decor; tile.textureTile = resource.GetTexture(textureFloorName.at(type)); if (decor != TileDecorType::None) tile.textureDecor = resource.GetTexture(textureDecorName.at(decor)); //if (textureFloorName != "") // tile.textureTile = resource.GetTexture(textureFloorName); //if (decor != TileDecorType::None && textureDecorName != "") // tile.textureDecor = resource.GetTexture(textureDecorName); return tile; } //----------------------------------------------------------------------------- void Tile::Draw(IGameCamera* camera, const Vector2& pos) { if (!textureTile) return; // Floor render DrawCubeTexture(*textureTile, { pos.x, -0.5f, pos.y }, 1, 1, 1, WHITE); //DrawModel(model, Vector3{ (float)x, 0.0f, (float)y }, 0.5f, WHITE); // object render if (!textureDecor || decor == TileDecorType::None) return; DrawBillboard(camera->GetCamera(), *textureDecor, { pos.x, 1.0f, pos.y }, 2.0f, WHITE); //DrawCubeTexture(m_resourceMgr.textureTree, Vector3{ (float)x, 0.5f, (float)y }, 1, 1, 1, WHITE); //DrawCubeTexture(tx, Vector3{ (float)x, 1.5f, (float)y }, 1, 1, 1, GREEN); //DrawCubeTexture(tx, Vector3{ (float)x, 0.5f, (float)y }, 0.25f, 1, 0.25f, BROWN); } //-----------------------------------------------------------------------------
42.269231
99
0.572338
warzes
2abe9aca53375ac18c7ffd4c74d19f614c434b00
440
cpp
C++
contest/AtCoder/abc054/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/AtCoder/abc054/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/AtCoder/abc054/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "string.hpp" #include "vector.hpp" int main() { int n(in), m(in); Vector<String> a(n, in), b(m, in); for (int i = 0; i <= n - m; ++i) { for (int j = 0; j <= n - m; ++j) { bool f = true; for (int y = 0; y < m; ++y) { if (a[i + y].substr(j, m) != b[y]) { f = false; } } if (f) { cout << true << endl; return 0; } } } cout << false << endl; }
19.130435
44
0.381818
not522
2ac161fe17f70736e67259973c29806aaf9d8dbb
5,200
cpp
C++
Lighting/readFiles.cpp
arturnista/glfwstudy
fa24539c88149d388aebada68e6e10b862e19829
[ "MIT" ]
null
null
null
Lighting/readFiles.cpp
arturnista/glfwstudy
fa24539c88149d388aebada68e6e10b862e19829
[ "MIT" ]
null
null
null
Lighting/readFiles.cpp
arturnista/glfwstudy
fa24539c88149d388aebada68e6e10b862e19829
[ "MIT" ]
null
null
null
#define _SCL_SECURE_NO_WARNINGS #pragma warning(disable:4996) #include "readFiles.h" const char* readFile(string filename) { string fullFileData; ifstream openedFile(filename.c_str()); if (openedFile.is_open()) { string line; while (getline(openedFile, line)) { fullFileData += line + '\n'; } openedFile.close(); } // Copy the string char * writable = new char[fullFileData.size() + 1]; std::copy(fullFileData.begin(), fullFileData.end(), writable); writable[fullFileData.size()] = '\0'; return writable; } void fetchFileData(string filename, vector<GLfloat>& pointsVector, vector<GLuint>& indexVector, vector<GLfloat>& normalVector) { ifstream openedFile(filename.c_str()); if (openedFile.is_open()) { string line; string strNumber; while(!openedFile.eof()) { openedFile >> line; if(line.compare("v") == 0) { openedFile >> strNumber; pointsVector.push_back( stof(strNumber) ); openedFile >> strNumber; pointsVector.push_back( stof(strNumber) ); openedFile >> strNumber; pointsVector.push_back( stof(strNumber) ); } else if(line.compare("vn") == 0) { openedFile >> strNumber; normalVector.push_back( stof(strNumber) ); openedFile >> strNumber; normalVector.push_back( stof(strNumber) ); openedFile >> strNumber; normalVector.push_back( stof(strNumber) ); } else if(line.compare("f") == 0) { int count = 3; for (size_t i = 0; i < count; i++) { openedFile >> strNumber; int doubleIdx = strNumber.find("//"); if(doubleIdx > 0) { string fstNumber = strNumber.substr(0, doubleIdx); string secNumber = strNumber.substr(doubleIdx + 2); indexVector.push_back( stof(fstNumber) ); // normalVector.push_back( stof(secNumber) ); } else { int singleIdx = strNumber.find("/"); if(singleIdx > 0) { string fstNumber = strNumber.substr(0, singleIdx); string nextString = strNumber.substr(singleIdx + 1); int nextIndex = nextString.find("/"); string secNumber = nextString.substr(0, nextIndex); string trdNumber = nextString.substr(nextIndex + 1); indexVector.push_back( stof(fstNumber) ); // normalVector.push_back( stof(trdNumber) ); } else { indexVector.push_back( stof(strNumber) ); } } } } } openedFile.close(); } } gameObject readObjectFile(string filename, float size, vec3 color) { std::vector<GLfloat> pointsVector = {}; std::vector<GLuint> indexVector = {}; std::vector<GLfloat> normalVector = {}; fetchFileData(filename, pointsVector, indexVector, normalVector); int pointsCounter = pointsVector.size() * 3; int vertexCounter = indexVector.size(); cout << filename << "\t"; cout << "vertex count" << " = " << pointsVector.size() << '\t'; cout << "face count" << " = " << vertexCounter << '\n'; GLfloat *points = new GLfloat[pointsCounter]; float lineSize = 9; int counter = 0; for (size_t i = 0; i < pointsCounter; i += lineSize) { // Position points[i + 0] = pointsVector.at(counter); points[i + 1] = pointsVector.at(counter + 1); points[i + 2] = pointsVector.at(counter + 2); // Color points[i + 3] = color.x; points[i + 4] = color.y; points[i + 5] = color.z; if(normalVector.size() > 0) { points[i + 6] = normalVector.at(counter); points[i + 7] = normalVector.at(counter + 1); points[i + 8] = normalVector.at(counter + 2); } else { points[i + 6] = 1.0f; points[i + 7] = 0.0f; points[i + 8] = 0.0f; } counter += 3; } // copy(pointsVector.begin(), pointsVector.end(), points); // if(size != 1) for (size_t i = 0; i < pointsCounter; i++) points[i] = points[i] * size; GLuint VBO = 0; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, pointsCounter * sizeof(GLfloat), points, GL_STATIC_DRAW); GLuint VAO = 0; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); // Positions glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, lineSize * sizeof(GLfloat), (void*)0); glEnableVertexAttribArray(0); // Colors glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, lineSize * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); // Normal glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, lineSize * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); if(vertexCounter > 0) { GLuint *indexArray = new GLuint[vertexCounter]; copy(indexVector.begin(), indexVector.end(), indexArray); for (size_t i = 0; i < vertexCounter; i++) indexArray[i] = indexArray[i] - 1; GLuint EBO = 0; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * vertexCounter, indexArray, GL_STATIC_DRAW); } return { VAO, vertexCounter, size, }; } gameObject readObjectFile(string filename, float size) { glm::vec3 color = glm::vec3( static_cast <float> (rand()) / static_cast <float> (RAND_MAX), static_cast <float> (rand()) / static_cast <float> (RAND_MAX), static_cast <float> (rand()) / static_cast <float> (RAND_MAX) ); return readObjectFile(filename, size, color); }
29.050279
107
0.660577
arturnista
2ac6b4e01d4de1730cfa471c02c28130113840c8
8,498
hpp
C++
foedus_code/foedus-core/include/foedus/storage/hash/hash_reserve_impl.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/storage/hash/hash_reserve_impl.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/storage/hash/hash_reserve_impl.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #ifndef FOEDUS_STORAGE_HASH_HASH_RESERVE_IMPL_HPP_ #define FOEDUS_STORAGE_HASH_HASH_RESERVE_IMPL_HPP_ #include "foedus/error_code.hpp" #include "foedus/storage/hash/fwd.hpp" #include "foedus/storage/hash/hash_combo.hpp" #include "foedus/storage/hash/hash_id.hpp" #include "foedus/thread/fwd.hpp" #include "foedus/xct/sysxct_functor.hpp" namespace foedus { namespace storage { namespace hash { /** * @brief A system transaction to reserve a physical record(s) in a hash data page. * @ingroup HASH * @see SYSXCT * @details * A record insertion happens in two steps: * \li During Execution: Physically inserts a deleted record for the key in the data page. * \li During Commit: Logically flips the delete-bit and installs the payload. * * This system transaction does the former. * * This does nothing and returns kErrorCodeOk in the following cases: * \li The page turns out to already contain a satisfying physical record for the key. * * In all other cases, this sysxct creates or finds the record. * In other words, this sysxct guarantees a success as far as it returns kErrorCodeOk. * * Locks taken in this sysxct (in order of taking): * \li Page-lock of the target or the tail page if target_ is not the tail * (in the order of the chain, so no deadlock). * \li Record-lock of an existing, matching record. Only when we have to expand the record. * This also happens after the page-lock of the enclosing page, before the page-lock of * following pages, so every lock is in order. * * Note, however, that it might not be in address order (address order might be tail -> head). * We thus might have a false deadlock-abort. However, as far as the first lock on the * target_ page is unconditional, all locks after that should be non-racy, so all try-lock * should succeed. We might want to specify a bit larger max_retries (5?) for this reason. * * @par Differences from Masstree's reserve * This sysxct is simpler than masstree::ReserveRecords for a few reasons. * \li No need to split the page * \li No need to adopt a split page * * We thus contain all required logics (reserve/expansion/migrate) in this sysxct. * In all circumstances, this sysxct finds or reserves the required record. * Simpler for the caller. * * So far this sysxct installs only one physical record at a time. * TASK(Hideaki): Probably it helps by batching several records. */ struct ReserveRecords final : public xct::SysxctFunctor { /** Thread context */ thread::Thread* const context_; /** * @brief The data page to install a new physical record. * @details * This might NOT be the head page of the hash bin. * The contract here is that the caller must be sure that * any pages before this page in the chain must not contain a record * of the given key that is not marked as moved. * In other words, the caller must have checked that there is no such record * before hint_check_from_ of target_. * * \li Example 1: the caller found an existing record in target_ that is not moved. * hint_check_from_ < target_->get_key_count(), and target_ might not be the tail of the bin. * \li Example 2: the caller found no existing non-moved record. * hint_check_from_ == target_->get_key_count(), and target_ is the tail of the bin. * * Of course, by the time this sysxct takes a lock, other threads might insert * more records, some of which might have the key. This sysxct thus needs to * resume search from target_ and hint_check_from_ (but, not anywhere before!). */ HashDataPage* const target_; /** The key of the new record */ const void* const key_; /** * Hash info of the key. * It's &, so lifetime of the caller's HashCombo object must be longer than this sysxct. */ const HashCombo& combo_; /** Byte length of the key */ const KeyLength key_length_; /** Minimal required length of the payload */ const PayloadLength payload_count_; /** * When we expand the record or allocate a new record, we might * allocate a larger-than-necessary space guided by this hint. * It's useful to avoid future record expansion. * @pre aggressive_payload_count_hint_ >= payload_count_ */ const PayloadLength aggressive_payload_count_hint_; /** * The in-page location from which this sysxct will look for matching records. * The caller is \e sure that no record before this position can match the slice. * Thanks to append-only writes in data pages, the caller can guarantee that the records * it observed are final. * * In most cases, this is same as key_count after locking, thus completely avoiding the re-check. * In some cases, the caller already found a matching key in this index, but even in that case * this sysxct must re-search after locking because the record might be now moved. */ const DataPageSlotIndex hint_check_from_; /** * [Out] The slot of the record that is found or created. * As far as this sysxct returns kErrorCodeOk, this guarantees the following. * @post out_slot_ != kSlotNotFound * @post out_page_'s out_slot_ is at least at some point a valid non-moved record * of the given key with satisfying max-payload length. */ DataPageSlotIndex out_slot_; /** * [Out] The page that contains the found/created record. * As far as this sysxct returns kErrorCodeOk, out_page_ is either the target_ itself * or some page after target_. * @post out_page_ != nullptr */ HashDataPage* out_page_; ReserveRecords( thread::Thread* context, HashDataPage* target, const void* key, KeyLength key_length, const HashCombo& combo, PayloadLength payload_count, PayloadLength aggressive_payload_count_hint, DataPageSlotIndex hint_check_from) : xct::SysxctFunctor(), context_(context), target_(target), key_(key), combo_(combo), key_length_(key_length), payload_count_(payload_count), aggressive_payload_count_hint_(aggressive_payload_count_hint), hint_check_from_(hint_check_from), out_slot_(kSlotNotFound), out_page_(nullptr) { } virtual ErrorCode run(xct::SysxctWorkspace* sysxct_workspace) override; /** * The main loop (well, recursion actually). */ ErrorCode find_or_create_or_expand( xct::SysxctWorkspace* sysxct_workspace, HashDataPage* page, DataPageSlotIndex examined_records); ErrorCode expand_record( xct::SysxctWorkspace* sysxct_workspace, HashDataPage* page, DataPageSlotIndex index); ErrorCode find_and_lock_spacious_tail( xct::SysxctWorkspace* sysxct_workspace, HashDataPage* from_page, HashDataPage** tail); /** * Installs it as a fresh-new physical record, assuming the given page is the tail * and already locked. */ ErrorCode create_new_record_in_tail_page(HashDataPage* tail); ErrorCode create_new_tail_page( HashDataPage* cur_tail, HashDataPage** new_tail); DataPageSlotIndex search_within_page( const HashDataPage* page, DataPageSlotIndex key_count, DataPageSlotIndex examined_records) const; /** * Appends a new physical record to the page. * The caller must make sure there is no race in the page. * In other words, the page must be either locked or a not-yet-published page. */ DataPageSlotIndex append_record_to_page(HashDataPage* page, xct::XctId initial_xid) const; }; } // namespace hash } // namespace storage } // namespace foedus #endif // FOEDUS_STORAGE_HASH_HASH_RESERVE_IMPL_HPP_
40.660287
99
0.730525
sam1016yu
2acbac70735b4347da398070125b85a5e9b2a90a
2,907
cpp
C++
src/Extensions/EditorTheme.cpp
Razdeep/cp-editor2
e0e25b38c10d284be2072b6a3572a5fbee8ca40a
[ "Apache-2.0" ]
null
null
null
src/Extensions/EditorTheme.cpp
Razdeep/cp-editor2
e0e25b38c10d284be2072b6a3572a5fbee8ca40a
[ "Apache-2.0" ]
null
null
null
src/Extensions/EditorTheme.cpp
Razdeep/cp-editor2
e0e25b38c10d284be2072b6a3572a5fbee8ca40a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019-2020 Ashar Khan <ashar786khan@gmail.com> * * This file is part of CP Editor. * * CP Editor 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. * * I will not be responsible if CP Editor behaves in unexpected way and * causes your ratings to go down and or lose any important contest. * * Believe Software is "Software" and it isn't immune to bugs. * */ #include "Extensions/EditorTheme.hpp" #include "Core/EventLogger.hpp" #include "Util.hpp" #include <QFile> #include <QSyntaxStyle> namespace Extensions { QSyntaxStyle *EditorTheme::light = nullptr; QSyntaxStyle *EditorTheme::dracula = nullptr; QSyntaxStyle *EditorTheme::monokai = nullptr; QSyntaxStyle *EditorTheme::solarized = nullptr; QSyntaxStyle *EditorTheme::solarizedDark = nullptr; QSyntaxStyle *EditorTheme::getLightTheme() { if (light != nullptr) return light; else return QSyntaxStyle::defaultStyle(); } QSyntaxStyle *EditorTheme::getMonokaiTheme() { if (monokai != nullptr) return monokai; else { auto content = Util::readFile(":/styles/monokai.xml", "Read Style"); if (content.isNull()) return nullptr; monokai = new QSyntaxStyle(); monokai->load(content); return monokai; } } QSyntaxStyle *EditorTheme::getDraculaTheme() { if (dracula != nullptr) return dracula; else { auto content = Util::readFile(":/styles/dracula.xml", "Read Style"); if (content.isNull()) return nullptr; dracula = new QSyntaxStyle(); dracula->load(content); return dracula; } } QSyntaxStyle *EditorTheme::getSolarizedTheme() { if (solarized != nullptr) return solarized; else { auto content = Util::readFile(":/styles/solarized.xml", "Read Style"); if (content.isNull()) return nullptr; solarized = new QSyntaxStyle(); solarized->load(content); return solarized; } } QSyntaxStyle *EditorTheme::getSolarizedDarkTheme() { if (solarizedDark != nullptr) return solarizedDark; else { auto content = Util::readFile(":/styles/solarizedDark.xml", "Read Style"); if (content.isNull()) return nullptr; solarizedDark = new QSyntaxStyle(); solarizedDark->load(content); return solarizedDark; } } void EditorTheme::release() { if (light != nullptr) delete light; if (dracula != nullptr) delete dracula; if (monokai != nullptr) delete monokai; if (solarized != nullptr) delete solarized; if (solarizedDark != nullptr) delete solarizedDark; } } // namespace Extensions
26.189189
82
0.644995
Razdeep
2acd2900dca1e1a85d725b02556d24d99816a584
5,680
cc
C++
third_party/webrtc/src/chromium/src/base/feature_list.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
8
2016-02-08T11:59:31.000Z
2020-05-31T15:19:54.000Z
third_party/webrtc/src/chromium/src/base/feature_list.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
1
2021-05-05T11:11:31.000Z
2021-05-05T11:11:31.000Z
third_party/webrtc/src/chromium/src/base/feature_list.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
7
2016-02-09T09:28:14.000Z
2020-07-25T19:03:36.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/feature_list.h" #include <utility> #include <vector> #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/strings/string_split.h" namespace base { namespace { // Pointer to the FeatureList instance singleton that was set via // FeatureList::SetInstance(). Does not use base/memory/singleton.h in order to // have more control over initialization timing. Leaky. FeatureList* g_instance = nullptr; // Splits a comma-separated string containing feature names into a vector. std::vector<std::string> SplitFeatureListString(const std::string& input) { return SplitString(input, ",", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY); } } // namespace FeatureList::FeatureList() : initialized_(false) {} FeatureList::~FeatureList() {} void FeatureList::InitializeFromCommandLine( const std::string& enable_features, const std::string& disable_features) { DCHECK(!initialized_); // Process disabled features first, so that disabled ones take precedence over // enabled ones (since RegisterOverride() uses insert()). for (const auto& feature_name : SplitFeatureListString(disable_features)) { RegisterOverride(feature_name, OVERRIDE_DISABLE_FEATURE, nullptr); } for (const auto& feature_name : SplitFeatureListString(enable_features)) { RegisterOverride(feature_name, OVERRIDE_ENABLE_FEATURE, nullptr); } } bool FeatureList::IsFeatureOverriddenFromCommandLine( const std::string& feature_name, OverrideState state) const { auto it = overrides_.find(feature_name); return it != overrides_.end() && it->second.overridden_state == state && !it->second.overridden_by_field_trial; } void FeatureList::RegisterFieldTrialOverride(const std::string& feature_name, OverrideState override_state, FieldTrial* field_trial) { DCHECK(field_trial); DCHECK(!ContainsKey(overrides_, feature_name) || !overrides_.find(feature_name)->second.field_trial) << "Feature " << feature_name << " has conflicting field trial overrides: " << overrides_.find(feature_name)->second.field_trial->trial_name() << " / " << field_trial->trial_name(); RegisterOverride(feature_name, override_state, field_trial); } void FeatureList::AssociateReportingFieldTrial( const std::string& feature_name, OverrideState for_overridden_state, FieldTrial* field_trial) { DCHECK( IsFeatureOverriddenFromCommandLine(feature_name, for_overridden_state)); // Only one associated field trial is supported per feature. This is generally // enforced server-side. OverrideEntry* entry = &overrides_.find(feature_name)->second; if (entry->field_trial) { NOTREACHED() << "Feature " << feature_name << " already has trial: " << entry->field_trial->trial_name() << ", associating trial: " << field_trial->trial_name(); return; } entry->field_trial = field_trial; } // static bool FeatureList::IsEnabled(const Feature& feature) { return GetInstance()->IsFeatureEnabled(feature); } // static FeatureList* FeatureList::GetInstance() { return g_instance; } // static void FeatureList::SetInstance(scoped_ptr<FeatureList> instance) { DCHECK(!g_instance); instance->FinalizeInitialization(); // Note: Intentional leak of global singleton. g_instance = instance.release(); } // static void FeatureList::ClearInstanceForTesting() { delete g_instance; g_instance = nullptr; } void FeatureList::FinalizeInitialization() { DCHECK(!initialized_); initialized_ = true; } bool FeatureList::IsFeatureEnabled(const Feature& feature) { DCHECK(initialized_); DCHECK(CheckFeatureIdentity(feature)) << feature.name; auto it = overrides_.find(feature.name); if (it != overrides_.end()) { const OverrideEntry& entry = it->second; // Activate the corresponding field trial, if necessary. if (entry.field_trial) entry.field_trial->group(); // TODO(asvitkine) Expand this section as more support is added. return entry.overridden_state == OVERRIDE_ENABLE_FEATURE; } // Otherwise, return the default state. return feature.default_state == FEATURE_ENABLED_BY_DEFAULT; } void FeatureList::RegisterOverride(const std::string& feature_name, OverrideState overridden_state, FieldTrial* field_trial) { DCHECK(!initialized_); // Note: The semantics of insert() is that it does not overwrite the entry if // one already exists for the key. Thus, only the first override for a given // feature name takes effect. overrides_.insert(std::make_pair( feature_name, OverrideEntry(overridden_state, field_trial))); } bool FeatureList::CheckFeatureIdentity(const Feature& feature) { AutoLock auto_lock(feature_identity_tracker_lock_); auto it = feature_identity_tracker_.find(feature.name); if (it == feature_identity_tracker_.end()) { // If it's not tracked yet, register it. feature_identity_tracker_[feature.name] = &feature; return true; } // Compare address of |feature| to the existing tracked entry. return it->second == &feature; } FeatureList::OverrideEntry::OverrideEntry(OverrideState overridden_state, FieldTrial* field_trial) : overridden_state(overridden_state), field_trial(field_trial), overridden_by_field_trial(field_trial != nullptr) {} } // namespace base
33.216374
80
0.712676
bopopescu
2acd9c96f14697bc28ea6bbcba21a2d4fb13b485
288
cc
C++
test/foo_test.cc
jingleman/cmake-gtest-gbench-starter
19bb4e3c17a2dea4c372d9cdbfab1eb557d1a5f0
[ "MIT" ]
27
2017-01-14T19:48:26.000Z
2022-01-30T01:09:16.000Z
test/foo_test.cc
jingleman/cmake-gtest-gbench-starter
19bb4e3c17a2dea4c372d9cdbfab1eb557d1a5f0
[ "MIT" ]
1
2018-11-12T19:53:37.000Z
2018-11-30T18:23:10.000Z
test/foo_test.cc
jingleman/cmake-gtest-gbench-starter
19bb4e3c17a2dea4c372d9cdbfab1eb557d1a5f0
[ "MIT" ]
13
2017-02-12T00:53:53.000Z
2021-10-02T01:59:00.000Z
#include <iostream> #include "gtest/gtest.h" #include "nemo/foo.hh" TEST(NemoFoo, Positives) { EXPECT_EQ(38, nemo::foo(-4)); EXPECT_EQ(42, nemo::foo(0)); } TEST(NemoFoo, Negatives) { EXPECT_NE(-1, nemo::foo(99)); EXPECT_NE(0, nemo::foo(-41)); EXPECT_NE(42, nemo::foo(42)); }
18
31
0.642361
jingleman
2ace9b357ca42e5121c2dfc314cc8d4e2f176681
4,707
hpp
C++
test_conformance/clcpp/math_funcs/power_funcs.hpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
1
2020-06-05T04:01:03.000Z
2020-06-05T04:01:03.000Z
test_conformance/clcpp/math_funcs/power_funcs.hpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
3
2020-03-25T07:42:27.000Z
2020-04-02T13:23:42.000Z
test_conformance/clcpp/math_funcs/power_funcs.hpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
3
2020-10-26T02:53:08.000Z
2021-02-12T14:59:41.000Z
// // Copyright (c) 2017 The Khronos Group Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef TEST_CONFORMANCE_CLCPP_MATH_FUNCS_POWER_FUNCS_HPP #define TEST_CONFORMANCE_CLCPP_MATH_FUNCS_POWER_FUNCS_HPP #include <limits> #include <type_traits> #include <cmath> #include "common.hpp" #define DEFINE_BINARY_POWER_FUNC_INT(NAME, HOST_FUNC, USE_ULP, ULP, ULP_EMBEDDED, MIN1, MAX1, MIN2, MAX2) \ struct power_func_ ## NAME : public binary_func<cl_float, cl_int, cl_float> \ { \ power_func_ ## NAME(bool is_embedded) : m_is_embedded(is_embedded) \ { \ \ } \ \ std::string str() \ { \ return #NAME; \ } \ \ std::string headers() \ { \ return "#include <opencl_math>\n"; \ } \ /* Reference value type is cl_double */ \ cl_double operator()(const cl_float& x, const cl_int& y) \ { \ return (HOST_FUNC)(static_cast<cl_double>(x), y); \ } \ \ cl_float min1() \ { \ return MIN1; \ } \ \ cl_float max1() \ { \ return MAX1; \ } \ \ cl_int min2() \ { \ return MIN2; \ } \ \ cl_int max2() \ { \ return MAX2; \ } \ \ std::vector<cl_float> in1_special_cases() \ { \ return { \ cl_float(-1.0f), \ cl_float(0.0f), \ cl_float(-0.0f), \ }; \ } \ \ std::vector<cl_int> in2_special_cases() \ { \ return { \ 2, 3, -1, 1, -2, 2 \ }; \ } \ \ bool use_ulp() \ { \ return USE_ULP; \ } \ \ float ulp() \ { \ if(m_is_embedded) \ { \ return ULP_EMBEDDED; \ } \ return ULP; \ } \ private: \ bool m_is_embedded; \ }; // group_name, func_name, reference_func, use_ulp, ulp, ulp_for_embedded, max_delta, min1, max1 MATH_FUNCS_DEFINE_UNARY_FUNC(power, cbrt, std::cbrt, true, 2.0f, 4.0f, 0.001f, -1000.0f, -9.0f) MATH_FUNCS_DEFINE_UNARY_FUNC(power, rsqrt, reference::rsqrt, true, 2.0f, 4.0f, 0.001f, 1.0f, 100.0f) MATH_FUNCS_DEFINE_UNARY_FUNC(power, sqrt, std::sqrt, true, 3.0f, 4.0f, 0.001f, 1.0f, 100.0f) // group_name, func_name, reference_func, use_ulp, ulp, ulp_for_embedded, max_delta, min1, max1, min2, max2 MATH_FUNCS_DEFINE_BINARY_FUNC(power, pow, std::pow, true, 16.0f, 16.0f, 0.001f, 1.0f, 100.0f, 1.0f, 10.0f) MATH_FUNCS_DEFINE_BINARY_FUNC(power, powr, reference::powr, true, 16.0f, 16.0f, 0.001f, 1.0f, 100.0f, 1.0f, 10.0f) // func_name, reference_func, use_ulp, ulp, ulp_for_embedded, min1, max1, min2, max2 DEFINE_BINARY_POWER_FUNC_INT(pown, std::pow, true, 16.0f, 16.0f, 1.0f, 100.0f, 1, 10) DEFINE_BINARY_POWER_FUNC_INT(rootn, reference::rootn, true, 16.0f, 16.0f, -100.0f, 100.0f, -10, 10) // power functions AUTO_TEST_CASE(test_power_funcs) (cl_device_id device, cl_context context, cl_command_queue queue, int n_elems) { int error = CL_SUCCESS; int last_error = CL_SUCCESS; // Check for EMBEDDED_PROFILE bool is_embedded_profile = false; char profile[128]; last_error = clGetDeviceInfo(device, CL_DEVICE_PROFILE, sizeof(profile), (void *)&profile, NULL); RETURN_ON_CL_ERROR(last_error, "clGetDeviceInfo") if (std::strcmp(profile, "EMBEDDED_PROFILE") == 0) is_embedded_profile = true; // gentype cbrt(gentype x); // gentype rsqrt(gentype x); // gentype sqrt(gentype x); TEST_UNARY_FUNC_MACRO((power_func_cbrt(is_embedded_profile))) TEST_UNARY_FUNC_MACRO((power_func_sqrt(is_embedded_profile))) TEST_UNARY_FUNC_MACRO((power_func_rsqrt(is_embedded_profile))) // gentype pow(gentype x, gentype y); // gentype powr(gentype x, gentype y); TEST_BINARY_FUNC_MACRO((power_func_pow(is_embedded_profile))) TEST_BINARY_FUNC_MACRO((power_func_powr(is_embedded_profile))) // gentype pown(gentype x, intn y); // gentype rootn(gentype x, intn y); TEST_BINARY_FUNC_MACRO((power_func_pown(is_embedded_profile))) TEST_BINARY_FUNC_MACRO((power_func_rootn(is_embedded_profile))) if(error != CL_SUCCESS) { return -1; } return error; } #endif // TEST_CONFORMANCE_CLCPP_MATH_FUNCS_POWER_FUNCS_HPP
30.564935
114
0.647334
jainvikas8
2acfa040b8768fabb1f707f57acffb09db8ad8e8
10,266
cpp
C++
src/player.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
11
2015-03-02T07:43:00.000Z
2021-12-04T04:53:02.000Z
src/player.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
1
2015-03-28T17:17:13.000Z
2016-10-10T05:49:07.000Z
src/player.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
3
2016-11-04T01:14:31.000Z
2020-05-07T23:42:27.000Z
/**************************** Copyright © 2006-2015 Luke Salisbury This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ****************************/ #include "engine.h" #include "elix/elix_string.hpp" #include "core.h" #include "game_config.h" #include "game_system.h" #include "display/display_functions.h" #include "platform_media.h" extern ObjectEffect default_fx; /* - Controller Layout axis 0: X/Y/Z -255 to 255. axis 1: A/B/C -255 to 255. pointer: 2d location. button 00: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 01: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 02: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 03: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 04: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 05: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 06: 0 - unpressed, 1 - Just pressed, 2 - holding (menu) button 07: 0 - unpressed, 1 - Just pressed, 2 - holding (right) button 08: 0 - unpressed, 1 - Just pressed, 2 - holding (left) button 09: 0 - unpressed, 1 - Just pressed, 2 - holding (down) button 10: 0 - unpressed, 1 - Just pressed, 2 - holding (up) button 11: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 12: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 13: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 14: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 15: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) internal button 16: (confirm) 0 - unpressed, 1 - Just pressed, 2 - holding internal button 17: (cancel) 0 - unpressed, 1 - Just pressed, 2 - holding internal button 18: (pointer press) 0 - unpressed, 1 - Just pressed, 2 - holding internal button 19: (shutdown) 0 - unpressed, 1 - Just pressed, 2 - holding */ inline int KeyboardAxis(int key1, int key2) { if ( key1 && !key2 ) return -255; else if ( !key1 && key2 ) return 255; return 0; } Player::Player(uint32_t id, uint8_t control) { this->_id = id; this->SetControls((uint8_t)id); this->_control = control; this->timer = 0; this->_entity = NULL; this->_pointer[0] = this->_pointer[1] = this->_pointer[2] = 10; this->PlayerColour = default_fx; this->PlayerColour.primary_colour.r = this->PlayerColour.primary_colour.b = this->PlayerColour.primary_colour.g = this->PlayerColour.primary_colour.a = 200; } Player::~Player() { this->ClearController(); if ( this->_entity ) { this->_entity->Delete(); this->_entity = NULL; } } std::string Player::GetControllerName() { return this->control_name; } void Player::SetControls( std::string controller_name ) { this->control_name = controller_name; this->SetupController( controller_name ); } void Player::SetControls(uint8_t preset) { std::string control_value = "default"; if ( lux::config ) { std::string control_name = "player.controller"; control_name.append( 1, (char)(preset + '0') ); control_value = lux::config->GetString(control_name); } this->SetControls( control_value ); } /* Cache Input */ void Player::CachePointerValues() { switch (this->_pointerConfig.device) { case CONTROLAXIS: { //TODO this->_pointer[0] += lux::core->GetInput(CONTROLAXIS, this->_pointerConfig.device_number,this->_pointerConfig.sym[0]) / 128; this->_pointer[1] += lux::core->GetInput(CONTROLAXIS, this->_pointerConfig.device_number,this->_pointerConfig.sym[2]) / 128; this->_pointer[2] = 1; break; } case MOUSEAXIS: { this->_pointer[0] = lux::core->GetInput(MOUSEAXIS, 0,0); this->_pointer[1] = lux::core->GetInput(MOUSEAXIS, 0,1); this->_pointer[2] = 1; break; } default: { this->_pointer[0] = this->_pointer[1] = this->_pointer[2] = 0; break; } } } void Player::CacheAxisValues( uint8_t n ) { switch (this->_controllerConfig[n].device) { case KEYBOARD: { int key1, key2; /* X axis */ key1 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[0]); key2 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[1]); this->_controller[(n*3)+0] = KeyboardAxis(key1, key2); /* y axis */ key1 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[2]); key2 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[3]); this->_controller[(n*3)+1] = KeyboardAxis(key1, key2); /* z axis */ key1 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[4]); key2 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[5]); this->_controller[(n*3)+2] = KeyboardAxis(key1, key2); break; } case CONTROLAXIS: { this->_controller[(n*3)+0] = lux::core->GetInput(CONTROLAXIS, this->_controllerConfig[n].device_number, this->_controllerConfig[n].sym[0]); this->_controller[(n*3)+1] = lux::core->GetInput(CONTROLAXIS, this->_controllerConfig[n].device_number,this->_controllerConfig[n].sym[2]); this->_controller[(n*3)+2] = lux::core->GetInput(CONTROLAXIS, this->_controllerConfig[n].device_number,this->_controllerConfig[n].sym[4]); break; } default: break; } // if ( this->_buttonConfig[n].device == CONTROLBUTTON || this->_buttonConfig[n].device == CONTROLAXIS ) // lux::core->SystemMessage(SYSTEM_MESSAGE_DEBUG) << "axis[" << +n << "] x:" << this->_controller[(n*3)+0] << " y:" << this->_controller[(n*3)+1] << " z:" << this->_controller[(n*3)+2] << std::endl; } void Player::CacheButtonValues(uint8_t n) { if ( lux::core == NULL ) return; int key = lux::core->GetInput( this->_buttonConfig[n].device, this->_buttonConfig[n].device_number, this->_buttonConfig[n].sym ); if ( key ) this->_button[n] = (this->_button[n] ? 2 : 1); else this->_button[n] = 0; // if ( this->_buttonConfig[n].device == CONTROLBUTTON || this->_buttonConfig[n].device == CONTROLAXIS ) // lux::core->SystemMessage(SYSTEM_MESSAGE_DEBUG) << "button[" << +n << "] " << this->_button[n] << std::endl; } void Player::Loop() { if (_control == LOCAL) { /* Pointer */ this->CachePointerValues(); /* Button/Axis */ for (uint8_t n = 0; n < 19; n++) { if (n < 2) { this->CacheAxisValues(n); } this->CacheButtonValues(n); } #ifdef NETWORKENABLED if ( lux::core->GetTime() > (this->timer + 333) ) { this->timer = lux::core->GetTime(); if ( this->_entity ) { this->_entity->displaymap = lux::gameworld->active_map->Ident(); if ( lux::core->CreateMessage((uint8_t)4, true) ) { lux::core->MessageAppend(this->_entity->x); lux::core->MessageAppend(this->_entity->y); lux::core->MessageAppend(this->_entity->displaymap); lux::core->MessageSend(); } } } #endif } else if ( this->_control == REMOTE ) { } } LuxSprite * Player::GetInputSprite( int8_t axis, int8_t key, int8_t pointer ) { LuxSprite * sprite = NULL; if ( axis >= 0 && axis < 12 ) { uint8_t a = axis/6; // Axis (Either 1 or 2) uint8_t s = axis%6; // Axis Direction int32_t m = 0; if ( this->_controllerConfig[a].device == CONTROLAXIS ) { m = ( s % 2 ? 0 : 0x80000000 ); //If remainder, we want positive value } sprite = lux::engine->media.GetInputImage( this->_controllerConfig[a].device, this->_controllerConfig[a].device_number, this->_controllerConfig[a].sym[s] | m ); } else if ( key >= 0 && key < 19 ) { sprite = lux::engine->media.GetInputImage(this->_buttonConfig[key].device, this->_buttonConfig[key].device_number, this->_buttonConfig[key].sym); } else if ( pointer >= 0 ) { sprite = lux::engine->media.GetInputImage(this->_pointerConfig.device, this->_pointerConfig.device_number, this->_pointerConfig.sym[0]); } return sprite; } int16_t Player::GetControllerAxis(uint8_t axis) { if (axis < 6) { return (int16_t)this->_controller[axis]; } return -1; } int16_t Player::GetButton(uint8_t key) { if (key < 19) { return (int16_t)this->_button[key]; } return -1; } int16_t Player::GetPointer(uint8_t axis) { if (axis < 2) { return (int16_t)this->_pointer[axis]; } return -1; } void Player::SetControllerAxis(uint8_t axis, int16_t value) { if (axis < 4) { this->_controller[axis] = value; } } void Player::SetButton(uint8_t key, int16_t value) { if (key < 16) { this->_button[key] = value; } } void Player::SetPointer(uint8_t axis, int16_t value) { if ( axis < 2 ) { this->_pointer[axis] = value; } } MapObject *Player::GetPointerObject() { return NULL; } /* Entity */ Entity * Player::GetEntity() { return this->_entity; } void Player::SetEntity(Entity * entity) { this->_entity = entity; } void Player::SetEntityPostion( fixed x, fixed y, uint8_t z_layer, uint32_t mapid ) { if ( this->_entity ) { #ifdef NETWORKENABLED lux::core->NetworkLock(); #endif this->_entity->x = x; this->_entity->y = y; this->_entity->z_layer = z_layer; this->_entity->displaymap = mapid; #ifdef NETWORKENABLED lux::core->NetworkUnlock(); #endif } } void Player::Message( int32_t * data, uint32_t size ) { if ( this->_entity ) { #ifdef NETWORKENABLED lux::core->NetworkLock(); #endif this->_entity->callbacks->Push( this->_entity->_data, size ); this->_entity->callbacks->PushArray( this->_entity->_data, data, size, NULL ); this->_entity->callbacks->Push( this->_entity->_data, 0 ); this->_entity->Call("NetMessage", (char*)""); #ifdef NETWORKENABLED lux::core->NetworkUnlock(); #endif } } void Player::SetName(std::string name) { this->_name = name; } std::string Player::GetName( ) { return this->_name; }
27.449198
243
0.667933
mokoi
2ad14750c3fdc803624cffafce401d86c4f6f585
3,130
hpp
C++
libs/cargo-fd/internals/from-fdstore-internet-visitor.hpp
Samsung/cargo
a96848e803fe8277c3b21e8c172afa9a99e364d7
[ "Apache-2.0" ]
18
2016-01-27T09:14:17.000Z
2022-01-04T09:56:03.000Z
libs/cargo-fd/internals/from-fdstore-internet-visitor.hpp
Samsung/cargo
a96848e803fe8277c3b21e8c172afa9a99e364d7
[ "Apache-2.0" ]
null
null
null
libs/cargo-fd/internals/from-fdstore-internet-visitor.hpp
Samsung/cargo
a96848e803fe8277c3b21e8c172afa9a99e364d7
[ "Apache-2.0" ]
7
2016-03-07T03:18:05.000Z
2022-01-04T09:56:08.000Z
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Pawel Kubik (p.kubik@samsung.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ /** * @file * @author Pawel Kubik (p.kubik@samsung.com) * @brief Visitor for reading from an internet socket file descriptor */ #ifndef CARGO_FD_INTERNALS_FROM_FDSTORE_INTERNET_VISITOR_HPP #define CARGO_FD_INTERNALS_FROM_FDSTORE_INTERNET_VISITOR_HPP #include "cargo-fd/internals/from-fdstore-visitor-base.hpp" #include <endian.h> #include <cstring> namespace cargo { namespace internals { /** * Internet file descriptor reading visitor. */ class FromFDStoreInternetVisitor : public FromFDStoreVisitorBase<FromFDStoreInternetVisitor> { public: explicit FromFDStoreInternetVisitor(int fd) : FromFDStoreVisitorBase(fd) { } FromFDStoreInternetVisitor(FromFDStoreVisitorBase<FromFDStoreInternetVisitor>& visitor) : FromFDStoreVisitorBase<FromFDStoreInternetVisitor>(visitor) { } template<typename T> void visitImpl(T& value) { readInternal(value); } private: template<typename T, typename std::enable_if<std::is_arithmetic<T>::value && sizeof(T) == 2, int>::type = 0> void readInternal(T& value) { uint16_t rawValue; mStore.read(&rawValue, sizeof(T)); rawValue = be16toh(rawValue); ::memcpy(&value, &rawValue, sizeof(value)); } template<typename T, typename std::enable_if<std::is_arithmetic<T>::value && sizeof(T) == 4, int>::type = 0> void readInternal(T& value) { uint32_t rawValue; mStore.read(&rawValue, sizeof(T)); rawValue = be32toh(rawValue); ::memcpy(&value, &rawValue, sizeof(value)); } template<typename T, typename std::enable_if<std::is_arithmetic<T>::value && sizeof(T) == 8, int>::type = 0> void readInternal(T& value) { uint64_t rawValue; mStore.read(&rawValue, sizeof(T)); rawValue = be64toh(rawValue); ::memcpy(&value, &rawValue, sizeof(value));; } template<typename T, typename std::enable_if<!std::is_arithmetic<T>::value || sizeof(T) == 1, int>::type = 0> void readInternal(T& v) { FromFDStoreVisitorBase<FromFDStoreInternetVisitor>::visitImpl(v); } }; } // namespace internals } // namespace cargo #endif // CARGO_FD_INTERNALS_FROM_FDSTORE_INTERNET_VISITOR_HPP
29.528302
94
0.644728
Samsung
2ad78f66c799e817221b4d87cf20030462b9b7cf
10,289
cpp
C++
source/main.cpp
DavidAce/DMRG
e465fd903eade1bf6aa74daacd8e2cf02e9e9332
[ "MIT" ]
9
2017-10-31T22:50:28.000Z
2022-03-10T15:45:27.000Z
source/main.cpp
DavidAce/DMRG
e465fd903eade1bf6aa74daacd8e2cf02e9e9332
[ "MIT" ]
null
null
null
source/main.cpp
DavidAce/DMRG
e465fd903eade1bf6aa74daacd8e2cf02e9e9332
[ "MIT" ]
1
2019-07-16T00:27:56.000Z
2019-07-16T00:27:56.000Z
/*! \file */ #include <algorithms/class_algorithm_launcher.h> #include <config/nmspc_settings.h> #include <general/nmspc_tensor_omp.h> #include <h5pp/h5pp.h> #include <io/filesystem.h> #include <math/rnd.h> #include <tools/common/log.h> #if defined(OPENBLAS_AVAILABLE) #include <cblas.h> #include <openblas_config.h> #endif #if defined(MKL_AVAILABLE) #define MKL_Complex8 std::complex<float> #define MKL_Complex16 std::complex<double> // #include <mkl.h> #include <mkl_service.h> #endif #include <config/class_dmrg_config.h> #include <general/stack_trace.h> #include <getopt.h> #include <gitversion.h> #include <thread> #if __has_include(<unistd.h>) #include <unistd.h> #endif void print_usage() { std::printf( R"( ========== DMRG++ ============ Usage : DMRG++ [-option <value>]. -h : Help. Shows this text. -b <positive integer> : Integer whose bitfield sets the initial product state. Negative is unused (default -1) -c <.cfg or .h5 filename> : Full or relative path to a config file or hdf5 file from a previous simulation (which has a config file) (default = input.cfg) -n <stl threads> : Number of C++11 threads (Used by Eigen::Tensor) -o <output filename base> : Full or relative path to the output file (output). The seed number will be appended to this filename unless -x is passed. -i <.cfg or .h5 filename> : Full or relative path to a config file or hdf5 file from a previous simulation (which has a config file) (default = input.cfg) -s <seed> : Positive number that seeds the random number generator (default = 1) -t <omp threads> : Number of OpenMP threads -v : Enables trace-level verbosity -x : Do not append seed to the output filename. )"); } void clean_up() { if(not settings::output::use_temp_dir) return; if(fs::exists(settings::output::tmp::hdf5_temp_path)) { try { tools::log->info("Cleaning up temporary file: [{}]", settings::output::tmp::hdf5_temp_path); h5pp::hdf5::moveFile(settings::output::tmp::hdf5_temp_path, settings::output::tmp::hdf5_final_path, h5pp::FilePermission::REPLACE); } catch(const std::exception &err) { tools::log->info("Cleaning not needed: {}", err.what()); } } H5garbage_collect(); H5Eprint(H5E_DEFAULT, stderr); } std::string filename_append_number(const std::string &filename, const long number) { if(number < 0) return filename; // Append the seed_model to the output filename h5pp::fs::path oldFileName = filename; h5pp::fs::path newFileName = filename; if(oldFileName.stem().string().find(std::to_string(number)) != std::string::npos) return filename; newFileName.replace_filename(oldFileName.stem().string() + "_" + std::to_string(number) + oldFileName.extension().string()); tools::log->info("Appended number [{}] to filename: [{}]", number, newFileName.string()); return newFileName.string(); } /*! \brief Main function. Sets simulation parameters and excecutes the desired algorithms. \return an integer 0 upon exit success */ int main(int argc, char *argv[]) { // Register termination codes and what to do in those cases debug::register_callbacks(); // Make sure to move the file back from temp location std::atexit(clean_up); std::at_quick_exit(clean_up); tools::log = tools::Logger::setLogger("DMRG++ main", 0, true); using namespace tools; #if __has_include(<unistd.h>) char name[HOST_NAME_MAX]; auto err = gethostname(name, HOST_NAME_MAX); if(err == 0) tools::log->info("Hostname : {}", name); #endif // print current Git status tools::log->info("Git branch : {}", GIT::BRANCH); tools::log->info(" commit hash : {}", GIT::COMMIT_HASH); tools::log->info(" revision : {}", GIT::REVISION); // Here we use getopt to parse CLI input // Note that CLI input always override config-file values // wherever they are found (config file, h5 file) bool append_seed = true; std::string config; std::string output; long verbosity = -1; long seed = -1; long bitfield = -1; long omp_threads = -1; long stl_threads = -1; while(true) { char opt = static_cast<char>(getopt(argc, argv, "hb:c:i:n:o:s:t:vx")); if(opt == EOF) break; if(optarg == nullptr) tools::log->info("Parsing input argument: -{}", opt); else tools::log->info("Parsing input argument: -{} {}", opt, optarg); switch(opt) { case 'b': bitfield = std::strtol(optarg, nullptr, 10); continue; case 'c': case 'i': config = std::string(optarg); continue; case 'n': stl_threads = std::strtol(optarg, nullptr, 10); continue; case 'o': output = std::string(optarg); continue; case 's': seed = std::strtol(optarg, nullptr, 10); continue; case 't': omp_threads = std::strtol(optarg, nullptr, 10); continue; case 'v': verbosity = 0; continue; case 'x': append_seed = false; continue; case ':': tools::log->error("Option -{} needs a value", opt); break; case 'h': case '?': default: print_usage(); exit(0); case -1: break; } break; } /* There may be multiple config files to consider: 1) Given from CLI (.config/.h5) 2) Inside the output file "<output>_<seed>.h5" if it already exists. What should one do? Simplest solution: Always ignore case 2)! Taking 2) into account leads to very confusing policies. What are the implications? - If CLI passes a .config file we have to override some of its settings: - output */ /*! It's important that we do things in this order: A1: config file not given: use the default input/input.config A2: config file given with .config/h5 extension: load given config B: Override settings with parameters given through CLI C: generate output filename. If the seed is already on the filename, it is not appended again. */ // B: Try loading given config file. // Note that there is a default "input/input.config" if none was given if(not config.empty()) { class_dmrg_config dmrg_config(config); if(dmrg_config.file_exists) { dmrg_config.load(); settings::load_config(dmrg_config); // B2 } else throw std::runtime_error(fmt::format("Could not find config file: {}", config)); // Invalid file given settings::input::config_filename = config; } // else use default config // B: Override settings if(seed >= 0) settings::input::seed = seed; if(bitfield >= 0) settings::input::bitfield = bitfield; if(stl_threads >= 0) settings::threading::stl_threads = static_cast<int>(stl_threads); if(omp_threads >= 0) settings::threading::omp_threads = static_cast<int>(omp_threads); if(not output.empty()) settings::output::output_filepath = output; if(verbosity >= 0) settings::console::verbosity = static_cast<size_t>(verbosity); tools::log = tools::Logger::setLogger("DMRG++ main", settings::console::verbosity, settings::console::timestamp); // C: Generate the correct output filename based on given seeds if(append_seed) { settings::output::output_filepath = filename_append_number(settings::output::output_filepath, settings::input::seed); settings::output::output_filepath = filename_append_number(settings::output::output_filepath, settings::input::bitfield); } // Seed with random::device initially (This also takes care of srand used by Eigen) // This is to make reproducible simulations rnd::seed(settings::input::seed); // Set the number of threads to be used #if defined(EIGEN_USE_THREADS) if(settings::threading::stl_threads <= 0) { settings::threading::stl_threads = (int) std::thread::hardware_concurrency(); } Textra::omp::setNumThreads(settings::threading::stl_threads); tools::log->info("Using Eigen Tensor with {} C++11 threads", Textra::omp::num_threads); #else if(settings::threading::stl_threads > 1) tools::log->warn("EIGEN_USE_THREADS is not defined: " "Failed to enable threading in Eigen::Tensor with stl_threads = {}", settings::threading::stl_threads); #endif #if defined(_OPENMP) if(settings::threading::omp_threads <= 0) { settings::threading::omp_threads = (int) std::thread::hardware_concurrency(); } omp_set_num_threads(settings::threading::omp_threads); // Should only need this. Both Eigen (non-Tensor) and MKL listen to this // omp_set_max_active_levels(1); tools::log->info("Using OpenMP with {} threads and {} active levels", omp_get_max_threads(), omp_get_max_active_levels()); #endif #if defined(OPENBLAS_AVAILABLE) auto openblas_parallel_mode = openblas_get_parallel(); std::string openblas_parallel_str; if(openblas_parallel_mode == 0) openblas_parallel_str = "seq"; if(openblas_parallel_mode == 1) openblas_parallel_str = "threads"; if(openblas_parallel_mode == 2) openblas_parallel_str = "openmp"; if(openblas_parallel_mode == 1) openblas_set_num_threads(settings::threading::omp_threads); // Use the omp_threads level for blas-related threading tools::log->info("{} compiled with parallel mode [{}] for target {} with config {} | multithread threshold {} | running with {} threads", OPENBLAS_VERSION, openblas_parallel_str, openblas_get_corename(), openblas_get_config(), OPENBLAS_GEMM_MULTITHREAD_THRESHOLD, openblas_get_num_threads()); #endif #if defined(MKL_AVAILABLE) tools::log->info("Using Intel MKL with {} threads", mkl_get_max_threads()); #endif // Initialize the algorithm class // This class stores simulation data automatically to a file specified in the config file class_algorithm_launcher launcher; // Run the algorithms launcher.run_algorithms(); return 0; }
43.597458
159
0.648848
DavidAce
2ade04cfa5f59cb6558411487dafbfd39a12c9b5
2,515
cpp
C++
pop/src/commands/PopCommand.cpp
webOS-ports/mojomail
49358ac2878e010f5c6e3bd962f047c476c11fc3
[ "Apache-2.0" ]
6
2015-01-09T02:20:27.000Z
2021-01-02T08:14:23.000Z
mojomail/pop/src/commands/PopCommand.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
3
2019-05-11T19:17:56.000Z
2021-11-24T16:04:36.000Z
mojomail/pop/src/commands/PopCommand.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
6
2015-01-09T02:21:13.000Z
2021-01-02T02:37:10.000Z
// @@@LICENSE // // Copyright (c) 2009-2013 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // LICENSE@@@ #include "commands/PopCommand.h" #include "client/PopSession.h" #include "commands/PopCommandResult.h" #include <sstream> #include "client/SyncSession.h" using namespace std; MojLogger PopCommand::s_log("com.palm.pop.client"); PopCommand::PopCommand(Listener& listener, Command::Priority priority) : Command(listener, priority), m_log(s_log), m_lastFunction(NULL), m_isCancelled(false) { } PopCommand::~PopCommand() { } bool PopCommand::PrepareToRun() { if (m_isCancelled) { return false; } else { return true; } } void PopCommand::RunIfReady() { if(PrepareToRun()) { RunImpl(); } } void PopCommand::Run() { MojLogInfo(m_log, "running command %s", Describe().c_str()); try { RunIfReady(); } catch(const exception& e) { Failure(e); } catch(...) { Failure(boost::unknown_exception()); } } const MojRefCountedPtr<PopCommandResult>& PopCommand::GetResult() { if(m_result.get()) { return m_result; } else { m_result.reset(new PopCommandResult()); return m_result; } } void PopCommand::Run(MojSignal<>::SlotRef slot) { if(m_result.get()) { m_result->ConnectDoneSlot(slot); } else { m_result.reset(new PopCommandResult(slot)); } Run(); } void PopCommand::SetResult(const MojRefCountedPtr<PopCommandResult>& result) { m_result = result; } void PopCommand::Cleanup() { } void PopCommand::Cancel() { m_isCancelled = true; // No need to remove command from command manager. The command should be // taken out of comamnd queue before it is cancelled. Cleanup(); } void PopCommand::Status(MojObject& status) const { MojErr err; err = status.putString("class", Describe().c_str()); ErrorToException(err); if(m_lastFunction != NULL) { err = status.putString("lastFunction", m_lastFunction); ErrorToException(err); } if(m_isCancelled) { err = status.put("cancelled", true); ErrorToException(err); } }
19.496124
76
0.706958
webOS-ports
2adfa4f053b54d03783143ef2975b341585ef9de
429
cpp
C++
1-Iniciante/10/2754.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
1-Iniciante/10/2754.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
1-Iniciante/10/2754.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
#include <stdio.h> int main(){ double a, b; a = 234.345; b = 45.698; printf("%.6lf - %.6lf\n", a, b); printf("%.0lf - %.0lf\n", a, b); printf("%.1lf - %.1lf\n", a, b); printf("%.2lf - %.2lf\n", a, b); printf("%.3lf - %.3lf\n", a, b); printf("%.6e - %.6e\n", a, b); printf("%.6E - %.6E\n", a, b); printf("%.3lf - %.3lf\n", a, b); printf("%.3lf - %.3lf\n", a, b); return 0; }
21.45
36
0.417249
pedrospaulo
2ae11facb33c494f65b3fd0e9ced0c75457a3985
108
cpp
C++
src/core/operand.cpp
Koensw/Kintex
8977b6ceee75d6067bddb696572e6298ff667a03
[ "MIT" ]
1
2020-08-28T18:00:27.000Z
2020-08-28T18:00:27.000Z
src/core/operand.cpp
Koensw/Kintex
8977b6ceee75d6067bddb696572e6298ff667a03
[ "MIT" ]
null
null
null
src/core/operand.cpp
Koensw/Kintex
8977b6ceee75d6067bddb696572e6298ff667a03
[ "MIT" ]
null
null
null
#include "operand.h" using namespace kintex; Value Operand::result(Environment &env){ return *this; }
15.428571
41
0.712963
Koensw
2ae191ffc744a8211ebbf6e56ec0bc93226e076a
1,447
cpp
C++
Source/UnrealCPP/OnComponentHit/OnComponentHit.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
6
2018-04-22T15:27:39.000Z
2021-11-02T17:33:58.000Z
Source/UnrealCPP/OnComponentHit/OnComponentHit.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
null
null
null
Source/UnrealCPP/OnComponentHit/OnComponentHit.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
4
2018-07-26T15:39:46.000Z
2020-12-28T08:10:35.000Z
// Harrison McGuire // UE4 Version 4.18.2 // https://github.com/Harrison1/unrealcpp // https://severallevels.io // https://harrisonmcguire.com #include "OnComponentHit.h" #include "Components/BoxComponent.h" #include "Components/StaticMeshComponent.h" // Sets default values AOnComponentHit::AOnComponentHit() { // 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; // Use a sphere as a simple collision representation MyComp = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComp")); MyComp->SetSimulatePhysics(true); MyComp->SetNotifyRigidBodyCollision(true); MyComp->BodyInstance.SetCollisionProfileName("BlockAllDynamic"); MyComp->OnComponentHit.AddDynamic(this, &AOnComponentHit::OnCompHit); // Set as root component RootComponent = MyComp; } // Called when the game starts or when spawned void AOnComponentHit::BeginPlay() { Super::BeginPlay(); } // Called every frame void AOnComponentHit::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AOnComponentHit::OnCompHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL)) { if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, FString::Printf(TEXT("I Hit: %s"), *OtherActor->GetName())); } }
27.826923
159
0.750518
Harrison1
2ae3ba705b6e7d9040649b9836c3bc144838a5dc
387
cc
C++
clfsm/CLReflect.v1/CLReflectionSystem.cc
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
null
null
null
clfsm/CLReflect.v1/CLReflectionSystem.cc
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
null
null
null
clfsm/CLReflect.v1/CLReflectionSystem.cc
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
1
2021-09-14T18:37:16.000Z
2021-09-14T18:37:16.000Z
#include "CLReflectionSystem.h" using namespace std; using namespace CLReflect; static CLReflectionSystem* _instance; CLReflectionSystem::CLReflectionSystem() { _metaStore = shared_ptr<CLMetaRegister>(new CLMetaRegister()); } CLReflectionSystem* CLReflectionSystem::getInstance() { if (_instance == NULL) _instance = new CLReflectionSystem(); return _instance; }
20.368421
66
0.757106
mipalgu
2ae78bbf1a3a33bd97dabb65c87239644c78f816
4,449
cpp
C++
Drivers/src/MPU6050.cpp
John-Carr/SolarGatorsBSP_STM
df68ccd2add244c90a573a5d4e1de5400361a2b5
[ "MIT" ]
null
null
null
Drivers/src/MPU6050.cpp
John-Carr/SolarGatorsBSP_STM
df68ccd2add244c90a573a5d4e1de5400361a2b5
[ "MIT" ]
null
null
null
Drivers/src/MPU6050.cpp
John-Carr/SolarGatorsBSP_STM
df68ccd2add244c90a573a5d4e1de5400361a2b5
[ "MIT" ]
null
null
null
/* * MPU6050.cpp * * Created on: Jan 24, 2022 * Author: John Carr */ #include "MPU6050.hpp" namespace SolarGators { namespace Drivers { MPU6050::MPU6050(I2C_HandleTypeDef *hi2c, uint8_t addr):hi2c_(hi2c),addr_(addr) { } MPU6050::~MPU6050() { } uint8_t MPU6050::Init() { uint8_t check; uint8_t Data; // check device ID WHO_AM_I HAL_I2C_Mem_Read(hi2c_, addr_, WHO_AM_I_REG, 1, &check, 1, i2c_timeout); if (check == 104) // 0x68 will be returned by the sensor if everything goes well { // power management register 0X6B we should write all 0's to wake the sensor up Data = 0; HAL_I2C_Mem_Write(hi2c_, addr_, PWR_MGMT_1_REG, 1, &Data, 1, i2c_timeout); // Set DATA RATE of 1KHz by writing SMPLRT_DIV register Data = 0x07; HAL_I2C_Mem_Write(hi2c_, addr_, SMPLRT_DIV_REG, 1, &Data, 1, i2c_timeout); // Set accelerometer configuration in ACCEL_CONFIG Register // XA_ST=0,YA_ST=0,ZA_ST=0, FS_SEL=0 -> 2g Data = 0x00; HAL_I2C_Mem_Write(hi2c_, addr_, ACCEL_CONFIG_REG, 1, &Data, 1, i2c_timeout); // Set Gyroscopic configuration in GYRO_CONFIG Register // XG_ST=0,YG_ST=0,ZG_ST=0, FS_SEL=0 -> 250 deg/s Data = 0x00; HAL_I2C_Mem_Write(hi2c_, addr_, GYRO_CONFIG_REG, 1, &Data, 1, i2c_timeout); return 0; } return 1; } void MPU6050::ReadAccel() { uint8_t Rec_Data[6]; // Read 6 BYTES of data starting from ACCEL_XOUT_H register HAL_I2C_Mem_Read(hi2c_, addr_, ACCEL_XOUT_H_REG, 1, Rec_Data, 6, i2c_timeout); accel_.x = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); accel_.y = (int16_t) (Rec_Data[2] << 8 | Rec_Data[3]); accel_.z = (int16_t) (Rec_Data[4] << 8 | Rec_Data[5]); } void MPU6050::ReadGyro() { uint8_t Rec_Data[6]; // Read 6 BYTES of data starting from GYRO_XOUT_H register HAL_I2C_Mem_Read(hi2c_, addr_, GYRO_XOUT_H_REG, 1, Rec_Data, 6, i2c_timeout); gyro_.x = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); gyro_.y = (int16_t) (Rec_Data[2] << 8 | Rec_Data[3]); gyro_.z = (int16_t) (Rec_Data[4] << 8 | Rec_Data[5]); } void MPU6050::ReadTemp() { uint8_t Rec_Data[2]; int16_t temp; // Read 2 BYTES of data starting from TEMP_OUT_H_REG register HAL_I2C_Mem_Read(hi2c_, addr_, TEMP_OUT_H_REG, 1, Rec_Data, 2, i2c_timeout); temp = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); temperature_ = (float) ((int16_t) temp / (float) 340.0 + (float) 36.53); } void MPU6050::ReadAll() { uint8_t Rec_Data[14]; // Read 14 BYTES of data starting from ACCEL_XOUT_H register HAL_I2C_Mem_Read(hi2c_, addr_, ACCEL_XOUT_H_REG, 1, Rec_Data, 14, i2c_timeout); accel_.x = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); accel_.y = (int16_t) (Rec_Data[2] << 8 | Rec_Data[3]); accel_.z = (int16_t) (Rec_Data[4] << 8 | Rec_Data[5]); temperature_ = (int16_t) (Rec_Data[6] << 8 | Rec_Data[7]); gyro_.x = (int16_t) (Rec_Data[8] << 8 | Rec_Data[9]); gyro_.y = (int16_t) (Rec_Data[10] << 8 | Rec_Data[11]); gyro_.z = (int16_t) (Rec_Data[12] << 8 | Rec_Data[13]); } point_3d_t MPU6050::GetRawAccel() { ReadAccel(); return GetLastAccel(); } fpoint_3d_t MPU6050::GetAdjAccel() { ReadAccel(); return GetLastAdjAccel(); } point_3d_t MPU6050::GetLastAccel() { return accel_; } fpoint_3d_t MPU6050::GetLastAdjAccel() { fpoint_3d_t ret; /*** convert the RAW values into acceleration in 'g' we have to divide according to the Full scale value set in FS_SEL I have configured FS_SEL = 0. So I am dividing by 16384.0 for more details check ACCEL_CONFIG Register ****/ ret.x = static_cast<float>(accel_.x) / 16384.0; ret.y = static_cast<float>(accel_.y) / 16384.0; ret.z = static_cast<float>(accel_.z) / 14418.0; return ret; } point_3d_t MPU6050::GetRawGyro() { ReadGyro(); return gyro_; } fpoint_3d_t MPU6050::GetAdjGyro() { ReadGyro(); return GetLastAdjGyro(); } point_3d_t MPU6050::GetLastGyro() { return gyro_; } fpoint_3d_t MPU6050::GetLastAdjGyro() { fpoint_3d_t ret; /*** convert the RAW values into dps (�/s) we have to divide according to the Full scale value set in FS_SEL I have configured FS_SEL = 0. So I am dividing by 131.0 for more details check GYRO_CONFIG Register ****/ ret.x = static_cast<float>(gyro_.x) / 131.0; ret.y = static_cast<float>(gyro_.y) / 131.0; ret.z = static_cast<float>(gyro_.z) / 131.0; return ret; } } /* namespace Drivers */ } /* namespace SolarGators */
27.128049
85
0.665093
John-Carr
2ae921a5e20ad74efac5998139bc703a9e69d222
1,814
hpp
C++
src/db_client.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/db_client.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/db_client.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
#ifndef DB_CLIENT_HPP_INCLUDED #define DB_CLIENT_HPP_INCLUDED #include <string> #include <functional> #include <boost/intrusive_ptr.hpp> #include "formula_callable.hpp" #include "formula_callable_definition.hpp" #include "variant.hpp" class db_client; typedef boost::intrusive_ptr<db_client> db_client_ptr; // Class representing a client to the Anura backend database. Designed to be // used by server processes. Use USE_DB_CLIENT to compile this functionality in. class db_client : public game_logic::formula_callable { public: struct error { explicit error(const std::string& msg); std::string msg; }; // Create an instance to connect to the database. static db_client_ptr create(); virtual ~db_client(); // Call this function to process all remaining outstanding operations. // If timeout_us is non-zero, it will cause a timeout if completion isn't // achieved by this time. You must call process() to make progress on // ongoing operations. // // Returns true iff there are still outstanding operations. virtual bool process(int timeout_us=0) = 0; enum PUT_OPERATION { PUT_SET, PUT_ADD, PUT_REPLACE }; // Function to put the given document into the database with the // associated key. Will call on_done when it completes or on_error if it // encountered an error along the way. virtual void put(const std::string& key, variant doc, std::function<void()> on_done, std::function<void()> on_error, PUT_OPERATION op=PUT_SET) = 0; // Function to get the given document from the database. Will call on_done // with the document on completion (null if no document is found). virtual void get(const std::string& key, std::function<void(variant)> on_done, int lock_seconds=0) = 0; virtual void remove(const std::string& key) = 0; private: DECLARE_CALLABLE(db_client); }; #endif
31.824561
148
0.757993
sweetkristas
2af075aae50298928cf55c5df1dbf088ddc2a313
57,048
cc
C++
local/CrystalSystem.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
local/CrystalSystem.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
local/CrystalSystem.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
#undef LCM_SUPPRESS_VIEWS #include <cstdlib> #include "CrystalSystem.h" #include "lcm_MetaPropagation.h" #include "cmatrix.h" #include "rmatrix.h" #include "space_T.h" #include "ScratchList.h" #include "matlabio.h" #include "ListList.h" #include "NMR.h" namespace libcmatrix { using ::std::sqrt; const size_t invalid_value=-1; /****************************************************************/ CrystalSymmetriseBase::CrystalSymmetriseBase(size_t N, size_t M, size_t neigs,int flags) : neigs_(neigs), ncells_(N), total_(M*N), useeigsym_(flags & MetaFlags::UseEigSymmetry), scalefacs(neigs*neigs+1,DEADBEEF) { const size_t max(neigs*neigs); if (neigs % N) throw InvalidParameter("CrystalSymmetriseBase"); for (size_t j=1;j<=max;j++) { if ( (max % j)==0) scalefacs(j)=N/sqrt(double(j)); } maxstates_=long(1)<<total_; } //Basic 1D symmetriser class SimpleSymmetrise : public CrystalSymmetriseBase { public: SimpleSymmetrise(int N, int M, int flags_); complex symmetrise(Matrix<double>& store, magicsize_t,magicsize_t,int k) const { return symmetrise_(store,k); } complex symmetrise(Matrix<complex>& store, magicsize_t,magicsize_t,int k) const { return symmetrise_(store,k); } CrystalSymmetriseBase* clone() const { return new SimpleSymmetrise(*this); } void addtoevals(BaseList<complex>& evals, size_t blki, size_t blkj, size_t r, size_t c) const; bool haspermutation() const { return false; } private: List<complex> eigfacs; template<typename T> complex symmetrise_(Matrix<T>&, int k) const; }; struct simple_creator { explicit simple_creator(size_t N_,size_t M_) : M(M_), shift(M_*N_-M_), mask((1<<M)-1) {} const size_t M; const size_t shift; const state_t mask; magicsize_t push_states(List<state_t>& state_list, BaseList<bool> used, state_t current) const { size_t count=0; const state_t start=current; do { used(current)=true; //flag state used count++; state_list.push_back(current); current=(current>>M) | ((current & mask)<<shift); //apply translation } while (current!=start); //stop when we return to beginning return count; } }; void CrystalSymmetriseBase::makeindices() { if (linkedstates_.empty()) throw Failed("CrystalSymmetriseBase::makeindices called before linked states created"); const long totdim=maxstates(); //total number of states //indexes take a state number and return the set(block) number and position (index) within set state_to_block_.create(totdim,invalid_value); state_to_index_.create(totdim,invalid_value); for (size_t blk=permutation_blocks();blk--;) { const BaseList<state_t> clist(linkedstates_(blk)); size_t j=clist.size(); for (;j--;) { state_to_block_(clist(j))=blk; state_to_index_(clist(j))=j; } } } void CrystalSymmetriseBase::make_eigfacs(BaseList<complex> eigfacs) { const size_t N=eigfacs.size(); for (size_t j=N;j--;) eigfacs(j)=expi(2*M_PI*double(j)/N); //store e^2pi i n/N } SimpleSymmetrise::SimpleSymmetrise(int N, int M_, int flags_) : CrystalSymmetriseBase(N,M_,N,flags_), eigfacs(N) { useeigs = useeigsym_ ? 1+N/2 : N; //number of active eigenvalues isreal_.create(useeigs,false); isreal_.front()=true; if (!useeigsym_ || ((N & 1)==0)) isreal_(N/2)=true; size_t j,k; make_eigfacs(eigfacs); haseig.create(N+1,useeigs,false); //haseig(j,k) is true if a set of size j contains eigenvalue k, where j is a factor of N for (j=1;j<=N;j++) { if ( (N % j)==0) { const size_t step=N/j; for (k=0;k<useeigs;k+=step) haseig(j,k)=true; } } simple_creator creator(N,M_); getsymmetry(creator); //get sets of symmetry-linked states } /***************************************************/ CrystalOpGenerator::CrystalOpGenerator(const spinhalf_system& sys_, const CrystalStructure& cstructv, int flagsv, int verbosev) : SpinOpGeneratorBase(cstructv,sys_.nspins(),flagsv,verbosev), sysp_(N_==1 ? &sys_ : sys_.clone(N_),N_==1 ? mxflag::nondynamic : mxflag::normal) { create(); } CrystalOpGenerator::CrystalOpGenerator(const spinhalf_system& sys_, const CrystalStructure& cstructv, const char *nuclabel, int flagsv, int verbosev) : SpinOpGeneratorBase(cstructv,sys_.nspins(),flagsv,verbosev), sysp_(N_==1 ? &sys_ : sys_.clone(N_),N_==1 ? mxflag::nondynamic : mxflag::normal) { create(ExplicitList<1,nuclei_spec>(nuclabel)); } CrystalOpGenerator::CrystalOpGenerator(const spinhalf_system& sys_, const CrystalStructure& cstructv, const BaseList<nuclei_spec>& blocknucsv, int flagsv, int verbosev) : SpinOpGeneratorBase(cstructv,sys_.nspins(),flagsv,verbosev), sysp_(N_==1 ? &sys_ : sys_.clone(N_),N_==1 ? mxflag::nondynamic : mxflag::normal) { create(blocknucsv); } CrystalOpGenerator::CrystalOpGenerator(const HamiltonianStructure& structurev, const CrystalStructure& cstructv, int verbosev) : SpinOpGeneratorBase(cstructv,structurev,verbosev), sysp_(new spinhalf_system(structurev.spinsystem(),N_),mxflag::normal) { if (quadrupole_order()!=1) throw Failed("CrystalOpGenerator doesn't support 2nd order quadrupoles"); create(structurev.blockingnuclei()); } template<typename T> void CrystalOpGenerator::create(BlockedMatrix<T>& dest, const block_pattern& blkspec) const { block_pattern::iterator iter(blkspec); // const size_t limit=actual_mzblocks(); const size_t eigblks(eigstr_.eigblocks()); const size_t mzblks=blkspec.blocks; const size_t totblks(eigblks*mzblks); // size_t mzlevels=blkspec.mzlevels; // if (blkspec.hasmiddle) // mzlevels=(mzlevels+1)/2; //actual cutoff ScratchList<size_t> rstr(totblks); ScratchList<size_t> cstr(totblks); size_t r,c,mz; bool ismiddle; while (iter.next(r,c,mz,ismiddle)) { // if (r>=mzlevels) { // r=c; // assert(blkspec.hasmiddle); // } // else { // if (c>=mzlevels) { // c=r; // assert(blkspec.hasmiddle); // } // } // if (ismiddle) { // if (c>r) // c=r; // else // r=c; // } for (size_t k=eigblks;k--;) { const size_t ind(eigstr_.index(mz,k)); rstr(ind)=eigsizes(r,k); cstr(ind)=eigsizes(c,k); } } if (verbose()>1) std::cout << "Creating empty BlockedMatrix: rows: " << rstr << " cols: " << cstr << '\n'; dest.create(rstr,cstr); } //iterates over a set of blocks class CrystalSystem_iterator { public: CrystalSystem_iterator(const CrystalOpGenerator&); //zero coherence blocks CrystalSystem_iterator(const CrystalOpGenerator&, const block_pattern&, size_t nuc, int coher, bool isupper =false); bool next(size_t&, size_t&); //are we blocked by coherence? // bool isblocked() const { return sym.isblocked(); } template<typename T> void addsym(MatrixTensor<complex>&, size_t blki, size_t blkj, int l, int m, int k, bool, Type2Type<T>); template<typename T> void addsym(BlockedMatrixTensor<complex>&, size_t blki, size_t blkj, int l, int m, bool, Type2Type<T>); template<class T> void addsym(BlockedMatrix<complex>&, size_t, size_t, Type2Type<T>, bool); template<class T> void addsym(cmatrix&, size_t, size_t, int k, const T&, bool); template<class T> void addsym(complex&, size_t, size_t, int k, const T&, bool); void add(BlockedMatrix<complex>&, const BaseList<complex>&, size_t, size_t) const; void add_hermitian(BlockedMatrix<complex>&, const BaseList<complex>&, size_t, size_t) const; void add(cmatrix&, complex, size_t, size_t, int) const; void add_hermitian(cmatrix&, complex, size_t, size_t, int) const; void mla(BlockedMatrix<complex>&, double,const operator_spec&); bool Ipevalues(DynamicList<complex>&, size_t blki,size_t blkj,int); bool Fpevalues(DynamicList<complex>&, size_t blki,size_t blkj,size_t nuc =NULL_NUCLEUS); void docreate(); bool isdiagonal() const { return (rmzind==cmzind); } void ensure_null(BlockedMatrixTensor<complex>&, int l) const; void ensure_null(BlockedMatrix<complex>&) const; size_t rows(size_t k) const { return rblkstr(k); } size_t cols(size_t k) const { return cblkstr(k); } template<class T> bool Hcoupling_matrix(const Matrix<T>& couplings,int,int,size_t blki,size_t blkj); bool A2_matrix(const Matrix<space_T>& tensors,size_t blki,size_t blkj,int m); bool A2_matrix(const rmatrix& couplings,size_t blki,size_t blkj) { return Hcoupling_matrix(couplings,2,-1,blki,blkj); } bool A2_matrix(const Matrix<space_T>& couplings,size_t blki,size_t blkj) { return Hcoupling_matrix(couplings,2,-1,blki,blkj); } bool A0_matrix(const rmatrix& couplings,size_t blki,size_t blkj) { return Hcoupling_matrix(couplings,1,1,blki,blkj); } size_t get_block(int eval) const { return sym.eigstr_.index(mzcount,eval); } rmatrix& get_store(size_t rs, size_t cs, const Type2Type<double>&) { rmatrix& res(rstores(rs,cs)); if (!res) res.create(rs,cs); return res; } cmatrix& get_store(size_t rs, size_t cs, const Type2Type<complex>&) { cmatrix& res(cstores(rs,cs)); if (!res) res.create(rs,cs); return res; } double symmetrise0(const Type2Type<double>&) const { return ncells*H00; } complex symmetrise0(const Type2Type<complex>&) const { return float_t(ncells)*H00c; } double symmetrise0(size_t rs,size_t cs, const Type2Type<double>&) const { return scalefacs(rs*cs)*sum(rstores(rs,cs)); } complex symmetrise0(size_t rs,size_t cs, const Type2Type<complex>&) const { return scalefacs(rs*cs)*sum(cstores(rs,cs)); } private: const CrystalOpGenerator& sym; const CrystalSymmetriseBase& symmetriser; size_t useeigs; const List<double>& scalefacs; const List<size_t>& state_to_block; const List<size_t>& state_to_index; int coher_; //coherence being considered BaseList<size_t> nucmzinds; size_t ncells; size_t neigs; bool finished; //true if there are no blocks left bool isupper; //true if problem is symmetric and we are only iterating over upper diagonal size_t rmzind,cmzind; //current row/col block size_t mzcount; bool bumpmz; BaseList<size_t> cwhich; //current set (row,column) of states BaseList<size_t> rwhich; size_t brablks,ketblks; //number of bra/ket states size_t rows_,cols_; //size of mz2 block size_t crow,ccol; //current bra/ket index Matrix<rmatrix> rstores; Matrix<cmatrix> cstores; double H00; complex H00c; DynamicList<complex> evalues; BaseList<size_t> rblkstr; BaseList<size_t> cblkstr; int verbose; // bool ismiddle; block_pattern::iterator mziter; void resetmz2(); bool nextmz2() { mzcount++; size_t mzeigSD; //!< ignored - could be merged with mzcount, but don't want to touch! if (mziter.next(rmzind,cmzind,mzeigSD)) { resetmz2(); return true; } return false; } void init(size_t selnuc); }; class CrystalSystem_diagiterator { public: CrystalSystem_diagiterator(const CrystalOpGenerator&); bool next(size_t&); size_t get_block(int eval) const { return sym.eigstr_.index(mzind,eval); } private: const CrystalOpGenerator& sym; BaseList<size_t> rwhich; //current set of states int blki; //current index size_t mzind; bool bumpmz; void resetmz2(); }; CrystalSystem_diagiterator::CrystalSystem_diagiterator(const CrystalOpGenerator& Sym) : sym(Sym) { mzind=Sym.actual_mzblocks()-1; resetmz2(); } void CrystalSystem_diagiterator::resetmz2() { rwhich.create(sym.blockindices(mzind)); blki=rwhich.length()-1; bumpmz=false; } bool CrystalSystem_diagiterator::next(size_t& blk) { if (bumpmz) { mzind--; resetmz2(); } if (blki<0) return false; //finished blk = rwhich(blki--); if ((blki<0) && mzind) bumpmz=true; return true; } CrystalSystem_iterator::CrystalSystem_iterator(const CrystalOpGenerator& Sym) : sym(Sym), symmetriser(*(Sym.symmetriserp_)), scalefacs(symmetriser.scale_factors()), state_to_block(symmetriser.state_to_block()), state_to_index(symmetriser.state_to_index()), coher_(0), isupper(false), mziter(Sym.diag_blkspec_) { init(Sym.defaultnucleus_); } CrystalSystem_iterator::CrystalSystem_iterator(const CrystalOpGenerator& Sym, const block_pattern& blkspec, size_t selnuc, int coherv, bool isupper_) : sym(Sym), symmetriser(*(Sym.symmetriserp_)), scalefacs(symmetriser.scale_factors()), state_to_block(symmetriser.state_to_block()), state_to_index(symmetriser.state_to_index()), coher_(coherv), isupper(isupper_), mziter(blkspec) { if (isupper && (coherv!=0)) throw InternalError("CrystalSystem_iterator: isupper incompatible with non-zero coherences"); init(selnuc); } void CrystalSystem_iterator::init(size_t selnuc) { useeigs=symmetriser.actual_eigenvalues(); ncells=symmetriser.ncells(); neigs=symmetriser.eigenvalues(); finished=false; rstores.create(neigs+1,neigs+1); cstores.create(neigs+1,neigs+1); // evalues.create(symmetriser.actual_eigenvalues(),mxflag::normal); evalues.create(symmetriser.actual_eigenvalues()); //!< removed normal flag (May 10) Why there? verbose=sym.verbose(); if (selnuc) nucmzinds.create(sym.allmzinds_.row(sym.nuctoindex(selnuc))); bumpmz=false; nextmz2(); mzcount=0; } //reset after changing rmzind/cmzind void CrystalSystem_iterator::resetmz2() { size_t usermz=rmzind; size_t usecmz=cmzind; const size_t maxind=sym.mzsizes.size(); if (rmzind>=maxind) usermz=cmzind; else { if (cmzind>=maxind) usecmz=rmzind; } // if (rmzind>cmzind) // usermz=cmzind; // else // usecmz=rmzind; // } rblkstr.create(sym.eigsizes.row(usermz)); //get block structure for given mz pair cblkstr.create(sym.eigsizes.row(usecmz)); rows_=sym.mzsizes(usermz); //size of block cols_=sym.mzsizes(usecmz); //if single state set, store set number for quick reference //store junk value otherwise to catch attempts to use firstrblk in other cases // if (rows_==1) // firstrblk=int(sym.mzblocking_(usermz).front()); // else // firstrblk=-1; //must use actual indices here! rwhich.create(sym.blockindices(rmzind)); //update rwhich etc. to point to current set of bra states cwhich.create(sym.blockindices(cmzind)); brablks=rwhich.length(); ketblks=cwhich.length(); crow=ccol=0; } bool CrystalSystem_iterator::next(size_t& rblk, size_t& cblk) { int blkcoher; do { if (bumpmz) { if (!nextmz2()) finished=true; else { resetmz2(); bumpmz=false; } } if (finished) return false; //iterator is exhausted? rblk=rwhich(crow); //read current position cblk=cwhich(ccol); ccol++; //increment col index if (ccol==ketblks) { crow++; //increment row index ccol= isupper ? crow : 0; //upper diagonal only? if (crow==brablks) //finished state block? bumpmz=true; } if (nucmzinds.empty()) return true; blkcoher=(int)nucmzinds(cblk)-(int)nucmzinds(rblk); } while (blkcoher!=coher_); return true; } //construct dipolar matrix for given set of bra/ket states //ignore couplings to spins of type nuc (unless NULL_NUCLEUS) template<class T> bool CrystalSystem_iterator::Hcoupling_matrix(const Matrix<T>& couplings, int scalez, int scalexy, size_t blki, size_t blkj) { if (sym.nspins()!=couplings.cols()) throw Mismatch("Hcoupling_matrix: coupling matrix doesn't match CrystalOpGenerator"); const ListList<state_t>& linkedstates(symmetriser.linkedstates()); const BaseList<state_t> cstates(linkedstates(blkj)); const size_t blkisize=linkedstates.size(blki); const size_t blkjsize=linkedstates.size(blkj); rmatrix& H(rstores(blkisize,blkjsize)); //where we'll store the temporary matrix bool issingle=(blkisize==1) && (blkjsize==1); //single element? reducer_<double,T> reduce; //clear temporary matrix if (issingle) H00=0.0; else { if (!H) //if temp. matrix doesn't exist, make it H.create(blkisize,blkjsize); H=0; } const basespin_system& sys=*(sym.sysp_); const double scalez2=scalez*0.5; const size_t total(sym.nspins()); const size_t M(sym.nspins_cell()); for (size_t j=0;j<M;j++) { const state_t maskj=maskelement(total,j); for (size_t k=0;k<M;k++) { //loop over spin pairs const bool ishomo=(sys(j)==sys(k)); //homonuclear coupling for (size_t cell=0;cell<ncells;cell++) { //loop over cells if ((j>k) || cell) { //don't count both (0,j)-(0,k) and (0,k)-(0,j) const size_t sk=sym.cell_to_spin(cell,k); //index of spin (cell,k) const state_t masksk=maskelement(total,sk); const T& curcoup((j<sk) ? couplings(j,sk) : couplings(sk,j)); if (!curcoup) continue; const double coup=(cell ? 0.25 : 0.5)*reduce(curcoup); if (coup==0.0) continue; const state_t mask=maskj | masksk; //has bits corresponding to spins j & sk set for (size_t jj=blkjsize;jj--;) { const state_t cstate=cstates(jj); //current ket state const bool isflip=!(cstate & maskj) ^ !(cstate & masksk); if (blki==blkj) { //zz components const double del= isflip ? -coup : coup; if (issingle) ::libcmatrix::mla(H00,scalez2,del); else ::libcmatrix::mla(H(jj,jj),scalez2,del); } if (ishomo && isflip) { const state_t nstate=cstate ^ mask; //flip spin states if (state_to_block(nstate)==blki ) { //is new spin state within bra states? if (issingle) H00+=scalexy*coup; else H(state_to_index(nstate),jj)+=scalexy*coup; } } } } } } } if (verbose>1) { std::cout << "H" << blki << "," << blkj; if (issingle) std::cout << ": " << H00 << "\n"; else std::cout << ":\n" << H << "\n"; } return issingle; } //return true if result is single element //corresponding function for spinning Hamiltonian (Fourier component m) bool CrystalSystem_iterator::A2_matrix(const Matrix<space_T>& tensors,size_t blki, size_t blkj, int m) { if (sym.nspins_cell()!=tensors.rows()) throw Mismatch("Hcoupling_matrix"); const ListList<state_t>& linkedstates(symmetriser.linkedstates()); const BaseList<state_t> cstates(linkedstates(blkj)); const size_t blkisize=linkedstates.size(blki); const size_t blkjsize=linkedstates.size(blkj); cmatrix& H=cstores(blkisize,blkjsize); const bool issingle=(blkisize==1) && (blkjsize==1); if (issingle) H00c=0.0; else { if (!H) H.create(blkisize,blkjsize); H=0; } const basespin_system& sys=*(sym.sysp_); const size_t total(sym.nspins()); const size_t M(sym.nspins_cell()); for (size_t j=0;j<M;j++) { const state_t maskj=maskelement(total,j); for (size_t k=0;k<M;k++) { const bool ishomo=(sys(j)==sys(k)); for (size_t cell=0;cell<ncells;cell++) { if ((j>k) || cell) { const size_t sk=sym.cell_to_spin(cell,k); const state_t masksk=maskelement(total,sk); const space_T& curtens((j<sk) ? tensors(j,sk) : tensors(sk,j)); if (!curtens) continue; const state_t mask=maskj | masksk; const complex coup=(cell ? 0.25 : 0.5)*curtens(2,m); for (size_t jj=blkjsize;jj--;) { const state_t cstate=cstates(jj); const bool isflip = !(cstate & maskj) ^ !(cstate & masksk); if (blki==blkj) { const complex del= isflip ? -coup : coup; if (issingle) H00c+=del; else H(jj,jj)+=del; } if (ishomo && isflip) { const state_t nstate=cstate ^ mask; if (state_to_block(nstate)==blki ) { if (issingle) H00c-=coup; else H(state_to_index(nstate),jj)-=coup; } } } } } } } if (verbose>1) { std::cout << "H(" << m << ")" << blki << "," << blkj; if (issingle) std::cout << ": " << H00c << "\n"; else std::cout << ":\n" << H << "\n"; } return issingle; } //return value corresponding to eigenvalue m of H transformed into symmetrised basis template<class T> complex SimpleSymmetrise::symmetrise_(Matrix<T>& H, int m) const { if (m==0) throw Failed("symmetrise: don't use for k=0!"); const size_t blkisize=H.rows(); const size_t blkjsize=H.cols(); if (!haseig(blkisize,m) || !haseig(blkjsize,m)) //don't have that eigenvalue for this no. of bra/ket states throw Failed("symmetrise: eigenvalue doesn't exist in given block"); complex s(0.0); for (size_t ii=blkisize;ii--;) { const BaseList<T> Hii=H.row(ii); size_t wh=(m*(ncells_-ii)) % ncells_; for (size_t jj=0;jj<blkjsize;jj++) { // const size_t wh=(m*(jj-ii+N)) % N; mla(s,Hii(jj),eigfacs(wh)); wh+=m; if (wh>=ncells_) wh-=ncells_; } } return s*scalefacs(blkisize*blkjsize); } //return 2 mz for given nucleus type and state int CrystalOpGenerator::mz2val(size_t nuc,state_t state) const { int retval=0; const size_t total(nspins()); for (size_t j=0;j<nspins_cell();j++) { //loop over spins in unit cell if ((*sysp_)(j).nucleus()!=nuc) continue; for (size_t i=0;i<N_;i++) { //loop over cells if (state & maskelement(total,cell_to_spin_(i,j))) //count -1/2 for bit set, +1/2 for not set retval--; else retval++; } } return retval; } //return 2 Fz for given state (val) and total number of spins // = (bits unset)-(bits set) = total bits - 2 (bits set) int CrystalOpGenerator::mz2val(state_t val) const { int retval(nspins()); while (val) { //while still some bits set if (val & 1) retval-=2; val>>=1; } return retval; } //compute symmetrised Iz for given spin ListList<double> diag_Iz(const CrystalOpGenerator& sys, size_t spinn) { return sys.diag_Iz(spinn); } void CrystalOpGenerator::mla_Fz(ListList<double>& dest, double scale, nuclei_spec whichn) const { const size_t nuc=whichn(); if (nuc!=NULL_NUCLEUS) ::libcmatrix::mla(dest,scale,diag_Fz(nuc)); else { if (tzops_.empty()) throw Failed("Can't compute unspecific Fz here"); for (size_t j=nspins_cell();j--;) ::libcmatrix::mla(dest,scale,tzops_(j)); } } void CrystalOpGenerator::rawdiag_Fz(ListList<double>& dest, size_t nuc) const { const basespin_system& sys(spinsystem()); List<size_t> whichspins(nspins_cell()); whichspins.create(0); for (size_t i=nspins_cell();i--;) { if (sys(i).nucleus()==nuc) whichspins.push_back(i); } make_tzop(dest,whichspins); } // construct symmetrised z operator void CrystalOpGenerator::mla_Iz(ListList<double>& tzop, double scale, size_t spinn) const { if (tzops_.empty()) throw Failed("Can't compute Iz when permutation active"); ::libcmatrix::mla(tzop,scale,tzops_(spinn)); } void CrystalOpGenerator::make_tzop(ListList<double>& tzop, const BaseList<size_t>& spins) const { create(tzop); #ifndef NDEBUG tzop=DEADBEEF; //easier to spot problems #endif const size_t n(spins.size()); ScratchList<state_t> masks(n); const size_t total(nspins()); size_t j,k,ablk; for (j=n;j--;) masks(j)=maskelement(total,spins(j)); CrystalSystem_diagiterator iter(*this); const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); const size_t useeigs=symmetriserp_->actual_eigenvalues(); while (iter.next(ablk)) { //loop over state sets const BaseList<state_t> states(linkedstates(ablk)); const size_t blksize=states.length(); const BaseList<int> ptrs(eigptrs.row(ablk)); //stash value of eigptrs for set double sum=0.0; for (j=n;j--;) { const state_t& mask(masks(j)); for (k=blksize;k--;) //loop over states sum+=Izelement_raw(states(k) & mask); } sum*=N_/blksize; for (k=useeigs;k--;) {//store result (sum) in correct position (ptrs(k)) of each eigenvalue block (k) const size_t ind(iter.get_block(k)); const int ptr(ptrs(k)); if (ptr>=0) //easy way to check that eigenvalue is present (tzop(ind))(size_t(ptr))=sum; } } if (verbose()>1) std::cout << "Computed Fz for spins " << spins << ": " << tzop << '\n'; } /* given system spanning reduced Hilbert space construct "reverse index" taking state to index within sub-space */ void makerindex(List<size_t>& rind,const spinhalf_system& sys) { const BaseList<state_t> states=sys.ketstates(); rind.create(sys.size()); rind=-1; //fill with dummy for (size_t i=states.length();i--;) //loop over sub-space rind(states(i))=i; } //return sum over columns in source in dest template<class T> void colsum(List<T>& dest,const Matrix<T>& source) { if (!source) throw Undefined("colsum"); size_t r=source.rows(); dest=source.row(--r); for (;r--;) dest+=source.row(r); } void CrystalOpGenerator::makemzinds(Matrix<size_t>& allmzinds, List<size_t>& maxmzinds, const BaseList<size_t>& nucs) { const size_t ntypes=nucs.size(); const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); const size_t permblocks=linkedstates.size(); allmzinds.create(ntypes,permblocks); maxmzinds.create(ntypes); size_t nuci,j; for (nuci=0;nuci<ntypes;nuci++) { //calculate 2mz for all blocks and all nuclei const size_t tmpnuc=indextonuc(nuci); BaseList<size_t> curmz2(allmzinds.row(nuci)); const size_t maxI2(sysp_->nspins(tmpnuc)); for (j=permblocks;j--;) curmz2(j)=(maxI2-mz2val(tmpnuc,linkedstates(j,0)))/2; maxmzinds(nuci)=size_t(maxI2+1.5); } } //Common part of CrystalOpGenerator constructor (private) void CrystalOpGenerator::create(const BaseList<nuclei_spec>& nucs) { if (M_<1 || N_<1) throw InvalidParameter("CrystalOpGenerator"); if (cstruct.dimensions()<2 && !cstruct.haspermutation()) symmetriserp_.reset(new SimpleSymmetrise(N_,M_,flags())); else { #ifdef LCM_ENABLE_GENERICPERIODIC symmetriserp_.reset(new GeneralSymmetrise(cstruct,M_,flags(),verbose())); #else throw Failed("library compiled without support for periodicity in >1 dimension"); #endif } const size_t useeigs=symmetriserp_->actual_eigenvalues(); const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); const size_t permblocks=linkedstates.size(); if (verbose()) { std::cout << "Found " << permblocks << " sets of symmetry-linked states\n"; if (verbose()>1) std::cout << linkedstates << '\n'; } init_blockstr(useeigs,nucs); defaultnucleus_= (indextonuc.size()==1) ? indextonuc.front() : NULL_NUCLEUS; //find sizes of eigenvalue blocks const size_t nblocks(actual_mzblocks()); eigsizes.create(nblocks,useeigs,size_t(0)); eigptrs.create(permblocks,useeigs,-1); size_t j,k; List<int> eigcount(useeigs); const CrystalSymmetriseBase& symmetriser(*symmetriserp_); List< List<size_t> > subsizes(useeigs*mzblocking_.size()); for (size_t indexi=mzblocking_.size();indexi--;) { //loop over mz blocks const bool included(indexi<nblocks); const ListList<size_t> curmzblocking(mzblocking_(indexi)); eigcount=0; for (size_t minorj=curmzblocking.size();minorj--;) { const BaseList<size_t> cwhich(curmzblocking(minorj)); for (j=cwhich.length();j--;) { //loop over each set size_t blk=cwhich(j); const magicsize_t shape=symmetriser.blockshape(blk); const BaseList<bool> whichvalues(symmetriser.which_eigenvalues(shape)); //eigptrs(blk,k) gives the index within the symmetrised block for eigenvalue k generated from set blk for (k=useeigs;k--;) { if (whichvalues(k)) { eigptrs(blk,k)=eigcount(k)++; if (included) { List<size_t>& cursubsize(subsizes(index(indexi,k))); if (cursubsize.empty()) cursubsize.create(curmzblocking.size(),size_t(0U)); cursubsize(minorj)++; } } } } } if (included) { BaseList<size_t> csizes(eigsizes.row(indexi)); csizes+=eigcount; } } if (verbose()) { std::cout << "Eigenvalue distribution:\n" << eigsizes; double flopc=0; const BaseList<size_t> asrow(eigsizes.row()); for (j=asrow.size();j--;) { const size_t csize(asrow(j)); flopc+=csize*csize*csize; } std::cout << "Flop count: " << flopc << '\n'; if (verbose()>1) std::cout << "Eigenvalue pointers:\n" << eigptrs; } mzsizes.create(nblocks); for (j=nblocks;j--;) { const BaseList<size_t> blks(blockindices(j)); size_t mzsize=0; for (k=blks.length();k--;) { const size_t blk(blks(k)); mzsize+=linkedstates.size(blk); } mzsizes(j)=mzsize; } if (verbose()) std::cout << "Sizes of mz blocks: " << mzsizes << '\n'; diagstr_.create(nblocks*useeigs); //diagonal structure for (size_t mz=nblocks;mz--;) { for (k=useeigs;k--;) { const size_t ind(eigstr_.index(mz,k)); diagstr_(ind)=eigsizes(mz,k); } } if (verbose()>1) std::cout << "Overall diagonal structure: " << diagstr_ << '\n'; if (flags() & MetaFlags::UsePartitioning) { partitioned_diagstr_=subsizes; init_partitioning(); } //don't built z operators if permutation symmetry active if (!symmetriserp_->haspermutation()) { tzops_.create(M_); for (size_t m=0;m<M_;m++) { make_tzop(tzops_(m),m); if (verbose()) std::cout << "Iz_" << m << ": " << tzops_(m) << '\n'; } } diag_blkspec_=block_pattern(*this); } void CrystalSymmetriseBase::print(std::ostream& ostr) const { ostr << "Linked states: " << linkedstates_ << "\n"; ostr << "Eigenvalue pattern:\n" << haseig; } std::ostream& operator<< (std::ostream& ostr, const CrystalOpGenerator& a) { if (a.N_==0) return ostr << "<undefined>\n"; ostr << "Total spin system: " << *(a.sysp_) << "\n"; ostr << "Number of cells: " << a.N_ << "\n"; const SpinOpGeneratorBase& asbase(a); asbase.print(ostr); if (a.verbose()) { a.symmetriserp_->print(ostr); ostr << "Eigenvalue distribution:\n" << a.eigsizes << "\n"; if (a.verbose()>1) ostr << "Ptrs:\n" << a.eigptrs << "\n"; } return ostr; } void CrystalSystem_iterator::ensure_null(BlockedMatrix<complex>& Hmats) const { if (!Hmats) { sym.create(Hmats); Hmats=complex(0.0); } } void CrystalSystem_iterator::ensure_null(BlockedMatrixTensor<complex>& Htens, int l) const { if (!Htens) { sym.create(Htens); Htens=complex(0.0); } if (!(Htens.front().have_rank(l))) Htens.ensure_rank(l,complex(0.0)); } //add symmetrised block (blki,blkj) to spinning Hamiltonian component m template<typename T> void CrystalSystem_iterator::addsym(MatrixTensor<complex>& Htens, size_t blki,size_t blkj,int l, int m, int eval,bool issingle, Type2Type<T> realcomplex) { if (issingle && (eval!=0)) return; BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); //k=0 is special case if (eval==0) { const size_t blkisize(symmetriser.blocksize(blki)); const size_t blkjsize(symmetriser.blocksize(blkj)); const complex val= complex(issingle ? symmetrise0(realcomplex) : symmetrise0(blkisize,blkjsize,realcomplex)); if (Htens.ismatrix()) { cmatrix& Hsym=Htens.matrix(l,m); Hsym(reigptrs.front(),ceigptrs.front())+=val; } else Htens.element(l,m)+=val; } else { const magicsize_t blkishape(symmetriser.blockshape(blki)); const magicsize_t blkjshape(symmetriser.blockshape(blkj)); const int dr=reigptrs(eval); const int dc=ceigptrs(eval); if ((dr>=0) && (dc>=0)) { //if eigenvalue exists const size_t lrows(symmetriser.blocksize(blki)); const size_t lcols(symmetriser.blocksize(blkj)); const complex val=symmetriser.symmetrise(get_store(lrows,lcols,realcomplex),blkishape,blkjshape,eval); if (Htens.ismatrix()) { cmatrix& Hsym=Htens.matrix(l,m); Hsym(dr,dc)+=val; } else { assert((dr==0) && (dc==0)); Htens.element(l,m)+=val; } } } } template<typename T> void CrystalSystem_iterator::addsym(BlockedMatrixTensor<complex>& Htens, size_t blki,size_t blkj,int l,int m, bool issingle, Type2Type<T> realcomplex) { if (issingle) { const size_t ind(get_block(0)); addsym(Htens(ind),blki,blkj,l,m,0,true,realcomplex); return; } for (size_t eval=useeigs;eval--;) { const size_t ind(get_block(eval)); addsym(Htens(ind),blki,blkj,l,m,eval,false,realcomplex); } } template<class T> void CrystalSystem_iterator::addsym(complex& Hk,size_t blki,size_t blkj,int eval,const T& type_, bool issingle) { assert((sym.eigptrs(blki,eval)==0) && (sym.eigptrs(blkj,eval)==0)); if (issingle) { if (eval==0) Hk+=symmetrise0(type_); return; } const size_t lrows(symmetriser.blocksize(blki)); const size_t lcols(symmetriser.blocksize(blkj)); if (eval==0) Hk+=symmetrise0(lrows,lcols,type_); else { const magicsize_t rs=symmetriser.blockshape(blki); const magicsize_t cs=symmetriser.blockshape(blkj); Matrix<T>& store(get_store(lrows,lcols,type_)); Hk+=symmetriser.symmetrise(store,rs,cs,eval); } } template<class T> void CrystalSystem_iterator::addsym(cmatrix& Hk,size_t blki,size_t blkj,int eval,const T& type_, bool issingle) { const int dr=sym.eigptrs(blki,eval); const int dc=sym.eigptrs(blkj,eval); if (issingle) { if (eval==0) Hk(dr,dc)+=symmetrise0(type_); return; } const size_t lrows=symmetriser.blocksize(blki); const size_t lcols=symmetriser.blocksize(blkj); if (eval==0) Hk(dr,dc)+=symmetrise0(lrows,lcols,type_); else { if ((dc>=0) && (dr>=0)) { const magicsize_t rs=symmetriser.blockshape(blki); const magicsize_t cs=symmetriser.blockshape(blkj); Hk(dr,dc)+=symmetriser.symmetrise(get_store(lrows,lcols,type_),rs,cs,eval); } } } template<class T> void CrystalSystem_iterator::addsym(BlockedMatrix<complex>& Hmats,size_t blki,size_t blkj, Type2Type<T> type_, bool issingle) { if (issingle) { const size_t ind(get_block(0)); addsym(Hmats(ind),blki,blkj,0,type_,true); return; } BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); cmatrix& Hsym0(Hmats(get_block(0))); Hsym0(reigptrs.front(),ceigptrs.front())+=symmetrise0(symmetriser.blocksize(blki),symmetriser.blocksize(blkj),type_); const size_t lrows=symmetriser.blocksize(blki); const size_t lcols=symmetriser.blocksize(blkj); const magicsize_t rs=symmetriser.blockshape(blki); const magicsize_t cs=symmetriser.blockshape(blkj); Matrix<T>& store(get_store(lrows,lcols,type_)); for (size_t eval=1;eval<useeigs;eval++) { const int dr=reigptrs(eval); const int dc=ceigptrs(eval); if ((dc>=0) && (dr>=0)) { const size_t ind(get_block(eval)); cmatrix& Hsym(Hmats(ind)); Hsym(size_t(dr),size_t(dc))+=symmetriser.symmetrise(store,rs,cs,eval); } } } void CrystalOpGenerator::add_A2(BlockedMatrixTensor<complex>& Htens, const Matrix<space_T>& tensors) const { size_t blki,blkj; CrystalSystem_iterator iter(*this); iter.ensure_null(Htens,2); while (iter.next(blki,blkj)) { for (int m=-2;m<=2;m++) { const bool issingle=iter.A2_matrix(tensors,blki,blkj,m); iter.addsym(Htens,blki,blkj,2,m,issingle,Type2Type<complex>()); } } } void CrystalOpGenerator::add_A0(BlockedMatrixTensor<complex>& Htens, const Matrix<double>& A0s) const { size_t blki,blkj; CrystalSystem_iterator iter(*this); iter.ensure_null(Htens,0); while (iter.next(blki,blkj)) { const bool issingle=iter.A0_matrix(A0s,blki,blkj); iter.addsym(Htens,blki,blkj,0,0,issingle,Type2Type<double>()); } } template<class T> void CrystalOpGenerator::add_A2(BlockedMatrix<complex>& Hmats, const Matrix<T>& couplings) const { CrystalSystem_iterator iter(*this); iter.ensure_null(Hmats); size_t blki,blkj; while (iter.next(blki,blkj)) { const bool issingle=iter.A2_matrix(couplings,blki,blkj); iter.addsym(Hmats,blki,blkj,Type2Type<double>(),issingle); } } void CrystalOpGenerator::add_A0(BlockedMatrix<complex>& Hmats, const rmatrix& couplings) const { CrystalSystem_iterator iter(*this); iter.ensure_null(Hmats); size_t blki,blkj; while (iter.next(blki,blkj)) { const bool issingle=iter.A0_matrix(couplings,blki,blkj); iter.addsym(Hmats,blki,blkj,Type2Type<double>(),issingle); } } //create symmetrised shift Hamiltonian, given shifts and complete set of symmetrised z operators ListList<double> diag_Hcs(const CrystalOpGenerator& sys, const BaseList<double>& shifts) { ListList<double> Hcs(mxflag::temporary); const size_t M=sys.nspins_cell(); if (M!=shifts.size()) throw Mismatch("diag_Hcs: size of shift vector"); for (size_t m=0;m<M;m++) mla(Hcs,shifts(m),sys.diag_Iz(m)); return Hcs; } static void multiply_full(cmatrix& dest, const complex& v, const BaseList<double>& H) { size_t n=H.size(); dest.create(n,n); dest=complex(0.0); for (;n--;) mla(dest(n,n),H(n),v); } static void mla(Tensor<cmatrix>& d, const Tensor<complex>& A, const BaseList<double>& H) { for (int l=A.rank();l>=0;l--) { if (A.have_rank(l)) { //rank present? if (!d.have_rank(l)) { d.ensure_rank(l); for (int m=-l;m<=l;m++) multiply_full(d(l,m),A(l,m),H); } else { for (int m=-l;m<=l;m++) mla(d(l,m),A(l,m),H); } } } } void CrystalOpGenerator::add_Hcs(BlockedMatrixTensor<complex>& Htens, const space_T& CSA, size_t m) const { if (Htens.size()!=diagstr_.size()) throw Mismatch("add_Hcs"); for (size_t k=Htens.size();k--;) //loop over eigenvalues switch (diagstr_(k)) { case 0: break; case 1: { space_T& curHisol=Htens(k).element(); ::libcmatrix::mla(curHisol,diag_Iz(m)(k).front(),CSA); } break; default: { Tensor<cmatrix>& curHtens=Htens(k).matrix(); ::libcmatrix::mla(curHtens,CSA,diag_Iz(m)(k)); } } } //special case for single state block (k=0 only) // void add_Hcs(space_T& Hisol, const CrystalOpGenerator& sys, const BaseList<space_T>& CSAs) // { // (void)sys.state(); //ensure single state // const size_t M=sys.nspins(); // if (M!=CSAs.length()) // throw Mismatch("add_Hcs"); // for (size_t m=M;m--;) // mla(Hisol,sys.diag_Iz(m)(0U,0U),CSAs(m)); // } void CrystalOpGenerator::add_Hcs(cmatrix& dest, double shift, size_t m, int k) const { ::libcmatrix::mla(dest,shift,diag_Iz(m)(k)); } template<class T1,class T2,class T3> void multiply(BlockedMatrix<T1>& d, const T2& v, const ListList<T3>& a) { LCM_STATIC_CHECK( LCM_DIM(T2)==0, BlockedMatrix_multiply); const size_t n=a.size(); ScratchList<size_t> sizes(n); size_t i; for (i=n;i--;) sizes(i)=a.size(i); d.create(sizes); for (i=n;i--;) multiply(d(i),v,a(i)); } void CrystalOpGenerator::add_Hcs(BlockedMatrix<complex>& dest, double shift, size_t m) const { ::libcmatrix::mla(dest,shift,diag_Iz(m)); } void CrystalOpGenerator::add_Hcs(ListList<double>& dest, double shift, size_t m) const { ::libcmatrix::mla(dest,shift,diag_Iz(m)); } void SimpleSymmetrise::addtoevals(BaseList<complex>& evals, size_t blki, size_t blkj, size_t r, size_t c) const { const size_t blkisize(linkedstates_.size(blki)); const size_t blkjsize(linkedstates_.size(blkj)); const double scale=scalefacs(blkisize*blkjsize); //normalisation factor evals(0)+=scale; //eigenvalue 0 const int mstep=ncells_+c-r; for (size_t m=1;m<useeigs;m++) { if (haseig(blkisize,m) && haseig(blkjsize,m)) { //if eigenvalue present const size_t wh=(m*mstep) % ncells_; mla(evals(m),scale,eigfacs(wh)); } } } //Symmetrised Ip bool CrystalSystem_iterator::Ipevalues(DynamicList<complex>& evals, size_t blki, size_t blkj, int spini) { const BaseList<state_t> cstates(symmetriser.linkedstates()(blkj)); const size_t total(sym.nspins()); if (verbose>2) { const BaseList<state_t> rstates(symmetriser.linkedstates()(blki)); std::cout << "Col states: "; printbin(std::cout,cstates,total); std::cout << '\n'; std::cout << "Row states: "; printbin(std::cout,rstates,total); std::cout << '\n'; } const state_t flipmask=~maskelement(total,spini); evals=0.0; //clear result bool haveany=false; for (size_t c=cstates.size();c--;) { const state_t nstate=cstates(c) & flipmask; // if bit is already clear, nstate cannot be in blki if (state_to_block(nstate)==blki) { symmetriser.addtoevals(evals,blki,blkj,state_to_index(nstate),c); haveany=true; } } return haveany; } bool CrystalSystem_iterator::Fpevalues(DynamicList<complex>& evals,size_t blki,size_t blkj,size_t nuc) { const BaseList<state_t> cstates(symmetriser.linkedstates()(blkj)); const size_t total(sym.nspins()); if (verbose>2) { const BaseList<state_t> rstates(symmetriser.linkedstates()(blki)); std::cout << "Col states: "; printbin(std::cout,cstates,total); std::cout << '\n'; std::cout << "Row states: "; printbin(std::cout,rstates,total); std::cout << '\n'; } bool haveany=false; evals=0.0; const size_t M(sym.nspins_cell()); for (size_t c=cstates.size();c--;) { //loop over ket states const state_t ostate=cstates(c); for (size_t spini=0;spini<M;spini++) { //loop over unit cell if (nuc==NULL_NUCLEUS || sym(spini).nucleus()==nuc) { //considering this spin? const state_t flipmask=~maskelement(total,spini); const state_t nstate=ostate & flipmask; // if bit is clear, nstate cannot be in blki if (state_to_block(nstate)==blki) { symmetriser.addtoevals(evals,blki,blkj,state_to_index(nstate),c); haveany=true; } } } } return haveany; } //accumulate symmetrised elements into final matrix set void CrystalSystem_iterator::add(BlockedMatrix<complex>& dest, const BaseList<complex>& evals, size_t blki, size_t blkj) const { BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); for (size_t eval=useeigs;eval--;) { int dr=reigptrs(eval); int dc=ceigptrs(eval); if ((dr>=0) && (dc>=0)) {//eigenvalue exists? const size_t ind(get_block(eval)); dest(ind)(size_t(dr),size_t(dc))+=evals(eval); } } } //ditto but for Hermitian operator where iterated over upper diagonal only void CrystalSystem_iterator::add_hermitian(BlockedMatrix<complex>& dest, const BaseList<complex>& evals, size_t blki, size_t blkj) const { BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); for (size_t eval=useeigs;eval--;) { int dr=reigptrs(eval); int dc=ceigptrs(eval); if ((dr>=0) && (dc>=0)) { assert(dr!=dc); const size_t ind(get_block(eval)); const complex& v=evals(eval); dest(ind)(size_t(dr),size_t(dc))+=v; dest(ind)(size_t(dc),size_t(dr))+=conj(v); } } } //as above, but for single eigenvalue void CrystalSystem_iterator::add(cmatrix& dest, complex v, size_t blki, size_t blkj, int eval) const { const int dr=sym.eigptrs(blki,eval); const int dc=sym.eigptrs(blkj,eval); if ((dr>=0) && (dc>=0)) dest(size_t(dr),size_t(dc))+=v; } void CrystalSystem_iterator::add_hermitian(cmatrix& dest, complex v, size_t blki, size_t blkj, int eval) const { const int dr=sym.eigptrs(blki,eval); const int dc=sym.eigptrs(blkj,eval); if ((dr>=0) && (dc>=0)) { dest(size_t(dr),size_t(dc))+=v; dest(size_t(dc),size_t(dr))+=conj(v); } } void CrystalOpGenerator::mla_Iz(ListList<double>& dest, double scale, const operator_spec& spec) const { if (spec.op!='z') throw InvalidParameter("mla_Iz: only valid for z operators"); if (spec.nuc==NULL_NUCLEUS) mla_Iz(dest,scale,spec.number); else mla_Fz(dest,scale,spec.nuc); } //ditto, all eigenvalues void CrystalOpGenerator::mla(BlockedMatrix<complex>& dest, block_pattern& blkspec, double scale, const operator_spec& opspec) const { if (opspec.op=='z') { //ignore 'c' as not valid ListList<double> destz; mla_Iz(destz,scale,opspec); dest+=destz; blkspec=block_pattern(*this); return; } blkspec=block_pattern(*this,opspec); if (!dest) { create(dest,blkspec); dest=complex(0.0); } else { if (dest.length()!=totalblocks()) throw Mismatch("rawmla"); } size_t nuc(opspec.nuc); if (nuc==NULL_NUCLEUS) nuc=(*sysp_)(opspec.number).nucleus(); CrystalSystem_iterator iter(*this,blkspec,nuc,1); iter.mla(dest,scale,opspec); } namespace { const char PUREERR[]="productoperator_spec: scale factor must be pure real or pure imaginary"; } void CrystalOpGenerator::add(BlockedMatrix<complex>& dest, block_pattern& blkspec, const productoperator_spec& spec) const { static const complex iconst(0.0,1.0); for (size_t i=spec.size();i--;) { const BaseList<operator_spec> opspec(spec.specs(i)); if (opspec.size()!=1) throw Failed("Can't use multi-spin productoperators with CrystalSystem"); const complex& cscale(spec.scales(i)); if (imag(cscale)) { if (real(cscale)) throw Failed(PUREERR); BlockedMatrix<complex> tmp; mla(tmp,blkspec,imag(cscale),opspec.front()); ::libcmatrix::mla(dest,iconst,tmp); } else mla(dest,blkspec,real(cscale),opspec.front()); } } void CrystalSystem_iterator::mla(BlockedMatrix<complex>& dest, double scale, const operator_spec& opspec) { size_t blki,blkj; const size_t nuc=opspec.nucleus(sym.spinsystem()); const bool notherm(sym.isblocked(nuc)); //if blocked by coherence, don't construct both sides of hermitian operators const bool isI=(opspec.nuc==NULL_NUCLEUS); while (next(blki,blkj)) { const bool haveany = isI ? Ipevalues(evalues,blki,blkj,opspec.number) : Fpevalues(evalues,blki,blkj,opspec.nuc); if (verbose>1) { std::cout << "I/Fp" << blki << "," << blkj << ": "; if (haveany) std::cout << evalues << '\n'; else std::cout << "<all zero>\n"; } if (!haveany) continue; switch (opspec.op) { case 'x': evalues*=0.5*scale; if (notherm) add(dest,evalues,blki,blkj); else add_hermitian(dest,evalues,blki,blkj); break; case 'y': evalues*=complex(0,-0.5*scale); if (notherm) add(dest,evalues,blki,blkj); else add_hermitian(dest,evalues,blki,blkj); break; case '+': if (scale!=1.0) evalues*=scale; add(dest,evalues,blki,blkj); break; case '-': if (scale!=1.0) evalues*=scale; conj_ip(evalues); add(dest,evalues,blkj,blki); break; default: throw InvalidParameter("Operator must be x, y, + , or -"); } } } void sum_permuted(rmatrix& dest,const rmatrix& source,const BaseList<size_t>& next, int N) { dest=source; rmatrix tmp; for (size_t i=1;i<N;i++) { tmp=dest(next,next); dest=tmp; dest+=source; } } void sum_permuted(List<double>& dest,const BaseList<double>& source,const BaseList<size_t>& next, int N) { dest=source; List<double> tmp; for (int i=1;i<N;i++) { tmp=dest(next); dest=tmp; tmp+=source; } } //Specialise default add_Hamiltonian template<class OutType, class StoreType> void add_coupling_Hamiltonians(OutType& dest, const CrystalOpGenerator& opgen, const HamiltonianStore<StoreType>& Hstore) { Matrix<double> A0s; Matrix<StoreType> A2s; Hstore.split_couplings(A0s,A2s); if (!!A0s) { if (opgen.verbose()>1) std::cout << "A0 couplings\n" << A0s; opgen.add_A0(dest,A0s); if (opgen.verbose()>1) std::cout << "After A0 add\n" << dest; } if (opgen.verbose()>1) std::cout << "A2 couplings\n" << A2s; opgen.add_A2(dest,A2s); } template<> void BlockedSpinningHamiltonianImpl<complex,CrystalOpGenerator>::interactions(const HamiltonianStore<space_T>& store) { const size_t verbose(opgen_.verbose()); BlockedMatrixTensor<complex> tmp; add_Hamiltonian(tmp,opgen_,store); size_t n(tmp.size()); List<SpinningHamiltonian>& H(*this); if (H.size()!=n) { if (H.empty()) H.create(n,SpinningHamiltonian(rotor_speed_,rotor_phase_,rinfo_)); else throw Mismatch("BlockedSpinningHamiltonian::interactions"); } for (;n--;) { MatrixTensor<complex>& source(tmp(n)); if (verbose>1) std::cout << "MatrixTensor(" << n << ")\n" << source << '\n'; SpinningHamiltonian& Hspin(H(n)); switch (source.rows()) { case 0: break; case 1: Hspin.tensor(source.element()); if (!!Hbase_) Hspin+=Hbase_(n); break; default: Hspin.tensor(source.matrix()); source.clear(); if (!!Hbase_) Hspin+=Hbase_(n); break; } } } template<> struct Ham_traits< BlockedMatrixTensor<complex> > { typedef space_T coupling_type; }; LCM_INSTANTIATE_TYPED_HAMILTONIANS(CrystalOpGenerator,complex) LCM_INSTANTIATE_SPINOPGEN_CREATE(CrystalOpGenerator) template void add_Hamiltonian<BlockedMatrix<complex>, CrystalOpGenerator, Tensor<complex> >(BlockedMatrix<complex>&, CrystalOpGenerator const&, HamiltonianStore< Tensor<libcmatrix::complex> > const&); //template<> BlockedFilter::BlockedFilter(const CrystalOpGenerator&, const BaseList<int>&); } //namespace libcmatrix // static void translate_raw(rmatrix &dest,const rmatrix &source,const BaseList<size_t> &TT) // { // const int n=TT.length(); // if (!issquare(source) || n!=source.rows()) throw Mismatch("translate_raw"); // dest.create(n,n); // for (int i=n;i--;) // for (int j=n;j--;) // dest(TT(i),TT(j))=source(i,j); // } // void Tmatrix(cmatrix& TV, const ListList<state_t>& TT, int total, const BaseList<size_t>& which) // { // int j; // const bool havesel=(which.length()!=0); // const size_t blks=havesel ? which.length() : TT.blocks(); // const long fulldim=long(1)<<total; // long totdim=0; //size of output matrix // if (havesel) { // for (j=blks;j--;) //sum over selected blocks // totdim+=TT.size(which(j)); // } // else // totdim=fulldim; // TV.create(totdim,totdim,0.0); //construct matrix to be filled // int point=0; // for (j=blks;j--;) { //loop over blocks // const BaseList<state_t> clist=TT(havesel ? which(j) : j); //get state list // const size_t size=clist.length(); // const double scale=1.0/sqrt((double)size); //normalisation factor // for (size_t n=size;n--;) { // for (size_t m=size;m--;) // TV(clist(m),point)=expi( (2*M_PI*m*n)/size)*scale; // point++; // } // } // } //create tensor of correct size (spinning) for eigenvalue, k, default value, val // void // CrystalOpGenerator::clear(Tensor<cmatrix>& ctens, int k, double val) const // { // if (ismatrix(k)) { // const size_t rows=rblkstr(k); // const size_t cols=cblkstr(k); // ctens.create(2,mxflag::maximum); // for (int m=-2;m<=2;m++) // create (2,0) matrix, even if unused // ctens(2,m).create(rows,cols,val); // } // else //if eigenvalue doesn't exist, kill off // ctens.clear(); // } // //space_T used to store "single element" H's in spinning case // void // CrystalOpGenerator::clear(space_T& Hisol, int k, double val) const // { // if (!ismatrix(k)) { // Hisol.create(2,mxflag::maximum); // Hisol=complex(val); // } // else // Hisol.clear(); // } // //create tensors of correct size (spinning) // void // CrystalOpGenerator::clear(List< Tensor<cmatrix> >& Htens, BaseList<space_T> Hisol, double val, double valisol) const // { // const bool use_isol=(Hisol.length()!=0); // Htens.create(useeigs); // for (size_t j=useeigs;j--;) { // if (ismatrix(j)) // clear(Htens(j),j,val); // else { // if (use_isol) // clear(Hisol(j),j,valisol); // } // } // } // void // CrystalOpGenerator::clear(BaseList<cmatrix> Hmats, BaseList<double> Hisol, double val, double valisol) const // { // if (Hmats.size()!=useeigs) // throw Mismatch("CrystalOpGenerator::clear"); // const size_t n=Hisol.size(); // if (n) { // if (n!=useeigs) // throw Mismatch("CrystalOpGenerator::clear"); // Hisol=valisol; // } // for (size_t j=useeigs;j--;) { // if (ismatrix(j)) // clear(Hmats(j),j,val); // else // Hmats(j).clear(); // } // } //void // CrystalOpGenerator::clear(BaseList<cmatrix> Hmats, double val) const // { // if (Hmats.size()!=useeigs) // throw Mismatch("CrystalOpGenerator::clear"); // for (size_t j=useeigs;j--;) // clear(Hmats(j),j,val); // } // void // CrystalOpGenerator::clear(List<cmatrix>& Hmats, List<double>& Hisol, double val, double valisol) const // { // Hmats.create(useeigs); // Hisol.create(useeigs); // clear(static_cast<BaseList<cmatrix>& >(Hmats),Hisol,val,valisol); // } // void // CrystalOpGenerator::clear(List<cmatrix>& Hmats, BaseList<double> Hisol, double val, double valisol) const // { // Hmats.create(useeigs); // clear(static_cast<BaseList<cmatrix>& >(Hmats),Hisol,val,valisol); // } // void // CrystalOpGenerator::clear(BlockedMatrix<complex>& Hmats, double val) const // { // if (isdiagonal()) // Hmats.create(rblkstr,val); // else // Hmats.create(rblkstr,cblkstr,val); // } // void // CrystalOpGenerator::clear(cmatrix& d, int k, double val) const // { // if (exists(k)) // d.create(rows(k),cols(k),val); // else // d.clear(); // } //add symmetrised block (blki,blkj) eigenvalue eval to (static) Hamiltonian // void // CrystalOpGenerator::place(cmatrix& Hk, complex& Hisol, size_t blki, size_t blkj, int eval) const // { // const int dr=sym.eigptrs(blki,eval); // const int dc=sym.eigptrs(blkj,eval); // const size_t rs=sym.T.size(blki); // const size_t cs=sym.T.size(blkj); // if (eval==0) { // if (ismatrix(0U)) // Hk(dr,dc)=csymmetrise0(rs,cs); // else // Hisol=csymmetrise0(rs,cs); // } // else { // if ((dr>=0) && (dc>=0)) { // if (ismatrix(eval)) // Hk(dr,dc)=csymmetrise(rs,cs,eval); // else { // Hisol=csymmetrise(rs,cs,eval); // } // } // } // } //calculate matrix that symmetrises w.r.t translation (not useful for large systems!) // void // CrystalOpGenerator::get_diag(cmatrix& D) const // { // List<size_t> rind; // makerindex(rind,*sysp_); //create state->index reverse index // D.create(sysp_->size(),sysp_->size(),0.0); //empty matrix // CrystalSystem_diagiterator iter(*this); // const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); // size_t blk; // size_t point=0; // while (iter.next(blk)) { //loop over state sets // const BaseList<state_t> states(linkedstates(blk)); //state list // const size_t blksize=states.size(); // const double scalef=1.0/sqrt(double(blksize)); //normalisation factor // for (size_t j=0;j<blksize;j++) { // for (size_t k=0;k<blksize;k++) // D(rind(states(k)),point)=eigfacs((j*k) % N_)*scalef; // point++; // } // } // if (point!=D.cols()) //sanity check - have we filled D? // throw Failed("get_diag"); // } //As above but restricted to single eigenvalue (usek) // void // CrystalOpGenerator::get_diag(cmatrix& D,int usek) const // { // List<size_t> rind; // makerindex(rind,sys); // D.create(rows(),diag_str_(usek),0.0); // CrystalSystem_diagiterator iter(*this); // size_t blk; // size_t point=0; // while (iter.next(blk)) { // const BaseList<state_t> states(linkedstates_(blk)); // const size_t blksize=states.size(); // if (sym.haseig(blksize,usek)) { // const double scalef=1.0/sqrt(double(blksize)); // for (size_t k=0;k<blksize;k++) // D(rind(states(k)),point)=sym.eigfacs( (usek*k) % N)*scalef; // point++; // } // } // if (point!=D.cols()) // throw Failed(); // } // void // CrystalOpGenerator::create(cmatrix& a, int k) const // { // const size_t rs=rblkstr(k); // if (isdiagonal()) // a.create(rs,rs); // else // a.create(rs,cblkstr(k)); // } // void // CrystalOpGenerator::create(MatrixTensor<complex>& a, int k) const // { // if (!isdiagonal()) // throw Failed("Can only create MatrixTensor objects for diagonal CrystalOpGenerator"); // a.create(rblkstr(k),2,mxflag::maximum); // } // void // CrystalOpGenerator::create(BlockedMatrix<complex>& Hmats) const // { // if (isdiagonal()) // Hmats.create(rblkstr); // else // Hmats.create(rblkstr,cblkstr); // } // void // CrystalOpGenerator::create(BlockedMatrixTensor<complex>& Htens) const // { // if (!isdiagonal()) // throw Failed("Can only create MatrixTensor objects for diagonal CrystalOpGenerator"); // Htens.create(rblkstr,2,mxflag::maximum); // } // void // CrystalOpGenerator::add_Hcoupling(complex& H, P_GENSPINNINGMATRIX func, const Matrix<space_T>& tensors, int m) const // { // if (firstrblk<0 || !(this->*func)(tensors,firstrblk,firstrblk,m)) // throw Failed("sym_Hdipolar_element: not single state block!"); // H+=symmetrise0(Type2Type<complex>()); // } //as above but for single eigenvalue // template<class Type> inline void CrystalOpGenerator::addtoeval(Type& s, size_t blkisize, size_t blkjsize, size_t r, size_t c, int m) // { // if (haseig(blkisize,m) && haseig(blkjsize,m)) { // const int wh=(m*(N+c-r)) % N; // mla(s,scalefacs(blkisize,blkjsize),eigfacs(wh)); // } // }
28.958376
200
0.661005
dch0ph