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
c6e930df04492ebf996d43d96cdbb444afe9fe03
4,763
cpp
C++
src/polycubed/src/server/Resources/Body/AbstractFactory.cpp
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/polycubed/src/server/Resources/Body/AbstractFactory.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/polycubed/src/server/Resources/Body/AbstractFactory.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/* * Copyright 2018 The Polycube Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AbstractFactory.h" #include <memory> #include <string> #include <utility> #include <vector> #include "CaseResource.h" #include "ChoiceResource.h" #include "JsonNodeField.h" #include "JsonValueField.h" #include "LeafListResource.h" #include "LeafResource.h" #include "ListKey.h" #include "ListResource.h" #include "ParentResource.h" namespace polycube::polycubed::Rest::Resources::Body { std::unique_ptr<Body::JsonValueField> AbstractFactory::JsonValueField() const { return std::make_unique<Body::JsonValueField>(); } std::unique_ptr<Body::JsonValueField> AbstractFactory::JsonValueField( LY_DATA_TYPE type, std::vector<std::shared_ptr<Validators::ValueValidator>> &&validators) const { return std::make_unique<Body::JsonValueField>(type, std::move(validators)); } std::unique_ptr<CaseResource> AbstractFactory::BodyCase( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent) const { return std::make_unique<CaseResource>(name, description, cli_example, parent, core_); } std::unique_ptr<ChoiceResource> AbstractFactory::BodyChoice( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, bool mandatory, std::unique_ptr<const std::string> &&default_case) const { return std::make_unique<ChoiceResource>(name, description, cli_example, parent, core_, mandatory, std::move(default_case)); } std::unique_ptr<LeafResource> AbstractFactory::BodyLeaf( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, std::unique_ptr<Body::JsonValueField> &&value_field, const std::vector<Body::JsonNodeField> &node_fields, bool configuration, bool init_only_config, bool mandatory, Types::Scalar type, std::unique_ptr<const std::string> &&default_value) const { return std::make_unique<LeafResource>( name, description, cli_example, parent, core_, std::move(value_field), node_fields, configuration, init_only_config, mandatory, type, std::move(default_value)); } std::unique_ptr<LeafListResource> AbstractFactory::BodyLeafList( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, std::unique_ptr<Body::JsonValueField> &&value_field, const std::vector<JsonNodeField> &node_fields, bool configuration, bool init_only_config, bool mandatory, Types::Scalar type, std::vector<std::string> &&default_value) const { return std::make_unique<LeafListResource>( name, description, cli_example, parent, core_, std::move(value_field), node_fields, configuration, init_only_config, mandatory, type, std::move(default_value)); } std::unique_ptr<ListResource> AbstractFactory::BodyList( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, std::vector<Resources::Body::ListKey> &&keys, const std::vector<JsonNodeField> &node_fields, bool configuration, bool init_only_config) const { return std::make_unique<ListResource>(name, description, cli_example, parent, core_, std::move(keys), node_fields, configuration, init_only_config); } std::unique_ptr<ParentResource> AbstractFactory::BodyGeneric( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, const std::vector<JsonNodeField> &node_fields, bool configuration, bool init_only_config, bool container_presence) const { return std::make_unique<ParentResource>( name, description, cli_example, parent, core_, node_fields, configuration, init_only_config, container_presence); } AbstractFactory::AbstractFactory(PolycubedCore *core) : core_(core) {} } // namespace polycube::polycubed::Rest::Resources::Body
43.3
80
0.720134
francescomessina
c6ecb3f9d09e07d4ef170f22a9beabdfa1093d60
2,009
cpp
C++
ass3/problem2.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
2
2021-07-24T15:01:50.000Z
2022-01-17T21:49:09.000Z
ass3/problem2.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
null
null
null
ass3/problem2.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <iostream> int main(int argc, char *argv[]) { std::string phrase; std::cout << "Enter a phrase: "; std::getline(std::cin, phrase); std::cout << phrase.size() << std::endl; int word_start = 0, temp_end = 0, word_end = 0, words = 0, proper = 0, repeat = 0; while (word_end != std::string::npos) { word_end = phrase.find(" ", word_start); if(word_end == std::string::npos) { temp_end = phrase.size(); } else { temp_end = word_end; } std::cout << phrase.substr(word_start, temp_end - word_start) << std::endl; words++; bool is_proper = true; bool is_repeat = false; char previous_letter = phrase[word_start]; for(int i = 0; i < (temp_end - word_start); i++) { if (!is_repeat) { if (i > 0) { if (phrase[word_start + i] == previous_letter) { is_repeat = true; } } } if (is_proper) { if (i == 0) { if (!(phrase[word_start + i] >= 'A' && phrase[word_start + i] <= 'Z')) { is_proper = false; } } else // i > 1 { if (!(phrase[word_start + i] >= 'a' && phrase[word_start + i] <= 'z')) { is_proper = false; } } } previous_letter = phrase[word_start + i]; } if(is_proper) { proper++; } if(is_repeat) { repeat++; } word_start = word_end + 1; } std::cout << words << std::endl; std::cout << proper << std::endl; std::cout << repeat << std::endl; }
28.7
90
0.390742
starcraft66
c6ee06713592b71f52636ffc964fb7833f6f73d7
1,614
cc
C++
obcache/libs/sql/storage.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
obcache/libs/sql/storage.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
obcache/libs/sql/storage.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
//========================================================================== // ObTools::ObCache::SQL: storage.cc // // Implementation of SQL storage manager // // Copyright (c) 2008 Paul Clark. All rights reserved // This code comes with NO WARRANTY and is subject to licence agreement //========================================================================== #include "ot-obcache-sql.h" #include "ot-log.h" #include "ot-text.h" namespace ObTools { namespace ObCache { namespace SQL { //-------------------------------------------------------------------------- // Load an object Object *Storage::load(object_id_t id) { // Get DB connection DB::AutoConnection db(db_pool); // Look up ID in main object table, to get type ref string types = db.select_value_by_id64("root", "_type", id, "_id"); if (types.empty()) throw Exception("Attempt to load non-existent object "+Text::i64tos(id)); type_id_t type = Text::stoi64(types); // Look up storer interface by type ref map<type_id_t, Storer *>::iterator p = storers.find(type); if (p == storers.end()) throw Exception("Attempt to load unknown type "+Text::i64tos(type)); Storer *storer = p->second; // Get storer to load it, using the same DB connection return storer->load(id, db); } //-------------------------------------------------------------------------- // Save an object void Storage::save(Object * /*ob*/) { // !!! Get type name from object get_name // !!! Look up storer interface // !!! Get DB connection // !!! Get storer to save it throw Exception("Not yet implemented!"); } }}} // namespaces
27.827586
77
0.547708
sandtreader
c6f6b6eb3310824525851ddd3eee4a3d9fc40439
14,375
cpp
C++
svntrunk/src/untabbed/ParaFrames/fft3d/libspitest/fftmain_libspi_float.cpp
Bhaskers-Blu-Org1/BlueMatter
1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e
[ "BSD-2-Clause" ]
7
2020-02-25T15:46:18.000Z
2022-02-25T07:04:47.000Z
svntrunk/src/untabbed/ParaFrames/fft3d/libspitest/fftmain_libspi_float.cpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
null
null
null
svntrunk/src/untabbed/ParaFrames/fft3d/libspitest/fftmain_libspi_float.cpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
5
2019-06-06T16:30:21.000Z
2020-11-16T19:43:01.000Z
/* Copyright 2001, 2019 IBM Corporation * * 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. * * 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. */ // // IBM T.J.W R.C. // Date : 24/01/2003 // Name : Maria Eleftheriou // Last Modified on: 09/24/03 by Maria Eleftheriou // fftmain.hpp // tests the 3D fft using MPI and fftw #if defined(USE_PK_ACTORS) #include <BonB/BGL_PartitionSPI.h> #include <rts.h> #include <Pk/API.hpp> #include <Pk/Compatibility.hpp> #include <stdio.h> #include <BonB/BGLTorusAppSupport.h> #include <BonB/BGLTorusAppSupport.c> #else #include <pk/platform.hpp> #include <pk/fxlogger.hpp> #endif #include <BlueMatter/complex.hpp> #include <fft3Dlib.hpp> #include <math.h> #define TYPE float #define FFT3D_STUCT_ALIGNMENT __attribute__ (( aligned( (0x01 << 6) ) )) #define FFT3D_STRUCT_ALIGNMENT __attribute__ (( aligned( (0x01 << 6) ) )) #define TOLERANCE (1./1000.) #define N_SIZE 128 #define MESS_SIZE 8 #define ITERATIONS 10 #define REGRESS_REVERSE #ifndef PKFXLOG_FFTMAIN #define PKFXLOG_FFTMAIN (0) #endif #ifndef PKFXLOG_FFTINTER #define PKFXLOG_FFTINTER (0) #endif #ifndef PKFXLOG_FFTITERATION #define PKFXLOG_FFTITERATION (0) #endif #ifndef PKFXLOG_FFTBENCHMARK #define PKFXLOG_FFTBENCHMARK (0) #endif struct FFT_PLAN { enum { P_X = MESS_SIZE, P_Y = MESS_SIZE, P_Z = MESS_SIZE }; enum { GLOBAL_SIZE_X = N_SIZE, GLOBAL_SIZE_Y = N_SIZE, GLOBAL_SIZE_Z = N_SIZE }; }; // CHECK needs to be removed #define FORWARD -1 #define REVERSE 1 typedef BGL3DFFT< FFT_PLAN, FORWARD, TYPE ,TYPE complex > FFT_FORWARD FFT3D_STRUCT_ALIGNMENT; typedef BGL3DFFT< FFT_PLAN, REVERSE, TYPE ,TYPE complex > FFT_REVERSE FFT3D_STRUCT_ALIGNMENT; static int compare ( TYPE complex* in, TYPE complex* rev, int localNx, int localNy, int localNz, double fftSz) { for(int i=0; i<localNx; i++) for(int j=0; j<localNy; j++) for(int k=0; k<localNz; k++) { int myIndex = i*localNy*localNz+j*localNz+k; if ( fabs(creal(in[myIndex])-creal(rev[myIndex])*fftSz) > TOLERANCE || fabs(cimag(in[myIndex])-cimag(rev[myIndex])*fftSz) > TOLERANCE ) { BegLogLine(1) << "[" << i << "," << j << "," << k << "] in=(" << creal(in[myIndex]) << "," << cimag(in[myIndex]) << ") rev*fftSz=(" << creal(rev[myIndex]*fftSz) << "," << cimag(rev[myIndex]*fftSz) << ")" << EndLogLine ; return 1; } } return 0; } // get processor mesh and fft size static void init( int argc, char*argv[], int& globalNx, int& globalNy, int& globalNz, int& pX, int& pY, int& pZ, int& subPx, int& subPy, int& subPz, int& iterations , int& markrank , int& markindex ) { BegLogLine(PKFXLOG_FFTMAIN) << "init argc=" << argc << EndLogLine ; for(int i=0; i<argc; i++) { BegLogLine(PKFXLOG_FFTMAIN) << "i=" << i << " argv[i]=" << argv[i] << EndLogLine ; if (!strcmp(argv[i],"-procmesh")) { pX = atoi(argv[++i]); pY = atoi(argv[++i]); pZ = atoi(argv[++i]); } if (!strcmp(argv[i],"-subprocmesh")) { subPx = atoi(argv[++i]); subPy = atoi(argv[++i]); subPz = atoi(argv[++i]); } if (!strcmp(argv[i],"-fftsize")) { globalNx = atoi(argv[++i]); globalNy = atoi(argv[++i]); globalNz = atoi(argv[++i]); } if (!strcmp(argv[i],"-iterations")) { iterations = atoi(argv[++i]) ; } if (!strcmp(argv[i],"-mark")) { markrank = atoi(argv[++i]) ; markindex = atoi(argv[++i]) ; } } } #if !defined(USE_PK_ACTORS) extern "C" { void * PkMain(int argc, char** argv, char** envp) ; } ; #endif static FFT_FORWARD fftForward; static FFT_REVERSE fftReverse; #if defined(USE_PK_ACTORS) int #else void * #endif PkMain(int argc, char** argv, char** envp) { #pragma execution_frequency(very_low) // complex ***in, ***tmp, ***out; // complex ***localOut; // int pX = FFT_PLAN::P_X ; // int pY = FFT_PLAN::P_Y ; // int pZ = FFT_PLAN::P_Z ; #if defined(USE_PK_ACTORS) int pX ; int pY ; int pZ ; if ( Platform::Thread::GetId() != 0 ) { for(;;) ; // hang here if on the IOP } Platform::Topology::GetDimensions(&pX, &pY, &pZ) ; #else int pX = Platform::Topology::mDimX ; int pY = Platform::Topology::mDimY ; int pZ = Platform::Topology::mDimZ ; #endif int globalNx = FFT_PLAN::GLOBAL_SIZE_X ; int globalNy = FFT_PLAN::GLOBAL_SIZE_Y ; int globalNz = FFT_PLAN::GLOBAL_SIZE_Z ; int iterations = ITERATIONS ; int markrank = 0 ; int markindex = 0 ; int subPx = -1 ; int subPy = -1 ; int subPz = -1 ; init(argc, argv, globalNx,globalNy,globalNz, pX, pY, pZ, subPx, subPy, subPz, iterations, markrank, markindex ); if ( -1 == subPx ) subPx = pX ; if ( -1 == subPy ) subPy = pY ; if ( -1 == subPz ) subPz = pZ ; int localNx = globalNx / pX ; int localNy = globalNy / pY ; int localNz = globalNz / pZ ; #if defined(USE_PK_ACTORS) int myRank = PkNodeGetId() ; // #if defined(PKTRACE) // pkTraceServer::Init() ; // #endif #else int myRank = Platform::Topology::GetAddressSpaceId(); #endif // if (myRank == 0) // { // printf( " proc mesh GLOBAL_SIZE_X = %d GLOBAL_SIZE_Y = %d GLOBAL_SIZE_Z = %d\n", // FFT_PLAN::GLOBAL_SIZE_X, // FFT_PLAN::GLOBAL_SIZE_Y, // FFT_PLAN::GLOBAL_SIZE_Z); // // printf(" 3D FFT of size [%d %d %d] on [%d %d %d] \n", // localNx, localNy, localNz, // FFT_PLAN::P_X, FFT_PLAN::P_Y, FFT_PLAN::P_Z); // } int arraySz= (globalNx*globalNy*globalNz)/(pX*pY*pZ); BegLogLine(PKFXLOG_FFTMAIN) << "PkMain" // << " FFT_PLAN::GLOBAL_SIZE_X=" << FFT_PLAN::GLOBAL_SIZE_X // << " FFT_PLAN::GLOBAL_SIZE_Y=" << FFT_PLAN::GLOBAL_SIZE_Y // << " FFT_PLAN::GLOBAL_SIZE_Z=" << FFT_PLAN::GLOBAL_SIZE_Z // << " FFT_PLAN::P_X=" << FFT_PLAN::P_X // << " FFT_PLAN::P_Y=" << FFT_PLAN::P_Y // << " FFT_PLAN::P_Z=" << FFT_PLAN::P_Z << " globalNx=" << globalNx << " globalNy=" << globalNy << " globalNz=" << globalNz << " pX=" << pX << " pY=" << pY << " pZ=" << pZ << " localNx=" << localNx << " localNy=" << localNy << " localNz=" << localNz << " arraySz=" << arraySz << EndLogLine ; TYPE complex * in = new TYPE complex[arraySz] ; TYPE complex * out = new TYPE complex[arraySz] ; TYPE complex * rev = new TYPE complex[arraySz] ; (fftReverse).Init(globalNx,globalNy,globalNz ,pX,pY,pZ ,subPx, subPy, subPz, 1 ); (fftForward).Init(globalNx,globalNy,globalNz ,pX,pY,pZ ,subPx, subPy, subPz, 1 ); #ifndef FFT_FIX_DATA srand48(myRank) ; // Arrange that different nodes get different seed data #endif for(unsigned int i=0; i<localNx; i++) for(unsigned int j=0; j<localNy; j++) for(unsigned int k=0; k<localNz; k++) { #ifdef FFT_FIX_DATA double rdata = 0.0 ; double idata = 0.0 ; #else double rdata = drand48(); double idata = drand48(); #endif int myIndex = i*localNy*localNz+j*localNz+k; in[myIndex] = rdata + I * idata ; } #ifdef FFT_FIX_DATA if ( markrank == myRank && markindex >= 0 && markindex < arraySz ) { in[markindex] = 1.0 ; } #endif // int iter =20; BegLogLine(PKFXLOG_FFTMAIN) << "Iterations starting" << EndLogLine ; // Do one forward and one reverse, to separate out initialisation effects (fftForward).DoFFT(in,out); (fftReverse).DoFFT(out, rev); // Main run long long oscillatorAtStart = #if defined(USE_PK_ACTORS) PkTimeGetRaw() #else Platform::Clock::Oscillator() #endif ; { BegLogLine(PKFXLOG_FFTINTER) << "Starting forwards FFT" << EndLogLine ; int nextlogiteration = 1 ; for(int i=0; i<iterations; i++) { if ( i >= nextlogiteration ) { BegLogLine(PKFXLOG_FFTITERATION) << "Forward iteration=" << i << EndLogLine ; nextlogiteration *= 2 ; } (fftForward).DoFFT(in,out); } BegLogLine(PKFXLOG_FFTINTER) << "Ending forwards FFT" << EndLogLine ; } // if(myRank==0) // for(unsigned int i=0; i<localNx; i++) // for(unsigned int j=0; j<localNy; j++) // for(unsigned int k=0; k<localNz; k++) // { // printf(" proc = %d out_forward[%d %d %d] = %f\n", // myRank, i, j, k, tmp[i][j][k].re, tmp[i][j][k].im ); // } // (fftReverse).Init(FFT_PLAN::GLOBAL_SIZE_X,FFT_PLAN::GLOBAL_SIZE_Y,FFT_PLAN::GLOBAL_SIZE_Z // ,FFT_PLAN::P_X,FFT_PLAN::P_Y,FFT_PLAN::P_Z); // for( int i=0; i<localNx; i++) // for( int j=0; j<localNy; j++) // for( int k=0; k<localNz; k++) // { // fftReverse.PutRecipSpaceElement(i, j, k, // fftForward.GetRecipSpaceElement( i, j, k ) ); // } long long oscillatorAtMid = #if defined(USE_PK_ACTORS) PkTimeGetRaw() #else Platform::Clock::Oscillator() #endif ; { BegLogLine(PKFXLOG_FFTINTER) << "Starting reverse FFT" << EndLogLine ; int nextlogiteration = 1 ; for(int i=0; i<iterations; i++) { if ( i >= nextlogiteration ) { BegLogLine(PKFXLOG_FFTITERATION) << "Reverse iteration=" << i << EndLogLine ; nextlogiteration *= 2 ; } (fftReverse).DoFFT(out, rev); } BegLogLine(PKFXLOG_FFTINTER) << "Ending reverse FFT" << EndLogLine ; } long long oscillatorAtEnd = #if defined(USE_PK_ACTORS) PkTimeGetRaw() #else Platform::Clock::Oscillator() #endif ; BegLogLine(PKFXLOG_FFTBENCHMARK) << "Benchmark sizeof(TYPE)=" << sizeof(TYPE) << " globalNx=" << globalNx << " globalNy=" << globalNy << " globalNz=" << globalNz << " pX=" << pX << " pY=" << pY << " pZ=" << pZ << " iterations=" << iterations << " forward_clocks=" << oscillatorAtMid-oscillatorAtStart << " reverse_clocks=" << oscillatorAtEnd-oscillatorAtMid << " forward_time_per_iter_ns=" << (oscillatorAtMid-oscillatorAtStart)*(1000.0/700.0)/iterations << " reverse_time_per_iter_ns=" << (oscillatorAtEnd-oscillatorAtMid)*(1000.0/700.0)/iterations << EndLogLine ; double fftSz = 1.0/(double)(localNx*pX*localNy*pY*localNz*pZ); // for( int i=0; i<localNx; i++) // for( int j=0; j<localNy; j++) // for( int k=0; k<localNz; k++) // { // out[i][j][k] = (fftReverse.GetRealSpaceElement(i, j, k )); // out[i][j][k].re = fftSz*out[i][j][k].re; // out[i][j][k].im = fftSz*out[i][j][k].im; // // cout<<"OUT["<<i<<"]["<<j<<"][" <<k<< "] =" << out[i][j][k] <<endl; // } //#define PRINT_OUTPUT #ifdef PRINT_OUTPUT for(unsigned int i=0; i<localNx; i++) for(unsigned int j=0; j<localNy; j++) for(unsigned int k=0; k<localNz; k++) { int myIndex = i*localNy*localNz+j*localNz+k; BegLogLine(1) << "[" << i << "," << j << "," << k << "] in=(" << in[myIndex].re << "," << in[myIndex].im << ") out=(" << out[myIndex].re << "," << out[myIndex].im << ") rev=(" << rev[myIndex].re << "," << rev[myIndex].im << ")" << EndLogLine ; // tmp[i][j][k] = fftForward.GetRecipSpaceElement( i, j, k ); // BegLogLine(1) // << "[" << i // << "," << j // << "," << k // << "] in=(" << in[i][j][k].re // << "," << in[i][j][k].im // << ") out_forward=(" << tmp[i][j][k].re // << "," << tmp[i][j][k].im // << ") out=(" << out[i][j][k].re // << "," << out[i][j][k].im // << ")" // << EndLogLine ; // printf(" proc = %d out_forward[%d %d %d] = %f\n", // myRank, i, j, k, tmp[i][j][k].re, tmp[i][j][k].im ); // printf(" proc %d out_reverse[%d %d %d] = %f\n", // myRank, i, j, k, out[i][j][k].re, tmp[i][j][k].im ); } #endif #if defined(A2A_WITH_ACTORS) #if defined(USE_PK_ACTORS) PacketAlltoAllv_PkActors::ReportFifoHistogram() ; #else PacketAlltoAllv_Actors::ReportFifoHistogram() ; #endif #else PacketAlltoAllv::ReportFifoHistogram() ; #endif #ifdef REGRESS_REVERSE if(compare(in, rev, localNx, localNy, localNz, fftSz) == 1) { BegLogLine(1) << "FAILED FFT-REVERSE TEST :-( " << EndLogLine ; // printf( "FAILED FFT-REVERSE TEST :-( \n" ); } else { BegLogLine(1) << "PASSED FFT-REVERSE TEST :-) " << EndLogLine ; // printf( "PASSED FFT-REVERSE TEST :-) \n" ); } #endif BegLogLine(PKFXLOG_FFTMAIN) << "PkMain complete" << EndLogLine ; #if defined(USE_PK_ACTORS) // 'Barrier' here spins until all nodes have finshed their last FFT; otherwise some nodes // can exit before emptying their transmit FIFOs PkCo_Barrier() ; #if defined(PKTRACE) pkTraceServer::FlushBuffer() ; #endif exit(0) ; // Bring 'Pk' down explicitly return 0 ; #else return NULL ; #endif }
27.750965
118
0.5824
Bhaskers-Blu-Org1
c6f715c843a2145735014d0816d667ad033be0b1
571
cpp
C++
coding-for-fun/cpp/08_valueSwitchWithoutTemp.cpp
AnotherGithubDude/AnotherGithubDude
9ba334dfc1964e6e78920a7495865a2fc3e04d81
[ "CC0-1.0" ]
null
null
null
coding-for-fun/cpp/08_valueSwitchWithoutTemp.cpp
AnotherGithubDude/AnotherGithubDude
9ba334dfc1964e6e78920a7495865a2fc3e04d81
[ "CC0-1.0" ]
null
null
null
coding-for-fun/cpp/08_valueSwitchWithoutTemp.cpp
AnotherGithubDude/AnotherGithubDude
9ba334dfc1964e6e78920a7495865a2fc3e04d81
[ "CC0-1.0" ]
null
null
null
#include <iostream> using std::cout; using std::endl; // author: https://github.com/AnotherGithubDude, 2022 int main(){ int valueOne = 15, valueTwo = 8; cout << "valueOne original:" << valueOne << endl; cout << "valueTwo original:" << valueTwo << endl; valueOne += valueTwo; // 15 + 8 = 23 valueTwo = valueOne - valueTwo; // 23 - 8 = 15 valueOne -= valueTwo; // 23 - 15 = 8 cout << "valueOne after manipulation:" << valueOne << endl; cout << "valueTwo after manipulation:" << valueTwo << endl; return 0; }
33.588235
63
0.583187
AnotherGithubDude
c6f87265d7e832b2bf064d5cf9376071bf2540f6
1,150
hpp
C++
Level_3/II.3/CPP_2.3/CPP_2.3/LineSegment.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_3/II.3/CPP_2.3/CPP_2.3/LineSegment.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_3/II.3/CPP_2.3/CPP_2.3/LineSegment.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
// // LineSegment.hpp // CPP_2.3 // // Created by Zhehao Li on 2020/2/26. // Copyright © 2020 Zhehao Li. All rights reserved. // #ifndef LineSegment_hpp #define LineSegment_hpp #include "Point.hpp" #include <iostream> using namespace std; class LineSegment { private: Point startPoint; // e1 Point endPoint; // e2 public: // Constructor LineSegment(); // Default constructor LineSegment(const Point &p1, const Point &p2); // Initialize with two points LineSegment(const LineSegment &l); // Copy constructor // Destructor virtual ~LineSegment(); // Accessing functions Point Start() const; // May not change the data member Point End() const; // May not change the data member // Modifers void Start(const Point &pt); // Call by reference, may not change the original object void End(const Point &pt); // Overloading function name }; #endif /* LineSegment_hpp */
26.744186
112
0.551304
ZhehaoLi9705
c6ff79679ac9a8179c1b079104ba97f4879935bc
7,756
cpp
C++
android-28/android/content/pm/LauncherApps.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/content/pm/LauncherApps.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/content/pm/LauncherApps.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../ComponentName.hpp" #include "../Context.hpp" #include "../Intent.hpp" #include "../IntentSender.hpp" #include "./ApplicationInfo.hpp" #include "./LauncherActivityInfo.hpp" #include "./LauncherApps_Callback.hpp" #include "./LauncherApps_PinItemRequest.hpp" #include "./LauncherApps_ShortcutQuery.hpp" #include "./ShortcutInfo.hpp" #include "../../graphics/Rect.hpp" #include "../../graphics/drawable/Drawable.hpp" #include "../../os/Bundle.hpp" #include "../../os/Handler.hpp" #include "../../os/UserHandle.hpp" #include "../../../JString.hpp" #include "./LauncherApps.hpp" namespace android::content::pm { // Fields JString LauncherApps::ACTION_CONFIRM_PIN_APPWIDGET() { return getStaticObjectField( "android.content.pm.LauncherApps", "ACTION_CONFIRM_PIN_APPWIDGET", "Ljava/lang/String;" ); } JString LauncherApps::ACTION_CONFIRM_PIN_SHORTCUT() { return getStaticObjectField( "android.content.pm.LauncherApps", "ACTION_CONFIRM_PIN_SHORTCUT", "Ljava/lang/String;" ); } JString LauncherApps::EXTRA_PIN_ITEM_REQUEST() { return getStaticObjectField( "android.content.pm.LauncherApps", "EXTRA_PIN_ITEM_REQUEST", "Ljava/lang/String;" ); } // QJniObject forward LauncherApps::LauncherApps(QJniObject obj) : JObject(obj) {} // Constructors // Methods JObject LauncherApps::getActivityList(JString arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getActivityList", "(Ljava/lang/String;Landroid/os/UserHandle;)Ljava/util/List;", arg0.object<jstring>(), arg1.object() ); } android::content::pm::ApplicationInfo LauncherApps::getApplicationInfo(JString arg0, jint arg1, android::os::UserHandle arg2) const { return callObjectMethod( "getApplicationInfo", "(Ljava/lang/String;ILandroid/os/UserHandle;)Landroid/content/pm/ApplicationInfo;", arg0.object<jstring>(), arg1, arg2.object() ); } android::content::pm::LauncherApps_PinItemRequest LauncherApps::getPinItemRequest(android::content::Intent arg0) const { return callObjectMethod( "getPinItemRequest", "(Landroid/content/Intent;)Landroid/content/pm/LauncherApps$PinItemRequest;", arg0.object() ); } JObject LauncherApps::getProfiles() const { return callObjectMethod( "getProfiles", "()Ljava/util/List;" ); } android::graphics::drawable::Drawable LauncherApps::getShortcutBadgedIconDrawable(android::content::pm::ShortcutInfo arg0, jint arg1) const { return callObjectMethod( "getShortcutBadgedIconDrawable", "(Landroid/content/pm/ShortcutInfo;I)Landroid/graphics/drawable/Drawable;", arg0.object(), arg1 ); } android::content::IntentSender LauncherApps::getShortcutConfigActivityIntent(android::content::pm::LauncherActivityInfo arg0) const { return callObjectMethod( "getShortcutConfigActivityIntent", "(Landroid/content/pm/LauncherActivityInfo;)Landroid/content/IntentSender;", arg0.object() ); } JObject LauncherApps::getShortcutConfigActivityList(JString arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getShortcutConfigActivityList", "(Ljava/lang/String;Landroid/os/UserHandle;)Ljava/util/List;", arg0.object<jstring>(), arg1.object() ); } android::graphics::drawable::Drawable LauncherApps::getShortcutIconDrawable(android::content::pm::ShortcutInfo arg0, jint arg1) const { return callObjectMethod( "getShortcutIconDrawable", "(Landroid/content/pm/ShortcutInfo;I)Landroid/graphics/drawable/Drawable;", arg0.object(), arg1 ); } JObject LauncherApps::getShortcuts(android::content::pm::LauncherApps_ShortcutQuery arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getShortcuts", "(Landroid/content/pm/LauncherApps$ShortcutQuery;Landroid/os/UserHandle;)Ljava/util/List;", arg0.object(), arg1.object() ); } android::os::Bundle LauncherApps::getSuspendedPackageLauncherExtras(JString arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getSuspendedPackageLauncherExtras", "(Ljava/lang/String;Landroid/os/UserHandle;)Landroid/os/Bundle;", arg0.object<jstring>(), arg1.object() ); } jboolean LauncherApps::hasShortcutHostPermission() const { return callMethod<jboolean>( "hasShortcutHostPermission", "()Z" ); } jboolean LauncherApps::isActivityEnabled(android::content::ComponentName arg0, android::os::UserHandle arg1) const { return callMethod<jboolean>( "isActivityEnabled", "(Landroid/content/ComponentName;Landroid/os/UserHandle;)Z", arg0.object(), arg1.object() ); } jboolean LauncherApps::isPackageEnabled(JString arg0, android::os::UserHandle arg1) const { return callMethod<jboolean>( "isPackageEnabled", "(Ljava/lang/String;Landroid/os/UserHandle;)Z", arg0.object<jstring>(), arg1.object() ); } void LauncherApps::pinShortcuts(JString arg0, JObject arg1, android::os::UserHandle arg2) const { callMethod<void>( "pinShortcuts", "(Ljava/lang/String;Ljava/util/List;Landroid/os/UserHandle;)V", arg0.object<jstring>(), arg1.object(), arg2.object() ); } void LauncherApps::registerCallback(android::content::pm::LauncherApps_Callback arg0) const { callMethod<void>( "registerCallback", "(Landroid/content/pm/LauncherApps$Callback;)V", arg0.object() ); } void LauncherApps::registerCallback(android::content::pm::LauncherApps_Callback arg0, android::os::Handler arg1) const { callMethod<void>( "registerCallback", "(Landroid/content/pm/LauncherApps$Callback;Landroid/os/Handler;)V", arg0.object(), arg1.object() ); } android::content::pm::LauncherActivityInfo LauncherApps::resolveActivity(android::content::Intent arg0, android::os::UserHandle arg1) const { return callObjectMethod( "resolveActivity", "(Landroid/content/Intent;Landroid/os/UserHandle;)Landroid/content/pm/LauncherActivityInfo;", arg0.object(), arg1.object() ); } void LauncherApps::startAppDetailsActivity(android::content::ComponentName arg0, android::os::UserHandle arg1, android::graphics::Rect arg2, android::os::Bundle arg3) const { callMethod<void>( "startAppDetailsActivity", "(Landroid/content/ComponentName;Landroid/os/UserHandle;Landroid/graphics/Rect;Landroid/os/Bundle;)V", arg0.object(), arg1.object(), arg2.object(), arg3.object() ); } void LauncherApps::startMainActivity(android::content::ComponentName arg0, android::os::UserHandle arg1, android::graphics::Rect arg2, android::os::Bundle arg3) const { callMethod<void>( "startMainActivity", "(Landroid/content/ComponentName;Landroid/os/UserHandle;Landroid/graphics/Rect;Landroid/os/Bundle;)V", arg0.object(), arg1.object(), arg2.object(), arg3.object() ); } void LauncherApps::startShortcut(android::content::pm::ShortcutInfo arg0, android::graphics::Rect arg1, android::os::Bundle arg2) const { callMethod<void>( "startShortcut", "(Landroid/content/pm/ShortcutInfo;Landroid/graphics/Rect;Landroid/os/Bundle;)V", arg0.object(), arg1.object(), arg2.object() ); } void LauncherApps::startShortcut(JString arg0, JString arg1, android::graphics::Rect arg2, android::os::Bundle arg3, android::os::UserHandle arg4) const { callMethod<void>( "startShortcut", "(Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Rect;Landroid/os/Bundle;Landroid/os/UserHandle;)V", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object(), arg3.object(), arg4.object() ); } void LauncherApps::unregisterCallback(android::content::pm::LauncherApps_Callback arg0) const { callMethod<void>( "unregisterCallback", "(Landroid/content/pm/LauncherApps$Callback;)V", arg0.object() ); } } // namespace android::content::pm
30.415686
173
0.7295
YJBeetle
c6ffe920b92306e6248db3462edb7623ef403156
2,486
hpp
C++
ct_optcon/include/ct/optcon/nloc/algorithms/ilqr/iLQR.hpp
vklemm/control-toolbox
f5f8cf9331c0aecd721ff6296154e2a55c72f679
[ "BSD-2-Clause" ]
1
2019-12-01T14:45:18.000Z
2019-12-01T14:45:18.000Z
ct_optcon/include/ct/optcon/nloc/algorithms/ilqr/iLQR.hpp
deidaraho/control-toolbox
f0ccdf4b6c25e02948215fd3bff212d891f0fd69
[ "BSD-2-Clause" ]
null
null
null
ct_optcon/include/ct/optcon/nloc/algorithms/ilqr/iLQR.hpp
deidaraho/control-toolbox
f0ccdf4b6c25e02948215fd3bff212d891f0fd69
[ "BSD-2-Clause" ]
1
2021-04-01T20:05:31.000Z
2021-04-01T20:05:31.000Z
/********************************************************************************************************************** This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich. Licensed under the BSD-2 license (see LICENSE file in main directory) **********************************************************************************************************************/ #pragma once #include <ct/optcon/solver/NLOptConSettings.hpp> #include <ct/optcon/nloc/NLOCAlgorithm.hpp> namespace ct { namespace optcon { template <size_t STATE_DIM, size_t CONTROL_DIM, size_t P_DIM, size_t V_DIM, typename SCALAR = double, bool CONTINUOUS = true> class iLQR : public NLOCAlgorithm<STATE_DIM, CONTROL_DIM, P_DIM, V_DIM, SCALAR, CONTINUOUS> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW static const size_t STATE_D = STATE_DIM; static const size_t CONTROL_D = CONTROL_DIM; typedef NLOCAlgorithm<STATE_DIM, CONTROL_DIM, P_DIM, V_DIM, SCALAR, CONTINUOUS> Base; typedef typename Base::Policy_t Policy_t; typedef typename Base::Settings_t Settings_t; typedef typename Base::Backend_t Backend_t; typedef SCALAR Scalar_t; //! constructor iLQR(std::shared_ptr<Backend_t>& backend_, const Settings_t& settings); //! destructor virtual ~iLQR(); //! configure the solver virtual void configure(const Settings_t& settings) override; //! set an initial guess virtual void setInitialGuess(const Policy_t& initialGuess) override; //! runIteration combines prepareIteration and finishIteration /*! * For iLQR the separation between prepareIteration and finishIteration would actually not be necessary * @return */ virtual bool runIteration() override; /*! * for iLQR, as it is a purely sequential approach, we cannot prepare anything prior to solving, */ virtual void prepareIteration() override; /*! * for iLQR, finishIteration contains the whole main iLQR iteration. * @return */ virtual bool finishIteration() override; /*! * for iLQR, as it is a purely sequential approach, we cannot prepare anything prior to solving, */ virtual void prepareMPCIteration() override; /*! * for iLQR, finishIteration contains the whole main iLQR iteration. * @return */ virtual bool finishMPCIteration() override; }; } // namespace optcon } // namespace ct
28.574713
120
0.641191
vklemm
050040d4700ee9be39dd097dea40a8b51696163d
604
cpp
C++
_Online/Codechef/UWCOI2020/d.cpp
AYUSHMOHANJHA/Code4CP
7d50d45c5446ad917b4664fc7016d3c82655d947
[ "MIT" ]
null
null
null
_Online/Codechef/UWCOI2020/d.cpp
AYUSHMOHANJHA/Code4CP
7d50d45c5446ad917b4664fc7016d3c82655d947
[ "MIT" ]
null
null
null
_Online/Codechef/UWCOI2020/d.cpp
AYUSHMOHANJHA/Code4CP
7d50d45c5446ad917b4664fc7016d3c82655d947
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { long long int V,H,O,ans=0; cin>>V>>H>>O; for(long long int i=0;i<O;i++) { long long int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2; ans= ans+ abs(x1-x2); //cout<<"out"<<ans<<endl; if(((y1==1 && y2==1))|| ((y1==y2)&&((x1==y1)||(x2==y2)))) continue; else{ if((abs(y2-y1)*2)==0) ans= ans+ 4; else { ans= ans+(abs(y2-y1)*2); } } //cout<<"ans ="<<ans<<endl; } cout<<ans<<endl; return 0; }
22.37037
75
0.397351
AYUSHMOHANJHA
05007e5873f820766c43860a3e73bad97492ad66
843
cpp
C++
C++/medium/6. ZigZag Conversion.cpp
18810817370/LeetCodePracticeJava
e800e828cc64fedbc26e37f223d16ad9fdb711c2
[ "MIT" ]
1
2019-03-19T12:04:20.000Z
2019-03-19T12:04:20.000Z
C++/medium/6. ZigZag Conversion.cpp
18810817370/LeetCodePracticeJava
e800e828cc64fedbc26e37f223d16ad9fdb711c2
[ "MIT" ]
null
null
null
C++/medium/6. ZigZag Conversion.cpp
18810817370/LeetCodePracticeJava
e800e828cc64fedbc26e37f223d16ad9fdb711c2
[ "MIT" ]
null
null
null
/** * @author zly * * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) * * P A H N * A P L S I I G * Y I R * And then read line by line: "PAHNAPLSIIGYIR" * * Write the code that will take a string and make this conversion given a number of rows: * * string convert(string s, int numRows); * * Example 1: * Input: s = "PAYPALISHIRING", numRows = 3 * Output: "PAHNAPLSIIGYIR" * * Example 2: * Input: s = "PAYPALISHIRING", numRows = 4 * Output: "PINALSIGYAHRPI" * * Explanation: * * P I N * A L S I G * Y A H R * P I */ #include <string> class Solution { public: std::string convert(std::string s, int numRows) { } };
21.075
175
0.59312
18810817370
0500a0aeb8d0fef32c77298d1ea22d48fef8ca79
32,257
cxx
C++
main/ucbhelper/workben/myucp/myucp_content.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/ucbhelper/workben/myucp/myucp_content.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/ucbhelper/workben/myucp/myucp_content.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucbhelper.hxx" /************************************************************************** TODO ************************************************************************** *************************************************************************/ #include "osl/diagnose.h" #include "com/sun/star/beans/PropertyAttribute.hpp" #include "com/sun/star/beans/XPropertyAccess.hpp" #include "com/sun/star/lang/IllegalAccessException.hpp" #include "com/sun/star/sdbc/XRow.hpp" #include "com/sun/star/ucb/XCommandInfo.hpp" #include "com/sun/star/ucb/XPersistentPropertySet.hpp" #include "ucbhelper/contentidentifier.hxx" #include "ucbhelper/propertyvalueset.hxx" #include "ucbhelper/cancelcommandexecution.hxx" #include "myucp_content.hxx" #include "myucp_provider.hxx" #ifdef IMPLEMENT_COMMAND_INSERT #include "com/sun/star/ucb/InsertCommandArgument.hpp" #include "com/sun/star/ucb/MissingInputStreamException.hpp" #include "com/sun/star/ucb/MissingPropertiesException.hpp" #endif #ifdef IMPLEMENT_COMMAND_OPEN #include "com/sun/star/io/XOutputStream.hpp" #include "com/sun/star/io/XActiveDataSink.hpp" #include "com/sun/star/ucb/OpenCommandArgument2.hpp" #include "com/sun/star/ucb/OpenMode.hpp" #include "com/sun/star/ucb/UnsupportedDataSinkException.hpp" #include "com/sun/star/ucb/UnsupportedOpenModeException.hpp" #include "myucp_resultset.hxx" #endif using namespace com::sun::star; // @@@ Adjust namespace name. using namespace myucp; //========================================================================= //========================================================================= // // Content Implementation. // //========================================================================= //========================================================================= Content::Content( const uno::Reference< lang::XMultiServiceFactory >& rxSMgr, ::ucbhelper::ContentProviderImplHelper* pProvider, const uno::Reference< ucb::XContentIdentifier >& Identifier ) : ContentImplHelper( rxSMgr, pProvider, Identifier ) { // @@@ Fill m_aProps here or implement lazy evaluation logic for this. // m_aProps.aTitle = // m_aprops.aContentType = // m_aProps.bIsDocument = // m_aProps.bIsFolder = } //========================================================================= // virtual Content::~Content() { } //========================================================================= // // XInterface methods. // //========================================================================= // virtual void SAL_CALL Content::acquire() throw() { ContentImplHelper::acquire(); } //========================================================================= // virtual void SAL_CALL Content::release() throw() { ContentImplHelper::release(); } //========================================================================= // virtual uno::Any SAL_CALL Content::queryInterface( const uno::Type & rType ) throw ( uno::RuntimeException ) { uno::Any aRet; // @@@ Add support for additional interfaces. #if 0 aRet = cppu::queryInterface( rType, static_cast< yyy::Xxxxxxxxx * >( this ) ); #endif return aRet.hasValue() ? aRet : ContentImplHelper::queryInterface( rType ); } //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_COMMON_IMPL( Content ); //========================================================================= // virtual uno::Sequence< uno::Type > SAL_CALL Content::getTypes() throw( uno::RuntimeException ) { // @@@ Add own interfaces. static cppu::OTypeCollection* pCollection = 0; if ( !pCollection ) { osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() ); if ( !pCollection ) { static cppu::OTypeCollection aCollection( CPPU_TYPE_REF( lang::XTypeProvider ), CPPU_TYPE_REF( lang::XServiceInfo ), CPPU_TYPE_REF( lang::XComponent ), CPPU_TYPE_REF( ucb::XContent ), CPPU_TYPE_REF( ucb::XCommandProcessor ), CPPU_TYPE_REF( beans::XPropertiesChangeNotifier ), CPPU_TYPE_REF( ucb::XCommandInfoChangeNotifier ), CPPU_TYPE_REF( beans::XPropertyContainer ), CPPU_TYPE_REF( beans::XPropertySetInfoChangeNotifier ), CPPU_TYPE_REF( container::XChild ) ); pCollection = &aCollection; } } return (*pCollection).getTypes(); } //========================================================================= // // XServiceInfo methods. // //========================================================================= // virtual rtl::OUString SAL_CALL Content::getImplementationName() throw( uno::RuntimeException ) { // @@@ Adjust implementation name. // Prefix with reversed company domain name. return rtl::OUString::createFromAscii( "com.sun.star.comp.myucp.Content" ); } //========================================================================= // virtual uno::Sequence< rtl::OUString > SAL_CALL Content::getSupportedServiceNames() throw( uno::RuntimeException ) { // @@@ Adjust macro name. uno::Sequence< rtl::OUString > aSNS( 1 ); aSNS.getArray()[ 0 ] = rtl::OUString::createFromAscii( MYUCP_CONTENT_SERVICE_NAME ); return aSNS; } //========================================================================= // // XContent methods. // //========================================================================= // virtual rtl::OUString SAL_CALL Content::getContentType() throw( uno::RuntimeException ) { // @@@ Adjust macro name ( def in myucp_provider.hxx ). return rtl::OUString::createFromAscii( MYUCP_CONTENT_TYPE ); } //========================================================================= // // XCommandProcessor methods. // //========================================================================= // virtual uno::Any SAL_CALL Content::execute( const ucb::Command& aCommand, sal_Int32 /* CommandId */, const uno::Reference< ucb::XCommandEnvironment >& Environment ) throw( uno::Exception, ucb::CommandAbortedException, uno::RuntimeException ) { uno::Any aRet; if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "getPropertyValues" ) ) ) { ////////////////////////////////////////////////////////////////// // getPropertyValues ////////////////////////////////////////////////////////////////// uno::Sequence< beans::Property > Properties; if ( !( aCommand.Argument >>= Properties ) ) { OSL_ENSURE( sal_False, "Wrong argument type!" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( lang::IllegalArgumentException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), -1 ) ), Environment ); // Unreachable } aRet <<= getPropertyValues( Properties, Environment ); } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "setPropertyValues" ) ) ) { ////////////////////////////////////////////////////////////////// // setPropertyValues ////////////////////////////////////////////////////////////////// uno::Sequence< beans::PropertyValue > aProperties; if ( !( aCommand.Argument >>= aProperties ) ) { OSL_ENSURE( sal_False, "Wrong argument type!" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( lang::IllegalArgumentException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), -1 ) ), Environment ); // Unreachable } if ( !aProperties.getLength() ) { OSL_ENSURE( sal_False, "No properties!" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( lang::IllegalArgumentException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), -1 ) ), Environment ); // Unreachable } aRet <<= setPropertyValues( aProperties, Environment ); } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "getPropertySetInfo" ) ) ) { ////////////////////////////////////////////////////////////////// // getPropertySetInfo ////////////////////////////////////////////////////////////////// // Note: Implemented by base class. aRet <<= getPropertySetInfo( Environment ); } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "getCommandInfo" ) ) ) { ////////////////////////////////////////////////////////////////// // getCommandInfo ////////////////////////////////////////////////////////////////// // Note: Implemented by base class. aRet <<= getCommandInfo( Environment ); } #ifdef IMPLEMENT_COMMAND_OPEN else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "open" ) ) ) { ucb::OpenCommandArgument2 aOpenCommand; if ( !( aCommand.Argument >>= aOpenCommand ) ) { OSL_ENSURE( sal_False, "Wrong argument type!" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( lang::IllegalArgumentException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), -1 ) ), Environment ); // Unreachable } sal_Bool bOpenFolder = ( ( aOpenCommand.Mode == ucb::OpenMode::ALL ) || ( aOpenCommand.Mode == ucb::OpenMode::FOLDERS ) || ( aOpenCommand.Mode == ucb::OpenMode::DOCUMENTS ) ); if ( bOpenFolder /*&& isFolder( Environment )*/ ) { // open as folder - return result set uno::Reference< ucb::XDynamicResultSet > xSet = new DynamicResultSet( m_xSMgr, this, aOpenCommand, Environment ); aRet <<= xSet; } if ( aOpenCommand.Sink.is() ) { // Open document - supply document data stream. // Check open mode if ( ( aOpenCommand.Mode == ucb::OpenMode::DOCUMENT_SHARE_DENY_NONE ) || ( aOpenCommand.Mode == ucb::OpenMode::DOCUMENT_SHARE_DENY_WRITE ) ) { // Unsupported. ::ucbhelper::cancelCommandExecution( uno::makeAny( ucb::UnsupportedOpenModeException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), sal_Int16( aOpenCommand.Mode ) ) ), Environment ); // Unreachable } rtl::OUString aURL = m_xIdentifier->getContentIdentifier(); uno::Reference< io::XOutputStream > xOut = uno::Reference< io::XOutputStream >( aOpenCommand.Sink, uno::UNO_QUERY ); if ( xOut.is() ) { // @@@ write data into xOut } else { uno::Reference< io::XActiveDataSink > xDataSink( aOpenCommand.Sink, uno::UNO_QUERY ); if ( xDataSink.is() ) { uno::Reference< io::XInputStream > xIn /* @@@ your XInputStream + XSeekable impl. object */; xDataSink->setInputStream( xIn ); } else { // Note: aOpenCommand.Sink may contain an XStream // implementation. Support for this type of // sink is optional... ::ucbhelper::cancelCommandExecution( uno::makeAny( ucb::UnsupportedDataSinkException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), aOpenCommand.Sink ) ), Environment ); // Unreachable } } } } #endif // IMPLEMENT_COMMAND_OPEN #ifdef IMPLEMENT_COMMAND_INSERT else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "insert" ) ) ) { ////////////////////////////////////////////////////////////////// // insert ////////////////////////////////////////////////////////////////// ucb::InsertCommandArgument arg; if ( !( aCommand.Argument >>= arg ) ) { OSL_ENSURE( sal_False, "Wrong argument type!" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( lang::IllegalArgumentException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), -1 ) ), Environment ); // Unreachable } insert( arg.Data, arg.ReplaceExisting, Environment ); } #endif // IMPLEMENT_COMMAND_INSERT #ifdef IMPLEMENT_COMMAND_DELETE else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "delete" ) ) ) { ////////////////////////////////////////////////////////////////// // delete ////////////////////////////////////////////////////////////////// sal_Bool bDeletePhysical = sal_False; aCommand.Argument >>= bDeletePhysical; destroy( bDeletePhysical ); // Remove own and all children's Additional Core Properties. removeAdditionalPropertySet( sal_True ); // Remove own and all childrens(!) persistent data. // removeData(); } #endif // IMPLEMENT_COMMAND_DELETE else { ////////////////////////////////////////////////////////////////// // Unsupported command ////////////////////////////////////////////////////////////////// OSL_ENSURE( sal_False, "Content::execute - unsupported command!" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( ucb::UnsupportedCommandException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ) ) ), Environment ); // Unreachable } return aRet; } //========================================================================= // virtual void SAL_CALL Content::abort( sal_Int32 ) throw( uno::RuntimeException ) { // @@@ Implement logic to abort running commands, if this makes // sense for your content. } //========================================================================= // // Non-interface methods. // //========================================================================= // virtual rtl::OUString Content::getParentURL() { rtl::OUString aURL = m_xIdentifier->getContentIdentifier(); // @@@ Extract URL of parent from aURL and return it... return rtl::OUString(); } //========================================================================= // static uno::Reference< sdbc::XRow > Content::getPropertyValues( const uno::Reference< lang::XMultiServiceFactory >& rSMgr, const uno::Sequence< beans::Property >& rProperties, const ContentProperties& rData, const rtl::Reference< ::ucbhelper::ContentProviderImplHelper >& rProvider, const rtl::OUString& rContentId ) { // Note: Empty sequence means "get values of all supported properties". rtl::Reference< ::ucbhelper::PropertyValueSet > xRow = new ::ucbhelper::PropertyValueSet( rSMgr ); sal_Int32 nCount = rProperties.getLength(); if ( nCount ) { uno::Reference< beans::XPropertySet > xAdditionalPropSet; sal_Bool bTriedToGetAdditonalPropSet = sal_False; const beans::Property* pProps = rProperties.getConstArray(); for ( sal_Int32 n = 0; n < nCount; ++n ) { const beans::Property& rProp = pProps[ n ]; // Process Core properties. if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ContentType" ) ) ) { xRow->appendString ( rProp, rData.aContentType ); } else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Title" ) ) ) { xRow->appendString ( rProp, rData.aTitle ); } else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "IsDocument" ) ) ) { xRow->appendBoolean( rProp, rData.bIsDocument ); } else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "IsFolder" ) ) ) { xRow->appendBoolean( rProp, rData.bIsFolder ); } // @@@ Process other properties supported directly. #if 0 else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "xxxxxx" ) ) ) { } #endif else { // @@@ Note: If your data source supports adding/removing // properties, you should implement the interface // XPropertyContainer by yourself and supply your own // logic here. The base class uses the service // "com.sun.star.ucb.Store" to maintain Additional Core // properties. But using server functionality is preferred! // Not a Core Property! Maybe it's an Additional Core Property?! if ( !bTriedToGetAdditonalPropSet && !xAdditionalPropSet.is() ) { xAdditionalPropSet = uno::Reference< beans::XPropertySet >( rProvider->getAdditionalPropertySet( rContentId, sal_False ), uno::UNO_QUERY ); bTriedToGetAdditonalPropSet = sal_True; } if ( xAdditionalPropSet.is() ) { if ( !xRow->appendPropertySetValue( xAdditionalPropSet, rProp ) ) { // Append empty entry. xRow->appendVoid( rProp ); } } else { // Append empty entry. xRow->appendVoid( rProp ); } } } } else { // Append all Core Properties. xRow->appendString ( beans::Property( rtl::OUString::createFromAscii( "ContentType" ), -1, getCppuType( static_cast< const rtl::OUString * >( 0 ) ), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ), rData.aContentType ); xRow->appendString ( beans::Property( rtl::OUString::createFromAscii( "Title" ), -1, getCppuType( static_cast< const rtl::OUString * >( 0 ) ), beans::PropertyAttribute::BOUND ), rData.aTitle ); xRow->appendBoolean( beans::Property( rtl::OUString::createFromAscii( "IsDocument" ), -1, getCppuBooleanType(), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ), rData.bIsDocument ); xRow->appendBoolean( beans::Property( rtl::OUString::createFromAscii( "IsFolder" ), -1, getCppuBooleanType(), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ), rData.bIsFolder ); // @@@ Append other properties supported directly. // @@@ Note: If your data source supports adding/removing // properties, you should implement the interface // XPropertyContainer by yourself and supply your own // logic here. The base class uses the service // "com.sun.star.ucb.Store" to maintain Additional Core // properties. But using server functionality is preferred! // Append all Additional Core Properties. uno::Reference< beans::XPropertySet > xSet( rProvider->getAdditionalPropertySet( rContentId, sal_False ), uno::UNO_QUERY ); xRow->appendPropertySet( xSet ); } return uno::Reference< sdbc::XRow >( xRow.get() ); } //========================================================================= uno::Reference< sdbc::XRow > Content::getPropertyValues( const uno::Sequence< beans::Property >& rProperties, const uno::Reference< ucb::XCommandEnvironment >& /* xEnv */) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); return getPropertyValues( m_xSMgr, rProperties, m_aProps, rtl::Reference< ::ucbhelper::ContentProviderImplHelper >( m_xProvider.get() ), m_xIdentifier->getContentIdentifier() ); } //========================================================================= uno::Sequence< uno::Any > Content::setPropertyValues( const uno::Sequence< beans::PropertyValue >& rValues, const uno::Reference< ucb::XCommandEnvironment >& /* xEnv */) { osl::ClearableGuard< osl::Mutex > aGuard( m_aMutex ); uno::Sequence< uno::Any > aRet( rValues.getLength() ); uno::Sequence< beans::PropertyChangeEvent > aChanges( rValues.getLength() ); sal_Int32 nChanged = 0; beans::PropertyChangeEvent aEvent; aEvent.Source = static_cast< cppu::OWeakObject * >( this ); aEvent.Further = sal_False; // aEvent.PropertyName = aEvent.PropertyHandle = -1; // aEvent.OldValue = // aEvent.NewValue = const beans::PropertyValue* pValues = rValues.getConstArray(); sal_Int32 nCount = rValues.getLength(); uno::Reference< ucb::XPersistentPropertySet > xAdditionalPropSet; sal_Bool bTriedToGetAdditonalPropSet = sal_False; for ( sal_Int32 n = 0; n < nCount; ++n ) { const beans::PropertyValue& rValue = pValues[ n ]; if ( rValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ContentType" ) ) ) { // Read-only property! aRet[ n ] <<= lang::IllegalAccessException( rtl::OUString::createFromAscii( "Property is read-only!" ), static_cast< cppu::OWeakObject * >( this ) ); } else if ( rValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "IsDocument" ) ) ) { // Read-only property! aRet[ n ] <<= lang::IllegalAccessException( rtl::OUString::createFromAscii( "Property is read-only!" ), static_cast< cppu::OWeakObject * >( this ) ); } else if ( rValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "IsFolder" ) ) ) { // Read-only property! aRet[ n ] <<= lang::IllegalAccessException( rtl::OUString::createFromAscii( "Property is read-only!" ), static_cast< cppu::OWeakObject * >( this ) ); } else if ( rValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Title" ) ) ) { rtl::OUString aNewValue; if ( rValue.Value >>= aNewValue ) { if ( aNewValue != m_aProps.aTitle ) { aEvent.PropertyName = rValue.Name; aEvent.OldValue = uno::makeAny( m_aProps.aTitle ); aEvent.NewValue = uno::makeAny( aNewValue ); aChanges.getArray()[ nChanged ] = aEvent; m_aProps.aTitle = aNewValue; nChanged++; } else { // Old value equals new value. No error! } } else { aRet[ n ] <<= beans::IllegalTypeException( rtl::OUString::createFromAscii( "Property value has wrong type!" ), static_cast< cppu::OWeakObject * >( this ) ); } } // @@@ Process other properties supported directly. #if 0 else if ( rValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "xxxxxx" ) ) ) { } #endif else { // @@@ Note: If your data source supports adding/removing // properties, you should implement the interface // XPropertyContainer by yourself and supply your own // logic here. The base class uses the service // "com.sun.star.ucb.Store" to maintain Additional Core // properties. But using server functionality is preferred! // Not a Core Property! Maybe it's an Additional Core Property?! if ( !bTriedToGetAdditonalPropSet && !xAdditionalPropSet.is() ) { xAdditionalPropSet = getAdditionalPropertySet( sal_False ); bTriedToGetAdditonalPropSet = sal_True; } if ( xAdditionalPropSet.is() ) { try { uno::Any aOldValue = xAdditionalPropSet->getPropertyValue( rValue.Name ); if ( aOldValue != rValue.Value ) { xAdditionalPropSet->setPropertyValue( rValue.Name, rValue.Value ); aEvent.PropertyName = rValue.Name; aEvent.OldValue = aOldValue; aEvent.NewValue = rValue.Value; aChanges.getArray()[ nChanged ] = aEvent; nChanged++; } else { // Old value equals new value. No error! } } catch ( beans::UnknownPropertyException const & e ) { aRet[ n ] <<= e; } catch ( lang::WrappedTargetException const & e ) { aRet[ n ] <<= e; } catch ( beans::PropertyVetoException const & e ) { aRet[ n ] <<= e; } catch ( lang::IllegalArgumentException const & e ) { aRet[ n ] <<= e; } } else { aRet[ n ] <<= uno::Exception( rtl::OUString::createFromAscii( "No property set for storing the value!" ), static_cast< cppu::OWeakObject * >( this ) ); } } } if ( nChanged > 0 ) { // @@@ Save changes. // storeData(); aGuard.clear(); aChanges.realloc( nChanged ); notifyPropertiesChange( aChanges ); } return aRet; } #ifdef IMPLEMENT_COMMAND_INSERT //========================================================================= void Content::queryChildren( ContentRefList& rChildren ) { // @@@ Adapt method to your URL scheme... // Obtain a list with a snapshot of all currently instanciated contents // from provider and extract the contents which are direct children // of this content. ::ucbhelper::ContentRefList aAllContents; m_xProvider->queryExistingContents( aAllContents ); ::rtl::OUString aURL = m_xIdentifier->getContentIdentifier(); sal_Int32 nPos = aURL.lastIndexOf( '/' ); if ( nPos != ( aURL.getLength() - 1 ) ) { // No trailing slash found. Append. aURL += ::rtl::OUString::createFromAscii( "/" ); } sal_Int32 nLen = aURL.getLength(); ::ucbhelper::ContentRefList::const_iterator it = aAllContents.begin(); ::ucbhelper::ContentRefList::const_iterator end = aAllContents.end(); while ( it != end ) { ::ucbhelper::ContentImplHelperRef xChild = (*it); ::rtl::OUString aChildURL = xChild->getIdentifier()->getContentIdentifier(); // Is aURL a prefix of aChildURL? if ( ( aChildURL.getLength() > nLen ) && ( aChildURL.compareTo( aURL, nLen ) == 0 ) ) { nPos = aChildURL.indexOf( '/', nLen ); if ( ( nPos == -1 ) || ( nPos == ( aChildURL.getLength() - 1 ) ) ) { // No further slashes / only a final slash. It's a child! rChildren.push_back( ContentRef( static_cast< Content * >( xChild.get() ) ) ); } } ++it; } } //========================================================================= void Content::insert( const uno::Reference< io::XInputStream > & xInputStream, sal_Bool bReplaceExisting, const uno::Reference< ucb::XCommandEnvironment >& Environment ) throw( uno::Exception ) { osl::ClearableGuard< osl::Mutex > aGuard( m_aMutex ); // Check, if all required properties were set. #if 0 // @@@ add checks for property presence if ( m_aProps.xxxx == yyyyy ) { OSL_ENSURE( sal_False, "Content::insert - property value missing!" ); uno::Sequence< rtl::OUString > aProps( 1 ); aProps[ 0 ] = rtl::OUString::createFromAscii( "zzzz" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( ucb::MissingPropertiesException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ), aProps ) ), Environment ); // Unreachable } #endif bool bNeedInputStream = true; // @@@ adjust to real requirements if ( bNeedInputStream && !xInputStream.is() ) { OSL_ENSURE( sal_False, "Content::insert - No data stream!" ); ::ucbhelper::cancelCommandExecution( uno::makeAny( ucb::MissingInputStreamException( rtl::OUString(), static_cast< cppu::OWeakObject * >( this ) ) ), Environment ); // Unreachable } // Assemble new content identifier... uno::Reference< ucb::XContentIdentifier > xId /* @@@ create content identifier */; // Fail, if a resource with given id already exists. if ( !bReplaceExisting /*&& hasData( xId ) @@@ impl for hasData() */ ) { uno::Any aProps = uno::makeAny( beans::PropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Uri" ) ), -1, uno::makeAny( xId->getContentIdentifier() ), beans::PropertyState_DIRECT_VALUE ) ); ucbhelper::cancelCommandExecution( ucb::IOErrorCode_ALREADY_EXISTING, uno::Sequence< uno::Any >(&aProps, 1), Environment, rtl::OUString::createFromAscii( "content already existing!!" ), this ); // Unreachable } m_xIdentifier = xId; // @@@ // storeData(); aGuard.clear(); inserted(); } #endif // IMPLEMENT_COMMAND_INSERT #ifdef IMPLEMENT_COMMAND_DELETE //========================================================================= void Content::destroy( sal_Bool bDeletePhysical ) throw( uno::Exception ) { // @@@ take care about bDeletePhysical -> trashcan support uno::Reference< ucb::XContent > xThis = this; deleted(); osl::Guard< osl::Mutex > aGuard( m_aMutex ); // Process instanciated children... ContentRefList aChildren; queryChildren( aChildren ); ContentRefList::const_iterator it = aChildren.begin(); ContentRefList::const_iterator end = aChildren.end(); while ( it != end ) { (*it)->destroy( bDeletePhysical ); ++it; } } #endif // IMPLEMENT_COMMAND_DELETE
32.915306
86
0.516818
Grosskopf
0503741ce2ad85e705c04abe8804e60013210c82
3,148
cpp
C++
dependencies/PyMesh/src/IO/POLYParser.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
5
2018-06-04T19:52:02.000Z
2022-01-22T09:04:00.000Z
dependencies/PyMesh/src/IO/POLYParser.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
null
null
null
dependencies/PyMesh/src/IO/POLYParser.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
null
null
null
#include "POLYParser.h" #include "IOUtils.h" #include <iostream> #include <fstream> #include <sstream> #include <Core/EigenTypedef.h> #include <Core/Exception.h> using namespace PyMesh; bool POLYParser::parse(const std::string& filename) { std::ifstream fin(filename.c_str()); if (!fin.good()) { std::stringstream err_msg; err_msg << "Unable to read file " << filename; throw IOError(err_msg.str()); } parse_vertices(fin); parse_faces(fin); fin.close(); return true; } POLYParser::AttrNames POLYParser::get_attribute_names() const { return AttrNames(); } void POLYParser::export_vertices(Float* buffer) { std::copy(m_vertices.begin(), m_vertices.end(), buffer); } void POLYParser::export_faces(int* buffer) { std::copy(m_faces.begin(), m_faces.end(), buffer); } void POLYParser::export_voxels(int* buffer) { std::copy(m_voxels.begin(), m_voxels.end(), buffer); } void POLYParser::export_attribute(const std::string& name, Float* buffer) { std::cerr << "Warning: attribute " << name << " does not exist." << std::endl; } void POLYParser::parse_vertices(std::ifstream& fin) { std::string header = IOUtils::next_line(fin); size_t num_vertices, dim, num_attributes, bd_marker; sscanf(header.c_str(), "%zi %zi %zi %zi", &num_vertices, &dim, &num_attributes, &bd_marker); if (dim != 3) { throw IOError("Dim is not 3!"); } m_vertices.resize(num_vertices * dim); for (size_t i=0; i<num_vertices; i++) { assert(fin.good()); size_t index; Float x,y,z; fin >> index >> x >> y >> z; assert(index >= 0); assert(index < num_vertices); m_vertices[index*3 ] = x; m_vertices[index*3+1] = y; m_vertices[index*3+2] = z; for (size_t j=0; j<num_attributes; j++) { Float attr; fin >> attr; } if (bd_marker == 1) { Float bd; fin >> bd; } } } void POLYParser::parse_faces(std::ifstream& fin) { size_t num_faces, bd_marker; fin >> num_faces >> bd_marker; for (size_t i=0; i<num_faces; i++) { assert(fin.good()); std::string line = IOUtils::next_line(fin); size_t num_poly=0, num_holes=0, bd=0; size_t n = sscanf(line.c_str(), "%zi %zi %zi", &num_poly, &num_holes, &bd); assert(n >= 1); for (size_t j=0; j<num_poly; j++) { size_t num_corners; fin >> num_corners; if (i == 0 && j == 0) { m_vertex_per_face = num_corners; } else if (num_corners != m_vertex_per_face) { throw NotImplementedError("Mixed faces is not supported!"); } for (size_t k=0; k<num_corners; k++) { size_t corner; fin >> corner; m_faces.push_back(corner); } } assert(fin.good()); for (size_t j=0; j<num_holes; j++) { size_t hole_index; float x,y,z; fin >> hole_index >> x >> y >> z; } } }
27.137931
75
0.554956
aprieels
0504259f718b7b581be2c21ed357ac6b4dd2f21d
26,447
cpp
C++
src/dialogs/StartDialog.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
127
2021-10-29T19:01:32.000Z
2022-03-31T18:23:56.000Z
src/dialogs/StartDialog.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
90
2021-11-05T13:03:58.000Z
2022-03-30T16:42:49.000Z
src/dialogs/StartDialog.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
20
2021-10-30T12:25:33.000Z
2022-02-18T03:08:21.000Z
// // Copyright (c) 2016, Scientific Toolworks, Inc. // // This software is licensed under the MIT License. The LICENSE.md file // describes the conditions under which this software may be distributed. // // Author: Jason Haslam // #include "StartDialog.h" #include "AccountDialog.h" #include "CloneDialog.h" #include "IconLabel.h" #include "app/Application.h" #include "conf/RecentRepositories.h" #include "conf/RecentRepository.h" #include "host/Accounts.h" #include "host/Repository.h" #include "ui/Footer.h" #include "ui/MainWindow.h" #include "ui/ProgressIndicator.h" #include "ui/RepoView.h" #include "ui/TabWidget.h" #include <QAbstractItemModel> #include <QAbstractListModel> #include <QApplication> #include <QComboBox> #include <QDesktopServices> #include <QDialogButtonBox> #include <QFileDialog> #include <QHBoxLayout> #include <QIcon> #include <QLabel> #include <QLineEdit> #include <QListView> #include <QMessageBox> #include <QMenu> #include <QMultiMap> #include <QPushButton> #include <QPointer> #include <QSettings> #include <QStyledItemDelegate> #include <QTimer> #include <QTreeView> #include <QVBoxLayout> namespace { const QString kSubtitleFmt = "<h4 style='margin-top: 0px; color: gray'>%2</h4>"; const QString kGeometryKey = "geometry"; const QString kStartGroup = "start"; const QString kCloudIcon = ":/cloud.png"; enum Role { KindRole = Qt::UserRole, AccountRole, RepositoryRole }; class RepoModel : public QAbstractListModel { Q_OBJECT public: enum Row { Clone, Open, Init }; RepoModel(QObject *parent = nullptr) : QAbstractListModel(parent) { RecentRepositories *repos = RecentRepositories::instance(); connect(repos, &RecentRepositories::repositoryAboutToBeAdded, this, &RepoModel::beginResetModel); connect(repos, &RecentRepositories::repositoryAdded, this, &RepoModel::endResetModel); connect(repos, &RecentRepositories::repositoryAboutToBeRemoved, this, &RepoModel::beginResetModel); connect(repos, &RecentRepositories::repositoryRemoved, this, &RepoModel::endResetModel); } void setShowFullPath(bool enabled) { beginResetModel(); mShowFullPath = enabled; endResetModel(); } int rowCount(const QModelIndex &parent = QModelIndex()) const override { RecentRepositories *repos = RecentRepositories::instance(); return (repos->count() > 0) ? repos->count() : 3; } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { RecentRepositories *repos = RecentRepositories::instance(); if (repos->count() <= 0) { switch (role) { case Qt::DisplayRole: switch (index.row()) { case Clone: return tr("Clone Repository"); case Open: return tr("Open Existing Repository"); case Init: return tr("Initialize New Repository"); } case Qt::DecorationRole: { switch (index.row()) { case Clone: return QIcon(":/clone.png"); case Open: return QIcon(":/open.png"); case Init: return QIcon(":/new.png"); } } } return QVariant(); } RecentRepository *repo = repos->repository(index.row()); switch (role) { case Qt::DisplayRole: return mShowFullPath ? repo->path() : repo->name(); case Qt::UserRole: return repo->path(); } return QVariant(); } Qt::ItemFlags flags(const QModelIndex &index) const override { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (RecentRepositories::instance()->count() <= 0) flags &= ~Qt::ItemIsSelectable; return flags; } private: bool mShowFullPath = false; }; class HostModel : public QAbstractItemModel { Q_OBJECT public: HostModel(QStyle *style, QObject *parent = nullptr) : QAbstractItemModel(parent), mErrorIcon(style->standardIcon(QStyle::SP_MessageBoxCritical)) { Accounts *accounts = Accounts::instance(); connect(accounts, &Accounts::accountAboutToBeAdded, this, &HostModel::beginResetModel); connect(accounts, &Accounts::accountAdded, this, &HostModel::endResetModel); connect(accounts, &Accounts::accountAboutToBeRemoved, this, &HostModel::beginResetModel); connect(accounts, &Accounts::accountRemoved, this, &HostModel::endResetModel); connect(accounts, &Accounts::progress, this, [this](int accountIndex) { QModelIndex idx = index(0, 0, index(accountIndex, 0)); emit dataChanged(idx, idx, {Qt::DisplayRole}); }); connect(accounts, &Accounts::started, this, [this](int accountIndex) { beginResetModel(); endResetModel(); }); connect(accounts, &Accounts::finished, this, [this](int accountIndex) { beginResetModel(); endResetModel(); }); connect(accounts, &Accounts::repositoryAboutToBeAdded, this, &HostModel::beginResetModel); connect(accounts, &Accounts::repositoryAdded, this, &HostModel::endResetModel); connect(accounts, &Accounts::repositoryPathChanged, this, [this](int accountIndex, int repoIndex) { QModelIndex idx = index(repoIndex, 0, index(accountIndex, 0)); emit dataChanged(idx, idx, {Qt::DisplayRole}); }); } void setShowFullName(bool enabled) { beginResetModel(); mShowFullName = enabled; endResetModel(); } QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override { bool id = (!parent.isValid() || parent.internalId()); return createIndex(row, column, !id ? parent.row() + 1 : 0); } QModelIndex parent(const QModelIndex &index) const override { quintptr id = index.internalId(); return !id ? QModelIndex() : createIndex(id - 1, 0); } int rowCount(const QModelIndex &parent = QModelIndex()) const override { // no accounts Accounts *accounts = Accounts::instance(); if (accounts->count() <= 0) return !parent.isValid() ? 4 : 0; // account if (!parent.isValid()) return accounts->count(); if (parent.internalId()) return 0; // repos Account *account = accounts->account(parent.row()); int count = account->repositoryCount(); if (count > 0) return count; AccountError *error = account->error(); AccountProgress *progress = account->progress(); return (error->isValid() || progress->isValid()) ? 1 : 0; } int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 1; } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { // no accounts Accounts *accounts = Accounts::instance(); if (accounts->count() <= 0) { Account::Kind kind = static_cast<Account::Kind>(index.row()); switch (role) { case Qt::DisplayRole: return Account::name(kind); case Qt::DecorationRole: return Account::icon(kind); case KindRole: return kind; } return QVariant(); } // account quintptr id = index.internalId(); if (!id) { Account *account = accounts->account(index.row()); switch (role) { case Qt::DisplayRole: return account->username(); case Qt::DecorationRole: return Account::icon(account->kind()); case KindRole: return account->kind(); case AccountRole: return QVariant::fromValue(account); } return QVariant(); } // error Account *account = accounts->account(id - 1); AccountError *error = account->error(); if (error->isValid()) { switch (role) { case Qt::DisplayRole: return error->text(); case Qt::DecorationRole: return mErrorIcon; case Qt::ToolTipRole: return error->detailedText(); } return QVariant(); } // progress if (account->repositoryCount() <= 0) { switch (role) { case Qt::DisplayRole: return tr("Connecting"); case Qt::DecorationRole: return account->progress()->value(); case Qt::FontRole: { QFont font = static_cast<QWidget *>(QObject::parent())->font(); font.setItalic(true); return font; } default: return QVariant(); } } // repo int row = index.row(); Repository *repo = account->repository(row); switch (role) { case Qt::DisplayRole: return mShowFullName ? repo->fullName() : repo->name(); case Qt::DecorationRole: { QString path = account->repositoryPath(row); return path.isEmpty() ? QIcon(kCloudIcon) : QIcon(); } case KindRole: return account->kind(); case RepositoryRole: return QVariant::fromValue(repo); } return QVariant(); } Qt::ItemFlags flags(const QModelIndex &index) const override { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (Accounts::instance()->count() <= 0) flags &= ~Qt::ItemIsSelectable; return flags; } private: bool mShowFullName = false; QIcon mErrorIcon; }; class ProgressDelegate : public QStyledItemDelegate { public: ProgressDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {} void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); // Draw background. QStyledItemDelegate::paint(painter, opt, index); // Draw busy indicator. QVariant progress = index.data(Qt::DecorationRole); if (!progress.canConvert<int>()) return; QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); QStyle::SubElement se = QStyle::SE_ItemViewItemDecoration; QRect rect = style->subElementRect(se, &opt, opt.widget); ProgressIndicator::paint(painter, rect, "#808080", progress.toInt()); } protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override { QStyledItemDelegate::initStyleOption(option, index); if (index.data(Qt::DecorationRole).canConvert<int>()) { option->decorationSize = ProgressIndicator::size(); } else if (index.data(RepositoryRole).isValid()) { option->features |= QStyleOptionViewItem::HasDecoration; option->decorationSize = QSize(20, 20); } } }; } // namespace StartDialog::StartDialog(QWidget *parent) : QDialog(parent) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Choose Repository")); QIcon icon(":/Gittyup.iconset/icon_128x128.png"); IconLabel *iconLabel = new IconLabel(icon, 128, 128, this); QIcon title(":/logo-type_light@2x.png"); IconLabel *titleLabel = new IconLabel(title, 163, 38, this); QString subtitleText = kSubtitleFmt.arg(tr("Understand your history!")); QLabel *subtitle = new QLabel(subtitleText, this); subtitle->setAlignment(Qt::AlignHCenter); QVBoxLayout *left = new QVBoxLayout; left->addWidget(iconLabel); left->addWidget(titleLabel); left->addWidget(subtitle); left->addStretch(); mRepoList = new QListView(this); mRepoList->setIconSize(QSize(32, 32)); mRepoList->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(mRepoList, &QListView::clicked, this, [this](const QModelIndex &index) { if (!index.data(Qt::UserRole).isValid()) { switch (index.row()) { case RepoModel::Clone: mClone->trigger(); break; case RepoModel::Open: mOpen->trigger(); break; case RepoModel::Init: mInit->trigger(); break; } } }); connect(mRepoList, &QListView::doubleClicked, this, &QDialog::accept); RepoModel *repoModel = new RepoModel(mRepoList); mRepoList->setModel(repoModel); connect(repoModel, &RepoModel::modelReset, this, [this] { mRepoList->setCurrentIndex(mRepoList->model()->index(0, 0)); }); mRepoFooter = new Footer(mRepoList); connect(mRepoFooter, &Footer::minusClicked, this, [this] { // Sort selection in reverse order. QModelIndexList indexes = mRepoList->selectionModel()->selectedIndexes(); std::sort(indexes.begin(), indexes.end(), [](const QModelIndex &lhs, const QModelIndex &rhs) { return rhs.row() < lhs.row(); }); // Remove selected indexes from settings. foreach (const QModelIndex &index, indexes) RecentRepositories::instance()->remove(index.row()); }); QMenu *repoPlusMenu = new QMenu(this); mRepoFooter->setPlusMenu(repoPlusMenu); mClone = repoPlusMenu->addAction(tr("Clone Repository")); connect(mClone, &QAction::triggered, this, [this] { CloneDialog *dialog = new CloneDialog(CloneDialog::Clone, this); connect(dialog, &CloneDialog::accepted, this, [this, dialog] { if (MainWindow *window = openWindow(dialog->path())) window->currentView()->addLogEntry(dialog->message(), dialog->messageTitle()); }); dialog->open(); }); mOpen = repoPlusMenu->addAction(tr("Open Existing Repository")); connect(mOpen, &QAction::triggered, this, [this] { // FIXME: Filter out non-git dirs. QFileDialog *dialog = new QFileDialog(this, tr("Open Repository"), QDir::homePath()); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setFileMode(QFileDialog::Directory); dialog->setOption(QFileDialog::ShowDirsOnly); connect(dialog, &QFileDialog::fileSelected, this, &StartDialog::openWindow); dialog->open(); }); mInit = repoPlusMenu->addAction(tr("Initialize New Repository")); connect(mInit, &QAction::triggered, this, [this] { CloneDialog *dialog = new CloneDialog(CloneDialog::Init, this); connect(dialog, &CloneDialog::accepted, this, [this, dialog] { if (MainWindow *window = openWindow(dialog->path())) window->currentView()->addLogEntry(dialog->message(), dialog->messageTitle()); }); dialog->open(); }); QMenu *repoContextMenu = new QMenu(this); mRepoFooter->setContextMenu(repoContextMenu); QAction *clear = repoContextMenu->addAction(tr("Clear All")); connect(clear, &QAction::triggered, [] { RecentRepositories::instance()->clear(); }); QSettings settings; QAction *showFullPath = repoContextMenu->addAction(tr("Show Full Path")); bool recentChecked = settings.value("start/recent/fullpath").toBool(); showFullPath->setCheckable(true); showFullPath->setChecked(recentChecked); repoModel->setShowFullPath(recentChecked); connect(showFullPath, &QAction::triggered, this, [repoModel](bool checked) { QSettings().setValue("start/recent/fullpath", checked); repoModel->setShowFullPath(checked); }); QAction *filter = repoContextMenu->addAction(tr("Filter Non-existent Paths")); filter->setCheckable(true); filter->setChecked(settings.value("recent/filter", true).toBool()); connect(filter, &QAction::triggered, [](bool checked) { QSettings().setValue("recent/filter", checked); }); QVBoxLayout *middle = new QVBoxLayout; middle->setSpacing(0); middle->addWidget(new QLabel(tr("Repositories:"), this)); middle->addSpacing(8); // FIXME: Query style? middle->addWidget(mRepoList); middle->addWidget(mRepoFooter); mHostTree = new QTreeView(this); mHostTree->setHeaderHidden(true); mHostTree->setExpandsOnDoubleClick(false); mHostTree->setIconSize(QSize(32, 32)); mHostTree->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(mHostTree, &QTreeView::clicked, this, [this](const QModelIndex &index) { int rows = mHostTree->model()->rowCount(index); if (!rows && !index.data(RepositoryRole).isValid()) edit(index); }); connect(mHostTree, &QTreeView::doubleClicked, this, [this](const QModelIndex &index) { QModelIndex parent = index.parent(); if (parent.isValid()) { Account *account = parent.data(AccountRole).value<Account *>(); if (!account->repositoryPath(index.row()).isEmpty()) { accept(); return; } } edit(index); }); HostModel *hostModel = new HostModel(style(), mHostTree); mHostTree->setModel(hostModel); connect(hostModel, &QAbstractItemModel::modelReset, this, [this] { QModelIndex index = mHostTree->model()->index(0, 0); mHostTree->setRootIsDecorated(index.data(AccountRole).isValid()); mHostTree->expandAll(); }); mHostTree->setItemDelegate(new ProgressDelegate(this)); mHostFooter = new Footer(mHostTree); connect(mHostFooter, &Footer::plusClicked, this, [this] { edit(); }); connect(mHostFooter, &Footer::minusClicked, this, &StartDialog::remove); QMenu *hostContextMenu = new QMenu(this); mHostFooter->setContextMenu(hostContextMenu); QAction *refresh = hostContextMenu->addAction(tr("Refresh")); connect(refresh, &QAction::triggered, this, [] { Accounts *accounts = Accounts::instance(); for (int i = 0; i < accounts->count(); ++i) accounts->account(i)->connect(); }); QAction *showFullName = hostContextMenu->addAction(tr("Show Full Name")); bool remoteChecked = QSettings().value("start/remote/fullname").toBool(); showFullName->setCheckable(true); showFullName->setChecked(remoteChecked); hostModel->setShowFullName(remoteChecked); connect(showFullName, &QAction::triggered, this, [hostModel](bool checked) { QSettings().setValue("start/remote/fullname", checked); hostModel->setShowFullName(checked); }); // Clear the other list when this selection changes. QItemSelectionModel *repoSelModel = mRepoList->selectionModel(); connect(repoSelModel, &QItemSelectionModel::selectionChanged, this, [this] { if (!mRepoList->selectionModel()->selectedIndexes().isEmpty()) mHostTree->clearSelection(); updateButtons(); }); // Clear the other list when this selection changes. QItemSelectionModel *hostSelModel = mHostTree->selectionModel(); connect(hostSelModel, &QItemSelectionModel::selectionChanged, this, [this] { if (!mHostTree->selectionModel()->selectedIndexes().isEmpty()) mRepoList->clearSelection(); updateButtons(); }); QVBoxLayout *right = new QVBoxLayout; right->setSpacing(0); right->addWidget(new QLabel(tr("Remote:"), this)); right->addSpacing(8); // FIXME: Query style? right->addWidget(mHostTree); right->addWidget(mHostFooter); QHBoxLayout *top = new QHBoxLayout; top->addLayout(left); top->addSpacing(12); top->addLayout(middle); top->addSpacing(12); top->addLayout(right); QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Open | QDialogButtonBox::Cancel; mButtonBox = new QDialogButtonBox(buttons, this); connect(mButtonBox, &QDialogButtonBox::accepted, this, &StartDialog::accept); connect(mButtonBox, &QDialogButtonBox::rejected, this, &StartDialog::reject); QString text = tr("View Getting Started Video"); QPushButton *help = mButtonBox->addButton(text, QDialogButtonBox::ResetRole); connect(help, &QPushButton::clicked, [] { QDesktopServices::openUrl(QUrl("https://gitahead.com/#tutorials")); }); QVBoxLayout *layout = new QVBoxLayout(this); layout->addLayout(top); layout->addWidget(mButtonBox); } void StartDialog::accept() { QModelIndexList repoIndexes = mRepoList->selectionModel()->selectedIndexes(); QModelIndexList hostIndexes = mHostTree->selectionModel()->selectedIndexes(); QStringList paths; foreach (const QModelIndex &index, repoIndexes) paths.append(index.data(Qt::UserRole).toString()); QModelIndexList uncloned; foreach (const QModelIndex &index, hostIndexes) { QModelIndex parent = index.parent(); if (parent.isValid()) { Account *account = parent.data(AccountRole).value<Account *>(); QString path = account->repositoryPath(index.row()); if (path.isEmpty()) { uncloned.append(index); } else { paths.append(path); } } } // Clone the first repo. if (!uncloned.isEmpty()) { edit(uncloned.first()); return; } // FIXME: Fail if none of the windows were able to be opened? QDialog::accept(); if (paths.isEmpty()) return; // Open a new window for the first valid repo. MainWindow *window = MainWindow::open(paths.takeFirst()); while (!window && !paths.isEmpty()) window = MainWindow::open(paths.takeFirst()); if (!window) return; // Add the remainder as tabs. foreach (const QString &path, paths) window->addTab(path); } StartDialog *StartDialog::openSharedInstance() { static QPointer<StartDialog> dialog; if (dialog) { dialog->show(); dialog->raise(); dialog->activateWindow(); return dialog; } dialog = new StartDialog; dialog->show(); return dialog; } void StartDialog::showEvent(QShowEvent *event) { // Restore geometry. QSettings settings; settings.beginGroup(kStartGroup); if (settings.contains(kGeometryKey)) restoreGeometry(settings.value(kGeometryKey).toByteArray()); settings.endGroup(); QDialog::showEvent(event); } void StartDialog::hideEvent(QHideEvent *event) { QSettings settings; settings.beginGroup(kStartGroup); settings.setValue(kGeometryKey, saveGeometry()); settings.endGroup(); QDialog::hideEvent(event); } void StartDialog::updateButtons() { QModelIndexList repoIndexes = mRepoList->selectionModel()->selectedIndexes(); QModelIndexList hostIndexes = mHostTree->selectionModel()->selectedIndexes(); // Update dialog Open button. bool clone = false; QPushButton *open = mButtonBox->button(QDialogButtonBox::Open); open->setEnabled(!repoIndexes.isEmpty() || !hostIndexes.isEmpty()); foreach (const QModelIndex &index, hostIndexes) { QModelIndex parent = index.parent(); if (!parent.isValid()) { open->setEnabled(false); } else { Account *account = parent.data(AccountRole).value<Account *>(); if (Repository *repo = index.data(RepositoryRole).value<Repository *>()) { if (account->repositoryPath(index.row()).isEmpty()) clone = true; } else { open->setEnabled(false); } } } open->setText((clone && open->isEnabled()) ? tr("Clone") : tr("Open")); // Update repo list footer buttons. mRepoFooter->setMinusEnabled(!repoIndexes.isEmpty()); // Update host list footer buttons. mHostFooter->setMinusEnabled(false); if (!hostIndexes.isEmpty()) { QModelIndex index = hostIndexes.first(); Account *account = index.data(AccountRole).value<Account *>(); QString repoPath; QModelIndex parent = index.parent(); if (parent.isValid()) { Account *account = parent.data(AccountRole).value<Account *>(); repoPath = account->repositoryPath(index.row()); } mHostFooter->setMinusEnabled(account || !repoPath.isEmpty()); } } void StartDialog::edit(const QModelIndex &index) { // account if (!index.isValid() || !index.parent().isValid()) { Account *account = nullptr; if (index.isValid()) account = index.data(AccountRole).value<Account *>(); AccountDialog *dialog = new AccountDialog(account, this); if (!account && index.isValid()) dialog->setKind(index.data(KindRole).value<Account::Kind>()); dialog->open(); return; } // repo Repository *repo = index.data(RepositoryRole).value<Repository *>(); if (!repo) return; CloneDialog *dialog = new CloneDialog(CloneDialog::Clone, this, repo); connect(dialog, &CloneDialog::accepted, this, [this, index, dialog] { // Set local path. Account *account = Accounts::instance()->account(index.parent().row()); account->setRepositoryPath(index.row(), dialog->path()); // Open the repo. QCoreApplication::processEvents(); accept(); }); dialog->open(); } void StartDialog::remove() { QModelIndexList indexes = mHostTree->selectionModel()->selectedIndexes(); Q_ASSERT(!indexes.isEmpty()); // account QModelIndex index = indexes.first(); if (!index.parent().isValid()) { Account::Kind kind = index.data(KindRole).value<Account::Kind>(); QString name = index.data(Qt::DisplayRole).toString(); QString fmt = tr("<p>Are you sure you want to remove the %1 account for '%2'?</p>" "<p>Only the account association will be removed. Remote " "configurations and local clones will not be affected.</p>"); QMessageBox mb(QMessageBox::Warning, tr("Remove Account?"), fmt.arg(Account::name(kind), name), QMessageBox::Cancel, this); QPushButton *remove = mb.addButton(tr("Remove"), QMessageBox::AcceptRole); remove->setFocus(); mb.exec(); if (mb.clickedButton() == remove) { mHostTree->clearSelection(); Accounts::instance()->removeAccount(index.row()); } return; } // repo Repository *repo = index.data(RepositoryRole).value<Repository *>(); QString fmt = tr("<p>Are you sure you want to remove the remote repository association " "for %1?</p><p>The local clone itself will not be affected.</p>"); QMessageBox mb(QMessageBox::Warning, tr("Remove Repository Association?"), fmt.arg(repo->fullName()), QMessageBox::Cancel, this); QPushButton *remove = mb.addButton(tr("Remove"), QMessageBox::AcceptRole); remove->setFocus(); mb.exec(); if (mb.clickedButton() == remove) repo->account()->setRepositoryPath(index.row(), QString()); // Update minus and OK buttons. updateButtons(); } MainWindow *StartDialog::openWindow(const QString &repo) { // This dialog has to be hidden before opening another window so that it // doesn't automatically move to a position that still shows the dialog. hide(); if (MainWindow *window = MainWindow::open(repo)) { // Dismiss this dialog without trying to open the selection. reject(); return window; } else { show(); } return nullptr; } #include "StartDialog.moc"
31.863855
80
0.653609
mmahmoudian
0504fab6ccb4f2f2895ac3ac5c9ac2bebc8e4d0b
1,414
cpp
C++
n48.cpp
paolaguarasci/domJudge
830f5ca3f271732668930a2a8d3be98d96661691
[ "MIT" ]
null
null
null
n48.cpp
paolaguarasci/domJudge
830f5ca3f271732668930a2a8d3be98d96661691
[ "MIT" ]
null
null
null
n48.cpp
paolaguarasci/domJudge
830f5ca3f271732668930a2a8d3be98d96661691
[ "MIT" ]
null
null
null
/* 1 3 2 6 1 4 5 5 9 2 3 79 3 -5 */ #include <iostream> using namespace std; void leggo(int n[], int& dim); void seqCrescente(int [], int, int&, int&); int main() { int n[100]; int dim = 0; int lunghezzaSeq; int lmax, imax; leggo(n, dim); if (dim > 0) { seqCrescente(n, dim, imax, lmax); // cout << "lmax: " << lmax << " imax: " << imax; for (int i = imax; i < lmax + imax; i++) { cout << n[i]; } cout << endl << lmax; } else { cout << "Empty"; } return 0; } void leggo(int n[], int& dim) { int num; cin >> num; for (int i = 0; num >= 0; i++) { n[i] = num; cin >> num; dim++; } } void seqCrescente(int seq[], int dim, int& indiceMax, int& lmax) { int tab[100][2] = {1}; // array x * 2 con gli indici e le lunghezze delle sequenze crescenti int index = 0, lung = 0, j = 0; // trovo tutte le sequenza crescenti for (int i = 1; i < dim; i++) { if (seq[i] >= seq[i-1]) { tab[j][0]++; } else { tab[++j][1] = i; tab[j][0] = 1; } } // tra le sequenze crescenti trovo la sequenza più lunga lmax = tab[0][0]; indiceMax = 0; for(int i = 1; i <= j; i++) { // cout << "indice: " << tab[i][1] << " lunghezze: " << tab[i][0] << endl; if (tab[i][0] > lmax) { indiceMax = tab[i][1]; lmax = tab[i][0]; } } }
21.104478
95
0.466761
paolaguarasci
0507f73370ad0aee2ca09d0410ab0f0e2bb54435
15,227
cpp
C++
src/mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.cpp
Tokutek/tokumxse
9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d
[ "Apache-2.0" ]
29
2015-01-13T02:34:23.000Z
2022-01-30T16:57:10.000Z
src/mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.cpp
Tokutek/tokumxse
9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d
[ "Apache-2.0" ]
null
null
null
src/mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.cpp
Tokutek/tokumxse
9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d
[ "Apache-2.0" ]
12
2015-01-24T08:40:28.000Z
2017-10-04T17:23:39.000Z
// kv_dictionary_test_harness.cpp /*====== This file is part of Percona Server for MongoDB. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. Percona Server for MongoDB is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Percona Server for MongoDB 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Percona Server for MongoDB. If not, see <http://www.gnu.org/licenses/>. ======= */ #include <algorithm> #include <vector> #include <boost/scoped_ptr.hpp> #include "mongo/db/storage/kv/dictionary/kv_dictionary.h" #include "mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.h" #include "mongo/db/storage/kv/slice.h" #include "mongo/unittest/unittest.h" namespace mongo { using boost::scoped_ptr; TEST( KVDictionary, Simple1 ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); { const Slice hi = Slice::of("hi"); const Slice there = Slice::of("there"); scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); Status status = db->insert( opCtx.get(), hi, there, false ); ASSERT( status.isOK() ); status = db->get( opCtx.get(), hi, value ); ASSERT( status.isOK() ); status = db->remove( opCtx.get(), hi ); ASSERT( status.isOK() ); status = db->get( opCtx.get(), hi, value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); uow.commit(); } } } TEST( KVDictionary, Simple2 ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const Slice hi = Slice::of("hi"); const Slice there = Slice::of("there"); const Slice apple = Slice::of("apple"); const Slice bears = Slice::of("bears"); { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); Status status = db->insert( opCtx.get(), hi, there, false ); ASSERT( status.isOK() ); uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); Status status = db->insert( opCtx.get(), apple, bears, false ); ASSERT( status.isOK() ); uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; Status status = db->get( opCtx.get(), hi, value ); ASSERT( status.isOK() ); ASSERT( value.size() == 6 ); ASSERT( std::string( "there" ) == std::string( value.data() ) ); } { Slice value; Status status = db->get( opCtx.get(), apple, value ); ASSERT( status.isOK() ); ASSERT( value.size() == 6 ); ASSERT( std::string( "bears" ) == std::string( value.data() ) ); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); Status status = db->remove( opCtx.get(), hi ); ASSERT( status.isOK() ); uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; Status status = db->get( opCtx.get(), hi, value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); } { Slice value; Status status = db->get( opCtx.get(), apple, value ); ASSERT( status.isOK() ); ASSERT( value.size() == 6 ); ASSERT( std::string( "bears" ) == std::string( value.data() ) ); } { WriteUnitOfWork uow( opCtx.get() ); Status status = db->remove( opCtx.get(), apple ); ASSERT( status.isOK() ); uow.commit(); } { Slice value; Status status = db->get( opCtx.get(), apple, value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); } } } TEST( KVDictionary, InsertSerialGetSerial ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(i); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { for (unsigned char i = 0; i < nKeys; i++) { Slice value; Status status = db->get( opCtx.get(), Slice::of(i), value ); ASSERT( status.isOK() ); ASSERT( value.as<unsigned char>() == i ); } } } } static int _rng(int i) { return std::rand() % i; } TEST( KVDictionary, InsertRandomGetSerial ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; { std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } std::srand(unsigned(time(0))); std::random_shuffle(keys.begin(), keys.end(), _rng); scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; for (unsigned char i = 0; i < nKeys; i++) { Status status = db->get( opCtx.get(), Slice::of(i), value ); ASSERT( status.isOK() ); ASSERT( value.as<unsigned char>() == i ); } } } } TEST( KVDictionary, InsertRandomCursor ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; { std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } std::srand(unsigned(time(0))); std::random_shuffle(keys.begin(), keys.end(), _rng); scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; const int direction = 1; unsigned char i = 0; for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction)); c->ok(); c->advance(opCtx.get()), i++) { ASSERT( c->currKey().as<unsigned char>() == i ); ASSERT( c->currVal().as<unsigned char>() == i ); } } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; const int direction = -1; unsigned char i = nKeys - 1; for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction)); c->ok(); c->advance(opCtx.get()), i--) { ASSERT( c->currKey().as<unsigned char>() == i ); ASSERT( c->currVal().as<unsigned char>() == i ); } } } } TEST( KVDictionary, InsertDeleteCursor ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } std::srand(unsigned(time(0))); std::random_shuffle(keys.begin(), keys.end(), _rng); std::set<unsigned char> remainingKeys; std::set<unsigned char> deletedKeys; { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { unsigned char k = keys[i]; if (i < (nKeys / 2)) { Status status = db->remove( opCtx.get(), Slice::of(k) ); ASSERT( status.isOK() ); deletedKeys.insert(k); } else { remainingKeys.insert(k); } } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { const int direction = 1; unsigned char i = 0; for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction)); c->ok(); c->advance(opCtx.get()), i++) { unsigned char k = c->currKey().as<unsigned char>(); ASSERT( remainingKeys.count(k) == 1 ); ASSERT( deletedKeys.count(k) == 0 ); ASSERT( k == c->currVal().as<unsigned char>() ); remainingKeys.erase(k); } ASSERT( remainingKeys.empty() ); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { for (std::set<unsigned char>::const_iterator it = deletedKeys.begin(); it != deletedKeys.end(); it++) { unsigned char k = *it; Slice value; Status status = db->get( opCtx.get(), Slice::of(k), value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); ASSERT( value.size() == 0 ); } } } } TEST( KVDictionary, CursorSeekForward ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 101; // even number makes the test magic more complicated std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i += 2) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), 1 ) ); for (unsigned char i = 0; i < nKeys; i++) { cursor->seek( opCtx.get(), Slice::of(keys[i]) ); if ( i % 2 == 0 ) { ASSERT( cursor->currKey().as<unsigned char>() == i ); } else if ( i + 1 < nKeys ) { ASSERT( cursor->currKey().as<unsigned char>() == i + 1); } } } { scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), -1 ) ); for (unsigned char i = 1; i < nKeys; i++) { cursor->seek(opCtx.get(), Slice::of(keys[i])); if ( i % 2 == 0 ) { ASSERT( cursor->currKey().as<unsigned char>() == i ); } else { ASSERT( cursor->currKey().as<unsigned char>() == i - 1 ); } } } } } }
36.691566
95
0.481185
Tokutek
050cd93c7d069c1c46eabe25f58e16e30122a096
283
cc
C++
src/connectivity/overnet/lib/testing/flags.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
src/connectivity/overnet/lib/testing/flags.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
5
2020-09-06T09:02:06.000Z
2022-03-02T04:44:22.000Z
src/connectivity/overnet/lib/testing/flags.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 "src/connectivity/overnet/lib/testing/flags.h" DEFINE_bool(verbose, false, "Enable debug output in tests");
35.375
73
0.763251
zhangpf
050d721206e4519191d0c811903692239025a720
818
cpp
C++
leetcode/cpp/qt_remove_duplicates_from_sorted_array_ii.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_remove_duplicates_from_sorted_array_ii.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_remove_duplicates_from_sorted_array_ii.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/* Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. */ class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size() < 3) return nums.size(); int triple = 1; int res = 1; for(auto it = nums.begin()+1; it != nums.end();) { if(*it == *(it-1)) triple++; else triple = 1; if(triple >= 3) { nums.erase(it); triple = 2; continue; } res++; it++; } return res; } };
24.787879
156
0.503667
qiaotian
05136b7873a9835615730523a238a27a82c65822
179
cpp
C++
Zelig/Zelig/Test/LlilumWin32/LlilumWin32.cpp
NETMF/llilum
7ac7669fe205572e8b572b4f3697e5f802e574be
[ "MIT" ]
188
2015-07-08T21:13:28.000Z
2022-01-01T09:29:33.000Z
Zelig/Zelig/Test/LlilumWin32/LlilumWin32.cpp
lt72/llilum
7ac7669fe205572e8b572b4f3697e5f802e574be
[ "MIT" ]
239
2015-07-10T00:48:20.000Z
2017-09-21T14:04:58.000Z
Zelig/Zelig/Test/LlilumWin32/LlilumWin32.cpp
lt72/llilum
7ac7669fe205572e8b572b4f3697e5f802e574be
[ "MIT" ]
73
2015-07-09T21:02:42.000Z
2022-01-01T09:31:26.000Z
// LlilumWin32.cpp : Defines the entry point for the console application. // #include "stdafx.h" extern int LlosWin32_Main(void); int main() { return LlosWin32_Main(); }
13.769231
73
0.703911
NETMF
05136de571cc809415de1f2c8797dae229842f3c
6,219
hh
C++
src/outlinerindexedmesh.hh
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
4
2021-09-02T16:52:23.000Z
2022-02-07T16:39:50.000Z
src/outlinerindexedmesh.hh
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
87
2021-09-12T06:09:57.000Z
2022-02-15T00:05:43.000Z
src/outlinerindexedmesh.hh
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
1
2021-09-28T21:38:30.000Z
2021-09-28T21:38:30.000Z
/////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // // CCC AAA V V EEEEE OOO UU UU TTTTTT LL II NN NN EEEEE RRRRR // CC CC AA AA V V EE OO OO UU UU TT LL II NNN NN EE RR RR // CC AA AA V V EEE OO OO UU UU TT LL II NN N NN EEE RRRRR // CC CC AAAAAA V V EE OO OO UU UU TT LL II NN NNN EE RR R // CCc AA AA V EEEEE OOO UUUUU TT LLLLL II NN NN EEEEE RR R // // CAVE OUTLINER -- Cave 3D model processing software // // Copyright (C) 2021 by Jari Arkko -- See LICENSE.txt for license information. // /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #ifndef INDEXEDMESH_HH #define INDEXEDMESH_HH /////////////////////////////////////////////////////////////////////////////////////////////// // Includes /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "outlinertypes.hh" #include "outlinerconstants.hh" #include "outlinerdirection.hh" /////////////////////////////////////////////////////////////////////////////////////////////// // Internal data types //////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// struct IndexedMeshOneMeshOneTileFaces { unsigned int nFaces; unsigned int maxNFaces; const aiFace** faces; }; struct IndexedMeshOneMesh { const aiMesh* mesh; unsigned int nOutsideModelBoundingBox; struct IndexedMeshOneMeshOneTileFaces** tileMatrix; }; /////////////////////////////////////////////////////////////////////////////////////////////// // Class interface //////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /// /// This object represents an optimized index to the mesh faces /// contained in an imported 3D model. The imported model has a large /// datastructure of 'faces' -- typically millions or even tens of /// millions of faces. There is no efficient way to search for faces /// at a given location in the 3D or 2D space, however. The indexed /// mesh object sorts the faces into a 2D matrix of 'tiles'. For /// instance, a large model could be split into 20x20 or 400 tiles, so /// that when we are looking for a face within given (x,y) /// coordinates, we only need to look at the tile where (x,y) falls /// into. The indexing is performed only once, and all searches after /// the indexing operation can use the more efficient search. /// class IndexedMesh { public: /// Create an IndexedMesh object. IndexedMesh(unsigned int maxMeshesIn, unsigned int subdivisionsIn, const OutlinerBox3D& modelBoundingBox, const OutlinerBox2D& viewBoundingBox, enum outlinerdirection directionIn); /// Add a 3D scene to the optimized index. void addScene(const aiScene* scene); /// Add a 3D node to the optimized index. void addNode(const aiScene* scene, const aiNode* node); /// Add a 3D mesh to the optimized index. void addMesh(const aiScene* scene, const aiMesh* mesh); /// Quickly get faces associated with a given (x,y) point in the plan view. void getFaces(const aiMesh* mesh, outlinerreal x, outlinerreal y, unsigned int* p_nFaces, const aiFace*** p_faces); /// Print information about the contents of the mesh void describe(std::ostream& stream); /// Release all resources associated with the index. ~IndexedMesh(); private: unsigned int nMeshes; unsigned int maxMeshes; unsigned int subdivisions; OutlinerBox3D modelBoundingBox; OutlinerBox2D viewBoundingBox; enum outlinerdirection direction; outlinerreal tileSizeX; outlinerreal tileSizeY; struct IndexedMeshOneMesh* meshes; void addFaces(struct IndexedMeshOneMesh& shadow, const aiScene* scene, const aiMesh* mesh); void addFace(struct IndexedMeshOneMesh& shadow, const aiScene* scene, const aiMesh* mesh, const aiFace* face); void addToTile(struct IndexedMeshOneMesh& shadow, const aiScene* scene, const aiMesh* mesh, const aiFace* face, unsigned int tileX, unsigned int tileY); void getFacesTile(struct IndexedMeshOneMesh& shadow, const aiMesh* mesh, unsigned int tileX, unsigned int tileY, unsigned int* p_nFaces, const aiFace*** p_faces); void coordsToTile(outlinerreal x, outlinerreal y, unsigned int& tileX, unsigned int& tileY); void getShadow(const aiMesh* mesh, struct IndexedMeshOneMesh** shadow); unsigned int minFacesPerTile(struct IndexedMeshOneMesh& shadow, unsigned int& n); unsigned int maxFacesPerTile(struct IndexedMeshOneMesh& shadow, unsigned int& n); float avgFacesPerTile(struct IndexedMeshOneMesh& shadow); unsigned int countTilesWithFaces(struct IndexedMeshOneMesh& shadow); void countFaces(struct IndexedMeshOneMesh& shadow, unsigned int& nUniqueFaces, unsigned int& nFacesInTiles); }; #endif // INDEXEDMESH_HH
40.914474
95
0.49397
jariarkko
0518a93e88fa4fffa5d9b5458c47a279399e0780
12,963
cpp
C++
src/frontend/prettyprint/PrettyPrinter.cpp
WilliamHaslet/tip-compiler-extensions-project
4ad8a91b8eca50b58cc194b36fcd336898c6b9b3
[ "MIT" ]
null
null
null
src/frontend/prettyprint/PrettyPrinter.cpp
WilliamHaslet/tip-compiler-extensions-project
4ad8a91b8eca50b58cc194b36fcd336898c6b9b3
[ "MIT" ]
null
null
null
src/frontend/prettyprint/PrettyPrinter.cpp
WilliamHaslet/tip-compiler-extensions-project
4ad8a91b8eca50b58cc194b36fcd336898c6b9b3
[ "MIT" ]
null
null
null
#include "PrettyPrinter.h" #include <iostream> #include <sstream> void PrettyPrinter::print(ASTProgram *p, std::ostream &os, char c, int n) { PrettyPrinter visitor(os, c, n); p->accept(&visitor); } void PrettyPrinter::endVisit(ASTProgram * element) { std::string programString = ""; bool skip = true; for (auto &fn : element->getFunctions()) { if (skip) { programString = visitResults.back() + programString; visitResults.pop_back(); skip = false; continue; } programString = visitResults.back() + "\n" + programString; visitResults.pop_back(); } os << programString; os.flush(); } /* * General approach taken by visit methods. * - visit() is used to increase indentation (decrease should happen in endVisit). * - endVisit() should expect a string for all of its AST nodes in reverse order in visitResults. * Communicate the single string for the visited node by pushing to the back of visitedResults. */ /* * Before visiting function, record string for signature and setup indentation for body. * This visit method pushes a string result, that the endVisit method should extend. */ bool PrettyPrinter::visit(ASTFunction * element) { indentLevel++; return true; } /* * After visiting function, collect the string representations for the: * statements, declarations, formals, and then function name * they are on the visit stack in that order. */ void PrettyPrinter::endVisit(ASTFunction * element) { std::string bodyString = ""; for (auto &stmt : element->getStmts()) { bodyString = visitResults.back() + "\n" + bodyString; visitResults.pop_back(); } for (auto &decl : element->getDeclarations()) { bodyString = visitResults.back() + "\n" + bodyString; visitResults.pop_back(); } std::string formalsString = ""; bool skip = true; for(auto &formal : element->getFormals()) { if (skip) { formalsString = visitResults.back() + formalsString; visitResults.pop_back(); skip = false; continue; } formalsString = visitResults.back() + ", " + formalsString; visitResults.pop_back(); } // function name is last element on stack std::string functionString = visitResults.back(); visitResults.pop_back(); functionString += "(" + formalsString + ") \n{\n" + bodyString + "}\n"; indentLevel--; visitResults.push_back(functionString); } void PrettyPrinter::endVisit(ASTNumberExpr * element) { visitResults.push_back(std::to_string(element->getValue())); } void PrettyPrinter::endVisit(ASTVariableExpr * element) { visitResults.push_back(element->getName()); } void PrettyPrinter::endVisit(ASTBinaryExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + leftString + " " + element->getOp() + " " + rightString + ")"); } void PrettyPrinter::endVisit(ASTInputExpr * element) { visitResults.push_back("input"); } void PrettyPrinter::endVisit(ASTFunAppExpr * element) { std::string funAppString; /* * Skip printing of comma separator for last arg. */ std::string actualsString = ""; bool skip = true; for (auto &arg : element->getActuals()) { if (skip) { actualsString = visitResults.back() + actualsString; visitResults.pop_back(); skip = false; continue; } actualsString = visitResults.back() + ", " + actualsString; visitResults.pop_back(); } funAppString = visitResults.back() + "(" + actualsString + ")"; visitResults.pop_back(); visitResults.push_back(funAppString); } void PrettyPrinter::endVisit(ASTAllocExpr * element) { std::string init = visitResults.back(); visitResults.pop_back(); visitResults.push_back("alloc " + init); } void PrettyPrinter::endVisit(ASTRefExpr * element) { std::string var = visitResults.back(); visitResults.pop_back(); visitResults.push_back("&" + var); } void PrettyPrinter::endVisit(ASTDeRefExpr * element) { std::string base = visitResults.back(); visitResults.pop_back(); visitResults.push_back("*" + base); } void PrettyPrinter::endVisit(ASTNullExpr * element) { visitResults.push_back("null"); } void PrettyPrinter::endVisit(ASTFieldExpr * element) { std::string init = visitResults.back(); visitResults.pop_back(); visitResults.push_back(element->getField() + ":" + init); } void PrettyPrinter::endVisit(ASTRecordExpr * element) { /* * Skip printing of comma separator for last record element. */ std::string fieldsString = ""; bool skip = true; for (auto &f : element->getFields()) { if (skip) { fieldsString = visitResults.back() + fieldsString; visitResults.pop_back(); skip = false; continue; } fieldsString = visitResults.back() + ", " + fieldsString; visitResults.pop_back(); } std::string recordString = "{" + fieldsString + "}"; visitResults.push_back(recordString); } void PrettyPrinter::endVisit(ASTAccessExpr * element) { std::string accessString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(accessString + '.' + element->getField()); } void PrettyPrinter::endVisit(ASTDeclNode * element) { visitResults.push_back(element->getName()); } void PrettyPrinter::endVisit(ASTDeclStmt * element) { std::string declString = ""; bool skip = true; for (auto &id : element->getVars()) { if (skip) { declString = visitResults.back() + declString; visitResults.pop_back(); skip = false; continue; } declString = visitResults.back() + ", " + declString; visitResults.pop_back(); } declString = indent() + "var " + declString + ";"; visitResults.push_back(declString); } void PrettyPrinter::endVisit(ASTAssignStmt * element) { std::string rhsString = visitResults.back(); visitResults.pop_back(); std::string lhsString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + lhsString + " = " + rhsString + ";"); } bool PrettyPrinter::visit(ASTBlockStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTBlockStmt * element) { std::string stmtsString = ""; for (auto &s : element->getStmts()) { stmtsString = visitResults.back() + "\n" + stmtsString; visitResults.pop_back(); } indentLevel--; std::string blockString = indent() + "{\n" + stmtsString + indent() + "}"; visitResults.push_back(blockString); } /* * For a while the body should be indented, but not the condition. * Since conditions are expressions and their visit methods never indent * incrementing here works. */ bool PrettyPrinter::visit(ASTWhileStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTWhileStmt * element) { std::string bodyString = visitResults.back(); visitResults.pop_back(); std::string condString = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string whileString = indent() + "while (" + condString + ") \n" + bodyString; visitResults.push_back(whileString); } bool PrettyPrinter::visit(ASTIfStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTIfStmt * element) { std::string elseString; if (element->getElse() != nullptr) { elseString = visitResults.back(); visitResults.pop_back(); } std::string thenString = visitResults.back(); visitResults.pop_back(); std::string condString = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string ifString = indent() + "if (" + condString + ") \n" + thenString; if (element->getElse() != nullptr) { ifString += "\n" + indent() + "else\n" + elseString; } visitResults.push_back(ifString); } void PrettyPrinter::endVisit(ASTOutputStmt * element) { std::string argString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + "output " + argString + ";"); } void PrettyPrinter::endVisit(ASTErrorStmt * element) { std::string argString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + "error " + argString + ";"); } void PrettyPrinter::endVisit(ASTReturnStmt * element) { std::string argString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + "return " + argString + ";"); } void PrettyPrinter::endVisit(ASTArrayExpr * element) { /* * Skip printing of comma separator for last array element. */ std::string entriesString = ""; bool skip = true; for (auto &f : element->getEntries()) { if (skip) { entriesString = visitResults.back() + entriesString; visitResults.pop_back(); skip = false; continue; } entriesString = visitResults.back() + ", " + entriesString; visitResults.pop_back(); } std::string arrayString = "[" + entriesString + "]"; visitResults.push_back(arrayString); } void PrettyPrinter::endVisit(ASTTernaryExpr * element) { std::string elseString = visitResults.back(); visitResults.pop_back(); std::string thenString = visitResults.back(); visitResults.pop_back(); std::string condString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + condString + " ? " + thenString + " : " + elseString + ")"); } void PrettyPrinter::endVisit(ASTElementRefrenceOperatorExpr * element) { std::string index = visitResults.back(); visitResults.pop_back(); std::string array = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + array + "[" + index + "])"); } void PrettyPrinter::endVisit(ASTArrayLengthExpr * element) { std::string array = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(#" + array + ")"); } void PrettyPrinter::endVisit(ASTTrueExpr * element) { visitResults.push_back("true"); } void PrettyPrinter::endVisit(ASTFalseExpr * element) { visitResults.push_back("false"); } std::string PrettyPrinter::indent() const { return std::string(indentLevel*indentSize, indentChar); } void PrettyPrinter::endVisit(ASTAndExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + leftString + " and " + rightString + ")"); } void PrettyPrinter::endVisit(ASTDecrementStmt * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + e + "--;"); } bool PrettyPrinter::visit(ASTForIterStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTForIterStmt * element) { std::string bodyString = visitResults.back(); visitResults.pop_back(); std::string right = visitResults.back(); visitResults.pop_back(); std::string left = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string forString = indent() + "for (" + left + " : " + right + ") \n" + bodyString; visitResults.push_back(forString); } bool PrettyPrinter::visit(ASTForRangeStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTForRangeStmt * element) { std::string bodyString = visitResults.back(); visitResults.pop_back(); std::string fourString = ""; if (element->getFour() != nullptr) { fourString = visitResults.back(); visitResults.pop_back(); } std::string three = visitResults.back(); visitResults.pop_back(); std::string two = visitResults.back(); visitResults.pop_back(); std::string one = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string forString = indent() + "for (" + one + " : " + two + " .. " + three; if (element->getFour() != nullptr) { forString += " by " + fourString; } forString += ") \n" + bodyString; visitResults.push_back(forString); } void PrettyPrinter::endVisit(ASTIncrementStmt * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + e + "++;"); } void PrettyPrinter::endVisit(ASTNegationExpr * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back("-(" + e + ")"); } void PrettyPrinter::endVisit(ASTNotExpr * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(not " + e + ")"); } void PrettyPrinter::endVisit(ASTOfArrayExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("[" + leftString + " of " + rightString + "]"); } void PrettyPrinter::endVisit(ASTOrExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + leftString + " or " + rightString + ")"); }
27.40592
97
0.681709
WilliamHaslet
051be815dae73aabf927a2b29fbc7ab1de5fb6d6
1,129
hpp
C++
android-29/android/app/TimePickerDialog.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/app/TimePickerDialog.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/app/TimePickerDialog.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "./AlertDialog.hpp" namespace android::content { class Context; } namespace android::os { class Bundle; } namespace android::widget { class TimePicker; } namespace android::app { class TimePickerDialog : public android::app::AlertDialog { public: // Fields // QJniObject forward template<typename ...Ts> explicit TimePickerDialog(const char *className, const char *sig, Ts...agv) : android::app::AlertDialog(className, sig, std::forward<Ts>(agv)...) {} TimePickerDialog(QJniObject obj); // Constructors TimePickerDialog(android::content::Context arg0, JObject arg1, jint arg2, jint arg3, jboolean arg4); TimePickerDialog(android::content::Context arg0, jint arg1, JObject arg2, jint arg3, jint arg4, jboolean arg5); // Methods void onClick(JObject arg0, jint arg1) const; void onRestoreInstanceState(android::os::Bundle arg0) const; android::os::Bundle onSaveInstanceState() const; void onTimeChanged(android::widget::TimePicker arg0, jint arg1, jint arg2) const; void show() const; void updateTime(jint arg0, jint arg1) const; }; } // namespace android::app
26.255814
175
0.730735
YJBeetle
051ccf158ecc198ab08157812e03478dcebfdba8
3,131
cpp
C++
Training-Code/2015 Multi-University Training Contest 8/K.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Training-Code/2015 Multi-University Training Contest 8/K.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Training-Code/2015 Multi-University Training Contest 8/K.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> #include <cassert> #include <algorithm> const int MAXN = 100001; const int MAXM = 200001; const int MAXQ = 100001; const int MAXT = 600001; const int MAXI = 3000001; const int Maxlog = 30; struct Edge{ int node, next; }e[MAXM]; struct Query{ int op, x, y, answer; }q[MAXQ]; struct Trie{ int size, c[MAXI][2], s[MAXI]; int alloc() { size++; c[size][0] = c[size][1] = 0; s[size] = 0; return size; } void clear() { size = 0; alloc(); } void modify(int x, int d) { for (int i = Maxlog, p = 1; i >= 0; i--) { int bit = x >> i & 1; if (!c[p][bit]) c[p][bit] = alloc(); p = c[p][bit]; s[p] += d; assert(s[p] >= 0); } } int query(int x) { int ret = 0; for (int i = Maxlog, p = 1; i >= 0; i--) { int bit = x >> i & 1 ^ 1; if (c[p][bit] && s[c[p][bit]]) { ret |= 1 << i; p = c[p][bit]; } else p = c[p][bit ^ 1]; } return ret; } }trie; struct Tuple{ int first, second, third; Tuple() {} Tuple(int first, int second, int third) : first(first), second(second), third(third) {} }; int T, n, m, t, tot, h[MAXN], oL[MAXN], oR[MAXN], a[MAXN], b[MAXN]; std::vector<Tuple> tree[MAXT]; void update(int &x, int y) { if (x < y) x = y; } void addedge(int x, int y) { t++; e[t] = (Edge){y, h[x]}; h[x] = t; } void dfs(int x) { oL[x] = ++tot; for (int i = h[x]; i; i = e[i].next) { dfs(e[i].node); } oR[x] = tot; } void cover(int n, int l, int r, int x, int y, const Tuple &p) { if (r < x || l > y) return; if (x <= l && r <= y) { tree[n].push_back(p); return; } cover(n << 1, l, l + r >> 1, x, y, p); cover(n << 1 ^ 1, (l + r >> 1) + 1, r, x, y, p); } void cover(int n, int l, int r, int x, const Tuple &p) { tree[n].push_back(p); if (l == r) return; if (x <= (l + r >> 1)) cover(n << 1, l, l + r >> 1, x, p); else cover(n << 1 ^ 1, (l + r >> 1) + 1, r, x, p); } void travel(int n, int l, int r) { trie.clear(); for (std::vector<Tuple>::iterator it = tree[n].begin(); it != tree[n].end(); it++) { if (it -> third) trie.modify(it -> second, it -> third); else update(q[it -> first].answer, trie.query(it -> second)); } tree[n].clear(); if (l == r) return; travel(n << 1, l, l + r >> 1); travel(n << 1 ^ 1, (l + r >> 1) + 1, r); } int main() { freopen("K.in", "r", stdin); scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); t = tot = 0; std::fill(h + 1, h + n + 1, 0); for (int i = 2; i <= n; i++) { int fa; scanf("%d", &fa); addedge(fa, i); } dfs(1); for (int i = 1; i <= n; i++) { scanf("%d", a + i); b[i] = a[i]; cover(1, 1, n, oL[i], oR[i], Tuple(i, a[i], 1)); } for (int i = 1; i <= m; i++) { scanf("%d%d", &q[i].op, &q[i].x); if (q[i].op == 0) { scanf("%d", &q[i].y); cover(1, 1, n, oL[q[i].x], oR[q[i].x], Tuple(i, a[q[i].x], -1)); cover(1, 1, n, oL[q[i].x], oR[q[i].x], Tuple(i, a[q[i].x] = q[i].y, 1)); } else{ cover(1, 1, n, oL[q[i].x], Tuple(i, a[q[i].x], 0)); q[i].answer = 0; } } travel(1, 1, n); for (int i = 1; i <= m; i++) { if (q[i].op == 1) { printf("%d\n", q[i].answer); } } } return 0; }
21.155405
88
0.474928
PrayStarJirachi
051ed0cc007cfcbdef35914e5dad4facb166375e
5,648
cpp
C++
Lamp/src/Lamp/World/Terrain.cpp
SGS-Ivar/Lamp
e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2
[ "MIT" ]
null
null
null
Lamp/src/Lamp/World/Terrain.cpp
SGS-Ivar/Lamp
e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2
[ "MIT" ]
null
null
null
Lamp/src/Lamp/World/Terrain.cpp
SGS-Ivar/Lamp
e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2
[ "MIT" ]
null
null
null
#include "lppch.h" #include "Terrain.h" #include "Lamp/Core/Application.h" #include "Lamp/Rendering/Buffers/VertexBuffer.h" #include "Lamp/Rendering/Shader/ShaderLibrary.h" #include "Lamp/Rendering/RenderPipeline.h" #include "Lamp/Rendering/Textures/Texture2D.h" #include "Lamp/Rendering/Swapchain.h" #include "Lamp/Rendering/RenderCommand.h" #include "Lamp/Rendering/Renderer.h" #include "Lamp/Mesh/Materials/MaterialLibrary.h" #include "Lamp/Mesh/Mesh.h" #include "Platform/Vulkan/VulkanDevice.h" namespace Lamp { Terrain::Terrain(const std::filesystem::path& aHeightMap) { if (!std::filesystem::exists(aHeightMap)) { LP_CORE_ERROR("[Terrain]: Unable to load file {0}!", aHeightMap.string()); m_isValid = false; return; } m_heightMap = Texture2D::Create(aHeightMap); GenerateMeshFromHeightMap(); } Terrain::Terrain(Ref<Texture2D> heightMap) { m_heightMap = heightMap; GenerateMeshFromHeightMap(); } Terrain::~Terrain() { } void Terrain::Draw(Ref<RenderPipeline> pipeline) { SetupDescriptors(pipeline); RenderCommand::SubmitMesh(m_mesh, nullptr, m_descriptorSet.descriptorSets, (void*)glm::value_ptr(m_transform)); } Ref<Terrain> Terrain::Create(const std::filesystem::path& heightMap) { return CreateRef<Terrain>(heightMap); } Ref<Terrain> Terrain::Create(Ref<Texture2D> heightMap) { return CreateRef<Terrain>(heightMap); } void Terrain::SetupDescriptors(Ref<RenderPipeline> pipeline) { auto vulkanShader = pipeline->GetSpecification().shader; auto device = VulkanContext::GetCurrentDevice(); const uint32_t currentFrame = Application::Get().GetWindow().GetSwapchain()->GetCurrentFrame(); auto descriptorSet = vulkanShader->CreateDescriptorSets(); std::vector<VkWriteDescriptorSet> writeDescriptors; auto vulkanUniformBuffer = pipeline->GetSpecification().uniformBufferSets->Get(0, 0, currentFrame); auto vulkanTerrainBuffer = Renderer::Get().GetStorage().terrainDataBuffer; writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("CameraDataBuffer")); writeDescriptors[0].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[0].pBufferInfo = &vulkanUniformBuffer->GetDescriptorInfo(); writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("DirectionalLightBuffer")); writeDescriptors[1].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[1].pBufferInfo = &vulkanTerrainBuffer->GetDescriptorInfo(); if (m_heightMap) { writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("u_HeightMap")); writeDescriptors[2].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[2].pImageInfo = &m_heightMap->GetDescriptorInfo(); } auto vulkanScreenUB = pipeline->GetSpecification().uniformBufferSets->Get(3, 0, currentFrame); writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("ScreenDataBuffer")); writeDescriptors[3].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[3].pBufferInfo = &vulkanScreenUB->GetDescriptorInfo(); vkUpdateDescriptorSets(device->GetHandle(), (uint32_t)writeDescriptors.size(), writeDescriptors.data(), 0, nullptr); m_descriptorSet = descriptorSet; } void Terrain::GenerateMeshFromHeightMap() { std::vector<Vertex> vertices; std::vector<uint32_t> indices; const uint32_t patchSize = 64; const float uvScale = 1.f; m_scale = m_heightMap->GetHeight() / patchSize; const uint32_t vertexCount = patchSize * patchSize; vertices.resize(vertexCount); const float wx = 2.f; const float wy = 2.f; for (uint32_t x = 0; x < patchSize; x++) { for (uint32_t y = 0; y < patchSize; y++) { uint32_t index = (x + y * patchSize); vertices[index].position = { x * wx + wx / 2.f - (float)patchSize * wx / 2.f, 0.f, y * wy + wy / 2.f - patchSize * wy / 2.f }; vertices[index].textureCoords = glm::vec2{ (float)x / patchSize, (float)y / patchSize } *uvScale; } } const uint32_t w = patchSize - 1; const uint32_t indexCount = w * w * 4; indices.resize(indexCount); for (uint32_t x = 0; x < w; x++) { for (uint32_t y = 0; y < w; y++) { uint32_t index = (x + y * w) * 4; indices[index] = (x + y * patchSize); indices[index + 1] = (indices[index] + patchSize); indices[index + 2] = (indices[index + 1] + 1); indices[index + 3] = (indices[index] + 1); } } for (uint32_t x = 0; x < patchSize; x++) { for (uint32_t y = 0; y < patchSize; y++) { float heights[3][3]; for (int32_t hx = -1; hx <= 1; hx++) { for (int32_t hy = -1; hy <= 1; hy++) { heights[hx + 1][hy + 1] = GetHeight(x + hx, y + hy); } } glm::vec3 normal; normal.x = heights[0][0] - heights[2][0] + 2.f * heights[0][1] - 2.f * heights[2][1] + heights[0][2] - heights[2][2]; normal.y = heights[0][0] + 2.f * heights[1][0] + heights[2][0] - heights[0][2] - 2.f * heights[1][2] - heights[2][2]; normal.y = 0.25f * sqrtf(1.f - normal.x * normal.x - normal.y * normal.y); vertices[x + y * patchSize].normal = glm::normalize(normal * glm::vec3(2.f, 1.f, 2.f)); } } m_mesh = CreateRef<SubMesh>(vertices, indices, 0, ""); m_transform = glm::scale(glm::mat4(1.f), glm::vec3{ 2.f, 1.f, 2.f }); } float Terrain::GetHeight(uint32_t x, uint32_t y) { glm::ivec2 pos = glm::ivec2{ x, y } * glm::ivec2{ m_scale, m_scale }; pos.x = std::max(0, std::min(pos.x, (int)m_heightMap->GetWidth() - 1)); pos.y = std::max(0, std::min(pos.y, (int)m_heightMap->GetWidth() - 1)); pos /= glm::ivec2(m_scale); auto buffer = m_heightMap->GetData(); return buffer.Read<uint16_t>((pos.x + pos.y * m_heightMap->GetHeight()) * m_scale) / 65535.f; } }
31.730337
130
0.682011
SGS-Ivar
0521bcb8700ec078b1851d5078cee8775e91454f
351
hpp
C++
cpp_oop/5_spreadsheets/src/course.hpp
christosmarg/uni-assignments
bd3fdb78daf038d3a1f6ac1d7c4aad09e19bb795
[ "MIT" ]
null
null
null
cpp_oop/5_spreadsheets/src/course.hpp
christosmarg/uni-assignments
bd3fdb78daf038d3a1f6ac1d7c4aad09e19bb795
[ "MIT" ]
1
2021-06-03T22:25:48.000Z
2021-06-03T22:25:48.000Z
cpp_oop/5_spreadsheets/src/course.hpp
christosmarg/uni-assignments
bd3fdb78daf038d3a1f6ac1d7c4aad09e19bb795
[ "MIT" ]
1
2021-06-03T10:36:57.000Z
2021-06-03T10:36:57.000Z
#ifndef COURSE_HPP #define COURSE_HPP #include "xstring.hpp" struct Course { lab::xstring code; lab::xstring name; bool four_year; Course(const lab::xstring& code, const lab::xstring& name, const bool four_year) :code(code), name(name), four_year(four_year) {} }; #endif /* COURSE_HPP */
19.5
66
0.606838
christosmarg
05225662c211fe8b9b3f7ee59b1e24d0f267485e
11,641
cpp
C++
tests/test_layer_convolution.cpp
edeforas/BeeDNN
48de7aa5e7ea6a0b2f1d7b713f0a48c4b8b6a7e2
[ "MIT" ]
14
2019-11-13T05:14:40.000Z
2022-03-13T20:51:22.000Z
src/tests/test_layer_convolution.cpp
Qt-Widgets/BeeDNN
a117d5a1d990df3bc04a469b1b335cdd1add55df
[ "MIT" ]
66
2019-04-20T09:32:53.000Z
2021-12-25T10:35:11.000Z
src/tests/test_layer_convolution.cpp
Qt-Widgets/BeeDNN
a117d5a1d990df3bc04a469b1b335cdd1add55df
[ "MIT" ]
2
2020-05-03T18:53:08.000Z
2020-06-19T16:36:24.000Z
#include <iostream> #include <chrono> using namespace std; #include "LayerConvolution2D.h" ////////////////////////////////////////////////////////////////////////////// void compare_im2col() { cout << "Comparing im2col() and im2col_LUT():" << endl; Index iNbSamples=7, inRows = 31, inCols = 23, inChannels = 13, outChannels = 17; // all primes numbers MatrixFloat mIn, mCol, mColLUT, mIm, mImLUT; //fill with random data mIn.resize(iNbSamples, inRows * inCols*inChannels); mIn.setRandom(); //compare legacy and optimized forward computation LayerConvolution2D conv2d(inRows, inCols, inChannels, 5, 3, outChannels); conv2d.im2col(mIn, mCol); conv2d.im2col_LUT(mIn, mColLUT); float fMaxDiff = (mCol - mColLUT).cwiseAbs().maxCoeff(); //mIn.resize(iNbSamples*inRows*inChannels, inCols); //cout << "Image:" << endl << toString(mIn) << endl << endl; //cout << "Im2Col:" << endl << toString(mCol) << endl << endl; //cout << "Im2ColLUT:" << endl << toString(mColLUT) << endl << endl; //testu function if (fMaxDiff > 1.e-10) { cout << "Test failed! MaxDifference = " << fMaxDiff << endl; exit(-1); } else cout << "Test Succeded. MaxDifference = " << fMaxDiff << endl; } ////////////////////////////////////////////////////////////////////////////// void compare_fastlut_slow_computation() { cout << "Comparing fastlut and slow computation mode:" << endl; Index iNbSamples = 7, inRows = 31, inCols = 23, inChannels = 13, outChannels = 17; // all primes numbers MatrixFloat mIn, mOut, mOutFast, mIm, mImFast; //fill with random data mIn.resize(iNbSamples, inRows * inCols*inChannels); mIn.setRandom(); LayerConvolution2D conv2d(inRows, inCols, inChannels, 5, 3, outChannels); conv2d.fastLUT = false; conv2d.forward(mIn, mOut); conv2d.fastLUT = true; conv2d.forward(mIn, mOutFast); conv2d.fastLUT = false; conv2d.backpropagation(mIn, mOut, mIm); conv2d.fastLUT = true; conv2d.backpropagation(mIn, mOutFast, mImFast); float fMaxDiffOut = (mOut - mOutFast).cwiseAbs().maxCoeff(); float fMaxDiffIm = (mIm - mImFast).cwiseAbs().maxCoeff(); //testu function if (fMaxDiffOut > 1.e-10) { cout << "Test failed! MaxDifferenceOut = " << fMaxDiffOut << endl; exit(-1); } else cout << "Test Succeded. MaxDifferenceOut = " << fMaxDiffOut << endl; //testu function if (fMaxDiffIm > 1.e-6) { cout << "Test failed! MaxDifferenceIm = " << fMaxDiffIm << endl; exit(-1); } else cout << "Test Succeded. MaxDifferenceIm = " << fMaxDiffIm << endl; } ////////////////////////////////////////////////////////////////////////////// void simple_image_conv2d() { cout << "Simple convolution test:" << endl; MatrixFloat mIn, mOut, mKernel; mIn.setZero(5, 5); mIn(2, 2) = 1; mIn.resize(1, 5 * 5); mKernel.setZero(3, 3); mKernel(1, 0) = 1; mKernel(1, 1) = 2; mKernel(1, 2) = 1; mKernel.resize(1, 3 * 3); LayerConvolution2D conv2d(5,5,1,3,3,1); conv2d.weights() = mKernel; conv2d.forward(mIn, mOut); mOut.resize(3, 3); cout << "Image convoluted:" << endl; cout << toString(mOut) << endl<< endl; } ////////////////////////////////////////////////////////////////////////////// void batch_conv2d() { cout << "Batch convolution test:" << endl; MatrixFloat mIn, mOut, mKernel; mIn.setZero(10, 5); mIn(2, 2) = 1; mIn(2+5, 2) = 3; mIn.resize(2, 5 * 5); mKernel.setZero(3, 3); mKernel(1, 0) = 1; mKernel(1, 1) = 2; mKernel(1, 2) = 1; mKernel.resize(1, 3 * 3); LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1); conv2d.weights() = mKernel; conv2d.forward(mIn, mOut); mOut.resize(6, 3); cout << "Batch convoluted, 2 samples:" << endl; cout << toString(mOut) << endl << endl; } ///////////////////////////////////////////////////////////////// void image_2_input_channels_conv2d() { cout << "Image 2 input channels convolution test:" << endl; MatrixFloat mIn, mOut, mKernel; mIn.setZero(10, 5); mIn(2, 2) = 1; mIn(2 + 5, 2) = 3; mIn.resize(1, 2 * 5 * 5); mKernel.setZero(6, 3); mKernel(1, 0) = 1; mKernel(1, 1) = 2; mKernel(1, 2) = 1; mKernel(3, 1) = 1; mKernel(4, 1) = 2; mKernel(5, 1) = 1; mKernel.resize(1, 2 * 3 * 3); LayerConvolution2D conv2d(5, 5, 2, 3, 3, 1); conv2d.weights() = mKernel; conv2d.forward(mIn, mOut); mOut.resize(3, 3); cout << "Image 2 input channels convoluted:" << endl; cout << toString(mOut) << endl << endl; } ///////////////////////////////////////////////////////////////// void image_2_output_channels_conv2d() { cout << "Image 2 ouput channels convolution test:" << endl; MatrixFloat mIn, mOut, mKernel; mIn.setZero(5, 5); mIn(2, 2) = 1; mIn.resize(1, 5 * 5); mKernel.setZero(6, 3); mKernel(1, 0) = 1; mKernel(1, 1) = 2; mKernel(1, 2) = 1; mKernel(3, 1) = 3; mKernel(4, 1) = 5; mKernel(5, 1) = 3; mKernel.resize(2, 3 * 3); LayerConvolution2D conv2d(5, 5, 1, 3, 3, 2); conv2d.weights() = mKernel; conv2d.forward(mIn, mOut); mOut.resize(6, 3); cout << "Image 2 output channels convoluted:" << endl; cout << toString(mOut) << endl << endl; } ////////////////////////////////////////////////////////////////////////////// void forward_backward() { cout << "Forward then backward test:" << endl; Index iNbSamples = 5, inRows = 7, inCols = 11, inChannels = 13, outChannels = 17; // all primes numbers MatrixFloat mIn, mCol, mColLUT, mIm, mImLUT; //fill with incremented data mIn.resize(iNbSamples, inRows * inCols * inChannels); for (Index i = 0; i < mIn.size(); i++) mIn.data()[i] = (float)i; //forward and backward LayerConvolution2D conv2d(inRows, inCols, inChannels, 2, 3, outChannels); conv2d.forward(mIn, mCol); conv2d.backpropagation(mIn, mCol, mIm); cout << "mIm:" << endl << toString(mIm) << endl << endl; } ////////////////////////////////////////////////////////////////////////////// void simple_image_conv2d_stride2() { cout << "Simple convolution test stride2:" << endl; MatrixFloat mIn, mOut, mKernel; mIn.setZero(5, 5); mIn(0, 0) = 100; mIn(2, 2) = 122; mIn(3, 4) = 134; mIn.resize(1, 5 * 5); mKernel.setZero(3, 3); mKernel(0, 0) = 1; mKernel(0, 1) = 2; mKernel(0, 2) = 1; mKernel(1, 0) = 2; mKernel(1, 1) = 4; mKernel(1, 2) = 2; mKernel(2, 0) = 1; mKernel(2, 1) = 2; mKernel(2, 2) = 1; mKernel.resize(1, 3 * 3); LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1,2,2); conv2d.weights() = mKernel; conv2d.forward(mIn, mOut); mOut.resize(2, 2); cout << "Image convoluted stride2:" << endl; cout << toString(mOut) << endl << endl; } ////////////////////////////////////////////////////////////////////////////// void forward_conv2d_backprop_sgd() { cout << "Forward Conv2D and Backpropagation test:" << endl << endl; MatrixFloat mIn, mOut, mKernel, mGradientOut, mGradientIn; mIn.setZero(5, 5); mIn(2, 2) = 1; mIn.resize(1, 5 * 5); mKernel.setZero(3, 3); mKernel(1, 0) = 1; mKernel(1, 1) = 2; mKernel(1, 2) = 1; mKernel.resize(1, 3 * 3); LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1); //forward conv2d.weights() = mKernel; conv2d.forward(mIn, mOut); //backpropagation mGradientOut = mOut* 0.1f; mGradientOut(3+1) = -1.f; conv2d.backpropagation(mIn, mGradientOut, mGradientIn); //disp forward mOut.resize(3, 3); cout << "Forward :" << endl; cout << toString(mOut) << endl << endl; //disp backpropagation conv2d.gradient_weights().resize(3, 3); cout << "Backprop Weight gradient :" << endl; cout << toString(conv2d.gradient_weights()) << endl << endl; mGradientIn.resize(5, 5); cout << "Backprop Input gradient :" << endl; cout << toString(mGradientIn) << endl << endl; } ///////////////////////////////////////////////////////////////// void forward_stride2_backward() { cout << "Forward Conv2D and Backpropagation test:" << endl << endl; MatrixFloat mIn, mOut, mKernel, mGradientOut, mGradientIn; mIn.setZero(5, 5); mIn(2, 2) = 1; mIn.resize(1, 5 * 5); mKernel.setZero(3, 3); mKernel(1, 0) = 1; mKernel(1, 1) = 2; mKernel(1, 2) = 1; mKernel.resize(1, 3 * 3); LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1, 2, 2); //forward conv2d.weights() = mKernel; conv2d.forward(mIn, mOut); //backpropagation mGradientOut = mOut * 0.1f; mGradientOut(2 + 1) = -1.f; conv2d.backpropagation(mIn, mGradientOut, mGradientIn); //disp forward mOut.resize(2, 2); cout << "Forward :" << endl; cout << toString(mOut) << endl << endl; //disp backpropagation conv2d.gradient_weights().resize(3, 3); cout << "Backprop Weight gradient :" << endl; cout << toString(conv2d.gradient_weights()) << endl << endl; mGradientIn.resize(5, 5); cout << "Backprop Input gradient :" << endl; cout << toString(mGradientIn) << endl << endl; } ///////////////////////////////////////////////////////////////// void forward_time() { cout << "Forward conv2d time estimation:" << endl; int iNbSamples = 32; int iInRows = 64; int iInCols = 64; int iInChannels = 16; int iKernelRows = 3; int iKernelCols = 3; int iOutChannels = 32; int iNbConv = 10; MatrixFloat mIn; mIn.setRandom(iNbSamples, iInRows*iInCols*iInChannels); MatrixFloat mOut; LayerConvolution2D conv2d(iInRows, iInCols, iInChannels, iKernelRows, iKernelCols, iOutChannels); //measure forward time slow conv2d.fastLUT = false; auto start = chrono::steady_clock::now(); for(int i=0;i< iNbConv;i++) conv2d.forward(mIn, mOut); auto end = chrono::steady_clock::now(); auto delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); cout << "Time elapsed slow: " << delta << " ms" << endl; //measure forward time fastlut conv2d.fastLUT = true; start = chrono::steady_clock::now(); for (int i = 0; i < iNbConv; i++) conv2d.forward(mIn, mOut); end = chrono::steady_clock::now(); delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); cout << "Time elapsed fastlut: " << delta << " ms" << endl << endl; } ///////////////////////////////////////////////////////////////// void backward_time() { cout << "Backward conv2d time estimation:" << endl; int iNbSamples = 32; int iInRows = 64; int iInCols = 64; int iInChannels = 16; int iKernelRows = 3; int iKernelCols = 3; int iOutChannels = 32; int iNbConv = 10; MatrixFloat mIn,mOut, mOutGradient, mInGradient; mIn.setRandom(iNbSamples, iInRows*iInCols*iInChannels); LayerConvolution2D conv2d(iInRows, iInCols, iInChannels, iKernelRows, iKernelCols, iOutChannels); conv2d.forward(mIn, mOut); // init backward internal state //create random gradient mOutGradient = mOut; mOutGradient.setRandom(); //measure backward time slow conv2d.fastLUT = false; auto start = chrono::steady_clock::now(); for (int i = 0; i < iNbConv; i++) conv2d.backpropagation(mIn, mOutGradient, mInGradient); auto end = chrono::steady_clock::now(); auto delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); cout << "Time elapsed slow: " << delta << " ms" << endl; conv2d.fastLUT = true; start = chrono::steady_clock::now(); for (int i = 0; i < iNbConv; i++) conv2d.backpropagation(mIn, mOutGradient, mInGradient); end = chrono::steady_clock::now(); delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); cout << "Time elapsed fast: " << delta << " ms" << endl << endl; } ///////////////////////////////////////////////////////////////// int main() { compare_im2col(); compare_fastlut_slow_computation(); simple_image_conv2d(); batch_conv2d(); image_2_input_channels_conv2d(); image_2_output_channels_conv2d(); simple_image_conv2d_stride2(); forward_conv2d_backprop_sgd(); simple_image_conv2d_stride2(); forward_backward(); forward_stride2_backward(); forward_time(); backward_time(); } /////////////////////////////////////////////////////////////////
26.946759
105
0.605274
edeforas
0522d21ea9cdb3083806b59c1b4d52bd17a5e3d8
513
hpp
C++
src/utility/create_geometric_progression.hpp
Atsushi-Machida/OpenJij
e4bddebb13536eb26ff0b7b9fc6b1c75659fe934
[ "Apache-2.0" ]
61
2019-01-05T13:37:10.000Z
2022-03-11T02:11:08.000Z
src/utility/create_geometric_progression.hpp
Atsushi-Machida/OpenJij
e4bddebb13536eb26ff0b7b9fc6b1c75659fe934
[ "Apache-2.0" ]
79
2019-01-29T09:55:20.000Z
2022-02-19T04:06:20.000Z
src/utility/create_geometric_progression.hpp
29rou/OpenJij
c2579fba8710cf82b9e6761304f0042b365b595c
[ "Apache-2.0" ]
21
2019-01-07T07:55:10.000Z
2022-03-08T14:27:23.000Z
#ifndef OPENJIJ_UTILITY_CREATE_GEOMETRIC_PROGRESSION_HPP__ #define OPENJIJ_UTILITY_CREATE_GEOMETRIC_PROGRESSION_HPP__ namespace openjij { namespace utility { template<typename ForwardIterator, typename T> void make_geometric_progression(ForwardIterator first, ForwardIterator last, T value, T ratio) { for(;first != last; ++first) { *first = value; value *= ratio; } } } // namespace utility } // namespace openjij #endif
28.5
104
0.660819
Atsushi-Machida
05234580932f71158425be7736c55e1ee9b8c0b5
1,562
cpp
C++
vendor/bitsery/examples/flexible_syntax.cpp
lateefx01/Aston
0e0a2393eeac3946880c3e601c532d49e2cf3b44
[ "Apache-2.0" ]
null
null
null
vendor/bitsery/examples/flexible_syntax.cpp
lateefx01/Aston
0e0a2393eeac3946880c3e601c532d49e2cf3b44
[ "Apache-2.0" ]
null
null
null
vendor/bitsery/examples/flexible_syntax.cpp
lateefx01/Aston
0e0a2393eeac3946880c3e601c532d49e2cf3b44
[ "Apache-2.0" ]
null
null
null
#include <bitsery/bitsery.h> #include <bitsery/adapter/buffer.h> //include flexible header, to use flexible syntax #include <bitsery/flexible.h> //we also need additional traits to work with container types, //instead of including <bitsery/traits/vector.h> for vector traits, now we also need traits to work with flexible types. //so include everything from <bitsery/flexible/...> instead of <bitsery/traits/...> //otherwise we'll get static assert error, saying to define serialize function. #include <bitsery/flexible/vector.h> enum class MyEnum : uint16_t { V1, V2, V3 }; struct MyStruct { uint32_t i; MyEnum e; std::vector<float> fs; //define serialize function as usual template<typename S> void serialize(S &s) { //now we can use flexible syntax with s.archive(i, e, fs); } }; using namespace bitsery; //some helper types using Buffer = std::vector<uint8_t>; using OutputAdapter = OutputBufferAdapter<Buffer>; using InputAdapter = InputBufferAdapter<Buffer>; int main() { //set some random data MyStruct data{8941, MyEnum::V2, {15.0f, -8.5f, 0.045f}}; MyStruct res{}; //serialization, deserialization flow is unchanged as in basic usage Buffer buffer; auto writtenSize = quickSerialization<OutputAdapter>(buffer, data); auto state = quickDeserialization<InputAdapter>({buffer.begin(), writtenSize}, res); assert(state.first == ReaderError::NoError && state.second); assert(data.fs == res.fs && data.i == res.i && data.e == res.e); }
29.471698
120
0.690141
lateefx01
0523a9d28fa2439ada43f94402518b04e3129cc9
6,846
cpp
C++
src/Pulse.cpp
SteveRussell33/southpole-vcvrack
d7f57fdb75c5aa6c0a6aabad7a1da761f4e8ff81
[ "MIT" ]
null
null
null
src/Pulse.cpp
SteveRussell33/southpole-vcvrack
d7f57fdb75c5aa6c0a6aabad7a1da761f4e8ff81
[ "MIT" ]
1
2021-10-02T02:34:32.000Z
2021-10-02T02:34:32.000Z
src/Pulse.cpp
SteveRussell33/southpole-vcvrack
d7f57fdb75c5aa6c0a6aabad7a1da761f4e8ff81
[ "MIT" ]
2
2021-09-30T11:46:32.000Z
2022-01-10T17:34:10.000Z
#include "Southpole.hpp" struct Pulse : Module { enum ParamIds { TRIG_PARAM, REPEAT_PARAM, RESET_PARAM, RANGE_PARAM, DELAY_PARAM, TIME_PARAM, AMP_PARAM, // OFFSET_PARAM, SLEW_PARAM, NUM_PARAMS }; enum InputIds { TRIG_INPUT, CLOCK_INPUT, // REPEAT_INPUT, // RESET_INPUT, DELAY_INPUT, TIME_INPUT, AMP_INPUT, // OFFSET_INPUT, SLEW_INPUT, NUM_INPUTS }; enum OutputIds { CLOCK_OUTPUT, GATE_OUTPUT, EOC_OUTPUT, NUM_OUTPUTS }; enum LightIds { EOC_LIGHT, GATE_LIGHT, NUM_LIGHTS }; dsp::SchmittTrigger clock; dsp::SchmittTrigger trigger; dsp::SchmittTrigger triggerBtn; dsp::PulseGenerator clkPulse; dsp::PulseGenerator eocPulse; unsigned long delayt = 0; unsigned long gatet = 0; unsigned long clockt = 0; unsigned long clockp = 0; unsigned long delayTarget = 0; unsigned long gateTarget = 0; float level = 0; bool reset = true; bool repeat = false; bool range = false; bool gateOn = false; bool delayOn = false; float amp; float slew; static const int ndurations = 12; const float durations[ndurations] = { 1 / 256., 1 / 128., 1 / 64., 1 / 32., 1 / 16., 1 / 8., 3. / 16., 1 / 4., 1 / 3., 1 / 2., 3. / 4., .99 //,2.,3.,4. //,5.,6.,7.,8.,12.,16. }; Pulse() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); configParam(Pulse::TRIG_PARAM, 0.0, 1.0, 0., ""); configParam(Pulse::RESET_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::REPEAT_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::RANGE_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::TIME_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::DELAY_PARAM, 0.0, 1.0, 0.0, ""); configParam(Pulse::AMP_PARAM, 0.0, 1.0, 1.0, ""); configParam(Pulse::SLEW_PARAM, 0.0, 1.0, 0., ""); } void process(const ProcessArgs &args) override; }; void Pulse::process(const ProcessArgs &args) { bool triggered = false; reset = params[RESET_PARAM].getValue(); repeat = params[REPEAT_PARAM].getValue(); range = params[RANGE_PARAM].getValue(); if (triggerBtn.process(params[TRIG_PARAM].getValue())) { triggered = true; } if (trigger.process(inputs[TRIG_INPUT].getNormalVoltage(0.))) { triggered = true; //printf("%lu\n", gateTarget); } if (clock.process(inputs[CLOCK_INPUT].getNormalVoltage(0.))) { triggered = true; clkPulse.trigger(1e-3); clockp = clockt; clockt = 0; } float dt = 1e-3 * args.sampleRate; float sr = args.sampleRate; amp = clamp(params[AMP_PARAM].getValue() + inputs[AMP_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); slew = clamp(params[SLEW_PARAM].getValue() + inputs[SLEW_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); slew = pow(2., (1. - slew) * log2(sr)) / sr; if (range) slew *= .1; float delayTarget_ = clamp(params[DELAY_PARAM].getValue() + inputs[DELAY_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); float gateTarget_ = clamp(params[TIME_PARAM].getValue() + inputs[TIME_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f); if (inputs[CLOCK_INPUT].isConnected()) { clockt++; delayTarget = clockp * durations[int((ndurations - 1) * delayTarget_)]; gateTarget = clockp * durations[int((ndurations - 1) * gateTarget_)]; if (gateTarget < dt) gateTarget = dt; } else { unsigned int r = range ? 10 : 1; delayTarget = r * delayTarget_ * sr; gateTarget = r * gateTarget_ * sr + dt; } if (triggered && (reset || !gateOn || !delayOn)) { delayt = 0; delayOn = true; gateOn = false; } if (delayOn) { if (delayt < delayTarget) { delayt++; } else { delayOn = false; gateOn = true; gatet = 0; } } if (gateOn) { if (gatet < gateTarget) { gatet++; } else { eocPulse.trigger(1e-3); gateOn = false; if (repeat) { delayt = 0; delayOn = true; } } if (level < 1.) level += slew; if (level > 1.) level = 1.; } else { if (level > 0.) level -= slew; if (level < 0.) level = 0.; } outputs[CLOCK_OUTPUT].setVoltage(10. * clkPulse.process(1.0 / args.sampleRate)); outputs[EOC_OUTPUT].value = 10. * eocPulse.process(1.0 / args.sampleRate); outputs[GATE_OUTPUT].value = clamp(10.f * level * amp, -10.f, 10.f); lights[EOC_LIGHT].setSmoothBrightness(outputs[EOC_OUTPUT].value, args.sampleTime); lights[GATE_LIGHT].setSmoothBrightness(outputs[GATE_OUTPUT].value, args.sampleTime); } struct PulseWidget : ModuleWidget { PulseWidget(Module *module) { setModule(module); box.size = Vec(15 * 4, 380); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Pulse.svg"))); const float x1 = 5.; const float x2 = 35.; const float y1 = 40.; const float yh = 35.; addInput(createInput<sp_Port>(Vec(x1, y1 + 0 * yh), module, Pulse::CLOCK_INPUT)); addOutput(createOutput<sp_Port>(Vec(x2, y1 + 0 * yh), module, Pulse::CLOCK_OUTPUT)); addInput(createInput<sp_Port>(Vec(x1, y1 + 1 * yh), module, Pulse::TRIG_INPUT)); addParam(createParam<TL1105>(Vec(x2, y1 + 1 * yh), module, Pulse::TRIG_PARAM)); addParam(createParam<sp_Switch>(Vec(x1, y1 + 1.75 * yh), module, Pulse::RESET_PARAM)); addParam(createParam<sp_Switch>(Vec(x1, y1 + 2.25 * yh), module, Pulse::REPEAT_PARAM)); addParam(createParam<sp_Switch>(Vec(x1, y1 + 2.75 * yh), module, Pulse::RANGE_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 4 * yh), module, Pulse::TIME_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 4 * yh), module, Pulse::TIME_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 5 * yh), module, Pulse::DELAY_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 5 * yh), module, Pulse::DELAY_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 6 * yh), module, Pulse::AMP_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 6 * yh), module, Pulse::AMP_PARAM)); //addInput(createInput<sp_Port> (Vec(x1, y1+7*yh), module, Pulse::OFFSET_INPUT)); //addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1+7*yh), module, Pulse::OFFSET_PARAM)); addInput(createInput<sp_Port>(Vec(x1, y1 + 7 * yh), module, Pulse::SLEW_INPUT)); addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 7 * yh), module, Pulse::SLEW_PARAM)); addOutput(createOutput<sp_Port>(Vec(x1, y1 + 8.25 * yh), module, Pulse::EOC_OUTPUT)); addOutput(createOutput<sp_Port>(Vec(x2, y1 + 8.25 * yh), module, Pulse::GATE_OUTPUT)); addChild(createLight<SmallLight<RedLight>>(Vec(x1 + 7, y1 + 7.65 * yh), module, Pulse::EOC_LIGHT)); addChild(createLight<SmallLight<RedLight>>(Vec(x2 + 7, y1 + 7.65 * yh), module, Pulse::GATE_LIGHT)); } }; Model *modelPulse = createModel<Pulse, PulseWidget>("Pulse");
29.25641
124
0.631756
SteveRussell33
05265dcd314518a802f57b0a626a43fdc19c5a3e
9,012
cpp
C++
filter.cpp
ForensicTools/WirelessProximityMonitor_474-2135_Pittner-Sirianni-Swerling
b7a8569835e69cd3a417d860a6d98bf67f572963
[ "Apache-2.0" ]
2
2016-10-27T06:17:47.000Z
2021-01-05T10:17:57.000Z
filter.cpp
ForensicTools/WirelessProximityMonitor_474-2135_Pittner-Sirianni-Swerling
b7a8569835e69cd3a417d860a6d98bf67f572963
[ "Apache-2.0" ]
null
null
null
filter.cpp
ForensicTools/WirelessProximityMonitor_474-2135_Pittner-Sirianni-Swerling
b7a8569835e69cd3a417d860a6d98bf67f572963
[ "Apache-2.0" ]
2
2015-10-27T15:55:15.000Z
2017-11-24T12:55:25.000Z
/*/ * Project: Wireless Proximity Analyzer * * Repository: https://github.com/ForensicTools/WirelessProximityMonitor_474-2135_Pittner-Sirianni-Swerling * * Authors: * Joe Sirianni * Cal Pittner * Ross Swerling * * License: Apache v2 /*/ #include "filter.h" //Static lists of user input strings static const std::string days[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; static const std::string weekEnds[2] = {"Sat", "Sun"}; static const std::string weekDays[5] = {"Mon", "Tue", "Wed", "Thu", "Fri"}; static const std::string months[12] = {"Jan", "Feb", "Mar", "Apr", "May","Jun", "Jul","Aug","Sep", "Oct", "Nov", "Dec"}; static const std::string filterCommands[6] = {"time", "date", "days", "months", "dbm", "uniqMac"}; FILTER::FILTER() { clearFilter(); } FILTER::~FILTER() { } bool FILTER::filterPacket(packet_structure packet, std::list<packet_structure> packetList) { //Default answer is don't filter packet bool answer = false; //Structures for date and time time_t epoch_time = packet.epoch_time; struct tm *ptm = gmtime (&epoch_time); if(filterTime == true) { std::stringstream timeSs; timeSs << std::setfill('0'); //Time in readable format timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_hour); timeSs << ":"; timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_min); timeSs << ":"; timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_sec); //Checks if packet time within specified filter range if(startTime.compare(endTime) < 0) if((timeSs.str()).compare(startTime) < 0 || (timeSs.str()).compare(endTime) > 0) answer = true; //If start time is greater than end //It must extend into next day else if(startTime.compare(endTime) > 0) if((timeSs.str()).compare(startTime) > 0 || (timeSs.str()).compare(endTime) < 0) answer = true; else { if((timeSs.str()).compare(startTime) != 0) answer = true; } } if(filterDate == true && answer == false) { std::stringstream dateSs; dateSs << std::setfill('0'); //Date in readable format dateSs << std::setw(4) << static_cast<unsigned>(ptm->tm_year+1900); dateSs << "/"; dateSs << std::setw(2) << static_cast<unsigned>(ptm->tm_mon+1); dateSs << "/"; dateSs << std::setw(2) << static_cast<unsigned>(ptm->tm_mday); //Checks if it is with in the allowable filter date if(startDate.compare(endDate) < 0) if((dateSs.str()).compare(startDate) < 0 || (dateSs.str()).compare(endDate) > 0) answer = true; else if(startDate.compare(endDate) > 0) if((dateSs.str()).compare(startDate) > 0 || (dateSs.str()).compare(endDate) < 0) answer = true; else if((dateSs.str()).compare(startDate) != 0) answer = true; } if(filterDay == true && answer == false) { //Sets fiter to true answer = true; for(int i = 0; i <= (matchDays.size() - 1); i++) { //If packet day matches an allowed day //Filter is set back to false if(matchDays[i] == days[ptm->tm_wday]) { answer = false; break; } } } if(filterMonth == true && answer == false) { //Sets filter to true answer = true; for(int i = 0; i <= (matchMonths.size()-1); i++) { //If packet month matches an allowed month //Filter is set back to true if(matchMonths[i] == months[ptm->tm_mon]) { answer = false; break; } } } if(filterDbm == true && answer == false) { //Checks if dBm is within allowable filter rnage if(minDbm < packet.dbm || maxDbm > packet.dbm) answer=true; } if(uniqMac == true && answer == false) { //Checks packet MAC against all packets in the display filter list for(std::list<packet_structure>::iterator it = packetList.begin(); it != packetList.end(); it++) { if((it->mac).compare(packet.mac) == 0) { answer = true; break; } } } if( (blackList == true || whiteList == true) && answer == false) { if(whiteList == true) answer = true; //Checks packet MAC against all packets in the MAC list for(std::list<packet_structure>::iterator it = macList.begin(); it != macList.end(); it++) { if((it->mac).compare(packet.mac) == 0) { answer = !answer; //Tricky thinking break; } } } if( macMono == true && answer == false) { if((macAddr).compare(packet.mac) != 0) answer = true; } return answer; } bool FILTER::setFilter(std::string filter) { //Clears variables before setting them clearFilter(); //Initializes Syntax as good bool syntaxCheck = true; std::stringstream ss(filter); //Separates commands by spaces std::istringstream intConv; //Used for converting string numbers to type int std::string buff; //General string buffer std::string args; //Holds arguments for commands std::vector<std::string> commands; //Holds all commands //Separates commands by spaces and inputs them into list while(ss >> buff) { commands.push_back(buff); } //Parse each command if(commands.size() != 0) for(int i = 0; i <= (commands.size() - 1); i++) { buff.clear(); args.clear(); //Initial syntax check for '='; All commands should have this if((commands[i]).find_first_of("=") == std::string::npos) { syntaxCheck = false; break; } else //Split command into filter type and value for(size_t q = 0; q <= commands[i].find_first_of("=") - 1; q++) buff += commands[i].at(q); for(int q = commands[i].find_first_of("=") + 1; q <= ((commands[i]).size()-1); q++) args += commands[i].at(q); //Input values into variables if(buff.compare("time" ) == 0) { //Synatx check if(args.find_first_of("-")==std::string::npos) { syntaxCheck = false; break; } else { //Split start and end time filterTime = true; for(int q = 0; q <= args.find_first_of("-") - 1; q++) startTime += args.at(q); for(int q = args.find_first_of("-") + 1; q <= (args.size()-1); q++) endTime += args.at(q); } } else if(buff.compare("date") == 0) { //Syntax check if(args.find_first_of("-")==std::string::npos) { syntaxCheck = false; break; } else { //Split start and end date filterDate = true; for(int q = 0; q <= args.find_first_of("-"); q++) startDate += args.at(q); for(int q = args.find_first_of("-") + 1; q <= (args.size()-1); q++) endDate += args.at(q); } } else if(buff.compare("days") == 0) { filterDay = true; //Relplaces commas with spaces for(size_t q = args.find_first_of(","); q != std::string::npos; q = args.find_first_of(",", ++q)) { args[q] = ' '; } buff.clear(); ss.clear(); ss.str(args); //Puts days into vector based on spaces while(ss >> buff) matchDays.push_back(buff); } else if(buff.compare("months") == 0) { filterMonth = true; //Replaces commas with spaces for(size_t q = args.find_first_of(","); q != std::string::npos; q = args.find_first_of(",", ++q)) { args[q] = ' '; } buff.clear(); ss.clear(); ss.str(args); //Puts days into vector based on spaces while(ss >> buff) matchMonths.push_back(buff); } else if(buff.compare("dbm") == 0) { //Inital syntax check if(args.find_first_of("-") == std::string::npos) { syntaxCheck = false; break; } else { buff.clear(); //Gets Min dBm value for(int q = 0; q <= args.find_first_of("-") - 1; q++) buff += args.at(q); intConv.clear(); intConv.str(buff); intConv >> minDbm; //Convert to int buff.clear(); //Gets Max dBm value for(int q = args.find_first_of("-") + 1; q <= (args.size()-1); q++) buff += args.at(q); intConv.clear(); intConv.str(buff); intConv >> maxDbm; //Convert to int } //Syntax check for Min lt Max if(minDbm > maxDbm) syntaxCheck = false; else { //Converts numbers to negative minDbm *= - 1; maxDbm *= - 1; filterDbm = true; } } else if(buff.compare("uniqMac") == 0) { //Syntax checks if(args.compare("true") == 0) uniqMac = true; else if(args.compare("false") != 0) { syntaxCheck = false; break; } } else if(buff.compare("blackList") == 0 || buff.compare("whiteList") == 0) { ReadWrite open; open.readFromFile(args.c_str(), &macList); if( buff.compare("blackList") == 0 ) blackList=true; else whiteList=true; if( blackList == true && whiteList == true) { syntaxCheck = false; break; } } else if(buff.compare("mac") == 0) { macMono = true; macAddr = args.c_str(); } else { syntaxCheck = false; break; } } return syntaxCheck; } void FILTER::clearFilter() { //Clear variables & sets filter checks to false filterTime = false; startTime.clear(); endTime.clear(); filterDate = false; startDate.clear(); endDate.clear(); filterDay = false; matchDays.clear(); filterMonth = false; matchMonths.clear(); filterDbm = false; maxDbm = 0; minDbm = 0; uniqMac = false; macMono = false; macAddr.clear(); blackList = false; whiteList = false; macList.clear(); }
24.622951
107
0.604527
ForensicTools
0526d13aee63e9bf31145a969bebee925a18542c
2,642
cpp
C++
LeetCode/MaximumGap.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/MaximumGap.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/MaximumGap.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
#include <sstream> #include <stdio.h> #include <string> #include <cstring> #include <iostream> #include <vector> #include <map> #include <stack> #include <queue> #include <cmath> #include <algorithm> #include <cfloat> #include <climits> //#include <unordered_map> using namespace std; /* Time Complexity : O(n) Space Complexity : O(n) Trick: since it requires max gap between sorted elements, so we need to sort it anyway. Trick is to use Bucket Sort! Since they are all int, maxElem - minElem should be more than 1, avg gap is bucketSize=(maxElem - minElem)/size what we need is the max one, no need to calculate every gap, just those above avg. Special Cases : Summary: memset() : Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value. */ class Solution { public: int maximumGap(vector<int> &num) { int result = 0; if(num.size() == 0){ return result; } //get the min and max of the array int minElem = num[0]; int maxElem = num[0]; for(int i=1; i<num.size(); i++){ if(num[i] > maxElem){ maxElem = num[i]; }else if(num[i] < minElem){ minElem = num[i]; } } //init bucket sort int bucketSize = max(1, (maxElem - minElem)/(int)num.size()); int bucketNum = (maxElem - minElem)/bucketSize + 1; int bucketMin[bucketNum]; int bucketMax[bucketNum]; for(int i=0; i<bucketNum; i++){ bucketMin[i] = maxElem+1; bucketMax[i] = minElem-1; } for(int i=0; i<num.size(); i++){ int pos = (num[i] - minElem)/bucketSize; // cout<<"before :"<<bucketMin[pos]<<", "<<bucketMax[pos]<<endl; if(bucketMin[pos] > num[i]){ bucketMin[pos] = num[i]; } if(bucketMax[pos] < num[i]){ bucketMax[pos] = num[i]; } // cout<<bucketMin[pos]<<", "<<bucketMax[pos]<<endl; } //caculate max gap int lastMax = bucketMax[0]; for(int i=0; i<bucketNum; i++){ // cout<<bucketMin[i]<<", "<<bucketMax[i]<<endl; if(bucketMin[i] != maxElem+1){ result = max(result, bucketMin[i]-lastMax); lastMax = bucketMax[i]; } } return result; } }; int main(){ vector<int> input; input.push_back(1); input.push_back(10000000); Solution test; cout<<test.maximumGap(input)<<endl; return 0; }
29.032967
116
0.549205
Michael-Ma
0528eaf7fe79a9a2d4d4b46892fa36ac303fd382
3,223
cc
C++
crypto/cipher/aes_old.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
3
2017-04-24T07:00:59.000Z
2020-04-13T04:53:06.000Z
crypto/cipher/aes_old.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2017-01-10T04:23:55.000Z
2017-01-10T04:23:55.000Z
crypto/cipher/aes_old.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2020-04-13T04:53:07.000Z
2020-04-13T04:53:07.000Z
void AESState::expand_generic(const uint8_t* key, std::size_t len) { uint32_t nk = (len / 4); uint32_t n = num_rounds * 4; for (uint32_t i = 0; i < nk; ++i) { enc.u32[i] = RBE32(key, i); } for (uint32_t i = nk; i < n; ++i) { uint32_t temp = enc.u32[i - 1]; uint32_t p = (i / nk); uint32_t q = (i % nk); if (q == 0) { temp = S0(ROL32(temp, 8)) ^ (uint32_t(POW_X[p - 1]) << 24); } else if (nk == 8 && q == 4) { temp = S0(temp); } enc.u32[i] = enc.u32[i - nk] ^ temp; } for (uint32_t i = 0; i < n; i += 4) { uint32_t ei = n - (i + 4); for (uint32_t j = 0; j < 4; ++j) { uint32_t x = enc.u32[ei + j]; if (i > 0 && (i + 4) < n) { x = TD(S0(x)); } dec.u32[i + j] = x; } } } void AESState::encrypt_generic(uint8_t* dst, const uint8_t* src, std::size_t len) const { uint32_t s0, s1, s2, s3; uint32_t t0, t1, t2, t3; uint32_t index; while (len >= 16) { // Round 1: just XOR s0 = enc.u32[0] ^ RBE32(src, 0); s1 = enc.u32[1] ^ RBE32(src, 1); s2 = enc.u32[2] ^ RBE32(src, 2); s3 = enc.u32[3] ^ RBE32(src, 3); // Rounds 2 .. N - 1: shuffle and XOR index = 4; for (uint32_t i = 2; i < num_rounds; ++i) { t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = enc.u32[index + 0] ^ TE(t0, t1, t2, t3); s1 = enc.u32[index + 1] ^ TE(t1, t2, t3, t0); s2 = enc.u32[index + 2] ^ TE(t2, t3, t0, t1); s3 = enc.u32[index + 3] ^ TE(t3, t0, t1, t2); index += 4; } // Round N: S-box and XOR t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = enc.u32[index + 0] ^ S0(t0, t1, t2, t3); s1 = enc.u32[index + 1] ^ S0(t1, t2, t3, t0); s2 = enc.u32[index + 2] ^ S0(t2, t3, t0, t1); s3 = enc.u32[index + 3] ^ S0(t3, t0, t1, t2); WBE32(dst, 0, s0); WBE32(dst, 1, s1); WBE32(dst, 2, s2); WBE32(dst, 3, s3); src += 16; dst += 16; len -= 16; } DCHECK_EQ(len, 0U); } void AESState::decrypt_generic(uint8_t* dst, const uint8_t* src, std::size_t len) const { while (len >= 16) { // Round 1: just XOR uint32_t s0 = dec.u32[0] ^ RBE32(src, 0); uint32_t s1 = dec.u32[1] ^ RBE32(src, 1); uint32_t s2 = dec.u32[2] ^ RBE32(src, 2); uint32_t s3 = dec.u32[3] ^ RBE32(src, 3); uint32_t t0, t1, t2, t3; // Rounds 2 .. N - 1: shuffle and XOR uint32_t i = 4; for (uint32_t round = 2; round < num_rounds; ++round) { t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = dec.u32[i + 0] ^ TD(t0, t3, t2, t1); s1 = dec.u32[i + 1] ^ TD(t1, t0, t3, t2); s2 = dec.u32[i + 2] ^ TD(t2, t1, t0, t3); s3 = dec.u32[i + 3] ^ TD(t3, t2, t1, t0); i += 4; } // Round N: S-box and XOR t0 = s0; t1 = s1; t2 = s2; t3 = s3; s0 = dec.u32[i + 0] ^ S1(t0, t3, t2, t1); s1 = dec.u32[i + 1] ^ S1(t1, t0, t3, t2); s2 = dec.u32[i + 2] ^ S1(t2, t1, t0, t3); s3 = dec.u32[i + 3] ^ S1(t3, t2, t1, t0); WBE32(dst, 0, s0); WBE32(dst, 1, s1); WBE32(dst, 2, s2); WBE32(dst, 3, s3); src += 16; dst += 16; len -= 16; } DCHECK_EQ(len, 0U); }
25.579365
68
0.462302
chronos-tachyon
0529bd1e37bcd248d28b564a519583a39fc260e9
1,891
hh
C++
RAVL2/Math/Geometry/Euclidean/2D/Arc2d.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/2D/Arc2d.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/2D/Arc2d.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2002, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVL_ARC2D_HEADER #define RAVL_ARC2D_HEADER 1 //////////////////////////////////////////////////////////// //! userlevel=Normal //! author="Charles Galambos" //! date="10/3/1997" //! docentry="Ravl.API.Math.Geometry.2D" //! rcsid="$Id: Arc2d.hh 5240 2005-12-06 17:16:50Z plugger $" //! lib=RavlMath //! file="Ravl/Math/Geometry/Euclidean/2D/Arc2d.hh" #include "Ravl/Circle2d.hh" namespace RavlN { //: This class implements 2d circular arcs. class Arc2dC : public Circle2dC { public: inline Arc2dC() { ends[0] = 0; ends[1] = 0; } //: Default constructor. bool FitLSQ(const Array1dC<Point2dC> &points,RealT &residual); //: Fit points to a circle. // 'residual' is from the least squares fit and can be used to assess the quality of the // fit. Assumes the points are ordered around the arc. // Returns false if fit failed. inline RealT &StartAngle() { return ends[0]; } //: Start angle of arc, which proccedes clockwise. inline RealT StartAngle() const { return ends[0]; } //: Start angle of arc, which proccedes clockwise. inline RealT &EndAngle() { return ends[1]; } //: End angle of arc, which proccedes clockwise. inline RealT EndAngle() const { return ends[1]; } //: End angle of arc, which proccedes clockwise. bool Fit(const Point2dC &p1,const Point2dC &p2,const Point2dC &p3); //: Fit a circle through 3 points. // Returns false if the points are collinear. private: RealT ends[2]; }; } #endif
29.546875
92
0.639344
isuhao
052d23916e598beea6e6acdd623b7783544ded82
7,522
inl
C++
Jolt/Physics/Body/Body.inl
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
null
null
null
Jolt/Physics/Body/Body.inl
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
null
null
null
Jolt/Physics/Body/Body.inl
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
null
null
null
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #pragma once namespace JPH { Mat44 Body::GetWorldTransform() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read)); return Mat44::sRotationTranslation(mRotation, GetPosition()); } Mat44 Body::GetCenterOfMassTransform() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read)); return Mat44::sRotationTranslation(mRotation, mPosition); } Mat44 Body::GetInverseCenterOfMassTransform() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read)); return Mat44::sInverseRotationTranslation(mRotation, mPosition); } inline bool Body::sFindCollidingPairsCanCollide(const Body &inBody1, const Body &inBody2) { // One of these conditions must be true // - One of the bodies must be dynamic to collide // - A kinematic object can collide with a sensor if ((!inBody1.IsDynamic() && !inBody2.IsDynamic()) && !(inBody1.IsKinematic() && inBody2.IsSensor())) return false; // Check that body 1 is active uint32 body1_index_in_active_bodies = inBody1.GetIndexInActiveBodiesInternal(); JPH_ASSERT(!inBody1.IsStatic() && body1_index_in_active_bodies != Body::cInactiveIndex, "This function assumes that Body 1 is active"); // If the pair A, B collides we need to ensure that the pair B, A does not collide or else we will handle the collision twice. // If A is the same body as B we don't want to collide (1) // If A is dynamic and B is static we should collide (2) // If A is dynamic / kinematic and B is dynamic / kinematic we should only collide if (kinematic vs kinematic is ruled out by the if above) // - A is active and B is not yet active (3) // - A is active and B will become active during this simulation step (4) // - A is active and B is active, we require a condition that makes A, B collide and B, A not (5) // // In order to implement this we use the index in the active body list and make use of the fact that // a body not in the active list has Body.Index = 0xffffffff which is the highest possible value for an uint32. // // Because we know that A is active we know that A.Index != 0xffffffff: // (1) Because A.Index != 0xffffffff, if A.Index = B.Index then A = B, so to collide A.Index != B.Index // (2) A.Index != 0xffffffff, B.Index = 0xffffffff (because it's static and cannot be in the active list), so to collide A.Index != B.Index // (3) A.Index != 0xffffffff, B.Index = 0xffffffff (because it's not yet active), so to collide A.Index != B.Index // (4) A.Index != 0xffffffff, B.Index = 0xffffffff currently. But it can activate during the Broad/NarrowPhase step at which point it // will be added to the end of the active list which will make B.Index > A.Index (this holds only true when we don't deactivate // bodies during the Broad/NarrowPhase step), so to collide A.Index < B.Index. // (5) As tie breaker we can use the same condition A.Index < B.Index to collide, this means that if A, B collides then B, A won't static_assert(Body::cInactiveIndex == 0xffffffff, "The algorithm below uses this value"); if (body1_index_in_active_bodies >= inBody2.GetIndexInActiveBodiesInternal()) return false; JPH_ASSERT(inBody1.GetID() != inBody2.GetID(), "Read the comment above, A and B are the same body which should not be possible!"); // Bodies in the same group don't collide if (!inBody1.GetCollisionGroup().CanCollide(inBody2.GetCollisionGroup())) return false; return true; } void Body::AddRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite)); // This used to use the equation: d/dt R(t) = 1/2 * w(t) * R(t) so that R(t + dt) = R(t) + 1/2 * w(t) * R(t) * dt // See: Appendix B of An Introduction to Physically Based Modeling: Rigid Body Simulation II-Nonpenetration Constraints // URL: https://www.cs.cmu.edu/~baraff/sigcourse/notesd2.pdf // But this is a first order approximation and does not work well for kinematic ragdolls that are driven to a new // pose if the poses differ enough. So now we split w(t) * dt into an axis and angle part and create a quaternion with it. // Note that the resulting quaternion is normalized since otherwise numerical drift will eventually make the rotation non-normalized. float len = inAngularVelocityTimesDeltaTime.Length(); if (len > 1.0e-6f) { mRotation = (Quat::sRotation(inAngularVelocityTimesDeltaTime / len, len) * mRotation).Normalized(); JPH_ASSERT(!mRotation.IsNaN()); } } void Body::SubRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite)); // See comment at Body::AddRotationStep float len = inAngularVelocityTimesDeltaTime.Length(); if (len > 1.0e-6f) { mRotation = (Quat::sRotation(inAngularVelocityTimesDeltaTime / len, -len) * mRotation).Normalized(); JPH_ASSERT(!mRotation.IsNaN()); } } Vec3 Body::GetWorldSpaceSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inPosition) const { Mat44 inv_com = GetInverseCenterOfMassTransform(); return inv_com.Multiply3x3Transposed(mShape->GetSurfaceNormal(inSubShapeID, inv_com * inPosition)).Normalized(); } Mat44 Body::GetInverseInertia() const { JPH_ASSERT(IsDynamic()); return GetMotionProperties()->GetInverseInertiaForRotation(Mat44::sRotation(mRotation)); } void Body::AddForce(Vec3Arg inForce, Vec3Arg inPosition) { AddForce(inForce); AddTorque((inPosition - mPosition).Cross(inForce)); } void Body::AddImpulse(Vec3Arg inImpulse) { JPH_ASSERT(IsDynamic()); SetLinearVelocityClamped(mMotionProperties->GetLinearVelocity() + inImpulse * mMotionProperties->GetInverseMass()); } void Body::AddImpulse(Vec3Arg inImpulse, Vec3Arg inPosition) { JPH_ASSERT(IsDynamic()); SetLinearVelocityClamped(mMotionProperties->GetLinearVelocity() + inImpulse * mMotionProperties->GetInverseMass()); SetAngularVelocityClamped(mMotionProperties->GetAngularVelocity() + GetInverseInertia() * (inPosition - mPosition).Cross(inImpulse)); } void Body::AddAngularImpulse(Vec3Arg inAngularImpulse) { JPH_ASSERT(IsDynamic()); SetAngularVelocityClamped(mMotionProperties->GetAngularVelocity() + GetInverseInertia() * inAngularImpulse); } void Body::GetSleepTestPoints(Vec3 *outPoints) const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read)); // Center of mass is the first position outPoints[0] = mPosition; // The second and third position are on the largest axis of the bounding box Vec3 extent = mShape->GetLocalBounds().GetExtent(); int lowest_component = extent.GetLowestComponentIndex(); Mat44 rotation = Mat44::sRotation(mRotation); switch (lowest_component) { case 0: outPoints[1] = mPosition + extent.GetY() * rotation.GetColumn3(1); outPoints[2] = mPosition + extent.GetZ() * rotation.GetColumn3(2); break; case 1: outPoints[1] = mPosition + extent.GetX() * rotation.GetColumn3(0); outPoints[2] = mPosition + extent.GetZ() * rotation.GetColumn3(2); break; case 2: outPoints[1] = mPosition + extent.GetX() * rotation.GetColumn3(0); outPoints[2] = mPosition + extent.GetY() * rotation.GetColumn3(1); break; default: JPH_ASSERT(false); break; } } void Body::ResetSleepTestSpheres() { Vec3 points[3]; GetSleepTestPoints(points); mMotionProperties->ResetSleepTestSpheres(points); } } // JPH
40.224599
140
0.748072
All8Up
052e0076a749bff7e66e2f6740deccc5871819d3
2,981
cpp
C++
libs/TwoDLib/CSRAdapter.cpp
dekamps/miind
4b321c62c2bd27eb0d5d8336a16a9e840ba63856
[ "MIT" ]
13
2015-09-15T17:28:25.000Z
2022-03-22T20:26:47.000Z
libs/TwoDLib/CSRAdapter.cpp
dekamps/miind
4b321c62c2bd27eb0d5d8336a16a9e840ba63856
[ "MIT" ]
41
2015-08-25T07:50:55.000Z
2022-03-21T16:20:37.000Z
libs/TwoDLib/CSRAdapter.cpp
dekamps/miind
4b321c62c2bd27eb0d5d8336a16a9e840ba63856
[ "MIT" ]
9
2015-09-14T20:52:07.000Z
2022-03-08T12:18:18.000Z
// Copyright (c) 2005 - 2015 Marc de Kamps // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the 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 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 "CSRAdapter.hpp" #include "Euler.hpp" namespace { const MPILib::Time TOLERANCE = 1e-6; } using namespace TwoDLib; CSRAdapter::CSRAdapter ( Ode2DSystemGroup& group, const std::vector<TwoDLib::CSRMatrix>& vecmat, MPILib::Rate euler_timestep ): _group(group), _vec_csr_matrices(vecmat), _dydt(std::vector<MPILib::Mass>(group.Mass().size())), _euler_timestep(euler_timestep), _nr_iterations(this->NumberIterations()) { } void CSRAdapter::ClearDerivative() { TwoDLib::ClearDerivative(_dydt); } void CSRAdapter::CalculateDerivative ( const std::vector<MPILib::Rate>& vecrates ) { TwoDLib::CalculateDerivative ( _group, _dydt, _vec_csr_matrices, vecrates ); } MPILib::Number CSRAdapter::NumberIterations() const { MPILib::Time tstep = _group.MeshObjects()[0].TimeStep(); for ( const auto& mesh: _group.MeshObjects() ) if (std::abs((tstep - mesh.TimeStep())/mesh.TimeStep()) > TOLERANCE){ std::cerr << "Not all meshes in this group have the same time step. " << tstep << " " << mesh.TimeStep() << " " << tstep - mesh.TimeStep() << std::endl; exit(0); } MPILib::Number n_steps = static_cast<MPILib::Number>(std::round(tstep/_euler_timestep)); return n_steps; } void CSRAdapter::AddDerivative() { TwoDLib::AddDerivative ( _group.Mass(), _dydt, _euler_timestep ); }
36.353659
165
0.71788
dekamps
052f198e6637bc30eee8b06e9d73e0bf76f76519
1,058
cpp
C++
FeatureMatching/src/test.cpp
yubaoliu/Computer-Vision
2fe4d3e1db0a65ef8c9def5f84d5e494bec3faa9
[ "BSD-3-Clause" ]
null
null
null
FeatureMatching/src/test.cpp
yubaoliu/Computer-Vision
2fe4d3e1db0a65ef8c9def5f84d5e494bec3faa9
[ "BSD-3-Clause" ]
null
null
null
FeatureMatching/src/test.cpp
yubaoliu/Computer-Vision
2fe4d3e1db0a65ef8c9def5f84d5e494bec3faa9
[ "BSD-3-Clause" ]
null
null
null
#if 0 #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main(int argc, char** argv) { // Read source image. Mat im_src = imread("book2.jpg"); // Four corners of the book in source image vector<Point2f> pts_src; pts_src.push_back(Point2f(141, 131)); pts_src.push_back(Point2f(480, 159)); pts_src.push_back(Point2f(493, 630)); pts_src.push_back(Point2f(64, 601)); // Read destination image. Mat im_dst = imread("book1.jpg"); // Four corners of the book in destination image. vector<Point2f> pts_dst; pts_dst.push_back(Point2f(318, 256)); pts_dst.push_back(Point2f(534, 372)); pts_dst.push_back(Point2f(316, 670)); pts_dst.push_back(Point2f(73, 473)); // Calculate Homography Mat h = findHomography(pts_src, pts_dst); // Output image Mat im_out; // Warp source image to destination based on homography warpPerspective(im_src, im_out, h, im_dst.size()); // Display images imshow("Source Image", im_src); imshow("Destination Image", im_dst); imshow("Warped Source Image", im_out); waitKey(0); } #endif
24.045455
56
0.721172
yubaoliu
05354fa0a9663a8df41bc2d9162fe388f2c40333
11,402
cpp
C++
simulator/dummy_perception_publisher/src/pointcloud_creator.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
simulator/dummy_perception_publisher/src/pointcloud_creator.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
simulator/dummy_perception_publisher/src/pointcloud_creator.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "dummy_perception_publisher/node.hpp" #include "dummy_perception_publisher/signed_distance_function.hpp" #include <pcl/impl/point_types.hpp> #include <pcl/filters/voxel_grid_occlusion_estimation.h> #include <tf2/LinearMath/Transform.h> #include <tf2/LinearMath/Vector3.h> #include <functional> #include <limits> #include <memory> namespace { static constexpr double epsilon = 0.001; static constexpr double step = 0.05; static constexpr double vertical_theta_step = (1.0 / 180.0) * M_PI; static constexpr double vertical_min_theta = (-15.0 / 180.0) * M_PI; static constexpr double vertical_max_theta = (15.0 / 180.0) * M_PI; static constexpr double horizontal_theta_step = (0.1 / 180.0) * M_PI; static constexpr double horizontal_min_theta = (-180.0 / 180.0) * M_PI; static constexpr double horizontal_max_theta = (180.0 / 180.0) * M_PI; pcl::PointXYZ getPointWrtBaseLink( const tf2::Transform & tf_base_link2moved_object, double x, double y, double z) { const auto p_wrt_base = tf_base_link2moved_object(tf2::Vector3(x, y, z)); return pcl::PointXYZ(p_wrt_base.x(), p_wrt_base.y(), p_wrt_base.z()); } } // namespace void ObjectCentricPointCloudCreator::create_object_pointcloud( const ObjectInfo & obj_info, const tf2::Transform & tf_base_link2map, std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud) const { std::normal_distribution<> x_random(0.0, obj_info.std_dev_x); std::normal_distribution<> y_random(0.0, obj_info.std_dev_y); std::normal_distribution<> z_random(0.0, obj_info.std_dev_z); const auto tf_base_link2moved_object = tf_base_link2map * obj_info.tf_map2moved_object; const double min_z = -1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); const double max_z = 1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); pcl::PointCloud<pcl::PointXYZ> horizontal_candidate_pointcloud; pcl::PointCloud<pcl::PointXYZ> horizontal_pointcloud; { const double y = -1.0 * (obj_info.width / 2.0); for (double x = -1.0 * (obj_info.length / 2.0); x <= ((obj_info.length / 2.0) + epsilon); x += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } { const double y = 1.0 * (obj_info.width / 2.0); for (double x = -1.0 * (obj_info.length / 2.0); x <= ((obj_info.length / 2.0) + epsilon); x += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } { const double x = -1.0 * (obj_info.length / 2.0); for (double y = -1.0 * (obj_info.width / 2.0); y <= ((obj_info.width / 2.0) + epsilon); y += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } { const double x = 1.0 * (obj_info.length / 2.0); for (double y = -1.0 * (obj_info.width / 2.0); y <= ((obj_info.width / 2.0) + epsilon); y += step) { horizontal_candidate_pointcloud.push_back( getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0)); } } // 2D ray tracing size_t ranges_size = std::ceil((horizontal_max_theta - horizontal_min_theta) / horizontal_theta_step); std::vector<double> horizontal_ray_traced_2d_pointcloud; horizontal_ray_traced_2d_pointcloud.assign(ranges_size, std::numeric_limits<double>::infinity()); const int no_data = -1; std::vector<int> horizontal_ray_traced_pointcloud_indices; horizontal_ray_traced_pointcloud_indices.assign(ranges_size, no_data); for (size_t i = 0; i < horizontal_candidate_pointcloud.points.size(); ++i) { double angle = std::atan2(horizontal_candidate_pointcloud.at(i).y, horizontal_candidate_pointcloud.at(i).x); double range = std::hypot(horizontal_candidate_pointcloud.at(i).y, horizontal_candidate_pointcloud.at(i).x); if (angle < horizontal_min_theta || angle > horizontal_max_theta) { continue; } int index = (angle - horizontal_min_theta) / horizontal_theta_step; if (range < horizontal_ray_traced_2d_pointcloud[index]) { horizontal_ray_traced_2d_pointcloud[index] = range; horizontal_ray_traced_pointcloud_indices.at(index) = i; } } for (const auto & pointcloud_index : horizontal_ray_traced_pointcloud_indices) { if (pointcloud_index != no_data) { // generate vertical point horizontal_pointcloud.push_back(horizontal_candidate_pointcloud.at(pointcloud_index)); const double distance = std::hypot( horizontal_candidate_pointcloud.at(pointcloud_index).x, horizontal_candidate_pointcloud.at(pointcloud_index).y); for (double vertical_theta = vertical_min_theta; vertical_theta <= vertical_max_theta + epsilon; vertical_theta += vertical_theta_step) { const double z = distance * std::tan(vertical_theta); if (min_z <= z && z <= max_z + epsilon) { pcl::PointXYZ point; point.x = horizontal_candidate_pointcloud.at(pointcloud_index).x + x_random(random_generator); point.y = horizontal_candidate_pointcloud.at(pointcloud_index).y + y_random(random_generator); point.z = z + z_random(random_generator); pointcloud->push_back(point); } } } } } std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> ObjectCentricPointCloudCreator::create_pointclouds( const std::vector<ObjectInfo> & obj_infos, const tf2::Transform & tf_base_link2map, std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr & merged_pointcloud) const { std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds_tmp; pcl::PointCloud<pcl::PointXYZ>::Ptr merged_pointcloud_tmp(new pcl::PointCloud<pcl::PointXYZ>); for (const auto & obj_info : obj_infos) { pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_shared_ptr(new pcl::PointCloud<pcl::PointXYZ>); this->create_object_pointcloud( obj_info, tf_base_link2map, random_generator, pointcloud_shared_ptr); pointclouds_tmp.push_back(pointcloud_shared_ptr); } for (const auto & cloud : pointclouds_tmp) { for (const auto & pt : *cloud) { merged_pointcloud_tmp->push_back(pt); } } if (!enable_ray_tracing_) { merged_pointcloud = merged_pointcloud_tmp; return pointclouds_tmp; } pcl::PointCloud<pcl::PointXYZ>::Ptr ray_traced_merged_pointcloud_ptr( new pcl::PointCloud<pcl::PointXYZ>); pcl::VoxelGridOcclusionEstimation<pcl::PointXYZ> ray_tracing_filter; ray_tracing_filter.setInputCloud(merged_pointcloud_tmp); ray_tracing_filter.setLeafSize(0.25, 0.25, 0.25); ray_tracing_filter.initializeVoxelGrid(); std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds; for (size_t i = 0; i < pointclouds_tmp.size(); ++i) { pcl::PointCloud<pcl::PointXYZ>::Ptr ray_traced_pointcloud_ptr( new pcl::PointCloud<pcl::PointXYZ>); for (size_t j = 0; j < pointclouds_tmp.at(i)->size(); ++j) { Eigen::Vector3i grid_coordinates = ray_tracing_filter.getGridCoordinates( pointclouds_tmp.at(i)->at(j).x, pointclouds_tmp.at(i)->at(j).y, pointclouds_tmp.at(i)->at(j).z); int grid_state; if (ray_tracing_filter.occlusionEstimation(grid_state, grid_coordinates) != 0) { RCLCPP_ERROR(rclcpp::get_logger("dummy_perception_publisher"), "ray tracing failed"); } if (grid_state == 1) { // occluded continue; } else { // not occluded ray_traced_pointcloud_ptr->push_back(pointclouds_tmp.at(i)->at(j)); ray_traced_merged_pointcloud_ptr->push_back(pointclouds_tmp.at(i)->at(j)); } } pointclouds.push_back(ray_traced_pointcloud_ptr); } merged_pointcloud = ray_traced_merged_pointcloud_ptr; return pointclouds; } std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> EgoCentricPointCloudCreator::create_pointclouds( const std::vector<ObjectInfo> & obj_infos, const tf2::Transform & tf_base_link2map, std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr & merged_pointcloud) const { std::vector<std::shared_ptr<signed_distance_function::AbstractSignedDistanceFunction>> sdf_ptrs; for (const auto & obj_info : obj_infos) { const auto sdf_ptr = std::make_shared<signed_distance_function::BoxSDF>( obj_info.length, obj_info.width, tf_base_link2map * obj_info.tf_map2moved_object); sdf_ptrs.push_back(sdf_ptr); } const auto composite_sdf = signed_distance_function::CompositeSDF(sdf_ptrs); std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds(obj_infos.size()); for (size_t i = 0; i < obj_infos.size(); ++i) { pointclouds.at(i) = (pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>)); } std::vector<double> min_zs(obj_infos.size()); std::vector<double> max_zs(obj_infos.size()); for (size_t idx = 0; idx < obj_infos.size(); ++idx) { const auto & obj_info = obj_infos.at(idx); const auto tf_base_link2moved_object = tf_base_link2map * obj_info.tf_map2moved_object; const double min_z = -1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); const double max_z = 1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z(); min_zs.at(idx) = min_z; max_zs.at(idx) = max_z; } double angle = 0.0; const auto n_scan = static_cast<size_t>(std::floor(2 * M_PI / horizontal_theta_step)); for (size_t i = 0; i < n_scan; ++i) { angle += horizontal_theta_step; const auto dist = composite_sdf.getSphereTracingDist(0.0, 0.0, angle, visible_range_); if (std::isfinite(dist)) { const auto x_hit = dist * cos(angle); const auto y_hit = dist * sin(angle); const auto idx_hit = composite_sdf.nearest_sdf_index(x_hit, y_hit); const auto obj_info_here = obj_infos.at(idx_hit); const auto min_z_here = min_zs.at(idx_hit); const auto max_z_here = max_zs.at(idx_hit); std::normal_distribution<> x_random(0.0, obj_info_here.std_dev_x); std::normal_distribution<> y_random(0.0, obj_info_here.std_dev_y); std::normal_distribution<> z_random(0.0, obj_info_here.std_dev_z); for (double vertical_theta = vertical_min_theta; vertical_theta <= vertical_max_theta + epsilon; vertical_theta += vertical_theta_step) { const double z = dist * std::tan(vertical_theta); if (min_z_here <= z && z <= max_z_here + epsilon) { pointclouds.at(idx_hit)->push_back(pcl::PointXYZ( x_hit + x_random(random_generator), y_hit + y_random(random_generator), z + z_random(random_generator))); } } } } for (const auto & cloud : pointclouds) { for (const auto & pt : *cloud) { merged_pointcloud->push_back(pt); } } return pointclouds; }
43.353612
100
0.70628
meliketanrikulu
0536d938a6384b5a1119f032f2d0c84c64fd1773
1,581
hpp
C++
common/log.hpp
NematodCorp/Nematod
a81ad34ce957b12df1308c8c5111b0497084236b
[ "MIT" ]
3
2018-11-05T19:49:48.000Z
2018-11-10T18:03:22.000Z
common/log.hpp
NematodCorp/Nematod
a81ad34ce957b12df1308c8c5111b0497084236b
[ "MIT" ]
1
2018-11-10T19:00:24.000Z
2018-11-11T18:49:46.000Z
common/log.hpp
NematodCorp/Nematod
a81ad34ce957b12df1308c8c5111b0497084236b
[ "MIT" ]
1
2018-11-06T00:09:57.000Z
2018-11-06T00:09:57.000Z
#include <string> #include <iostream> #pragma once enum log_level {DEBUG = 0, INFO, WARNING, ERROR, LogLevelMax}; class Loggeable { public: void mute() {m_mute = true;}; void unmute() {m_mute = false;}; void filter(log_level min_lvl) {m_min_lvl = min_lvl;}; void prefix(std::string prefix) {m_prefix = std::move(prefix);}; template<typename... T> void log(log_level lvl, const char* fmt, T ... args) { if(lvl >= m_min_lvl && !m_mute) { *out_streams[lvl] << m_prefix; // don't store on the stack; no need to be reentrant and allows coroutines to have a tiny stack static char buff[2048]; std::snprintf(&buff[0], 2048, fmt, args...); // No buffer overflow there, sir ! *out_streams[lvl] << &buff[0]; } }; bool m_mute = false; log_level m_min_lvl = INFO; std::string m_prefix; std::ostream* out_streams[LogLevelMax] = { &std::clog, // DEBUG &std::cout, // INFO &std::cerr, // WARNING &std::cerr // ERROR }; }; inline Loggeable global_logger; template<typename... T> void log(log_level lvl, const char* fmt, T ... args) { global_logger.log(lvl, fmt, args...); } template<typename... T> void info(const char* fmt, T ... args) { global_logger.log(INFO, fmt, args...); } template<typename... T> void warn(const char* fmt, T ... args) { global_logger.log(WARNING, fmt, args...); } template<typename... T> void error(const char* fmt, T ... args) { global_logger.log(ERROR, fmt, args...); }
23.954545
108
0.595193
NematodCorp
053716be9aa19f62334322f7af88470a0a12524b
1,652
cc
C++
pdb/src/logicalPlan/source/LogicalPlan.cc
SeraphL/plinycompute
7788bc2b01d83f4ff579c13441d0ba90734b54a2
[ "Apache-2.0" ]
3
2019-05-04T05:17:30.000Z
2020-02-21T05:01:59.000Z
pdb/src/logicalPlan/source/LogicalPlan.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
3
2020-02-20T19:50:46.000Z
2020-06-25T14:31:51.000Z
pdb/src/logicalPlan/source/LogicalPlan.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
5
2019-02-19T23:17:24.000Z
2020-08-03T01:08:04.000Z
#include <LogicalPlan.h> #include <Lexer.h> #include <Parser.h> namespace pdb { LogicalPlan::LogicalPlan(const std::string &tcap, Vector<Handle<Computation>> &computations) { init(tcap, computations); } LogicalPlan::LogicalPlan(AtomicComputationList &computationsIn, pdb::Vector<pdb::Handle<pdb::Computation>> &allComputations) { init(computationsIn, allComputations); } void LogicalPlan::init(AtomicComputationList &computationsIn, pdb::Vector<pdb::Handle<pdb::Computation>> &allComputations) { computations = computationsIn; for (int i = 0; i < allComputations.size(); i++) { std::string compType = allComputations[i]->getComputationType(); compType += "_"; compType += std::to_string(i); pdb::ComputationNode temp(allComputations[i]); allConstituentComputations[compType] = temp; } } void LogicalPlan::init(const std::string &tcap, Vector<Handle<Computation>> &allComputations) { // get the string to compile std::string myLogicalPlan = tcap; myLogicalPlan.push_back('\0'); // where the result of the parse goes AtomicComputationList *myResult; // now, do the compilation yyscan_t scanner; LexerExtra extra{""}; yylex_init_extra(&extra, &scanner); const YY_BUFFER_STATE buffer{yy_scan_string(myLogicalPlan.data(), scanner)}; const int parseFailed{yyparse(scanner, &myResult)}; yy_delete_buffer(buffer, scanner); yylex_destroy(scanner); // if it didn't parse, get outta here if (parseFailed) { std::cout << "Parse error when compiling TCAP: " << extra.errorMessage; exit(1); } // copy all the computations init(*myResult, allComputations); delete myResult; } }
28.982456
126
0.72276
SeraphL
053722816d009703675ddb3e5da7403ebdba18f9
10,027
cpp
C++
Point_set_processing_3/test/Point_set_processing_3/read_test_with_different_pmaps.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Point_set_processing_3/test/Point_set_processing_3/read_test_with_different_pmaps.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Point_set_processing_3/test/Point_set_processing_3/read_test_with_different_pmaps.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <CGAL/Simple_cartesian.h> #include <CGAL/IO/read_points.h> #include <CGAL/property_map.h> #include <vector> #include <deque> #include <iostream> #include <fstream> typedef CGAL::Simple_cartesian<double> Kernel; typedef Kernel::Point_3 Point_3; typedef Kernel::Vector_3 Vector_3; typedef std::pair<Point_3, Vector_3> PointVectorPair; // this is going to be custom OutputIterator value_type struct dummy_counter { static std::size_t counter; dummy_counter() { ++counter; } operator std::size_t() { return counter-1; } }; std::size_t dummy_counter::counter = 0; bool check_points_and_vectors( const boost::vector_property_map<Point_3>& points, const boost::vector_property_map<Vector_3>& normals, const std::vector<PointVectorPair>& pv_pairs, const std::vector<std::size_t>& indices) { if(pv_pairs.size() != indices.size()) { std::cerr << "Error: inconsistency between point / normal size." << std::endl; return false; } for(std::size_t i = 0; i < pv_pairs.size(); ++i ) { if(pv_pairs[i].first != points[i]) { std::cerr << "Error: points are not equal." << std::endl; return false; } if(pv_pairs[i].second != normals[i]) { std::cerr << "Error: normals are not equal." << std::endl; return false; } } return true; } bool check_points( const boost::vector_property_map<Point_3>& points_1, const std::vector<Point_3>& points_2, const std::vector<std::size_t>& indices) { if(points_2.size() != indices.size()) { std::cerr << "Error: inconsistency between point / normal size." << std::endl; return false; } for(std::size_t i = 0; i < points_2.size(); ++i ) { if(points_2[i] != points_1[i]) { std::cerr << "Error: points are not equal." << std::endl; return false; } } return true; } bool test_no_deduction_points_and_normals_xyz(const std::string file_name) { boost::vector_property_map<Point_3> points; boost::vector_property_map<Vector_3> normals; std::vector<std::size_t> indices; std::vector<PointVectorPair> pv_pairs; // read with custom output iterator type dummy_counter::counter = 0; std::ifstream input(file_name); CGAL::IO::read_XYZ<dummy_counter>( input, back_inserter(indices), CGAL::parameters::point_map (points). normal_map (normals). geom_traits (Kernel())); // read with ordinary pmaps input.clear(); input.close(); input.open(file_name); CGAL::IO::read_XYZ( input, back_inserter(pv_pairs), CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()). normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()). geom_traits(Kernel())); return check_points_and_vectors(points, normals, pv_pairs, indices); } bool test_no_deduction_points_and_normals_off(const std::string file_name) { boost::vector_property_map<Point_3> points; boost::vector_property_map<Vector_3> normals; std::vector<std::size_t> indices; std::vector<PointVectorPair> pv_pairs; // read with custom output iterator type dummy_counter::counter = 0; std::ifstream input(file_name); CGAL::IO::read_OFF<dummy_counter>( input, back_inserter(indices), CGAL::parameters::point_map(points). normal_map(normals). geom_traits(Kernel())); // read with ordinary pmaps input.clear(); input.close(); input.open(file_name); CGAL::IO::read_OFF( input, back_inserter(pv_pairs), CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()). normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()). geom_traits(Kernel())); return check_points_and_vectors(points, normals, pv_pairs, indices); } bool test_no_deduction_points_xyz(const std::string file_name) { boost::vector_property_map<Point_3> points_1; \ std::vector<std::size_t> indices; std::vector<Point_3> points_2; // read with custom output iterator type dummy_counter::counter = 0; std::ifstream input(file_name); CGAL::IO::read_XYZ<dummy_counter>( input, back_inserter(indices), CGAL::parameters::point_map(points_1).geom_traits(Kernel())); // read with ordinary pmaps input.clear(); input.close(); input.open(file_name); CGAL::IO::read_XYZ( input, back_inserter(points_2), CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()). geom_traits(Kernel())); return check_points(points_1, points_2, indices); } bool test_no_deduction_points_off(const std::string file_name) { boost::vector_property_map<Point_3> points_1; std::vector<std::size_t> indices; std::vector<Point_3> points_2; // read with custom output iterator type dummy_counter::counter = 0; std::ifstream input(file_name); CGAL::IO::read_OFF<dummy_counter>( input, back_inserter(indices), CGAL::parameters::point_map(points_1). geom_traits(Kernel())); // read with ordinary pmaps input.clear(); input.close(); input.open(file_name); CGAL::IO::read_OFF( input, back_inserter(points_2), CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()). geom_traits(Kernel())); return check_points(points_1, points_2, indices); } void compile_test() { std::deque<Point_3> points; std::deque<Vector_3> normals; std::deque<PointVectorPair> pv_pairs; std::ifstream input; input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ( input, std::front_inserter(points)); input.clear(); input.close(); input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ( input, std::front_inserter(points), CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>())); input.clear(); input.close(); input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ( input, std::front_inserter(points), CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()). geom_traits(Kernel())); input.clear(); input.close(); // this will span all OutputIteratorValueType versions input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ<Point_3>( input, std::front_inserter(points)); input.clear(); input.close(); //----------------------------------------------------------------------- input.open("data/read_test/simple.off"); CGAL::IO::read_OFF( input, std::front_inserter(points)); input.clear(); input.close(); input.open("data/read_test/simple.off"); CGAL::IO::read_OFF( input, std::front_inserter(points), CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>())); input.clear(); input.close(); input.open("data/read_test/simple.off"); CGAL::IO::read_OFF( input, std::front_inserter(points), CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()). geom_traits(Kernel())); input.clear(); input.close(); // this will span all OutputIteratorValueType versions input.open("data/read_test/simple.off"); CGAL::IO::read_OFF<Point_3>( input, std::front_inserter(points)); input.clear(); input.close(); //----------------------------------------------------------------------- input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ( input, std::front_inserter(points), CGAL::parameters::normal_map(boost::dummy_property_map())); input.clear(); input.close(); input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ( input, std::front_inserter(pv_pairs), CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()). normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>())); input.clear(); input.close(); input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ( input, std::front_inserter(pv_pairs), CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()). normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()). geom_traits(Kernel())); input.clear(); input.close(); input.open("data/read_test/simple.xyz"); CGAL::IO::read_XYZ<Point_3>( input, std::front_inserter(points), CGAL::parameters::normal_map(boost::dummy_property_map())); input.clear(); input.close(); //----------------------------------------------------------------------- input.open("data/read_test/simple.off"); CGAL::IO::read_OFF( input, std::front_inserter(points), CGAL::parameters::normal_map(boost::dummy_property_map())); input.clear(); input.close(); input.open("data/read_test/simple.off"); CGAL::IO::read_OFF( input, std::front_inserter(pv_pairs), CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()). normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>())); input.clear(); input.close(); input.open("data/read_test/simple.off"); CGAL::IO::read_OFF( input, std::front_inserter(pv_pairs), CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()). normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()). geom_traits(Kernel())); input.clear(); input.close(); input.open("data/read_test/simple.off"); CGAL::IO::read_OFF<Point_3>( input, std::front_inserter(points), CGAL::parameters::normal_map(boost::dummy_property_map())); input.clear(); input.close(); } int main() { if(!test_no_deduction_points_and_normals_xyz("data/read_test/simple.xyz")) { return EXIT_FAILURE; } std::cerr << "test_no_deduction_points_and_normals_xyz OK." << std::endl; if(!test_no_deduction_points_and_normals_off("data/read_test/simple.off")) { return EXIT_FAILURE; } std::cerr << "test_no_deduction_points_and_normals_off OK." << std::endl; if(!test_no_deduction_points_xyz("data/read_test/simple.xyz")) { return EXIT_FAILURE; } std::cerr << "test_no_deduction_points_xyz OK." << std::endl; if(!test_no_deduction_points_off("data/read_test/simple.off")) { return EXIT_FAILURE; } std::cerr << "test_no_deduction_points_off OK." << std::endl; compile_test(); return EXIT_SUCCESS; }
28.896254
85
0.686846
ffteja
0539cedc2e509117633d4bb921f4e907502f5c00
7,143
cpp
C++
src/GSvar/DBTableWidget.cpp
imgag/ngs-bits
c0c6ff7d9d8324fffca78e162ce1181b20eefb39
[ "MIT" ]
85
2016-04-26T17:24:20.000Z
2022-03-11T12:33:39.000Z
src/GSvar/DBTableWidget.cpp
imgag/ngs-bits
c0c6ff7d9d8324fffca78e162ce1181b20eefb39
[ "MIT" ]
104
2016-08-09T22:18:32.000Z
2022-03-31T12:39:12.000Z
src/GSvar/DBTableWidget.cpp
imgag/ngs-bits
c0c6ff7d9d8324fffca78e162ce1181b20eefb39
[ "MIT" ]
28
2016-05-10T14:34:20.000Z
2021-10-14T07:22:39.000Z
#include "DBTableWidget.h" #include "Exceptions.h" #include "GUIHelper.h" #include <QHeaderView> #include <QAction> #include <QApplication> #include <QClipboard> #include <QKeyEvent> DBTableWidget::DBTableWidget(QWidget* parent) : QTableWidget(parent) { //general settings verticalHeader()->setVisible(false); setSelectionMode(QAbstractItemView::ExtendedSelection); setSelectionBehavior(QAbstractItemView::SelectRows); setWordWrap(false); connect(this, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(processDoubleClick(int, int))); //context menu setContextMenuPolicy(Qt::ActionsContextMenu); QAction* copy_action = new QAction(QIcon(":/Icons/CopyClipboard.png"), "Copy selection", this); addAction(copy_action); connect(copy_action, SIGNAL(triggered(bool)), this, SLOT(copySelectionToClipboard())); copy_action = new QAction(QIcon(":/Icons/CopyClipboard.png"), "Copy all", this); addAction(copy_action); connect(copy_action, SIGNAL(triggered(bool)), this, SLOT(copyTableToClipboard())); } void DBTableWidget::setData(const DBTable& table, int max_col_width) { QStringList headers = table.headers(); //table table_ = table.tableName(); //resize clearContents(); setRowCount(table.rowCount()); setColumnCount(headers.count()); //headers for(int c=0; c<headers.count(); ++c) { setHorizontalHeaderItem(c, GUIHelper::createTableItem(headers[c], Qt::AlignCenter)); } //content ids_.clear(); for(int r=0; r<table.rowCount(); ++r) { const DBRow& row = table.row(r); ids_ <<row.id(); for(int c=0; c<headers.count(); ++c) { setItem(r, c, GUIHelper::createTableItem(row.value(c))); } } //fomatting GUIHelper::resizeTableCells(this, max_col_width); } int DBTableWidget::columnIndex(const QString& column_header) const { for (int c=0; c<columnCount(); ++c) { if (horizontalHeaderItem(c)->text()==column_header) { return c; } } THROW(ArgumentException, "Could not find column with header '" + column_header + "'"); } QString DBTableWidget::columnHeader(int index) const { if (index<0 || index>=columnCount()) { THROW(ArgumentException, "Invalid column index " + QString::number(index) + ". The table has " + QString::number(columnCount()) + " columns!"); } return horizontalHeaderItem(index)->text(); } void DBTableWidget::setQualityIcons(const QString& column_header, const QStringList& quality_values) { //check if (quality_values.count()!=rowCount()) { THROW(ArgumentException, "Invalid quality value count '" + QString::number(quality_values.count()) + "' in DBTableWidget::setQualityIcons - expected '" + QString::number(rowCount()) + "'!"); } int c = columnIndex(column_header); for(int r=0; r<rowCount(); ++r) { QTableWidgetItem* table_item = item(r, c); if (table_item==nullptr) continue; const QString& quality = quality_values[r]; styleQuality(table_item, quality); } setColumnWidth(c, columnWidth(c) + 25); } void DBTableWidget::setColumnTooltips(const QString& column_header, const QStringList& tooltips) { if (tooltips.count()!=rowCount()) { THROW(ArgumentException, "Invalid tooltip count '" + QString::number(tooltips.count()) + "' in DBTableWidget::setColumnTooltips - expected '" + QString::number(rowCount()) + "'!"); } int c = columnIndex(column_header); for(int r=0; r<rowCount(); ++r) { QTableWidgetItem* table_item = item(r, c); if (table_item==nullptr) continue; table_item->setToolTip(tooltips[r]); } } void DBTableWidget::setColumnColors(const QString& column_header, const QList<QColor>& colors) { if (colors.count()!=rowCount()) { THROW(ArgumentException, "Invalid color count '" + QString::number(colors.count()) + "' in DBTableWidget::setColumnColors - expected '" + QString::number(rowCount()) + "'!"); } int c = columnIndex(column_header); for (int r=0; r<rowCount(); ++r) { const QColor& color = colors[r]; if (!color.isValid()) continue; QTableWidgetItem* table_item = item(r, c); if (table_item==nullptr) continue; table_item->setBackgroundColor(color); } } void DBTableWidget::setBackgroundColorIfContains(const QString& column_header, const QColor& color, const QString& substring) { setBackgroundColorIf(column_header, color, [substring](const QString& str) { return str.contains(substring); }); } void DBTableWidget::setBackgroundColorIfEqual(const QString& column_header, const QColor& color, const QString& text) { setBackgroundColorIf(column_header, color, [text](const QString& str) { return str==text; }); } void DBTableWidget::setBackgroundColorIfLt(const QString& column_header, const QColor& color, double cutoff) { setBackgroundColorIf(column_header, color, [cutoff](const QString& str) { bool ok; double value = str.toDouble(&ok); if (!ok) return false; return value<cutoff; }); } void DBTableWidget::setBackgroundColorIfGt(const QString& column_header, const QColor& color, double cutoff) { setBackgroundColorIf(column_header, color, [cutoff](const QString& str) { bool ok; double value = str.toDouble(&ok); if (!ok) return false; return value>cutoff; }); } void DBTableWidget::showTextAsTooltip(const QString& column_header) { int c = columnIndex(column_header); for (int r=0; r<rowCount(); ++r) { QTableWidgetItem* table_item = item(r, c); if (table_item==nullptr) continue; table_item->setToolTip(table_item->text()); } } QSet<int> DBTableWidget::selectedRows() const { QSet<int> output; foreach(const QTableWidgetSelectionRange& range, selectedRanges()) { for (int row=range.topRow(); row<=range.bottomRow(); ++row) { output << row; } } return output; } QSet<int> DBTableWidget::selectedColumns() const { QSet<int> output; foreach(const QTableWidgetSelectionRange& range, selectedRanges()) { for (int col=range.leftColumn(); col<=range.rightColumn(); ++col) { output << col; } } return output; } const QString& DBTableWidget::getId(int r) const { if (r<0 || r>=rowCount()) { THROW(ArgumentException, "Invalid row index '" + QString::number(r) + "' in DBTableWidget::getId!"); } return ids_[r]; } const QString& DBTableWidget::tableName() const { return table_; } void DBTableWidget::styleQuality(QTableWidgetItem* item, const QString& quality) { //init static QIcon i_good = QIcon(":/Icons/quality_good.png"); static QIcon i_medium = QIcon(":/Icons/quality_medium.png"); static QIcon i_bad = QIcon(":/Icons/quality_bad.png"); static QIcon i_na = QIcon(":/Icons/quality_unset.png"); //icon if (quality=="good") item->setIcon(i_good); else if (quality=="medium") item->setIcon(i_medium); else if (quality=="bad") item->setIcon(i_bad); else item->setIcon(i_na); //tooltip item->setToolTip(quality); } void DBTableWidget::keyPressEvent(QKeyEvent* event) { if(event->matches(QKeySequence::Copy)) { copySelectionToClipboard(); event->accept(); return; } QTableWidget::keyPressEvent(event); } void DBTableWidget::copySelectionToClipboard() { GUIHelper::copyToClipboard(this, true); } void DBTableWidget::copyTableToClipboard() { GUIHelper::copyToClipboard(this, false); } void DBTableWidget::processDoubleClick(int row, int /*column*/) { emit rowDoubleClicked(row); }
26.752809
192
0.718886
imgag
053c2d811dfd686c00564d58c6632bc76de66a0c
3,218
cpp
C++
src/xpcc/ui/display/image/skull_64x64.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
161
2015-01-13T15:52:06.000Z
2020-02-13T01:26:04.000Z
src/xpcc/ui/display/image/skull_64x64.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
281
2015-01-06T12:46:40.000Z
2019-01-06T13:06:57.000Z
src/xpcc/ui/display/image/skull_64x64.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
51
2015-03-03T19:56:12.000Z
2020-03-22T02:13:36.000Z
#include <xpcc/architecture/driver/accessor.hpp> namespace bitmap { FLASH_STORAGE(uint8_t skull_64x64[]) = { 64, 64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe0, 0x60, 0x30, 0x18, 0x08, 0x0c, 0x0c, 0x04, 0x06, 0x06, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x06, 0x06, 0x04, 0x0c, 0x0c, 0x18, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3e, 0x07, 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x03, 0x0f, 0x7c, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xf0, 0x80, 0x03, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x03, 0x80, 0xf0, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0x40, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x0e, 0xfc, 0x7f, 0x00, 0x00, 0x3e, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x3c, 0x00, 0x00, 0x7f, 0xfc, 0x0e, 0x07, 0x01, 0x00, 0x00, 0x00, 0x80, 0x80, 0xc0, 0x80, 0x80, 0x00, 0x00, 0x00, 0xf0, 0xb8, 0x9e, 0x8f, 0x80, 0x80, 0x80, 0x83, 0x07, 0x0c, 0x18, 0x18, 0x30, 0x30, 0x60, 0x6f, 0xfc, 0xf0, 0xe0, 0xc0, 0xc0, 0xc1, 0xc1, 0x83, 0x03, 0x01, 0x00, 0x00, 0x00, 0xfc, 0xfe, 0xff, 0x00, 0xff, 0xfe, 0xf8, 0x00, 0x00, 0x00, 0x01, 0x03, 0x83, 0x81, 0xc1, 0xc0, 0xe0, 0xe0, 0xf0, 0xfc, 0xcf, 0x40, 0x60, 0x30, 0x10, 0x1c, 0x0e, 0x03, 0x01, 0x00, 0x01, 0x1f, 0x30, 0x60, 0xc0, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x06, 0x04, 0x0c, 0x0c, 0x18, 0x18, 0x30, 0x30, 0x63, 0xff, 0x31, 0x0d, 0xe3, 0x0f, 0x5c, 0xf0, 0x90, 0xf0, 0x11, 0xe1, 0x20, 0xe0, 0x10, 0xf1, 0x11, 0xf0, 0x90, 0x90, 0xdc, 0x0f, 0xf1, 0x0f, 0xf9, 0xff, 0xc7, 0x61, 0x61, 0x30, 0x30, 0x18, 0x18, 0x0c, 0x04, 0x06, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xb0, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x18, 0x08, 0x0c, 0x0c, 0x86, 0xc2, 0xc3, 0x6f, 0x7e, 0x70, 0xc1, 0x83, 0x82, 0x07, 0x04, 0x07, 0x08, 0x0f, 0x09, 0x0f, 0x09, 0x0f, 0x09, 0x05, 0x04, 0x05, 0x82, 0xc3, 0xe0, 0x70, 0x7f, 0x6f, 0xc6, 0xcc, 0x8c, 0x08, 0x18, 0x10, 0x30, 0x20, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x7e, 0x60, 0x40, 0x60, 0x30, 0x1c, 0x06, 0x02, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x02, 0x02, 0x02, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x02, 0x06, 0x1c, 0x30, 0x60, 0x40, 0x60, 0x3c, 0x06, 0x03, 0x01, 0x00, 0x00, 0x00, }; }
160.9
385
0.664388
walmis
053fcca323c4447ee6623674f58cb92f9d4915c3
36,384
cc
C++
L1Trigger/GlobalTriggerAnalyzer/src/L1RetrieveL1Extra.cc
malbouis/cmssw
16173a30d3f0c9ecc5419c474bb4d272c58b65c8
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1Trigger/GlobalTriggerAnalyzer/src/L1RetrieveL1Extra.cc
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1Trigger/GlobalTriggerAnalyzer/src/L1RetrieveL1Extra.cc
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** * \class L1RetrieveL1Extra * * * Description: retrieve L1Extra collection, return validity flag and pointer to collection. * * Implementation: * <TODO: enter implementation details> * * \author: Vasile Mihai Ghete - HEPHY Vienna * * */ // this class header #include "L1Trigger/GlobalTriggerAnalyzer/interface/L1RetrieveL1Extra.h" // system include files #include <iostream> #include <memory> #include <string> // user include files #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" // constructor L1RetrieveL1Extra::L1RetrieveL1Extra(const edm::ParameterSet& paramSet, edm::ConsumesCollector&& iC) : // m_tagL1ExtraMuon(paramSet.getParameter<edm::InputTag>("TagL1ExtraMuon")), m_tagL1ExtraIsoEG(paramSet.getParameter<edm::InputTag>("TagL1ExtraIsoEG")), m_tagL1ExtraNoIsoEG(paramSet.getParameter<edm::InputTag>("TagL1ExtraNoIsoEG")), m_tagL1ExtraCenJet(paramSet.getParameter<edm::InputTag>("TagL1ExtraCenJet")), m_tagL1ExtraForJet(paramSet.getParameter<edm::InputTag>("TagL1ExtraForJet")), m_tagL1ExtraTauJet(paramSet.getParameter<edm::InputTag>("TagL1ExtraTauJet")), m_tagL1ExtraEtMissMET(paramSet.getParameter<edm::InputTag>("TagL1ExtraEtMissMET")), m_tagL1ExtraEtMissHTM(paramSet.getParameter<edm::InputTag>("TagL1ExtraEtMissHTM")), m_tagL1ExtraHFRings(paramSet.getParameter<edm::InputTag>("TagL1ExtraHFRings")), // // m_validL1ExtraMuon(false), m_validL1ExtraIsoEG(false), m_validL1ExtraNoIsoEG(false), m_validL1ExtraCenJet(false), m_validL1ExtraForJet(false), m_validL1ExtraTauJet(false), m_validL1ExtraETT(false), m_validL1ExtraETM(false), m_validL1ExtraHTT(false), m_validL1ExtraHTM(false), m_validL1ExtraHfBitCounts(false), m_validL1ExtraHfRingEtSums(false), // m_l1ExtraMuon(nullptr), m_l1ExtraIsoEG(nullptr), m_l1ExtraNoIsoEG(nullptr), m_l1ExtraCenJet(nullptr), m_l1ExtraForJet(nullptr), m_l1ExtraTauJet(nullptr), m_l1ExtraETT(nullptr), m_l1ExtraETM(nullptr), m_l1ExtraHTT(nullptr), m_l1ExtraHTM(nullptr), m_l1ExtraHfBitCounts(nullptr), m_l1ExtraHfRingEtSums(nullptr) // { m_tagL1ExtraMuonTok = iC.consumes<l1extra::L1MuonParticleCollection>(m_tagL1ExtraMuon); m_tagL1ExtraIsoEGTok = iC.consumes<l1extra::L1EmParticleCollection>(m_tagL1ExtraIsoEG); m_tagL1ExtraNoIsoEGTok = iC.consumes<l1extra::L1EmParticleCollection>(m_tagL1ExtraNoIsoEG); m_tagL1ExtraCenJetTok = iC.consumes<l1extra::L1JetParticleCollection>(m_tagL1ExtraCenJet); m_tagL1ExtraForJetTok = iC.consumes<l1extra::L1JetParticleCollection>(m_tagL1ExtraForJet); m_tagL1ExtraTauJetTok = iC.consumes<l1extra::L1JetParticleCollection>(m_tagL1ExtraTauJet); m_tagL1ExtraEtMissMETTok = iC.consumes<l1extra::L1EtMissParticleCollection>(m_tagL1ExtraEtMissMET); m_tagL1ExtraEtMissHTMTok = iC.consumes<l1extra::L1EtMissParticleCollection>(m_tagL1ExtraEtMissHTM); m_tagL1ExtraHFRingsTok = iC.consumes<l1extra::L1HFRingsCollection>(m_tagL1ExtraHFRings); // empty } // destructor L1RetrieveL1Extra::~L1RetrieveL1Extra() { // empty } void L1RetrieveL1Extra::retrieveL1ExtraObjects(const edm::Event& iEvent, const edm::EventSetup& evSetup) { // edm::Handle<l1extra::L1MuonParticleCollection> collL1ExtraMuon; iEvent.getByToken(m_tagL1ExtraMuonTok, collL1ExtraMuon); if (collL1ExtraMuon.isValid()) { m_validL1ExtraMuon = true; m_l1ExtraMuon = collL1ExtraMuon.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1MuonParticleCollection with input tag \n " << m_tagL1ExtraMuon << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraMuon = false; m_l1ExtraMuon = nullptr; } // edm::Handle<l1extra::L1EmParticleCollection> collL1ExtraIsoEG; iEvent.getByToken(m_tagL1ExtraIsoEGTok, collL1ExtraIsoEG); if (collL1ExtraIsoEG.isValid()) { m_validL1ExtraIsoEG = true; m_l1ExtraIsoEG = collL1ExtraIsoEG.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EmParticleCollection with input tag \n " << m_tagL1ExtraIsoEG << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraIsoEG = false; m_l1ExtraIsoEG = nullptr; } edm::Handle<l1extra::L1EmParticleCollection> collL1ExtraNoIsoEG; iEvent.getByToken(m_tagL1ExtraNoIsoEGTok, collL1ExtraNoIsoEG); if (collL1ExtraNoIsoEG.isValid()) { m_validL1ExtraNoIsoEG = true; m_l1ExtraNoIsoEG = collL1ExtraNoIsoEG.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EmParticleCollection with input tag \n " << m_tagL1ExtraNoIsoEG << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraNoIsoEG = false; m_l1ExtraNoIsoEG = nullptr; } // edm::Handle<l1extra::L1JetParticleCollection> collL1ExtraCenJet; iEvent.getByToken(m_tagL1ExtraCenJetTok, collL1ExtraCenJet); if (collL1ExtraCenJet.isValid()) { m_validL1ExtraCenJet = true; m_l1ExtraCenJet = collL1ExtraCenJet.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1JetParticleCollection with input tag \n " << m_tagL1ExtraCenJet << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraCenJet = false; m_l1ExtraCenJet = nullptr; } edm::Handle<l1extra::L1JetParticleCollection> collL1ExtraForJet; iEvent.getByToken(m_tagL1ExtraForJetTok, collL1ExtraForJet); if (collL1ExtraForJet.isValid()) { m_validL1ExtraForJet = true; m_l1ExtraForJet = collL1ExtraForJet.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1JetParticleCollection with input tag \n " << m_tagL1ExtraForJet << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraForJet = false; m_l1ExtraForJet = nullptr; } edm::Handle<l1extra::L1JetParticleCollection> collL1ExtraTauJet; iEvent.getByToken(m_tagL1ExtraTauJetTok, collL1ExtraTauJet); if (collL1ExtraTauJet.isValid()) { m_validL1ExtraTauJet = true; m_l1ExtraTauJet = collL1ExtraTauJet.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1JetParticleCollection with input tag \n " << m_tagL1ExtraTauJet << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraTauJet = false; m_l1ExtraTauJet = nullptr; } // edm::Handle<l1extra::L1EtMissParticleCollection> collL1ExtraEtMissMET; iEvent.getByToken(m_tagL1ExtraEtMissMETTok, collL1ExtraEtMissMET); if (collL1ExtraEtMissMET.isValid()) { m_validL1ExtraETT = true; m_validL1ExtraETM = true; m_l1ExtraETT = collL1ExtraEtMissMET.product(); m_l1ExtraETM = collL1ExtraEtMissMET.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EtMissParticleCollection with input tag \n " << m_tagL1ExtraEtMissMET << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraETT = false; m_validL1ExtraETM = false; m_l1ExtraETT = nullptr; m_l1ExtraETM = nullptr; } edm::Handle<l1extra::L1EtMissParticleCollection> collL1ExtraEtMissHTM; iEvent.getByToken(m_tagL1ExtraEtMissHTMTok, collL1ExtraEtMissHTM); if (collL1ExtraEtMissHTM.isValid()) { m_validL1ExtraHTT = true; m_validL1ExtraHTM = true; m_l1ExtraHTT = collL1ExtraEtMissHTM.product(); m_l1ExtraHTM = collL1ExtraEtMissHTM.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EtMissParticleCollection with input tag \n " << m_tagL1ExtraEtMissHTM << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraHTT = false; m_validL1ExtraHTM = false; m_l1ExtraHTT = nullptr; m_l1ExtraHTM = nullptr; } // edm::Handle<l1extra::L1HFRingsCollection> collL1ExtraHFRings; iEvent.getByToken(m_tagL1ExtraHFRingsTok, collL1ExtraHFRings); if (collL1ExtraHFRings.isValid()) { m_validL1ExtraHfBitCounts = true; m_validL1ExtraHfRingEtSums = true; m_l1ExtraHfBitCounts = collL1ExtraHFRings.product(); m_l1ExtraHfRingEtSums = collL1ExtraHFRings.product(); } else { LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1HFRingsCollection with input tag \n " << m_tagL1ExtraHFRings << "\n not found in the event.\n" << "\n Return pointer 0 and false validity tag." << std::endl; m_validL1ExtraHfBitCounts = false; m_validL1ExtraHfRingEtSums = false; m_l1ExtraHfBitCounts = nullptr; m_l1ExtraHfRingEtSums = nullptr; } } /// input tag for a given collection const edm::InputTag L1RetrieveL1Extra::inputTagL1ExtraColl(const L1GtObject& gtObject) const { edm::InputTag emptyInputTag; switch (gtObject) { case Mu: { return m_tagL1ExtraMuon; } break; case NoIsoEG: { return m_tagL1ExtraNoIsoEG; } break; case IsoEG: { return m_tagL1ExtraIsoEG; } break; case CenJet: { return m_tagL1ExtraCenJet; } break; case ForJet: { return m_tagL1ExtraForJet; } break; case TauJet: { return m_tagL1ExtraTauJet; } break; case ETM: case ETT: { return m_tagL1ExtraEtMissMET; } break; case HTT: case HTM: { return m_tagL1ExtraEtMissHTM; } break; case JetCounts: { // TODO update when JetCounts will be available return emptyInputTag; } break; case HfBitCounts: case HfRingEtSums: { return m_tagL1ExtraHFRings; } break; case TechTrig: { return emptyInputTag; } break; case Castor: { return emptyInputTag; } break; case BPTX: { return emptyInputTag; } break; case GtExternal: { return emptyInputTag; } break; case ObjNull: { return emptyInputTag; } break; default: { edm::LogInfo("L1GtObject") << "\n '" << gtObject << "' is not a recognized L1GtObject. "; return emptyInputTag; } break; } return emptyInputTag; } const bool L1RetrieveL1Extra::validL1ExtraColl(const L1GtObject& gtObject) const { switch (gtObject) { case Mu: { return m_validL1ExtraMuon; } break; case NoIsoEG: { return m_validL1ExtraNoIsoEG; } break; case IsoEG: { return m_validL1ExtraIsoEG; } break; case CenJet: { return m_validL1ExtraCenJet; } break; case ForJet: { return m_validL1ExtraForJet; } break; case TauJet: { return m_validL1ExtraTauJet; } break; case ETM: { return m_validL1ExtraETM; } break; case ETT: { return m_validL1ExtraETT; } break; case HTT: { return m_validL1ExtraHTT; } break; case HTM: { return m_validL1ExtraHTM; } break; case JetCounts: { // TODO update when JetCounts will be available return false; } break; case HfBitCounts: { return m_validL1ExtraHfBitCounts; } break; case HfRingEtSums: { return m_validL1ExtraHfRingEtSums; } break; case TechTrig: { return false; } break; case Castor: { return false; } break; case BPTX: { return false; } break; case GtExternal: { return false; } break; case ObjNull: { return false; } break; default: { edm::LogInfo("L1GtObject") << "\n '" << gtObject << "' is not a recognized L1GtObject. "; return false; } break; } return false; } void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr, const L1GtObject& gtObject, const bool checkBxInEvent, const int bxInEvent, const bool checkObjIndexInColl, const int objIndexInColl) const { if (!validL1ExtraColl(gtObject)) { oStr << "\n L1Extra collection for L1 GT object " << l1GtObjectEnumToString(gtObject) << " with collection input tag " << inputTagL1ExtraColl(gtObject) << " not valid." << std::endl; } switch (gtObject) { case Mu: { oStr << "\n Mu collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1MuonParticleCollection::const_iterator iterColl = m_l1ExtraMuon->begin(); iterColl != m_l1ExtraMuon->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " PT = " << std::right << std::setw(6) << (iterColl->pt()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " PT = " << std::right << std::setw(6) << (iterColl->pt()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " PT = " << std::right << std::setw(6) << (iterColl->pt()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case NoIsoEG: { oStr << "\n NoIsoEG collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1EmParticleCollection::const_iterator iterColl = m_l1ExtraNoIsoEG->begin(); iterColl != m_l1ExtraNoIsoEG->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case IsoEG: { oStr << "\n IsoEG collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1EmParticleCollection::const_iterator iterColl = m_l1ExtraIsoEG->begin(); iterColl != m_l1ExtraIsoEG->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case CenJet: { oStr << "\n CenJet collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1JetParticleCollection::const_iterator iterColl = m_l1ExtraCenJet->begin(); iterColl != m_l1ExtraCenJet->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case ForJet: { oStr << "\n ForJet collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1JetParticleCollection::const_iterator iterColl = m_l1ExtraForJet->begin(); iterColl != m_l1ExtraForJet->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case TauJet: { oStr << "\n TauJet collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1JetParticleCollection::const_iterator iterColl = m_l1ExtraTauJet->begin(); iterColl != m_l1ExtraTauJet->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case ETM: { oStr << "\n ETM collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraETM->begin(); iterColl != m_l1ExtraETM->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case ETT: { oStr << "\n ETT collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraETT->begin(); iterColl != m_l1ExtraETT->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl; } } } break; case HTT: { oStr << "\n HTT collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraHTT->begin(); iterColl != m_l1ExtraHTT->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl; } } } break; case HTM: { oStr << "\n HTM collection\n" << std::endl; int indexInColl = -1; for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraHTM->begin(); iterColl != m_l1ExtraHTM->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { indexInColl++; if (!checkObjIndexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } else { if (objIndexInColl == indexInColl) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } } else { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV" << " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl; } } } break; case JetCounts: { // TODO print if and when JetCounts will be available } break; case HfBitCounts: { oStr << "\n HfBitCounts collection\n" << std::endl; for (l1extra::L1HFRingsCollection::const_iterator iterColl = m_l1ExtraHfBitCounts->begin(); iterColl != m_l1ExtraHfBitCounts->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { if (!checkObjIndexInColl) { for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount << " HF counts = " << (iterColl->hfBitCount((l1extra::L1HFRings::HFRingLabels)iCount)) << std::endl; } } else { for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) { if (objIndexInColl == iCount) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount << " HF counts = " << (iterColl->hfBitCount((l1extra::L1HFRings::HFRingLabels)iCount)) << std::endl; } } } } } else { for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) { if (objIndexInColl == iCount) { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " count = " << iCount << " HF counts = " << (iterColl->hfBitCount((l1extra::L1HFRings::HFRingLabels)iCount)) << std::endl; } } } } } break; case HfRingEtSums: { oStr << "\n HfRingEtSums collection\n" << std::endl; for (l1extra::L1HFRingsCollection::const_iterator iterColl = m_l1ExtraHfRingEtSums->begin(); iterColl != m_l1ExtraHfRingEtSums->end(); ++iterColl) { if (checkBxInEvent) { if (iterColl->bx() != bxInEvent) { continue; oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl; } else { if (!checkObjIndexInColl) { for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount << " HF ET sum = " << (iterColl->hfEtSum((l1extra::L1HFRings::HFRingLabels)iCount)) << " GeV" << std::endl; } } else { for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) { if (objIndexInColl == iCount) { oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount << " HF ET sum = " << (iterColl->hfEtSum((l1extra::L1HFRings::HFRingLabels)iCount)) << " GeV" << std::endl; } } } } } else { for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) { if (objIndexInColl == iCount) { oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " count = " << iCount << " HF ET sum = " << (iterColl->hfEtSum((l1extra::L1HFRings::HFRingLabels)iCount)) << " GeV" << std::endl; } } } } } break; case TechTrig: { // do nothing, not in L1Extra } break; case Castor: { // do nothing, not in L1Extra } break; case BPTX: { // do nothing, not in L1Extra } break; case GtExternal: { // do nothing, not in L1Extra } break; case ObjNull: { // do nothing, not in L1Extra } break; default: { edm::LogInfo("L1GtObject") << "\n '" << gtObject << "' is not a recognized L1GtObject. "; // do nothing } break; } } void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr, const L1GtObject& gtObject, const int bxInEvent) const { bool checkBxInEvent = true; bool checkObjIndexInColl = false; int objIndexInColl = -1; printL1Extra(oStr, gtObject, checkBxInEvent, bxInEvent, checkObjIndexInColl, objIndexInColl); } void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr, const L1GtObject& gtObject) const { bool checkBxInEvent = false; bool checkObjIndexInColl = false; int bxInEvent = 999; int objIndexInColl = -1; printL1Extra(oStr, gtObject, checkBxInEvent, bxInEvent, checkObjIndexInColl, objIndexInColl); } void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr, const int iBxInEvent) const { printL1Extra(oStr, Mu, iBxInEvent); printL1Extra(oStr, NoIsoEG, iBxInEvent); printL1Extra(oStr, IsoEG, iBxInEvent); printL1Extra(oStr, CenJet, iBxInEvent); printL1Extra(oStr, ForJet, iBxInEvent); printL1Extra(oStr, TauJet, iBxInEvent); printL1Extra(oStr, ETM, iBxInEvent); printL1Extra(oStr, ETT, iBxInEvent); printL1Extra(oStr, HTT, iBxInEvent); printL1Extra(oStr, HTM, iBxInEvent); // printL1Extra(oStr, JetCounts, iBxInEvent); printL1Extra(oStr, HfBitCounts, iBxInEvent); printL1Extra(oStr, HfRingEtSums, iBxInEvent); } void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr) const { printL1Extra(oStr, Mu); printL1Extra(oStr, NoIsoEG); printL1Extra(oStr, IsoEG); printL1Extra(oStr, CenJet); printL1Extra(oStr, ForJet); printL1Extra(oStr, TauJet); printL1Extra(oStr, ETM); printL1Extra(oStr, ETT); printL1Extra(oStr, HTT); printL1Extra(oStr, HTM); // printL1Extra(oStr, JetCounts); printL1Extra(oStr, HfBitCounts); printL1Extra(oStr, HfRingEtSums); }
38.138365
120
0.529491
malbouis
053fe1de8b7fab54dc2d72ddab913bb93f94350e
1,093
cpp
C++
Sid's Levels/Level - 3/Strings/Print Zig Zag.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 3/Strings/Print Zig Zag.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 3/Strings/Print Zig Zag.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: string convert(string s, int n) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA if(n == 0 || n == 1) return s; string res; for(int i = 1; i <= n; i++) { int j = i-1; char dir = 'd'; while(j < s.length()) { if(i == 1 || i == n) { res.push_back(s[j]); j += (2*n - 2); } else { if(dir == 'd') { res.push_back(s[j]); j += 2*(n - i); dir = 'u'; } else { res.push_back(s[j]); j += 2*(i-1); dir = 'd'; } } } } return res; } };
26.02381
73
0.270814
Tiger-Team-01
0541a6396de3e6c962f643736055c56af454f607
697
cpp
C++
solutions/1519.number-of-nodes-in-the-sub-tree-with-the-same-label.368499531.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/1519.number-of-nodes-in-the-sub-tree-with-the-same-label.368499531.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/1519.number-of-nodes-in-the-sub-tree-with-the-same-label.368499531.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: vector<int> countSubTrees(int n, vector<vector<int>> &edges, string labels) { vector<vector<int>> g(n); for (auto &v : edges) { g[v[0]].push_back(v[1]); g[v[1]].push_back(v[0]); } vector<int> ans(n); dfs(ans, g, labels); return ans; } vector<int> dfs(vector<int> &ans, vector<vector<int>> &g, string &labels, int i = 0, int parent = -1) { vector<int> temp(26); for (int j : g[i]) { if (j == parent) continue; auto temp2 = dfs(ans, g, labels, j, i); for (int i = 0; i < 26; i++) temp[i] += temp2[i]; } ans[i] = ++temp[labels[i] - 'a']; return temp; } };
23.233333
79
0.503587
satu0king
0545631a19f54567eaa05572e446c7537b19479c
1,257
cxx
C++
Code/Common/itkVersion.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
1
2018-04-15T13:32:43.000Z
2018-04-15T13:32:43.000Z
Code/Common/itkVersion.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
Code/Common/itkVersion.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkVersion.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkVersion.h" namespace itk { Version::Version() { } Version::~Version() { } const char * Version::GetITKVersion() { return ITK_VERSION; } int Version::GetITKMajorVersion() { return ITK_VERSION_MAJOR; } int Version::GetITKMinorVersion() { return ITK_VERSION_MINOR; } int Version::GetITKBuildVersion() { return ITK_VERSION_PATCH; } const char * Version::GetITKSourceVersion() { return ITK_SOURCE_VERSION; } } // end namespace itk
19.640625
78
0.645982
kiranhs
054627523bd8bbc1ec171e158df0b12656096828
1,071
cpp
C++
SWUST OJ/0275.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
SWUST OJ/0275.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
SWUST OJ/0275.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
//Author:LanceYu #include<iostream> #include<string> #include<cstring> #include<cstdio> #include<fstream> #include<iosfwd> #include<sstream> #include<fstream> #include<cwchar> #include<iomanip> #include<ostream> #include<vector> #include<cstdlib> #include<queue> #include<set> #include<ctime> #include<algorithm> #include<complex> #include<cmath> #include<valarray> #include<bitset> #include<iterator> #define ll long long using namespace std; const double clf=1e-8; //const double e=2.718281828; const double PI=3.141592653589793; const int MMAX=2147483647; const int mod=1e9+7; //priority_queue<int>p; //priority_queue<int,vector<int>,greater<int> >pq; int main() { int n,book[12]={31,28,31,30,31,30,31,31,30,31,30,31}; int d,h,m,month; while(scanf("%d",&n)!=EOF) { d=1;h=0;m=0;month=1; while(n>=86400) { n-=86400; d++; } while(n>=3600) { n-=3600; h++; } while(n>=60) { n-=60; m++; } while(d>book[month-1]) { d-=book[month-1]; month++; } printf("2009-%02d-%02d %02d:%02d:%02d\n",month,d,h,m,n); } return 0; }
16.227273
58
0.656396
windcry1
0546b851cff43d48229d17b30e9a59085ce670de
7,264
c++
C++
mvcutil/ModelView.c++
kevinbajaj/Computer-Graphics
93c4fa9062249711e86b621728599846f7d2b80b
[ "MIT" ]
null
null
null
mvcutil/ModelView.c++
kevinbajaj/Computer-Graphics
93c4fa9062249711e86b621728599846f7d2b80b
[ "MIT" ]
null
null
null
mvcutil/ModelView.c++
kevinbajaj/Computer-Graphics
93c4fa9062249711e86b621728599846f7d2b80b
[ "MIT" ]
null
null
null
// ModelView.c++ - an Abstract Base Class for a combined Model and View for OpenGL #include <iostream> #include "ModelView.h" #include "Controller.h" cryph::AffPoint ModelView::eye(0, 0, 2); cryph::AffPoint ModelView::center(0, 0, 0); cryph::AffVector ModelView::up(0, 1, 0); double ModelView::mcRegionOfInterest[6] = { -1.0, 1.0, -1.0, 1.0, -1.0, 1.0 }; ProjectionType ModelView::projType = PERSPECTIVE; cryph::AffVector ModelView::obliqueProjectionDir(0.25, 0.5, 1.0); double ModelView::ecZmin = -2.0; double ModelView::ecZmax = -0.01; // for perspective, must be strictly < 0 double ModelView::zpp = -1.0; // for perspective, must be strictly < 0 double ModelView::dynamic_zoomScale = 1.0; // dynamic zoom cryph::Matrix4x4 ModelView::dynamic_view; // dynamic 3D rotation/pan ModelView::ModelView() { } ModelView::~ModelView() { } #if 0 void ModelView::addToGlobalRotationDegrees(double rx, double ry, double rz) { // TODO: 1. UPDATE dynamic_view // TODO: 2. Use dynamic_view in ModelView::getMatrices } #endif void ModelView::addToGlobalZoom(double increment) { dynamic_zoomScale += increment; // TODO: Use dynamic_zoomScale in ModelView::getMatrices } // compute2DScaleTrans determines the current model coordinate region of // interest and then uses linearMap to determine how to map coordinates // in the region of interest to their proper location in Logical Device // Space. (Returns float[] because glUniform currently favors float[].) void ModelView::compute2DScaleTrans(float* scaleTransF) // CLASS METHOD { double xmin = mcRegionOfInterest[0]; double xmax = mcRegionOfInterest[1]; double ymin = mcRegionOfInterest[2]; double ymax = mcRegionOfInterest[3]; // preserve aspect ratio. Make "region of interest" wider or taller to // match the Controller's viewport aspect ratio. double vAR = Controller::getCurrentController()->getViewportAspectRatio(); matchAspectRatio(xmin, xmax, ymin, ymax, vAR); double scaleTrans[4]; linearMap(xmin, xmax, -1.0, 1.0, scaleTrans[0], scaleTrans[1]); linearMap(ymin, ymax, -1.0, 1.0, scaleTrans[2], scaleTrans[3]); for (int i=0 ; i<4 ; i++) scaleTransF[i] = static_cast<float>(scaleTrans[i]); } #if 0 void ModelView::getMatrices(cryph::Matrix4x4& mc_ec, cryph::Matrix4x4& ec_lds) { // TODO: // 1. Create the mc_ec matrix: // Matrix M_ECu is created from the eye, center, and up. You can use the // following utility from Matrix4x4: // // cryph::Matrix4x4 cryph::Matrix4x4::lookAt( // const cryph::AffPoint& eye, const cryph::AffPoint& center, // const cryph::AffVector& up); // // NOTE: eye, center, and up are specified in MODEL COORDINATES (MC) // // So, for example: // cryph::Matrix4x4 M_ECu = cryph::Matrix4x4::lookAt(eye, center, up); // // a) For project 2: mc_ec = M_ECu // b) For project 3: mc_ec = dynamic_view * M_ECu // // 2. Create the ec_lds matrix: // Using the WIDTHS of the established mcRegionOfInterest: // i) Adjust in the x OR y direction to match the viewport aspect ratio; // ii) Scale both widths by dynamic_zoom; // iii) create the matrix using the method for the desired type of projection. // // Any of the three Matrix4x4 methods shown below (declared in Matrix4x4.h) // can be used to create ec_lds. On a given call to this "getMatrices" routine, // you will use EXACTLY ONE of them, depending on what type of projection you // currently want. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!! All coordinate data in the parameter lists below are specified !!!!!! // !!!!! in EYE COORDINATES (EC)! Be VERY sure you understand what that !!!!!! // !!!!! means! (This is why I emphasized "WIDTHS" above.) !!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /* The three choices: cryph::Matrix4x4 cryph::Matrix4x4::orthogonal(double ecXmin, double ecXmax, double ecYmin, double ecYmax, double ecZmin, double ecZmax); cryph::Matrix4x4 cryph::Matrix4x4::perspective(double zpp, double ecXmin, double ecXmax, double ecYmin, double ecYmax, double ecZmin, double ecZmax); cryph::Matrix4x4 cryph::Matrix4x4::oblique(double zpp, double ecXmin, double ecXmax, double ecYmin, double ecYmax, double ecZmin, double ecZmax, const cryph::AffVector& projDir); */ // For example: // ec_lds = cryph::Matrix4x4::perspective(zpp, ecXmin, ecXmax, ecYmin, ecYmax, ecZmin, ecZmax); // // RECALL: Use the class variables ecZmin, ecZmax, and zpp in these calls. // THEN IN THE CALLER OF THIS METHOD: // // float mat[16]; // glUniformMatrix4fv(ppuLoc_mc_ec, 1, false, mc_ec.extractColMajor(mat)); // glUniformMatrix4fv(ppuLoc_ec_lds, 1, false, ec_lds.extractColMajor(mat)); // // (The extractColMajor method copies the elements of the matrix into the given // array which is assumed to be of length 16. It then returns the array pointer // so it can be used as indicated in the two calls. Since the array is immediately // copied by glUniformMatrix to the GPU, "mat" can be reused as indicated.) } #endif // linearMap determines the scale and translate parameters needed in // order to map a value, f (fromMin <= f <= fromMax) to its corresponding // value, t (toMin <= t <= toMax). Specifically: t = scale*f + trans. void ModelView::linearMap(double fromMin, double fromMax, double toMin, double toMax, double& scale, double& trans) // CLASS METHOD { scale = (toMax - toMin) / (fromMax - fromMin); trans = toMin - scale*fromMin; } void ModelView::matchAspectRatio(double& xmin, double& xmax, double& ymin, double& ymax, double vAR) { double wHeight = ymax - ymin; double wWidth = xmax - xmin; double wAR = wHeight / wWidth; if (wAR > vAR) { // make window wider wWidth = wHeight / vAR; double xmid = 0.5 * (xmin + xmax); xmin = xmid - 0.5*wWidth; xmax = xmid + 0.5*wWidth; } else { // make window taller wHeight = wWidth * vAR; double ymid = 0.5 * (ymin + ymax); ymin = ymid - 0.5*wHeight; ymax = ymid + 0.5*wHeight; } } GLint ModelView::ppUniformLocation(GLuint glslProgram, const std::string& name) { GLint loc = glGetUniformLocation(glslProgram, name.c_str()); if (loc < 0) std::cerr << "Could not locate per-primitive uniform: '" << name << "'\n"; return loc; } GLint ModelView::pvAttribLocation(GLuint glslProgram, const std::string& name) { GLint loc = glGetAttribLocation(glslProgram, name.c_str()); if (loc < 0) std::cerr << "Could not locate per-vertex attribute: '" << name << "'\n"; return loc; } void ModelView::setECZminZmax(double zMinIn, double zMaxIn) { ecZmin = zMinIn; ecZmax = zMaxIn; } void ModelView::setEyeCenterUp(cryph::AffPoint E, cryph::AffPoint C, cryph::AffVector Up) { eye = E; center = C; up = Up; } void ModelView::setMCRegionOfInterest(double xyz[6]) { for (int i=0 ; i<6 ; i++) mcRegionOfInterest[i] = xyz[i]; } void ModelView::setProjection(ProjectionType pType) { projType = pType; } void ModelView::setProjectionPlaneZ(double zppIn) { zpp = zppIn; }
33.62963
96
0.664372
kevinbajaj
d72c143415fdfdece9ba1ed5b038a340b8a934fa
3,263
cpp
C++
src/app/decorations/qgsdecorationlayoutextentdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/app/decorations/qgsdecorationlayoutextentdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/app/decorations/qgsdecorationlayoutextentdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsdecorationlayoutextentdialog.cpp ---------------------------- begin : May 2017 copyright : (C) 2017 by Nyall Dawson email : nyall dot dawson at gmail dot com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsdecorationlayoutextentdialog.h" #include "qgsdecorationlayoutextent.h" #include "qgslogger.h" #include "qgshelp.h" #include "qgsstyle.h" #include "qgssymbol.h" #include "qgssymbolselectordialog.h" #include "qgisapp.h" #include "qgsguiutils.h" #include "qgssettings.h" #include "qgstextformatwidget.h" #include "qgsgui.h" QgsDecorationLayoutExtentDialog::QgsDecorationLayoutExtentDialog( QgsDecorationLayoutExtent &deco, QWidget *parent ) : QDialog( parent ) , mDeco( deco ) { setupUi( this ); QgsGui::enableAutoGeometryRestore( this ); connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsDecorationLayoutExtentDialog::buttonBox_accepted ); connect( buttonBox, &QDialogButtonBox::rejected, this, &QgsDecorationLayoutExtentDialog::buttonBox_rejected ); mSymbolButton->setSymbolType( QgsSymbol::Fill ); updateGuiElements(); connect( buttonBox->button( QDialogButtonBox::Apply ), &QAbstractButton::clicked, this, &QgsDecorationLayoutExtentDialog::apply ); connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsDecorationLayoutExtentDialog::showHelp ); mSymbolButton->setMapCanvas( QgisApp::instance()->mapCanvas() ); mSymbolButton->setMessageBar( QgisApp::instance()->messageBar() ); } void QgsDecorationLayoutExtentDialog::updateGuiElements() { grpEnable->setChecked( mDeco.enabled() ); mSymbolButton->setSymbol( mDeco.symbol()->clone() ); mButtonFontStyle->setTextFormat( mDeco.textFormat() ); mCheckBoxLabelExtents->setChecked( mDeco.labelExtents() ); } void QgsDecorationLayoutExtentDialog::updateDecoFromGui() { mDeco.setEnabled( grpEnable->isChecked() ); mDeco.setSymbol( mSymbolButton->clonedSymbol< QgsFillSymbol >() ); mDeco.setTextFormat( mButtonFontStyle->textFormat() ); mDeco.setLabelExtents( mCheckBoxLabelExtents->isChecked() ); } void QgsDecorationLayoutExtentDialog::buttonBox_accepted() { apply(); accept(); } void QgsDecorationLayoutExtentDialog::apply() { updateDecoFromGui(); mDeco.update(); } void QgsDecorationLayoutExtentDialog::buttonBox_rejected() { reject(); } void QgsDecorationLayoutExtentDialog::showHelp() { QgsHelp::openHelp( QStringLiteral( "introduction/general_tools.html#decorations" ) ); }
35.857143
132
0.616917
dyna-mis
d72d3816f06b7a338593573a0828983531085e4e
6,849
cpp
C++
graph/graph.cpp
RapidsAtHKUST/ContinuousSubgraphMatching
f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5
[ "MIT" ]
null
null
null
graph/graph.cpp
RapidsAtHKUST/ContinuousSubgraphMatching
f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5
[ "MIT" ]
null
null
null
graph/graph.cpp
RapidsAtHKUST/ContinuousSubgraphMatching
f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5
[ "MIT" ]
null
null
null
#include <algorithm> #include <fstream> #include <iostream> #include <queue> #include <sstream> #include <tuple> #include <vector> #include "utils/types.h" #include "utils/utils.h" #include "graph/graph.h" Graph::Graph() : edge_count_(0) , vlabel_count_(0) , elabel_count_(0) , neighbors_{} , elabels_{} , updates_{} , vlabels_{} {} void Graph::AddVertex(uint id, uint label) { if (id >= vlabels_.size()) { vlabels_.resize(id + 1, NOT_EXIST); vlabels_[id] = label; neighbors_.resize(id + 1); elabels_.resize(id + 1); } else if (vlabels_[id] == NOT_EXIST) { vlabels_[id] = label; } vlabel_count_ = std::max(vlabel_count_, label + 1); // print graph /*std::cout << "labels: "; for (uint i = 0; i < vlabels_.size(); i++) { std::cout << i << ":" << vlabels_[i] << " ("; for (uint j = 0; j < neighbors_[i].size(); j++) { std::cout << neighbors_[i][j] << ":" << elabels_[i][j] << " "; } std::cout << ")" << std::endl; }*/ } void Graph::RemoveVertex(uint id) { vlabels_[id] = NOT_EXIST; neighbors_[id].clear(); elabels_[id].clear(); } void Graph::AddEdge(uint v1, uint v2, uint label) { auto lower = std::lower_bound(neighbors_[v1].begin(), neighbors_[v1].end(), v2); if (lower != neighbors_[v1].end() && *lower == v2) return; size_t dis = std::distance(neighbors_[v1].begin(), lower); neighbors_[v1].insert(lower, v2); elabels_[v1].insert(elabels_[v1].begin() + dis, label); lower = std::lower_bound(neighbors_[v2].begin(), neighbors_[v2].end(), v1); dis = std::distance(neighbors_[v2].begin(), lower); neighbors_[v2].insert(lower, v1); elabels_[v2].insert(elabels_[v2].begin() + dis, label); edge_count_++; elabel_count_ = std::max(elabel_count_, label + 1); // print graph /*std::cout << "labels: "; for (uint i = 0; i < vlabels_.size(); i++) { std::cout << i << ":" << vlabels_[i] << " ("; for (uint j = 0; j < neighbors_[i].size(); j++) { std::cout << neighbors_[i][j] << ":" << elabels_[i][j] << " "; } std::cout << ")" << std::endl; }*/ } void Graph::RemoveEdge(uint v1, uint v2) { auto lower = std::lower_bound(neighbors_[v1].begin(), neighbors_[v1].end(), v2); if (lower == neighbors_[v1].end() || *lower != v2) { std::cout << "deletion error" << std::endl; exit(-1); } neighbors_[v1].erase(lower); elabels_[v1].erase(elabels_[v1].begin() + std::distance(neighbors_[v1].begin(), lower)); lower = std::lower_bound(neighbors_[v2].begin(), neighbors_[v2].end(), v1); if (lower == neighbors_[v2].end() || *lower != v1) { std::cout << "deletion error" << std::endl; exit(-1); } neighbors_[v2].erase(lower); elabels_[v2].erase(elabels_[v2].begin() + std::distance(neighbors_[v2].begin(), lower)); edge_count_--; } uint Graph::GetVertexLabel(uint u) const { return vlabels_[u]; } const std::vector<uint>& Graph::GetNeighbors(uint v) const { return neighbors_[v]; } const std::vector<uint>& Graph::GetNeighborLabels(uint v) const { return elabels_[v]; } std::tuple<uint, uint, uint> Graph::GetEdgeLabel(uint v1, uint v2) const { uint v1_label, v2_label, e_label; v1_label = GetVertexLabel(v1); v2_label = GetVertexLabel(v2); const std::vector<uint> *nbrs; const std::vector<uint> *elabel; uint other; if (GetDegree(v1) < GetDegree(v2)) { nbrs = &GetNeighbors(v1); elabel = &elabels_[v1]; other = v2; } else { nbrs = &GetNeighbors(v2); elabel = &elabels_[v2]; other = v1; } long start = 0, end = nbrs->size() - 1, mid; while (start <= end) { mid = (start + end) / 2; if (nbrs->at(mid) < other) { start = mid + 1; } else if (nbrs->at(mid) > other) { end = mid - 1; } else { e_label = elabel->at(mid); return {v1_label, v2_label, e_label}; } } return {v1_label, v2_label, -1}; } uint Graph::GetDegree(uint v) const { return neighbors_[v].size(); } uint Graph::GetDiameter() const { uint diameter = 0; for (uint i = 0u; i < NumVertices(); i++) if (GetVertexLabel(i) != NOT_EXIST) { std::queue<uint> bfs_queue; std::vector<bool> visited(NumVertices(), false); uint level = UINT_MAX; bfs_queue.push(i); visited[i] = true; while (!bfs_queue.empty()) { level++; uint size = bfs_queue.size(); for (uint j = 0u; j < size; j++) { uint front = bfs_queue.front(); bfs_queue.pop(); const auto& nbrs = GetNeighbors(front); for (const uint nbr: nbrs) { if (!visited[nbr]) { bfs_queue.push(nbr); visited[nbr] = true; } } } } if (level > diameter) diameter = level; } return diameter; } void Graph::LoadFromFile(const std::string &path) { if (!io::file_exists(path.c_str())) { std::cout << "Failed to open: " << path << std::endl; exit(-1); } std::ifstream ifs(path); char type; while (ifs >> type) { if (type == 't') { char temp1; uint temp2; ifs >> temp1 >> temp2; } else if (type == 'v') { uint vertex_id, label; ifs >> vertex_id >> label; AddVertex(vertex_id, label); } else { uint from_id, to_id, label; ifs >> from_id >> to_id >> label; AddEdge(from_id, to_id, label); } } ifs.close(); } void Graph::LoadUpdateStream(const std::string &path) { if (!io::file_exists(path.c_str())) { std::cout << "Failed to open: " << path << std::endl; exit(-1); } std::ifstream ifs(path); std::string type; while (ifs >> type) { if (type == "v" || type == "-v") { uint vertex_id, label; ifs >> vertex_id >> label; updates_.emplace('v', type == "v", vertex_id, 0u, label); } else { uint from_id, to_id, label; ifs >> from_id >> to_id >> label; updates_.emplace('e', type == "e", from_id, to_id, label); } } ifs.close(); } void Graph::PrintMetaData() const { std::cout << "# vertices = " << NumVertices() << "\n# edges = " << NumEdges() << std::endl; }
24.99635
92
0.508833
RapidsAtHKUST
d72e486bcbda15f362cea696e6b9f10ad60daeeb
20,577
cc
C++
caffe2/core/net_dag.cc
Mathpix/caffe2
6687f8447545250cdeb63a4a9baaa6e25c32ad0d
[ "MIT" ]
1
2021-04-22T00:07:58.000Z
2021-04-22T00:07:58.000Z
caffe2/core/net_dag.cc
Mathpix/caffe2
6687f8447545250cdeb63a4a9baaa6e25c32ad0d
[ "MIT" ]
null
null
null
caffe2/core/net_dag.cc
Mathpix/caffe2
6687f8447545250cdeb63a4a9baaa6e25c32ad0d
[ "MIT" ]
null
null
null
#include "caffe2/core/net.h" #include <set> #include <stack> #include <unordered_map> #include <unordered_set> #include "caffe2/core/operator.h" #include "caffe2/core/static_tracepoint.h" #include "caffe2/core/timer.h" #include "caffe2/proto/caffe2.pb.h" #include "caffe2/utils/proto_utils.h" CAFFE2_DEFINE_bool( caffe2_disable_chaining, false, "Disable chaining logic (some latent multi-device issues)."); namespace caffe2 { namespace { bool sameDevice(const OperatorDef& lhs, const OperatorDef& rhs) { return lhs.device_option().device_type() == rhs.device_option().device_type() && lhs.device_option().cuda_gpu_id() == rhs.device_option().cuda_gpu_id(); } using OpIndex = int; DAGNetBase::ExecutionChains singleChains( const std::vector<internal::OperatorNode>& nodes) { DAGNetBase::ExecutionChains chains; for (auto i = 0; i < nodes.size(); ++i) { chains[i] = {i}; } return chains; } static void prune(int node_idx, std::vector<internal::OpGraphNode>& nodes) { // Ancestor table for tracking the visited nodes std::vector<bool> ancestors(nodes.size(), false); // stack element is pair of <curr_node, previous_node> std::stack<std::pair<int, int>> nodes_stack; // initialize the prev_node to be -1 nodes_stack.push(std::make_pair(node_idx, -1)); while (!nodes_stack.empty()) { const auto& node_pair = nodes_stack.top(); int curr = node_pair.first; int prev = node_pair.second; // If the node has already been visited, pop curr out of // stack and clean up the ancestor table CAFFE_ENFORCE(curr < ancestors.size(), "Out of bound access"); if (ancestors[curr]) { ancestors[curr] = false; nodes_stack.pop(); continue; } // Check if this has a parent that can be pruned: // if parent is not the previous node visited and is // an ancestor of the current traversar, it can be // pruned. if (prev >= 0) { std::vector<int> new_parents; for (auto parent : nodes[curr].parents_) { if (parent != prev && ancestors[parent]) { // We can prune this one nodes[parent].children_.erase( std::remove( nodes[parent].children_.begin(), nodes[parent].children_.end(), curr), nodes[parent].children_.end()); } else { new_parents.push_back(parent); } } nodes[curr].parents_ = new_parents; } ancestors[curr] = true; // Descend -- but only once from each node if (nodes[curr].visited_inputs == nodes[curr].num_orig_parents) { const auto& children = nodes[curr].children_; for (auto child : children) { nodes[child].visited_inputs++; nodes_stack.push(std::make_pair(child, curr)); } } } } /** * Prune redundant dependencies to improve chaining. * TODO: t15868555 This algorithm is fast but can miss dependencies. */ std::vector<internal::OpGraphNode> pruneOpNodeGraph( const std::vector<internal::OperatorNode>& orig_nodes) { Timer t; std::vector<internal::OpGraphNode> pruned; // Create a separate list of pruned operatornodes used // for the chaining computation. Because of the unique_ptr // in the OperatorNode, we cannot do a copy but have to // copy just the fields we need. for (auto& node : orig_nodes) { internal::OpGraphNode nd; nd.children_ = node.children_; nd.parents_ = node.parents_; nd.num_orig_parents = nd.parents_.size(); pruned.push_back(nd); } for (int i = 0; i < pruned.size(); ++i) { if (pruned[i].parents_.size() == 0) { prune(i, pruned); } } LOG(INFO) << "Operator graph pruning prior to chain compute took: " << t.Seconds() << " secs"; return pruned; } DAGNetBase::ExecutionChains computeChains( const std::vector<internal::OperatorNode>& orig_nodes) { const std::vector<internal::OpGraphNode> nodes = pruneOpNodeGraph(orig_nodes); vector<int> initial_frontier; for (int idx = 0; idx < nodes.size(); ++idx) { if (nodes[idx].parents_.size() == 0) { initial_frontier.push_back(idx); } } // We need to construct the node_seen_count to know how many inner edges each // node has. std::unordered_map<OpIndex, int> node_seen_count; for (int root_index : initial_frontier) { const auto& root = nodes[root_index]; std::stack<std::pair<OpIndex, std::vector<int>::const_iterator>> depth_stack; depth_stack.push(make_pair(root_index, root.children_.begin())); node_seen_count[root_index]++; CAFFE_ENFORCE( node_seen_count[root_index] == 1, "root node ", root_index, " visit count must be == 1"); while (depth_stack.size() > 0) { auto cur = depth_stack.top(); depth_stack.pop(); if (cur.second != nodes[cur.first].children_.end()) { OpIndex node_index = *cur.second; node_seen_count[node_index]++; cur.second++; depth_stack.push(cur); if (node_seen_count[node_index] == 1) { // Visit each child only once. depth_stack.push( make_pair(node_index, nodes[node_index].children_.begin())); } } } } // Now, we compute the set of execution chains An execution chain is // a linear set of nodes that can be executed on a single stream // (e.g. a chain of single input, single output operators) DAGNetBase::ExecutionChains chains; std::unordered_set<OpIndex> seen_nodes; std::vector<OpIndex> chain; std::pair<OpIndex, std::vector<int>::const_iterator> cur; std::stack<std::pair<OpIndex, std::vector<int>::const_iterator>> depth_stack; auto check_current_for_chaining = [&]() -> bool { return ( node_seen_count[cur.first] == 1 && (chain.size() == 0 || sameDevice( orig_nodes[cur.first].operator_->def(), orig_nodes[chain.back()].operator_->def()))); }; auto commit_chain = [&]() { if (chain.size() > 0) { CAFFE_ENFORCE( chains.insert({chain.front(), chain}).second, "Chain ", chain.front(), " was already added."); VLOG(2) << "Added chain: " << chain.front() << "with elements"; for (auto ch : chain) { VLOG(2) << ch << ", "; } chain.clear(); } }; auto depth_traverse = [&]() { while (cur.second != nodes[cur.first].children_.end() && seen_nodes.find(*cur.second) != seen_nodes.end()) { cur.second++; } if (cur.second != nodes[cur.first].children_.end()) { auto next = make_pair(*cur.second, nodes[*cur.second].children_.begin()); depth_stack.push(cur); depth_stack.push(next); } }; for (int root_index : initial_frontier) { depth_stack.push( make_pair(root_index, nodes[root_index].children_.begin())); while (depth_stack.size() > 0) { cur = depth_stack.top(); depth_stack.pop(); if (seen_nodes.find(cur.first) == seen_nodes.end()) { seen_nodes.insert(cur.first); // Has one child, can be candidate for chain or can be added to the // previous chain. if (nodes[cur.first].children_.size() == 1) { if (check_current_for_chaining()) { // Add oneself to the current chain. VLOG(1) << "Adding to existing chain" << cur.first; chain.push_back(cur.first); int index = *nodes[cur.first].children_.begin(); depth_stack.push(make_pair(index, nodes[index].children_.begin())); } else { // Can't belong to the previous chain, commit previous chain and // start a new one. commit_chain(); chain.push_back(cur.first); int index = *nodes[cur.first].children_.begin(); depth_stack.push(make_pair(index, nodes[index].children_.begin())); } } else if ( nodes[cur.first].children_.size() == 0 && check_current_for_chaining()) { // Add current node to the current chain and commit. chain.push_back(cur.first); commit_chain(); } else { // Node has more than one child. commit_chain(); // Add current node as an independent chain since it won't be a part // of a bigger chain. chain.push_back(cur.first); commit_chain(); depth_traverse(); } } else { // This node has been seen before, we will only traverse its children. // Commit any pending chains and continue traversing. commit_chain(); depth_traverse(); } } // End while // Check if this if is even needed. commit_chain(); } CAFFE_ENFORCE( seen_nodes.size() == nodes.size(), "Haven't seen all the nodes, expected number of nodes ", nodes.size(), ", but seen only ", seen_nodes.size(), "."); return chains; } } DAGNetBase::DAGNetBase(const NetDef& net_def, Workspace* ws) : NetBase(net_def, ws), operator_nodes_(net_def.op_size()) { // Blob creator allows us to track which operator created which blob. VLOG(1) << "Constructing DAGNet " << net_def.name(); std::map<string, int> blob_creator; std::map<string, std::set<int>> blob_readers; bool net_def_has_device_option = net_def.has_device_option(); // Initialize the operators for (int idx = 0; idx < net_def.op_size(); ++idx) { const OperatorDef& op_def = net_def.op(idx); VLOG(1) << "Creating operator #" << idx << ": " << op_def.name() << ":" << op_def.type(); if (!op_def.has_device_option() && net_def_has_device_option) { OperatorDef temp_def(op_def); temp_def.mutable_device_option()->CopyFrom(net_def.device_option()); operator_nodes_[idx].operator_ = CreateOperator(temp_def, ws); } else { operator_nodes_[idx].operator_ = CreateOperator(op_def, ws); } // Check the inputs, and set up parents if necessary. This addressese the // read after write case. auto checkInputs = [&](const google::protobuf::RepeatedPtrField<std::string>& inputs) { for (const string& input : inputs) { if (blob_creator.count(input) == 0) { VLOG(1) << "Input " << input << " not produced by this net. " << "Assuming it is pre-existing."; } else { int parent = blob_creator[input]; VLOG(1) << "op dependency (RaW " << input << "): " << parent << "->" << idx; operator_nodes_[idx].parents_.push_back(parent); operator_nodes_[parent].children_.push_back(idx); } // Add the current idx to the readers of this input. blob_readers[input].insert(idx); } }; checkInputs(op_def.input()); checkInputs(op_def.control_input()); // Check the outputs. for (const string& output : op_def.output()) { if (blob_creator.count(output) != 0) { // This addresses the write after write case - we will assume that all // writes are inherently sequential. int waw_parent = blob_creator[output]; VLOG(1) << "op dependency (WaW " << output << "): " << waw_parent << "->" << idx; operator_nodes_[idx].parents_.push_back(waw_parent); operator_nodes_[waw_parent].children_.push_back(idx); } // This addresses the write after read case - we will assume that writes // should only occur after all previous reads are finished. for (const int war_parent : blob_readers[output]) { VLOG(1) << "op dependency (WaR " << output << "): " << war_parent << "->" << idx; operator_nodes_[idx].parents_.push_back(war_parent); operator_nodes_[war_parent].children_.push_back(idx); } // Renew the creator of the output name. blob_creator[output] = idx; // The write would create an implicit barrier that all earlier readers of // this output is now parents of the current op, and future writes would // not need to depend on these earlier readers. Thus, we can clear up the // blob readers. blob_readers[output].clear(); } } // Now, make sure that the parent list and the children list do not contain // duplicated items. for (int i = 0; i < operator_nodes_.size(); ++i) { auto& node = operator_nodes_[i]; // Sort, remove duplicates, and delete self dependency. auto& p = node.parents_; std::sort(p.begin(), p.end()); p.erase(std::unique(p.begin(), p.end()), p.end()); p.erase(std::remove(p.begin(), p.end(), i), p.end()); // Do the same for the children vector. auto& c = node.children_; std::sort(c.begin(), c.end()); c.erase(std::unique(c.begin(), c.end()), c.end()); c.erase(std::remove(c.begin(), c.end(), i), c.end()); } execution_chains_ = (FLAGS_caffe2_disable_chaining ? singleChains(operator_nodes_) : computeChains(operator_nodes_)); // Tag operator nodes that start chains for (int i = 0; i < operator_nodes_.size(); ++i) { auto& node = operator_nodes_[i]; if (execution_chains_.find(i) != execution_chains_.end()) { node.is_chain_start_ = true; } else { node.is_chain_start_ = false; } node.runtime_parent_count_ = 0; } LOG(INFO) << "Number of parallel execution chains " << execution_chains_.size() << " Number of operators = " << net_def.op_size(); // TODO: do we want to make sure that there are no loops in the // dependency graph? // Figure out the initial frontier - this is the one we will feed into the job // queue to start a run. for (int idx = 0; idx < operator_nodes_.size(); ++idx) { if (operator_nodes_[idx].parents_.size() == 0) { initial_frontier_.push_back(idx); } } // Finally, start the workers. int num_workers = net_def.has_num_workers() ? net_def.num_workers() : 1; CAFFE_ENFORCE(num_workers > 0, "Must have a positive number of workers."); if (num_workers == 1) { LOG(WARNING) << "Number of workers is 1: this means that all operators " << "will be executed sequentially. Did you forget to set " << "num_workers in the NetDef?"; } num_workers_ = num_workers; int num_workers_to_start = num_workers_; // Option to start only one thread for first iteration. This hack is // needed to prevent deadlocks happening with CUDA and concurrent allocations // that operators do when run the first time. ArgumentHelper arg_helper(net_def); if (arg_helper.HasArgument("first_iter_only_one_worker")) { if (arg_helper.GetSingleArgument<int64_t>( "first_iter_only_one_worker", 0)) { num_workers_to_start = 1; } } for (int i = 0; i < num_workers_to_start; ++i) { VLOG(1) << "Start worker #" << i; workers_.push_back(std::thread(&DAGNetBase::WorkerFunction, this)); } } DAGNetBase::~DAGNetBase() { // Safely join all the workers before exiting. job_queue_.NoMoreJobs(); VLOG(1) << "Joining workers."; for (auto& worker : workers_) { worker.join(); } } bool DAGNetBase::Run() { // Lock the run_in_progress_ lock so that we do not accidentally call Run() // in parallel. std::unique_lock<std::mutex> run_lock(run_in_progress_); VLOG(1) << "Running parallel net."; // First, set up job queue. remaining_ops_ = operator_nodes_.size(); success_ = true; // TODO(jiayq): Start all worker threads. // Initialize the runtime parent count. for (auto& node : operator_nodes_) { node.runtime_parent_count_ = node.parents_.size(); } // Kickstart the job queue. for (auto& value : initial_frontier_) { job_queue_.Push(value); } std::unique_lock<std::mutex> mutex_lock(remaining_ops_mutex_); while (remaining_ops_ > 0) { VLOG(2) << "Remaining ops to run: " << remaining_ops_; cv_.wait(mutex_lock); } VLOG(2) << "All ops finished running."; for (const auto& op : operator_nodes_) { CAFFE_ENFORCE( op.runtime_parent_count_ == 0, "Operator ", op.operator_->def().name(), "(", op.operator_->def().type(), ") has some runtime parents left."); } // Ensure the number of workers matches the defined for (auto i = workers_.size(); i < num_workers_; ++i) { VLOG(1) << "Start worker #" << i; workers_.push_back(std::thread(&DAGNetBase::WorkerFunction, this)); } // If the above while loop finished, we know that the current run finished. return success_; } void DAGNetBase::WorkerFunction() { // WorkerFunctions() is an infinite loop until there are no more jobs to run. while (true) { int idx = 0; // If there is no more jobs - meaning that the DAGNetBase is destructing - // we will exit safely. if (!job_queue_.Pop(&idx)) { return; } VLOG(1) << "Running operator #" << idx << " " << operator_nodes_[idx].operator_->def().name() << "(" << operator_nodes_[idx].operator_->def().type() << ")."; CAFFE_ENFORCE( execution_chains_.find(idx) != execution_chains_.end(), "Can't find chain ", idx, "."); const auto& chain = execution_chains_[idx]; bool this_success = RunAt(execution_chains_[idx]); if (!this_success) { LOG(ERROR) << "Operator chain failed: " << ProtoDebugString(operator_nodes_[idx].operator_->def()); } // Do book-keeping for (const auto idx : chain) { for (const auto child : operator_nodes_[idx].children_) { const int count = --operator_nodes_[child].runtime_parent_count_; CAFFE_ENFORCE( count >= 0, "Found runtime parent count smaller than zero for ", "operator node ", operator_nodes_[child].operator_->def().name(), "(", operator_nodes_[child].operator_->def().type(), ")."); if (count != 0) { continue; } if (operator_nodes_[child].is_chain_start_) { VLOG(2) << "Pushing chain #" << child << " to queue."; job_queue_.Push(child); } } } // Notify that the processed op is incremented by one. { std::unique_lock<std::mutex> mutex_lock(remaining_ops_mutex_); remaining_ops_ -= chain.size(); success_ &= this_success; CAFFE_ENFORCE( remaining_ops_ >= 0, "All the operations should be finished by now, still have ", remaining_ops_, " remaining."); } cv_.notify_one(); VLOG(2) << "Finished executing operator #" << idx; } } vector<float> DAGNetBase::TEST_Benchmark( const int warmup_runs, const int main_runs, const bool run_individual) { LOG(INFO) << "Starting benchmark."; LOG(INFO) << "Running warmup runs."; CAFFE_ENFORCE( warmup_runs >= 0, "Number of warm up runs should be non negative, provided ", warmup_runs, "."); for (int i = 0; i < warmup_runs; ++i) { CAFFE_ENFORCE(Run(), "Warmup run ", i, " has failed."); } LOG(INFO) << "Main runs."; CAFFE_ENFORCE( main_runs >= 0, "Number of main runs should be non negative, provided ", main_runs, "."); Timer timer; for (int i = 0; i < main_runs; ++i) { CAFFE_ENFORCE(Run(), "Main run ", i, " has failed."); } auto millis = timer.MilliSeconds(); LOG(INFO) << "Main run finished. Milliseconds per iter: " << millis / main_runs << ". Iters per second: " << 1000.0 * main_runs / millis; if (run_individual) { LOG(INFO) << "DAGNet does not do per-op benchmark. To do so, " "switch to a simple net type."; } return vector<float>{millis / main_runs}; } class DAGNet : public DAGNetBase { public: using DAGNetBase::DAGNetBase; protected: bool RunAt(const std::vector<int>& chain) override { bool success = true; const auto& net_name = name_.c_str(); for (const auto i : chain) { const auto& op_name = operator_nodes_[i].operator_->def().name().c_str(); const auto& op_type = operator_nodes_[i].operator_->def().type().c_str(); CAFFE_SDT(operator_start, net_name, op_name, op_type); success &= operator_nodes_[i].operator_->Run(); CAFFE_SDT(operator_done, net_name, op_name, op_type); } return success; } }; namespace { REGISTER_NET(dag, DAGNet); } } // namespace caffe2
34.641414
80
0.613598
Mathpix
d72f579555964831034b81702a6a9e4e6174ee3c
335
cpp
C++
src/csapex_remote/src/io/request.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
21
2016-09-02T15:33:25.000Z
2021-06-10T06:34:39.000Z
src/csapex_remote/src/io/request.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
null
null
null
src/csapex_remote/src/io/request.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
10
2016-10-12T00:55:17.000Z
2020-04-24T19:59:02.000Z
/// HEADER #include <csapex/io/request.h> using namespace csapex; uint8_t Request::getPacketType() const { return PACKET_TYPE_ID; } Request::Request(uint8_t id) : request_id_(id) { } void Request::overwriteRequestID(uint8_t id) const { request_id_ = id; } uint8_t Request::getRequestID() const { return request_id_; }
13.958333
50
0.719403
ICRA-2018
d731a099b83ea4483d75ce4fff17f2dca59707b9
15,195
cpp
C++
examples/indirectdraw/indirectdraw.cpp
harskish/Vulkan
25be6e4fda8b0d16875a55a1a476209305d4a983
[ "MIT" ]
318
2016-05-30T18:53:13.000Z
2022-03-23T19:09:57.000Z
examples/indirectdraw/indirectdraw.cpp
harskish/Vulkan
25be6e4fda8b0d16875a55a1a476209305d4a983
[ "MIT" ]
47
2016-06-04T20:53:27.000Z
2020-12-21T17:14:21.000Z
examples/indirectdraw/indirectdraw.cpp
harskish/Vulkan
25be6e4fda8b0d16875a55a1a476209305d4a983
[ "MIT" ]
35
2016-06-08T11:05:02.000Z
2021-07-26T17:26:36.000Z
/* * Vulkan Example - Indirect drawing * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) * * Summary: * Use a device local buffer that stores draw commands for instanced rendering of different meshes stored * in the same buffer. * * Indirect drawing offloads draw command generation and offers the ability to update them on the GPU * without the CPU having to touch the buffer again, also reducing the number of drawcalls. * * The example shows how to setup and fill such a buffer on the CPU side, stages it to the device and * shows how to render it using only one draw command. * * See readme.md for details * */ #include <vulkanExampleBase.h> // Number of instances per object #if defined(__ANDROID__) #define OBJECT_INSTANCE_COUNT 1024 // Circular range of plant distribution #define PLANT_RADIUS 20.0f #else #define OBJECT_INSTANCE_COUNT 2048 // Circular range of plant distribution #define PLANT_RADIUS 25.0f #endif class VulkanExample : public vkx::ExampleBase { public: struct { vks::texture::Texture2DArray plants; vks::texture::Texture2D ground; } textures; // Vertex layout for the models vks::model::VertexLayout vertexLayout = vks::model::VertexLayout({ vks::model::VERTEX_COMPONENT_POSITION, vks::model::VERTEX_COMPONENT_NORMAL, vks::model::VERTEX_COMPONENT_UV, vks::model::VERTEX_COMPONENT_COLOR, }); struct { vks::model::Model plants; vks::model::Model ground; vks::model::Model skysphere; } models; // Per-instance data block struct InstanceData { glm::vec3 pos; glm::vec3 rot; float scale; uint32_t texIndex; }; // Contains the instanced data vks::Buffer instanceBuffer; // Contains the indirect drawing commands vks::Buffer indirectCommandsBuffer; uint32_t indirectDrawCount; struct { glm::mat4 projection; glm::mat4 view; } uboVS; struct { vks::Buffer scene; } uniformData; struct { vk::Pipeline plants; vk::Pipeline ground; vk::Pipeline skysphere; } pipelines; vk::PipelineLayout pipelineLayout; vk::DescriptorSet descriptorSet; vk::DescriptorSetLayout descriptorSetLayout; vk::Sampler samplerRepeat; uint32_t objectCount = 0; // Store the indirect draw commands containing index offsets and instance count per object std::vector<vk::DrawIndexedIndirectCommand> indirectCommands; VulkanExample() { title = "Indirect rendering"; camera.type = Camera::CameraType::firstperson; camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 512.0f); camera.setRotation(glm::vec3(-12.0f, 159.0f, 0.0f)); camera.setTranslation(glm::vec3(0.4f, 1.25f, 0.0f)); camera.movementSpeed = 5.0f; defaultClearColor = vks::util::clearColor({ 0.18f, 0.27f, 0.5f, 0.0f }); settings.overlay = true; } ~VulkanExample() { device.destroy(pipelines.plants); device.destroy(pipelines.ground); device.destroy(pipelines.skysphere); device.destroy(pipelineLayout); device.destroy(descriptorSetLayout); models.plants.destroy(); models.ground.destroy(); models.skysphere.destroy(); textures.plants.destroy(); textures.ground.destroy(); instanceBuffer.destroy(); indirectCommandsBuffer.destroy(); uniformData.scene.destroy(); } // Enable physical device features required for this example void getEnabledFeatures() override { // Example uses multi draw indirect if available if (deviceFeatures.multiDrawIndirect) { enabledFeatures.multiDrawIndirect = VK_TRUE; } // Enable anisotropic filtering if supported if (deviceFeatures.samplerAnisotropy) { enabledFeatures.samplerAnisotropy = VK_TRUE; } // Enable texture compression if (deviceFeatures.textureCompressionBC) { enabledFeatures.textureCompressionBC = VK_TRUE; } else if (deviceFeatures.textureCompressionASTC_LDR) { enabledFeatures.textureCompressionASTC_LDR = VK_TRUE; } else if (deviceFeatures.textureCompressionETC2) { enabledFeatures.textureCompressionETC2 = VK_TRUE; } }; void updateDrawCommandBuffer(const vk::CommandBuffer& drawCmdBuffer) { drawCmdBuffer.setViewport(0, viewport()); drawCmdBuffer.setScissor(0, scissor()); drawCmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSet, nullptr); // Plants drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.plants); // Binding point 0 : Mesh vertex buffer drawCmdBuffer.bindVertexBuffers(0, models.plants.vertices.buffer, { 0 }); // Binding point 1 : Instance data buffer drawCmdBuffer.bindVertexBuffers(1, instanceBuffer.buffer, { 0 }); drawCmdBuffer.bindIndexBuffer(models.plants.indices.buffer, 0, vk::IndexType::eUint32); // If the multi draw feature is supported: // One draw call for an arbitrary number of ojects // Index offsets and instance count are taken from the indirect buffer if (deviceFeatures.multiDrawIndirect) { drawCmdBuffer.drawIndexedIndirect(indirectCommandsBuffer.buffer, 0, indirectDrawCount, sizeof(VkDrawIndexedIndirectCommand)); } else { // If multi draw is not available, we must issue separate draw commands for (auto j = 0; j < indirectCommands.size(); j++) { drawCmdBuffer.drawIndexedIndirect(indirectCommandsBuffer.buffer, j * sizeof(VkDrawIndexedIndirectCommand), 1, sizeof(VkDrawIndexedIndirectCommand)); } } // Ground drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.ground); drawCmdBuffer.bindVertexBuffers(0, models.ground.vertices.buffer, { 0 }); drawCmdBuffer.bindIndexBuffer(models.ground.indices.buffer, 0, vk::IndexType::eUint32); drawCmdBuffer.drawIndexed(models.ground.indexCount, 1, 0, 0, 0); // Skysphere drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.skysphere); drawCmdBuffer.bindVertexBuffers(0, models.skysphere.vertices.buffer, { 0 }); drawCmdBuffer.bindIndexBuffer(models.skysphere.indices.buffer, 0, vk::IndexType::eUint32); drawCmdBuffer.drawIndexed(models.skysphere.indexCount, 1, 0, 0, 0); } void loadAssets() override { models.plants.loadFromFile(context, getAssetPath() + "models/plants.dae", vertexLayout, 0.0025f); models.ground.loadFromFile(context, getAssetPath() + "models/plane_circle.dae", vertexLayout, PLANT_RADIUS + 1.0f); models.skysphere.loadFromFile(context, getAssetPath() + "models/skysphere.dae", vertexLayout, 512.0f / 10.0f); // Textures std::string texFormatSuffix; vk::Format texFormat; // Get supported compressed texture format if (deviceFeatures.textureCompressionBC) { texFormatSuffix = "_bc3_unorm"; texFormat = vk::Format::eBc3UnormBlock; } else if (deviceFeatures.textureCompressionASTC_LDR) { texFormatSuffix = "_astc_8x8_unorm"; texFormat = vk::Format::eAstc8x8UnormBlock; } else if (deviceFeatures.textureCompressionETC2) { texFormatSuffix = "_etc2_unorm"; texFormat = vk::Format::eEtc2R8G8B8A8UnormBlock; } else { throw std::runtime_error("Device does not support any compressed texture format!"); } textures.plants.loadFromFile(context, getAssetPath() + "textures/texturearray_plants" + texFormatSuffix + ".ktx", texFormat); textures.ground.loadFromFile(context, getAssetPath() + "textures/ground_dry" + texFormatSuffix + ".ktx", texFormat); } void setupDescriptorPool() { // Example uses one ubo std::vector<vk::DescriptorPoolSize> poolSizes = { { vk::DescriptorType::eUniformBuffer, 1 }, { vk::DescriptorType::eCombinedImageSampler, 2 }, }; descriptorPool = device.createDescriptorPool({ {}, 2, (uint32_t)poolSizes.size(), poolSizes.data() }); } void setupDescriptorSetLayout() { std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings{ { 0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex }, { 1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment }, { 2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment }, }; descriptorSetLayout = device.createDescriptorSetLayout({ {}, static_cast<uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() }); pipelineLayout = device.createPipelineLayout(vk::PipelineLayoutCreateInfo{ {}, 1, &descriptorSetLayout }); } void setupDescriptorSet() { descriptorSet = device.allocateDescriptorSets({ descriptorPool, 1, &descriptorSetLayout })[0]; std::vector<vk::WriteDescriptorSet> writeDescriptorSets{ { descriptorSet, 0, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &uniformData.scene.descriptor }, { descriptorSet, 1, 0, 1, vk::DescriptorType::eCombinedImageSampler, &textures.plants.descriptor }, { descriptorSet, 2, 0, 1, vk::DescriptorType::eCombinedImageSampler, &textures.ground.descriptor }, }; device.updateDescriptorSets(writeDescriptorSets, nullptr); } void preparePipelines() { vks::pipelines::GraphicsPipelineBuilder builder{ device, pipelineLayout, renderPass }; builder.rasterizationState.frontFace = vk::FrontFace::eClockwise; builder.vertexInputState.appendVertexLayout(vertexLayout); // Ground builder.loadShader(getAssetPath() + "shaders/indirectdraw/ground.vert.spv", vk::ShaderStageFlagBits::eVertex); builder.loadShader(getAssetPath() + "shaders/indirectdraw/ground.frag.spv", vk::ShaderStageFlagBits::eFragment); pipelines.ground = builder.create(context.pipelineCache); builder.destroyShaderModules(); // Skysphere builder.loadShader(getAssetPath() + "shaders/indirectdraw/skysphere.vert.spv", vk::ShaderStageFlagBits::eVertex); builder.loadShader(getAssetPath() + "shaders/indirectdraw/skysphere.frag.spv", vk::ShaderStageFlagBits::eFragment); builder.rasterizationState.cullMode = vk::CullModeFlagBits::eFront; pipelines.skysphere = builder.create(context.pipelineCache); builder.destroyShaderModules(); // Indirect (and instanced) pipeline for the plants builder.rasterizationState.cullMode = vk::CullModeFlagBits::eBack; builder.vertexInputState.bindingDescriptions.push_back({ 1, sizeof(InstanceData), vk::VertexInputRate::eInstance }); builder.vertexInputState.attributeDescriptions.push_back({ 4, 1, vk::Format::eR32G32B32Sfloat, offsetof(InstanceData, pos) }); builder.vertexInputState.attributeDescriptions.push_back({ 5, 1, vk::Format::eR32G32B32Sfloat, offsetof(InstanceData, rot) }); builder.vertexInputState.attributeDescriptions.push_back({ 6, 1, vk::Format::eR32Sfloat, offsetof(InstanceData, scale) }); builder.vertexInputState.attributeDescriptions.push_back({ 7, 1, vk::Format::eR32Sint, offsetof(InstanceData, texIndex) }); builder.loadShader(getAssetPath() + "shaders/indirectdraw/indirectdraw.vert.spv", vk::ShaderStageFlagBits::eVertex); builder.loadShader(getAssetPath() + "shaders/indirectdraw/indirectdraw.frag.spv", vk::ShaderStageFlagBits::eFragment); pipelines.plants = builder.create(context.pipelineCache); builder.destroyShaderModules(); } // Prepare (and stage) a buffer containing the indirect draw commands void prepareIndirectData() { indirectCommands.clear(); // Create on indirect command for each mesh in the scene uint32_t m = 0; for (auto& modelPart : models.plants.parts) { VkDrawIndexedIndirectCommand indirectCmd{}; indirectCmd.instanceCount = OBJECT_INSTANCE_COUNT; indirectCmd.firstInstance = m * OBJECT_INSTANCE_COUNT; indirectCmd.firstIndex = modelPart.indexBase; indirectCmd.indexCount = modelPart.indexCount; indirectCommands.push_back(indirectCmd); m++; } objectCount = 0; for (auto indirectCmd : indirectCommands) { objectCount += indirectCmd.instanceCount; } indirectDrawCount = static_cast<uint32_t>(indirectCommands.size()); indirectCommandsBuffer = context.stageToDeviceBuffer(vk::BufferUsageFlagBits::eIndirectBuffer, indirectCommands); } // Prepare (and stage) a buffer containing instanced data for the mesh draws void prepareInstanceData() { std::vector<InstanceData> instanceData; instanceData.resize(objectCount); std::mt19937 rndGenerator((unsigned)time(NULL)); std::uniform_real_distribution<float> uniformDist(0.0f, 1.0f); for (uint32_t i = 0; i < objectCount; i++) { instanceData[i].rot = glm::vec3(0.0f, float(M_PI) * uniformDist(rndGenerator), 0.0f); float theta = 2 * float(M_PI) * uniformDist(rndGenerator); float phi = acos(1 - 2 * uniformDist(rndGenerator)); instanceData[i].pos = glm::vec3(sin(phi) * cos(theta), 0.0f, cos(phi)) * PLANT_RADIUS; instanceData[i].scale = 1.0f + uniformDist(rndGenerator) * 2.0f; instanceData[i].texIndex = i / OBJECT_INSTANCE_COUNT; } instanceBuffer = context.stageToDeviceBuffer(vk::BufferUsageFlagBits::eVertexBuffer, instanceData); } void prepareUniformBuffers() { uniformData.scene = context.createUniformBuffer(uboVS); updateUniformBuffer(true); } void updateUniformBuffer(bool viewChanged) { if (viewChanged) { uboVS.projection = camera.matrices.perspective; uboVS.view = camera.matrices.view; } memcpy(uniformData.scene.mapped, &uboVS, sizeof(uboVS)); } void prepare() { ExampleBase::prepare(); prepareIndirectData(); prepareInstanceData(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } void viewChanged() override { updateUniformBuffer(true); } void OnUpdateUIOverlay() override { if (!deviceFeatures.multiDrawIndirect) { if (ui.header("Info")) { ui.text("multiDrawIndirect not supported"); } } if (ui.header("Statistics")) { ui.text("Objects: %d", objectCount); } } }; VULKAN_EXAMPLE_MAIN()
42.325905
146
0.674103
harskish
d73235eda23c9c0ffa54e7accceacfbe68c9f960
268
cc
C++
src/day4.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
src/day4.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
src/day4.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
#include "day4.h" #include <iostream> int main(void) { static constexpr auto input = "yzbqklnj"; std::cout << "Day 4, part 1: " << day4::mineAdventCoin(input, false) << '\n'; std::cout << "Day 4, part 2: " << day4::mineAdventCoin(input, true) << '\n'; }
26.8
81
0.593284
LesnyRumcajs
d73460f4f5cde88221298654ff58a40e734caa23
5,328
cpp
C++
WML-Core/src/main/cpp/controllers/SmartController.cpp
JaciBrunning/WML
8f9f2498d3d766e99d5062478262ba12eeac9520
[ "MIT" ]
null
null
null
WML-Core/src/main/cpp/controllers/SmartController.cpp
JaciBrunning/WML
8f9f2498d3d766e99d5062478262ba12eeac9520
[ "MIT" ]
null
null
null
WML-Core/src/main/cpp/controllers/SmartController.cpp
JaciBrunning/WML
8f9f2498d3d766e99d5062478262ba12eeac9520
[ "MIT" ]
null
null
null
#include "controllers/SmartController.h" using namespace wml::controllers; bool SmartController::Exists(tAxis axis, bool value) { try { _axes.at(axis.id); } catch (std::out_of_range) { return !value; } return value; } bool SmartController::Exists(tButton button, bool value) { try { _buttons.at(button.id); } catch (std::out_of_range) { return !value; } return value; } bool SmartController::Exists(tPOV pov, bool value) { try { _POVs.at(pov.id); } catch (std::out_of_range) { return !value; } return value; } bool SmartController::Exists(std::vector<tAxis> axi, bool value) { bool val = value; for (auto axis : axi) val |= Exists(axis, value); return val; } bool SmartController::Exists(std::vector<tButton> buttons, bool value) { bool val = value; for (auto button : buttons) val |= Exists(button, value); return val; } bool SmartController::Exists(std::vector<tPOV> povs, bool value) { bool val = value; for (auto pov : povs) val |= Exists(pov, value); return val; } inputs::ContAxis *SmartController::GetObj(tAxis axis) { return Exists(axis) ? _axes.at(axis.id) : nullptr; } inputs::ContButton *SmartController::GetObj(tButton button) { return Exists(button) ? _buttons.at(button.id) : nullptr; } inputs::ContPOV *SmartController::GetObj(tPOV pov) { return Exists(pov) ? _POVs.at(pov.id) : nullptr; } void SmartController::Map(tAxis axis, inputs::ContAxis *newAxis, bool force) { if (!force) if (Exists(axis)) return; _axes[axis.id] = newAxis; } void SmartController::Map(tButton button, inputs::ContButton *newButton, bool force) { if (!force) if (Exists(button)) return; _buttons[button.id] = newButton; } void SmartController::Map(tPOV pov, inputs::ContPOV *newPOV, bool force) { if (!force) if (Exists(pov)) return; _POVs[pov.id] = newPOV; } void SmartController::Map(tAxis map_axis, tButton virt_button, double threshold, bool force) { if (!Exists(map_axis)) return; Map(virt_button, inputs::MakeAxisButton(GetObj(map_axis), threshold).at(0), force); // _axes.erase(_axes.find(map_axis.id)); } void SmartController::Map(tAxis map_axis, std::vector<tButton> virt_buttons, bool force) { if (!Exists(map_axis)) return; std::vector<inputs::AxisSelectorButton*> buttons = inputs::MakeAxisSelectorButtons(GetObj(map_axis), virt_buttons.size()); for (unsigned int i = 0; i < buttons.size(); i++) { if (virt_buttons.at(i) != noButton) Map(virt_buttons.at(i), buttons.at(i), force); } // _axes.erase(_axes.find(map_axis.id)); } void SmartController::PairAxis(tAxis primary_axis, tAxis secondary_axis, bool squared) { if (!Exists(primary_axis) || !Exists(secondary_axis)) return; std::pair<inputs::FieldAxis*, inputs::FieldAxis*> axi = inputs::MakeFieldAxi(new inputs::Field(std::make_pair<inputs::ContAxis*, inputs::ContAxis*>(GetObj(primary_axis), GetObj(secondary_axis)), squared)); Map(primary_axis, axi.first, true); Map(secondary_axis, axi.second, true); } void SmartController::Map(std::pair<tButton, tButton> map_buttons, std::vector<tButton> virt_buttons, bool wrap, bool force) { if (!Exists(std::vector<tButton>({ map_buttons.first, map_buttons.second }))) return; std::vector<inputs::ButtonSelectorButton*> buttons = inputs::MakeButtonSelectorButtons({ GetObj(map_buttons.first), GetObj(map_buttons.second) }, virt_buttons.size(), wrap); for (unsigned int i = 0; i < buttons.size(); i++) { if (virt_buttons.at(i) != noButton) Map(virt_buttons.at(i), buttons.at(i), force); } // _buttons.erase(_buttons.find(map_buttons.first.id)); // _buttons.erase(_buttons.find(map_buttons.second.id)); } void SmartController::Map(tPOV map_POV, std::map<Controller::POVPos, tButton> virt_buttons, bool force) { if (!Exists(map_POV)) return; std::map<Controller::POVPos, inputs::POVButton*> buttons = inputs::MakePOVButtons(GetObj(map_POV)); for (auto pair : virt_buttons) { if (pair.second != noButton) Map(pair.second, buttons.at(pair.first), force); } // _POVs.erase(_POVs.find(map_POV.id)); } // --------------------------------------------- INPUT GETTERS --------------------------------------------- double SmartController::Get(tAxis axis) { if (Exists(axis, false)) return 0; return GetObj(axis)->Get(); } bool SmartController::Get(tButton button, SmartController::ButtonMode mode) { if (Exists(button, false)) return false; switch (mode) { case ButtonMode::RAW: return GetObj(button)->Get(); case ButtonMode::ONRISE: return GetObj(button)->GetOnRise(); case ButtonMode::ONFALL: return GetObj(button)->GetOnFall(); case ButtonMode::ONCHANGE: return GetObj(button)->GetOnChange(); } return false; } wml::controllers::Controller::POVPos SmartController::Get(tPOV pov) { if (Exists(pov, false)) return kNone; return GetObj(pov)->Get(); } // ------------------------------------------- FEEDBACK SETTERS -------------------------------------------- void SmartController::Set(tRumble rumble, double value) { _cont->SetRumble(rumble.type, value); } // --------------------------------------------- UPDATE FUNCS ---------------------------------------------- void SmartController::UpdateButtonSelectors() { for (auto pair : _buttons) UpdateButtonSelector(tButton(-1, pair.first)); }
28.491979
207
0.665728
JaciBrunning
d73decfdfaea5c8975b7f9a10b1d10e17fa0b6fd
16,225
cpp
C++
ugene/src/plugins/external_tool_support/src/blast_plus/BlastPlusWorker.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins/external_tool_support/src/blast_plus/BlastPlusWorker.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins/external_tool_support/src/blast_plus/BlastPlusWorker.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BlastPlusWorker.h" #include "TaskLocalStorage.h" #include "BlastPlusSupport.h" #include "BlastNPlusSupportTask.h" #include "BlastPPlusSupportTask.h" #include "BlastXPlusSupportTask.h" #include "TBlastNPlusSupportTask.h" #include "TBlastXPlusSupportTask.h" #include <U2Lang/IntegralBusModel.h> #include <U2Lang/WorkflowEnv.h> #include <U2Lang/ActorPrototypeRegistry.h> #include <U2Lang/BaseTypes.h> #include <U2Lang/BaseSlots.h> #include <U2Lang/BasePorts.h> #include <U2Lang/BaseActorCategories.h> #include <U2Designer/DelegateEditors.h> #include <U2Lang/CoreLibConstants.h> #include <U2Core/AppContext.h> #include <U2Core/AppSettings.h> #include <U2Core/UserApplicationsSettings.h> #include <U2Core/ExternalToolRegistry.h> #include <U2Core/Log.h> #include <U2Core/FailTask.h> #include <U2Core/U2AlphabetUtils.h> #include <U2Core/DNASequenceObject.h> namespace U2 { namespace LocalWorkflow { /**************************** * BlastAllWorkerFactory ****************************/ const QString BlastPlusWorkerFactory::ACTOR_ID("blast-plus"); #define BLASTPLUS_PROGRAM_NAME "blast-type" #define BLASTPLUS_DATABASE_PATH "db-path" #define BLASTPLUS_DATABASE_NAME "db-name" #define BLASTPLUS_EXPECT_VALUE "e-val" #define BLASTPLUS_GROUP_NAME "result-name" #define BLASTPLUS_EXT_TOOL_PATH "tool-path" #define BLASTPLUS_TMP_DIR_PATH "temp-dir" //Additional options #define BLASTPLUS_ORIGINAL_OUT "blast-output" //path for output file #define BLASTPLUS_OUT_TYPE "type-output" //original option -m 0-11 #define BLASTPLUS_GAPPED_ALN "gapped-aln" //Perform gapped alignment (not available with tblastx) void BlastPlusWorkerFactory::init() { QList<PortDescriptor*> p; QList<Attribute*> a; Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), BlastPlusWorker::tr("Input sequence"), BlastPlusWorker::tr("Sequence for which annotations is searched.")); Descriptor oud(BasePorts::OUT_ANNOTATIONS_PORT_ID(), BlastPlusWorker::tr("Annotations"), BlastPlusWorker::tr("Found annotations.")); QMap<Descriptor, DataTypePtr> inM; inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE(); p << new PortDescriptor(ind, DataTypePtr(new MapDataType("blast.plus.seq", inM)), true /*input*/); QMap<Descriptor, DataTypePtr> outM; outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE(); p << new PortDescriptor(oud, DataTypePtr(new MapDataType("blast.plus.annotations", outM)), false /*input*/, true /*multi*/); Descriptor pn(BLASTPLUS_PROGRAM_NAME, BlastPlusWorker::tr("Search type"), BlastPlusWorker::tr("Select type of BLAST+ searches")); Descriptor dp(BLASTPLUS_DATABASE_PATH, BlastPlusWorker::tr("Database Path"), BlastPlusWorker::tr("Path with database files")); Descriptor dn(BLASTPLUS_DATABASE_NAME, BlastPlusWorker::tr("Database Name"), BlastPlusWorker::tr("Base name for BLAST+ DB files")); Descriptor ev(BLASTPLUS_EXPECT_VALUE, BlastPlusWorker::tr("Expected value"), BlastPlusWorker::tr("This setting specifies the statistical significance threshold for reporting matches against database sequences.")); Descriptor gn(BLASTPLUS_GROUP_NAME, BlastPlusWorker::tr("Annotate as"), BlastPlusWorker::tr("Name for annotations")); Descriptor etp(BLASTPLUS_EXT_TOOL_PATH, BlastPlusWorker::tr("Tool Path"), BlastPlusWorker::tr("External tool path")); Descriptor tdp(BLASTPLUS_TMP_DIR_PATH, BlastPlusWorker::tr("Temporary directory"), BlastPlusWorker::tr("Directory for temporary files")); Descriptor output(BLASTPLUS_ORIGINAL_OUT, BlastPlusWorker::tr("BLAST output"), BlastPlusWorker::tr("Location of BLAST output file.")); Descriptor outtype(BLASTPLUS_OUT_TYPE, BlastPlusWorker::tr("BLAST output type"), BlastPlusWorker::tr("Type of BLAST output file.")); Descriptor ga(BLASTPLUS_GAPPED_ALN, BlastPlusWorker::tr("Gapped alignment"), BlastPlusWorker::tr("Perform gapped alignment")); a << new Attribute(pn, BaseTypes::STRING_TYPE(), true, QVariant("blastn")); a << new Attribute(dp, BaseTypes::STRING_TYPE(), true, QVariant("")); a << new Attribute(dn, BaseTypes::STRING_TYPE(), true, QVariant("")); a << new Attribute(etp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(tdp, BaseTypes::STRING_TYPE(), true, QVariant("default")); a << new Attribute(ev, BaseTypes::NUM_TYPE(), false, QVariant(10.00)); a << new Attribute(gn, BaseTypes::STRING_TYPE(), false, QVariant("")); Attribute* gaAttr= new Attribute(ga, BaseTypes::BOOL_TYPE(), false, QVariant(true)); gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"blastn")); gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"blastp")); gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"gpu-blastp")); gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"blastx")); gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"tblastn")); a << gaAttr; a << new Attribute(output, BaseTypes::STRING_TYPE(), false, QVariant("")); a << new Attribute(outtype, BaseTypes::STRING_TYPE(), false, QVariant("5")); Descriptor desc(ACTOR_ID, BlastPlusWorker::tr("Local BLAST+ Search"), BlastPlusWorker::tr("Finds annotations for DNA sequence in local database")); ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); proto->addSlotRelation(BasePorts::IN_SEQ_PORT_ID(), BaseSlots::DNA_SEQUENCE_SLOT().getId(), BasePorts::OUT_ANNOTATIONS_PORT_ID(), BaseSlots::ANNOTATION_TABLE_SLOT().getId()); QMap<QString, PropertyDelegate*> delegates; { QVariantMap m; m["blastn"] = "blastn"; m["blastp"] = "blastp"; m["gpu-blastp"] = "gpu-blastp"; m["blastx"] = "blastx"; m["tblastn"] = "tblastn"; m["tblastx"] = "tblastx"; delegates[BLASTPLUS_PROGRAM_NAME] = new ComboBoxDelegate(m); } { QVariantMap m; m["minimum"] = 0.000001; m["maximum"] = 100000; m["singleStep"] = 1.0; m["decimals"] = 6; delegates[BLASTPLUS_EXPECT_VALUE] = new DoubleSpinBoxDelegate(m); } { QVariantMap m; m["use"] = true; m["not use"] = false; delegates[BLASTPLUS_GAPPED_ALN] = new ComboBoxDelegate(m); } { QVariantMap m; m["traditional pairwise (-outfmt 0)"] = 0; // m["query-anchored showing identities"] = 1; // m["query-anchored no identities"] = 2; // m["flat query-anchored, show identities"] = 3; // m["flat query-anchored, no identities"] = 4; m["XML (-outfmt 5)"] = 5; m["tabular (-outfmt 6)"] = 6; // m["tabular with comment lines"] = 7; // m["Text ASN.1"] = 8; // m["Binary ASN.1"] = 9; // m["Comma-separated values"] = 10; // m["BLAST archive format (ASN.1)"] = 11; delegates[BLASTPLUS_OUT_TYPE] = new ComboBoxDelegate(m); } delegates[BLASTPLUS_ORIGINAL_OUT] = new URLDelegate("", "out file", false); delegates[BLASTPLUS_DATABASE_PATH] = new URLDelegate("", "Database Directory", false, true); delegates[BLASTPLUS_EXT_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[BLASTPLUS_TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new BlastPlusPrompter()); proto->setIconPath(":external_tool_support/images/ncbi.png"); WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new BlastPlusWorkerFactory()); } /**************************** * BlastPlusPrompter ****************************/ BlastPlusPrompter::BlastPlusPrompter(Actor* p) : PrompterBase<BlastPlusPrompter>(p) { } QString BlastPlusPrompter::composeRichDoc() { IntegralBusPort* input = qobject_cast<IntegralBusPort*>(target->getPort(BasePorts::IN_SEQ_PORT_ID())); Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId()); QString unsetStr = "<font color='red'>"+tr("unset")+"</font>"; QString producerName = tr(" from <u>%1</u>").arg(producer ? producer->getLabel() : unsetStr); QString doc = tr("For sequence <u>%1</u> find annotations in database <u>%2</u>") .arg(producerName).arg(getHyperlink(BLASTPLUS_DATABASE_NAME, getRequiredParam(BLASTPLUS_DATABASE_NAME))); return doc; } /**************************** * BlastPlusWorker ****************************/ BlastPlusWorker::BlastPlusWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) { } void BlastPlusWorker::init() { input = ports.value(BasePorts::IN_SEQ_PORT_ID()); output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID()); } Task* BlastPlusWorker::tick() { if (input->hasMessage()) { Message inputMessage = getMessageAndSetupScriptValues(input); if (inputMessage.isEmpty()) { output->transit(); return NULL; } cfg.programName=actor->getParameter(BLASTPLUS_PROGRAM_NAME)->getAttributeValue<QString>(context); cfg.databaseNameAndPath=actor->getParameter(BLASTPLUS_DATABASE_PATH)->getAttributeValue<QString>(context) +"/"+ actor->getParameter(BLASTPLUS_DATABASE_NAME)->getAttributeValue<QString>(context); cfg.isDefaultCosts=true; cfg.isDefaultMatrix=true; cfg.isDefautScores=true; cfg.expectValue=actor->getParameter(BLASTPLUS_EXPECT_VALUE)->getAttributeValue<double>(context); cfg.groupName=actor->getParameter(BLASTPLUS_GROUP_NAME)->getAttributeValue<QString>(context); if(cfg.groupName.isEmpty()){ cfg.groupName="blast result"; } cfg.wordSize=0; cfg.isGappedAlignment=actor->getParameter(BLASTPLUS_GAPPED_ALN)->getAttributeValue<bool>(context); QString path=actor->getParameter(BLASTPLUS_EXT_TOOL_PATH)->getAttributeValue<QString>(context); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ if(cfg.programName == "blastn"){ AppContext::getExternalToolRegistry()->getByName(BLASTN_TOOL_NAME)->setPath(path); }else if(cfg.programName == "blastp"){ AppContext::getExternalToolRegistry()->getByName(BLASTP_TOOL_NAME)->setPath(path); // }else if(cfg.programName == "gpu-blastp"){ // https://ugene.unipro.ru/tracker/browse/UGENE-945 // AppContext::getExternalToolRegistry()->getByName(GPU_BLASTP_TOOL_NAME)->setPath(path); }else if(cfg.programName == "blastx"){ AppContext::getExternalToolRegistry()->getByName(BLASTX_TOOL_NAME)->setPath(path); }else if(cfg.programName == "tblastn"){ AppContext::getExternalToolRegistry()->getByName(TBLASTN_TOOL_NAME)->setPath(path); }else if(cfg.programName == "tblastx"){ AppContext::getExternalToolRegistry()->getByName(TBLASTX_TOOL_NAME)->setPath(path); } } path=actor->getParameter(BLASTPLUS_TMP_DIR_PATH)->getAttributeValue<QString>(context); if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){ AppContext::getAppSettings()->getUserAppsSettings()->setUserTemporaryDirPath(path); } SharedDbiDataHandler seqId = inputMessage.getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value<SharedDbiDataHandler>(); std::auto_ptr<U2SequenceObject> seqObj(StorageUtils::getSequenceObject(context->getDataStorage(), seqId)); if (NULL == seqObj.get()) { return NULL; } DNASequence seq = seqObj->getWholeSequence(); if( seq.length() < 1) { return new FailTask(tr("Empty sequence supplied to BLAST")); } cfg.querySequence=seq.seq; DNAAlphabet *alp = U2AlphabetUtils::findBestAlphabet(seq.seq); cfg.alphabet=alp; //TO DO: Check alphabet if(seq.alphabet->isAmino()) { if(cfg.programName == "blastn" || cfg.programName == "blastx" || cfg.programName == "tblastx") { return new FailTask(tr("Selected BLAST search with nucleotide input sequence")); } } else { if(cfg.programName == "blastp" || cfg.programName == "gpu-blastp" || cfg.programName == "tblastn") { return new FailTask(tr("Selected BLAST search with amino acid input sequence")); } } cfg.needCreateAnnotations=false; cfg.outputType=actor->getParameter(BLASTPLUS_OUT_TYPE)->getAttributeValue<int>(context); cfg.outputOriginalFile=actor->getParameter(BLASTPLUS_ORIGINAL_OUT)->getAttributeValue<QString>(context); if(cfg.outputType != 5 && cfg.outputOriginalFile.isEmpty()){ return new FailTask(tr("Not selected BLAST output file")); } if(cfg.programName == "blastn"){ cfg.megablast = true; cfg.wordSize = 28; cfg.windowSize = 0; }else{ cfg.megablast = false; cfg.wordSize = 3; cfg.windowSize = 40; } //set X dropoff values if(cfg.programName == "blastn"){ cfg.xDropoffFGA = 100; cfg.xDropoffGA = 20; cfg.xDropoffUnGA = 10; }else if (cfg.programName == "tblastx"){ cfg.xDropoffFGA = 0; cfg.xDropoffGA = 0; cfg.xDropoffUnGA = 7; }else{ cfg.xDropoffFGA = 25; cfg.xDropoffGA = 15; cfg.xDropoffUnGA = 7; } Task * t=NULL; if(cfg.programName == "blastn"){ t = new BlastNPlusSupportTask(cfg); }else if(cfg.programName == "blastp" || cfg.programName == "gpu-blastp"){ t = new BlastPPlusSupportTask(cfg); }else if(cfg.programName == "blastx"){ t = new BlastXPlusSupportTask(cfg); }else if(cfg.programName == "tblastn"){ t = new TBlastNPlusSupportTask(cfg); }else if(cfg.programName == "tblastx"){ t = new TBlastXPlusSupportTask(cfg); } connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished())); return t; } else if (input->isEnded()) { setDone(); output->setEnded(); } return NULL; } void BlastPlusWorker::sl_taskFinished() { BlastPlusSupportCommonTask* t = qobject_cast<BlastPlusSupportCommonTask*>(sender()); if (t->getState() != Task::State_Finished) return; if(output) { QList<SharedAnnotationData> res = t->getResultedAnnotations(); QString annName = actor->getParameter(BLASTPLUS_GROUP_NAME)->getAttributeValue<QString>(context); if(!annName.isEmpty()) { for(int i = 0; i<res.count();i++) { res[i]->name = annName; } } QVariant v = qVariantFromValue<QList<SharedAnnotationData> >(res); output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v)); } } void BlastPlusWorker::cleanup() { } } //namespace LocalWorkflow } //namespace U2
45.833333
155
0.659476
iganna
d73e1dbfd60bd978a0197c0a6322f580467bd0d5
2,820
cpp
C++
Algorithms/Search/Ice_Cream_Parlor.cpp
whitehatty/HackerRank
6b0f5716ccd69cdf5857ba2d00740eef2b6520af
[ "MIT" ]
null
null
null
Algorithms/Search/Ice_Cream_Parlor.cpp
whitehatty/HackerRank
6b0f5716ccd69cdf5857ba2d00740eef2b6520af
[ "MIT" ]
null
null
null
Algorithms/Search/Ice_Cream_Parlor.cpp
whitehatty/HackerRank
6b0f5716ccd69cdf5857ba2d00740eef2b6520af
[ "MIT" ]
null
null
null
/** Sunny and Johnny together have MM dollars they want to spend on ice cream. The parlor offers N flavors, and they want to choose two flavors so that they end up spending the whole amount. You are given the cost of these flavors. The cost of the ith flavor is denoted by ci. You have to display the indices of the two flavors whose sum is M. Input Format The first line of the input contains T; T test cases follow. Each test case follows the format detailed below: The first line contains M. The second line contains N. The third line contains N space-separated integers denoting the price of each flavor. Here, the ith integer denotes ci. Output Format Output two integers, each of which is a valid index of a flavor. The lower index must be printed first. Indices are indexed from 1 to N. Constraints 1 <= T <= 50 2 <= M <= 10000 2 <= N <= 10000 1 <= ci <= 10000, where i in [1,N] The prices of any two items may be the same and each test case has a unique solution. Sample Input 2 4 5 1 4 5 3 2 4 4 2 2 4 3 Sample Output 1 4 1 2 Explanation The sample input has two test cases. For the 1st, the amount M = 4 and there are 5 flavors at the store. The flavors indexed at 1 and 4 sum up to 4. For the 2nd test case, the amount M = 4 and the flavors indexed at 1 and 2 sum up to 4. **/ /** NOTE: http://stackoverflow.com/questions/4720271/find-a-pair-of-elements-from-an-array-whose-sum-equals-a-given-number There are 3 approaches to this solution: Let the sum be T and n be the size of array Approach 1: The naive way to do this would be to check all combinations (n choose 2). This exhaustive search is O(n2). Approach 2: A better way would be to sort the array. This takes O(n log n) Then for each x in array A, use binary search to look for T-x. This will take O(nlogn). So, overall search is O(n log n) Approach 3 : The best way would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion. Then for every x, we can just look up its complement, T-x, which is O(1). Overall the run time of this approach is O(n). **/ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { int t = 0; cin >> t; while(t--){ unsigned M = 0; unsigned N = 0; cin >> M >> N; unordered_map<int,unsigned> prices; for(unsigned i = 0; i < N; i++){ unsigned price = 0; cin >> price; prices.insert({price,i}); unordered_map<int,unsigned>::const_iterator got = prices.find(M-price); if(got != prices.end() && got->second != i){ cout << got->second + 1 << " " << i+1; } } cout << "\n"; } return 0; }
27.920792
152
0.673404
whitehatty
d73e6145a2c8970878dd166f37e79acabfd6be9c
2,536
hpp
C++
sfml/samples/wxwidgets/wxSFMLCanvas.hpp
fu7mu4/entonetics
d0b2643f039a890b25d5036cc94bfe3b4d840480
[ "MIT" ]
null
null
null
sfml/samples/wxwidgets/wxSFMLCanvas.hpp
fu7mu4/entonetics
d0b2643f039a890b25d5036cc94bfe3b4d840480
[ "MIT" ]
null
null
null
sfml/samples/wxwidgets/wxSFMLCanvas.hpp
fu7mu4/entonetics
d0b2643f039a890b25d5036cc94bfe3b4d840480
[ "MIT" ]
null
null
null
#ifndef WXSFMLCANVAS_HPP #define WXSFMLCANVAS_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Graphics.hpp> #include <wx/wx.h> //////////////////////////////////////////////////////////// /// wxSFMLCanvas allows to run SFML in a wxWidgets control //////////////////////////////////////////////////////////// class wxSFMLCanvas : public wxControl, public sf::RenderWindow { public : //////////////////////////////////////////////////////////// /// Construct the wxSFMLCanvas /// /// \param Parent : Parent of the control (NULL by default) /// \param Id : Identifier of the control (-1 by default) /// \param Position : Position of the control (wxDefaultPosition by default) /// \param Size : Size of the control (wxDefaultSize by default) /// \param Style : Style of the control (0 by default) /// //////////////////////////////////////////////////////////// wxSFMLCanvas(wxWindow* Parent = NULL, wxWindowID Id = -1, const wxPoint& Position = wxDefaultPosition, const wxSize& Size = wxDefaultSize, long Style = 0); //////////////////////////////////////////////////////////// /// Destructor /// //////////////////////////////////////////////////////////// virtual ~wxSFMLCanvas(); private : DECLARE_EVENT_TABLE() //////////////////////////////////////////////////////////// /// Notification for the derived class that moment is good /// for doing its update and drawing stuff /// //////////////////////////////////////////////////////////// virtual void OnUpdate(); //////////////////////////////////////////////////////////// /// Called when the window is idle - we can refresh our /// SFML window /// //////////////////////////////////////////////////////////// void OnIdle(wxIdleEvent&); //////////////////////////////////////////////////////////// /// Called when the window is repainted - we can display our /// SFML window /// //////////////////////////////////////////////////////////// void OnPaint(wxPaintEvent&); //////////////////////////////////////////////////////////// /// Called when the window needs to draw its background /// //////////////////////////////////////////////////////////// void OnEraseBackground(wxEraseEvent&); }; #endif // WXSFMLCANVAS_HPP
35.71831
160
0.375789
fu7mu4
d7416592bb226b7472f9b022160581cea7e0dc35
6,257
cc
C++
src/lib/process/tests/config_ctl_info_unittests.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
2
2021-06-29T09:56:34.000Z
2021-06-29T09:56:39.000Z
src/lib/process/tests/config_ctl_info_unittests.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
null
null
null
src/lib/process/tests/config_ctl_info_unittests.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2019 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <process/config_ctl_info.h> #include <exceptions/exceptions.h> #include <gtest/gtest.h> #include <sstream> #include <iostream> using namespace isc::process; using namespace isc::data; using namespace isc::util; // Verifies initializing via an access string and unparsing into elements // We just test basic unparsing, as more rigorous testing is done in // libkea-db testing which ConfibDBInfo uses. TEST(ConfigDbInfo, basicOperation) { ConfigDbInfo db; std::string access = "type=mysql user=tom password=terrific"; std::string redacted_access = "password=***** type=mysql user=tom"; std::string access_json = "{\n" " \"type\":\"mysql\", \n" " \"user\":\"tom\", \n" " \"password\":\"terrific\" \n" "} \n"; // Convert the above configuration into Elements for comparison. ElementPtr exp_elems; ASSERT_NO_THROW(exp_elems = Element::fromJSON(access_json)) << "test is broken"; // Initialize the db from an the access string db.setAccessString(access); EXPECT_EQ(access, db.getAccessString()); EXPECT_EQ(redacted_access, db.redactedAccessString()); // Convert the db into Elements and make sure they are as expected. ElementPtr db_elems; ASSERT_NO_THROW(db_elems = db.toElement()); EXPECT_TRUE(db_elems->equals(*exp_elems)); } // Verify that db parameter values may be retrieved. TEST(ConfigDbInfo, getParameterValue) { ConfigDbInfo db1; std::string access1 = "type=mysql name=keatest port=33 readonly=false"; db1.setAccessString(access1); std::string value; bool found = false; // Should find "type" ASSERT_NO_THROW(found = db1.getParameterValue("type", value)); EXPECT_TRUE(found); EXPECT_EQ("mysql", value); // Should find "name" ASSERT_NO_THROW(found = db1.getParameterValue("name", value)); EXPECT_TRUE(found); EXPECT_EQ("keatest", value); // Should find "port" ASSERT_NO_THROW(found = db1.getParameterValue("port", value)); EXPECT_TRUE(found); EXPECT_EQ("33", value); // Should find "readonly" ASSERT_NO_THROW(found = db1.getParameterValue("readonly", value)); EXPECT_TRUE(found); EXPECT_EQ("false", value); // Should not find "bogus" ASSERT_NO_THROW(found = db1.getParameterValue("bogus", value)); EXPECT_FALSE(found); } // Verify that db equality operators work correctly. TEST(ConfigDbInfo, equalityOperators) { ConfigDbInfo db1; std::string access1 = "type=mysql user=tom password=terrific"; ASSERT_NO_THROW(db1.setAccessString(access1)); ConfigDbInfo db2; std::string access2 = "type=postgresql user=tom password=terrific"; ASSERT_NO_THROW(db2.setAccessString(access2)); // Verify that the two unequal dbs are in fact not equal. EXPECT_FALSE(db1.equals(db2)); EXPECT_FALSE(db1 == db2); EXPECT_TRUE(db1 != db2); // Verify that the two equal dbs are in fact equal. db2.setAccessString(access1); EXPECT_TRUE(db1.equals(db2)); EXPECT_TRUE(db1 == db2); EXPECT_FALSE(db1 != db2); } // Verifies the basic operations of ConfigControlInfo TEST(ConfigControlInfo, basicOperation) { ConfigControlInfo ctl; // We should have no dbs in the list. EXPECT_EQ(0, ctl.getConfigDatabases().size()); // The default fetch time is 30 and it is unspecified. EXPECT_TRUE(ctl.getConfigFetchWaitTime().unspecified()); EXPECT_EQ(30, ctl.getConfigFetchWaitTime().get()); // Override the default fetch time. ctl.setConfigFetchWaitTime(Optional<uint16_t>(123)); EXPECT_EQ(123, ctl.getConfigFetchWaitTime().get()); // We should be able to add two distinct, valid dbs std::string access_str1 = "type=mysql host=machine1.org"; ASSERT_NO_THROW(ctl.addConfigDatabase(access_str1)); std::string access_str2 = "type=postgresql host=machine2.org"; ASSERT_NO_THROW(ctl.addConfigDatabase(access_str2)); // We should fail on a duplicate db. ASSERT_THROW(ctl.addConfigDatabase(access_str1), isc::BadValue); // We should have two dbs in the list. const ConfigDbInfoList& db_list = ctl.getConfigDatabases(); EXPECT_EQ(2, db_list.size()); // Verify the dbs in the list are as we expect them to be. EXPECT_EQ (access_str1, db_list[0].getAccessString()); EXPECT_EQ (access_str2, db_list[1].getAccessString()); // Verify we can find dbs based on a property values. const ConfigDbInfo& db_info = ctl.findConfigDb("type", "mysql"); EXPECT_FALSE(db_info == ConfigControlInfo::EMPTY_DB()); EXPECT_EQ (access_str1, db_info.getAccessString()); const ConfigDbInfo& db_info2 = ctl.findConfigDb("host", "machine2.org"); EXPECT_FALSE(db_info2 == ConfigControlInfo::EMPTY_DB()); EXPECT_EQ (access_str2, db_info2.getAccessString()); // Verify not finding a db reutrns EMPTY_DB(). const ConfigDbInfo& db_info3 = ctl.findConfigDb("type", "bogus"); EXPECT_TRUE(db_info3 == ConfigControlInfo::EMPTY_DB()); // Verify we can clear the list of dbs and the fetch time. ctl.clear(); EXPECT_EQ(0, ctl.getConfigDatabases().size()); EXPECT_TRUE(ctl.getConfigFetchWaitTime().unspecified()); EXPECT_EQ(30, ctl.getConfigFetchWaitTime().get()); } // Verifies the copy ctor and equality functions ConfigControlInfo TEST(ConfigControlInfo, copyAndEquality) { // Make an instance with two dbs. ConfigControlInfo ctl1; ASSERT_NO_THROW(ctl1.addConfigDatabase("type=mysql host=mach1.org")); ASSERT_NO_THROW(ctl1.addConfigDatabase("type=postgresql host=mach2.org")); ctl1.setConfigFetchWaitTime(Optional<uint16_t>(123)); // Clone that instance. ConfigControlInfo ctl2(ctl1); // They should be equal. EXPECT_TRUE(ctl1.equals(ctl2)); // Make a third instance with a different db. ConfigControlInfo ctl3; ASSERT_NO_THROW(ctl1.addConfigDatabase("type=cql host=other.org")); // They should not equal. EXPECT_FALSE(ctl3.equals(ctl1)); }
34.569061
78
0.704171
svenauhagen
d7423f024ea24e3355d5a6431e071084116aed15
2,009
cpp
C++
libs/libpeconv/tests/test_load_ntdll.cpp
fengjixuchui/memhunter
3f85e66d5d4cf83bd7b5d0d457a8e62c746ba703
[ "MIT" ]
354
2018-08-13T18:19:21.000Z
2022-03-20T10:37:20.000Z
libs/libpeconv/tests/test_load_ntdll.cpp
ZhuHuiBeiShaDiao/memhunter
37ce1488fa041199cc8761e473947affc3286b7b
[ "MIT" ]
3
2019-09-27T11:33:52.000Z
2020-04-21T17:15:28.000Z
libs/libpeconv/tests/test_load_ntdll.cpp
ZhuHuiBeiShaDiao/memhunter
37ce1488fa041199cc8761e473947affc3286b7b
[ "MIT" ]
90
2018-11-15T12:37:51.000Z
2022-02-14T11:12:39.000Z
#include "test_load_ntdll.h" #include "peconv.h" #include <iostream> #include "shellcodes.h" int (_cdecl *ntdll_tolower) (int) = NULL; NTSTATUS (NTAPI *ntdll_ZwAllocateVirtualMemory)( _In_ HANDLE ProcessHandle, _Inout_ PVOID *BaseAddress, _In_ ULONG_PTR ZeroBits, _Inout_ PSIZE_T RegionSize, _In_ ULONG AllocationType, _In_ ULONG Protect ) = NULL; //For now this is for manual tests only: int tests::test_ntdll(char *path) { CHAR ntdllPath[MAX_PATH]; ExpandEnvironmentStrings("%SystemRoot%\\system32\\ntdll.dll", ntdllPath, MAX_PATH); size_t v_size = 0; BYTE *ntdll_module = peconv::load_pe_module(ntdllPath, v_size, true, true); if (!ntdll_module) { return -1; } bool is64 = peconv::is64bit(ntdll_module); std::cout << "NTDLL loaded" << is64 << std::endl; FARPROC n_offset = peconv::get_exported_func(ntdll_module, "tolower"); if (n_offset == NULL) { return -1; } std::cout << "Got tolower: " << n_offset << std::endl; ntdll_tolower = (int (_cdecl *) (int)) n_offset; int out = ntdll_tolower('C'); std::cout << "To lower char: " << (char) out << std::endl; n_offset = peconv::get_exported_func(ntdll_module, "ZwAllocateVirtualMemory"); if (n_offset == NULL) { return -1; } PVOID base_addr = 0; SIZE_T buffer_size = 0x200; ntdll_ZwAllocateVirtualMemory = (NTSTATUS (NTAPI *)(HANDLE, PVOID *, ULONG_PTR, PSIZE_T, ULONG, ULONG)) n_offset; NTSTATUS status = ntdll_ZwAllocateVirtualMemory( GetCurrentProcess(), &base_addr, 0, &buffer_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE ); if (status != S_OK) { return -1; } printf("allocated: %p\n", base_addr); #ifndef _WIN64 memcpy(base_addr, messageBox32bit_sc, sizeof(messageBox32bit_sc)); #else memcpy(base_addr, messageBox64bit_sc, sizeof(messageBox64bit_sc)); #endif void (*shellc)(void) = (void (*)(void))base_addr; shellc(); return 0; }
30.439394
117
0.661025
fengjixuchui
d7427ec84324c3945f28973ffb18eda2d0383f2e
3,300
cc
C++
google/cloud/bigquery/internal/model_logging_decorator.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/bigquery/internal/model_logging_decorator.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/bigquery/internal/model_logging_decorator.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/bigquery/v2/model.proto #include "google/cloud/bigquery/internal/model_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/bigquery/v2/model.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace bigquery_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN ModelServiceLogging::ModelServiceLogging( std::shared_ptr<ModelServiceStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} StatusOr<google::cloud::bigquery::v2::Model> ModelServiceLogging::GetModel( grpc::ClientContext& context, google::cloud::bigquery::v2::GetModelRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::GetModelRequest const& request) { return child_->GetModel(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::bigquery::v2::ListModelsResponse> ModelServiceLogging::ListModels( grpc::ClientContext& context, google::cloud::bigquery::v2::ListModelsRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::ListModelsRequest const& request) { return child_->ListModels(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::bigquery::v2::Model> ModelServiceLogging::PatchModel( grpc::ClientContext& context, google::cloud::bigquery::v2::PatchModelRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::PatchModelRequest const& request) { return child_->PatchModel(context, request); }, context, request, __func__, tracing_options_); } Status ModelServiceLogging::DeleteModel( grpc::ClientContext& context, google::cloud::bigquery::v2::DeleteModelRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::bigquery::v2::DeleteModelRequest const& request) { return child_->DeleteModel(context, request); }, context, request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace bigquery_internal } // namespace cloud } // namespace google
38.372093
78
0.724848
sydney-munro
d74376d8fb46bcae3fbd0667d3b7940c45ef85a3
9,898
cc
C++
o3d/core/cross/class_manager.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
o3d/core/cross/class_manager.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
o3d/core/cross/class_manager.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2009, Google Inc. * 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 Google Inc. 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. */ // This file implements class ClassManager. #include "core/cross/bitmap.h" #include "core/cross/bounding_box.h" #include "core/cross/buffer.h" #include "core/cross/canvas.h" #include "core/cross/canvas_paint.h" #include "core/cross/canvas_shader.h" #include "core/cross/class_manager.h" #include "core/cross/clear_buffer.h" #include "core/cross/counter.h" #include "core/cross/curve.h" #include "core/cross/draw_context.h" #include "core/cross/draw_pass.h" #include "core/cross/effect.h" #include "core/cross/function.h" #include "core/cross/material.h" #include "core/cross/matrix4_axis_rotation.h" #include "core/cross/matrix4_composition.h" #include "core/cross/matrix4_scale.h" #include "core/cross/matrix4_translation.h" #include "core/cross/param_array.h" #include "core/cross/param_operation.h" #include "core/cross/primitive.h" #include "core/cross/render_surface_set.h" #include "core/cross/sampler.h" #include "core/cross/shape.h" #include "core/cross/skin.h" #include "core/cross/standard_param.h" #include "core/cross/state_set.h" #include "core/cross/stream.h" #include "core/cross/stream_bank.h" #include "core/cross/transform.h" #include "core/cross/tree_traversal.h" #include "core/cross/viewport.h" namespace o3d { ClassManager::ClassManager(ServiceLocator* service_locator) : service_locator_(service_locator), service_(service_locator_, this) { // Params AddTypedClass<ParamBoolean>(); AddTypedClass<ParamBoundingBox>(); AddTypedClass<ParamDrawContext>(); AddTypedClass<ParamDrawList>(); AddTypedClass<ParamEffect>(); AddTypedClass<ParamFloat>(); AddTypedClass<ParamFloat2>(); AddTypedClass<ParamFloat3>(); AddTypedClass<ParamFloat4>(); AddTypedClass<ParamFunction>(); AddTypedClass<ParamInteger>(); AddTypedClass<ParamMaterial>(); AddTypedClass<ParamMatrix4>(); AddTypedClass<ParamParamArray>(); AddTypedClass<ParamRenderSurface>(); AddTypedClass<ParamRenderDepthStencilSurface>(); AddTypedClass<ParamSampler>(); AddTypedClass<ParamSkin>(); AddTypedClass<ParamState>(); AddTypedClass<ParamStreamBank>(); AddTypedClass<ParamString>(); AddTypedClass<ParamTexture>(); AddTypedClass<ParamTransform>(); // Param operations. AddTypedClass<Matrix4AxisRotation>(); AddTypedClass<Matrix4Composition>(); AddTypedClass<Matrix4Scale>(); AddTypedClass<Matrix4Translation>(); AddTypedClass<ParamOp2FloatsToFloat2>(); AddTypedClass<ParamOp3FloatsToFloat3>(); AddTypedClass<ParamOp4FloatsToFloat4>(); AddTypedClass<ParamOp16FloatsToMatrix4>(); AddTypedClass<TRSToMatrix4>(); // SAS Params AddTypedClass<WorldParamMatrix4>(); AddTypedClass<WorldInverseParamMatrix4>(); AddTypedClass<WorldTransposeParamMatrix4>(); AddTypedClass<WorldInverseTransposeParamMatrix4>(); AddTypedClass<ViewParamMatrix4>(); AddTypedClass<ViewInverseParamMatrix4>(); AddTypedClass<ViewTransposeParamMatrix4>(); AddTypedClass<ViewInverseTransposeParamMatrix4>(); AddTypedClass<ProjectionParamMatrix4>(); AddTypedClass<ProjectionInverseParamMatrix4>(); AddTypedClass<ProjectionTransposeParamMatrix4>(); AddTypedClass<ProjectionInverseTransposeParamMatrix4>(); AddTypedClass<WorldViewParamMatrix4>(); AddTypedClass<WorldViewInverseParamMatrix4>(); AddTypedClass<WorldViewTransposeParamMatrix4>(); AddTypedClass<WorldViewInverseTransposeParamMatrix4>(); AddTypedClass<ViewProjectionParamMatrix4>(); AddTypedClass<ViewProjectionInverseParamMatrix4>(); AddTypedClass<ViewProjectionTransposeParamMatrix4>(); AddTypedClass<ViewProjectionInverseTransposeParamMatrix4>(); AddTypedClass<WorldViewProjectionParamMatrix4>(); AddTypedClass<WorldViewProjectionInverseParamMatrix4>(); AddTypedClass<WorldViewProjectionTransposeParamMatrix4>(); AddTypedClass<WorldViewProjectionInverseTransposeParamMatrix4>(); // Other Objects. AddTypedClass<Bitmap>(); AddTypedClass<Canvas>(); AddTypedClass<CanvasLinearGradient>(); AddTypedClass<CanvasPaint>(); AddTypedClass<ClearBuffer>(); AddTypedClass<Counter>(); AddTypedClass<Curve>(); AddTypedClass<DrawContext>(); AddTypedClass<DrawElement>(); AddTypedClass<DrawList>(); AddTypedClass<DrawPass>(); AddTypedClass<Effect>(); AddTypedClass<FunctionEval>(); AddTypedClass<IndexBuffer>(); AddTypedClass<Material>(); AddTypedClass<ParamArray>(); AddTypedClass<ParamObject>(); AddTypedClass<Primitive>(); AddTypedClass<RenderFrameCounter>(); AddTypedClass<RenderNode>(); AddTypedClass<RenderSurfaceSet>(); AddTypedClass<Sampler>(); AddTypedClass<SecondCounter>(); AddTypedClass<Shape>(); AddTypedClass<Skin>(); AddTypedClass<SkinEval>(); AddTypedClass<SourceBuffer>(); AddTypedClass<State>(); AddTypedClass<StateSet>(); AddTypedClass<StreamBank>(); AddTypedClass<Texture2D>(); AddTypedClass<TextureCUBE>(); AddTypedClass<TickCounter>(); AddTypedClass<Transform>(); AddTypedClass<TreeTraversal>(); AddTypedClass<VertexBuffer>(); AddTypedClass<Viewport>(); } void ClassManager::AddClass(const ObjectBase::Class* object_class, ObjectCreateFunc function) { DLOG_ASSERT(object_class_info_name_map_.find(object_class->name()) == object_class_info_name_map_.end()) << "attempt to register duplicate class name"; object_class_info_name_map_.insert( std::make_pair(object_class->name(), ObjectClassInfo(object_class, function))); DLOG_ASSERT(object_creator_class_map_.find(object_class) == object_creator_class_map_.end()) << "attempt to register duplicate class"; object_creator_class_map_.insert(std::make_pair(object_class, function)); } void ClassManager::RemoveClass(const ObjectBase::Class* object_class) { ObjectClassInfoNameMap::size_type ii = object_class_info_name_map_.erase( object_class->name()); DLOG_ASSERT(ii == 1) << "attempt to unregister non-existant class name"; ObjectCreatorClassMap::size_type jj = object_creator_class_map_.erase( object_class); DLOG_ASSERT(jj == 1) << "attempt to unregister non-existant class"; } const ObjectBase::Class* ClassManager::GetClassByClassName( const String& class_name) const { ObjectClassInfoNameMap::const_iterator iter = object_class_info_name_map_.find(class_name); if (iter == object_class_info_name_map_.end()) { // Try adding the o3d namespace prefix String prefixed_class_name(O3D_STRING_CONSTANT("") + class_name); iter = object_class_info_name_map_.find(prefixed_class_name); } return (iter != object_class_info_name_map_.end()) ? iter->second.class_type() : NULL; } bool ClassManager::ClassNameIsAClass( const String& derived_class_name, const ObjectBase::Class* base_class) const { const ObjectBase::Class* derived_class = GetClassByClassName( derived_class_name); return derived_class && ObjectBase::ClassIsA(derived_class, base_class); } // Factory method to create a new object by class name. ObjectBase::Ref ClassManager::CreateObject(const String& type_name) { ObjectClassInfoNameMap::const_iterator iter = object_class_info_name_map_.find(type_name); if (iter == object_class_info_name_map_.end()) { // Try adding the o3d namespace prefix String prefixed_type_name(O3D_STRING_CONSTANT("") + type_name); iter = object_class_info_name_map_.find(prefixed_type_name); } if (iter != object_class_info_name_map_.end()) { return ObjectBase::Ref(iter->second.creation_func()(service_locator_)); } return ObjectBase::Ref(); } // Factory method to create a new object by class. ObjectBase::Ref ClassManager::CreateObjectByClass( const ObjectBase::Class* object_class) { ObjectCreatorClassMap::const_iterator iter = object_creator_class_map_.find(object_class); if (iter != object_creator_class_map_.end()) { return ObjectBase::Ref(iter->second(service_locator_)); } return ObjectBase::Ref(); } std::vector<const ObjectBase::Class*> ClassManager::GetAllClasses() const { std::vector<const ObjectBase::Class*> classes; for (ObjectClassInfoNameMap::const_iterator it = object_class_info_name_map_.begin(); it != object_class_info_name_map_.end(); ++it) { classes.push_back(it->second.class_type()); } return classes; } } // namespace o3d
36.523985
75
0.757931
rwatson
d7438cc458f40e26ed19093f5f16246d52522ac3
15,072
cpp
C++
src/io/io_tty.cpp
name212/GrammarEngine
1912809d6a19977c9d2fff88279b76a6152b659d
[ "MIT" ]
55
2015-04-11T17:39:27.000Z
2022-01-07T17:52:22.000Z
src/io/io_tty.cpp
name212/GrammarEngine
1912809d6a19977c9d2fff88279b76a6152b659d
[ "MIT" ]
17
2017-11-22T13:31:11.000Z
2021-06-06T08:30:43.000Z
src/io/io_tty.cpp
qwazer/GrammarEngine
08e1eb7bdfd77f29a51a7063848d74b9171291c4
[ "MIT" ]
28
2015-05-21T08:27:31.000Z
2022-02-24T21:42:36.000Z
// ----------------------------------------------------------------------------- // File IO_TTY.CPP // // (c) by Elijah Koziev all rights reserved // // SOLARIX Intellectronix Project http://www.solarix.ru // https://github.com/Koziev/GrammarEngine // // Content: // Реализация TtyStream - потока для вывода символов на терминал (или в окно // эмуляции терминала для графических сред). // // 27.04.2007 - TtyUcs4Stream and TtyUtf8Stream are implemented for Windows and // Linux UNICODE console. // // 25.05.2007 - Utf8 tty stream bug fixed under linux UTF-8 console // ----------------------------------------------------------------------------- // // CD->20.06.1998 // LC->01.04.2018 // -------------- #include <lem/config.h> #include <stdio.h> #if defined LEM_DOS #include <conio.h> #elif defined LEM_UNIX #if LEM_USES_NCURSES==1 #include <curses.h> #endif #endif #include <lem/unicode.h> #include <lem/console_application.h> #include <lem/streams.h> #if defined LEM_WINDOWS #define WIN_CUI #include <windows.h> static HANDLE hOut = 0; #endif using namespace lem; #if defined LEM_UNIX // Make NCURSES initialization once. static volatile int inited_ncurses = 0; #endif TtyStreamStd::TtyStreamStd(void) :Stream(false, true) { SetMode(false, true, false); binary = false; return; } TtyStreamStd::~TtyStreamStd(void) {} void TtyStreamStd::close(void) { return; } void TtyStreamStd::write(const void *src, pos_type size) { for (pos_type i = 0; i < size; i++) put(((const char*)src)[i]); return; } void TtyStreamStd::put(char ch) { putchar(0x00ff & ch); return; } void TtyStreamStd::puts(const char *s) { ::puts(s); return; } int TtyStreamStd::get(void) { return 0; } bool TtyStreamStd::eof(void) const { return false; } lem::Stream::pos_type TtyStreamStd::seekp(off_type /*pos*/, int /*whereto*/) { return 0; } lem::Stream::pos_type TtyStreamStd::tellp(void) const { LEM_STOPIT; #if !defined LEM_BORLAND return pos_type(); #endif } bool TtyStreamStd::move(lem::Stream::off_type /*offset*/) { return false; } lem::Stream::pos_type TtyStreamStd::fsize(void) const { return 0; } void TtyStreamStd::flush(void) { fflush(stdout); return; } void TtyStreamStd::SetForeGroundColor(int iColor) {} void TtyStreamStd::SetBackGroundColor(int iColor) {} void TtyStreamStd::SetBlinkMode(bool blinks) {} void TtyStreamStd::SetHighLightMode(void) {} void TtyStreamStd::SetLowLightMode(void) {} void TtyStreamStd::SetNormalMode(void) {} lem::Stream::pos_type TtyStreamStd::read(void * /*dest*/, size_t /*size*/) { LEM_STOPIT; #if !defined LEM_BORLAND return pos_type(); #endif } // ############################################################## /*************************************************************************** Работа с терминалом стандартными UNIX-подобными средствами не составляет труда и интереса. Обращаю внимание лишь на способ, которым мы манипулируем цветовыми характеристиками выводимых символов (с помощью стандартной библиотеки NCURSES). Для управления цветом консоли Windows используются также стандартные функции WinAPI). ****************************************************************************/ TtyStream::TtyStream(void) :Stream(false, true) { SetMode(false, true, false); binary = false; #if defined LEM_UNIX && LEM_USES_NCURSES==1 // ************************************************ // Инициализация библиотеки NCURSES для LINUX // ************************************************ if (!inited_ncurses) { initscr(); start_color(); cbreak(); // nonl(); // intrflush(stdscr,FALSE); noecho(); scrollok(stdscr, TRUE); init_pair(1, COLOR_BLACK, COLOR_WHITE); init_pair(2, COLOR_BLUE, COLOR_BLACK); init_pair(3, COLOR_GREEN, COLOR_BLACK); init_pair(4, COLOR_CYAN, COLOR_BLACK); init_pair(5, COLOR_RED, COLOR_BLACK); init_pair(6, COLOR_MAGENTA, COLOR_BLACK); init_pair(7, COLOR_YELLOW, COLOR_BLACK); init_pair(8, COLOR_WHITE, COLOR_BLACK); refresh(); } inited_ncurses++; #endif #if defined WIN_CUI if (!hOut) hOut = GetStdHandle(STD_OUTPUT_HANDLE); fg = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED; bg = 0; #endif return; } int TtyStream::get(void) { return 0; } bool TtyStream::eof(void) const { return false; } Stream::pos_type TtyStream::tellp(void) const { LEM_STOPIT; #if !defined LEM_BORLAND return pos_type(); #endif } Stream::pos_type TtyStream::seekp(lem::Stream::off_type /*pos*/, int /*whereto*/) { return 0; } bool TtyStream::move(Stream::off_type /*offset*/) { return false; } Stream::pos_type TtyStream::fsize(void) const { return 0; } Stream::pos_type TtyStream::read(void * /*dest*/, size_t /*size*/) { LEM_STOPIT; #if !defined LEM_BORLAND return pos_type(); #endif } TtyStream::~TtyStream(void) { #if defined LEM_UNIX && LEM_USES_NCURSES==1 if (!--inited_ncurses) { // NCURSES should be closed endwin(); } #endif /* ... nothing to do ... */ return; } void TtyStream::close(void) { return; } void TtyStream::write(const void *src, pos_type size) { for (pos_type i = 0; i < size; i++) put(((const char*)src)[i]); return; } void TtyStream::put(char ch) { #if defined WIN_CUI char buf[1] = { ch }; DWORD dummy; SetConsoleTextAttribute(hOut, fg | bg); // set the current colors WriteConsoleA(hOut, buf, 1, &dummy, NULL); // put the char #elif defined LEM_WIN32 && defined LEM_CONSOLE printf("%c", ch); #elif defined LEM_UNIX && LEM_USES_NCURSES==1 // UNIX (including LINUX) does not require 0x0d character in eol's. // putchar(ch); addch(0x00ffU & lem::uint16_t(ch)); if (ch == '\n') { refresh(); } #else printf("%c", ch); if (ch == '\n') printf("\r"); #endif return; } void TtyStream::puts(const char *s) { #if defined WIN_CUI DWORD dummy; SetConsoleTextAttribute(hOut, fg | bg); WriteConsoleA(hOut, s, lem_strlen(s), &dummy, NULL); #elif defined LEM_WIN32 && defined LEM_CONSOLE int i = 0; while (s[i]) put(s[i++]); #else int i = 0; while (s[i]) put(s[i++]); #endif return; } // ********************************************************* // Все символы, застрявшие в буфере вывода, принудительно // отрисовываются на экране. // ********************************************************* void TtyStream::flush(void) { #if defined WIN_CUI // nothing to do #elif defined LEM_WIN32 && defined LEM_CONSOLE // nothing to do #elif defined LEM_UNIX && defined LEM_CONSOLE && LEM_USES_NCURSES==1 refresh(); #else fflush(stdout); #endif return; } /******************************************************** Индексом задается цвет символов для последующего вывода. *********************************************************/ void TtyStream::SetForeGroundColor(int iColor) { #if defined WIN_CUI switch (iColor) { case 0: fg = 0; break; case 1: fg = FOREGROUND_BLUE; break; case 2: fg = FOREGROUND_GREEN; break; case 3: fg = FOREGROUND_BLUE | FOREGROUND_GREEN; break; // CYAN case 4: fg = FOREGROUND_RED; break; case 5: fg = FOREGROUND_RED | FOREGROUND_BLUE; break; // MAGENTA case 6: fg = FOREGROUND_RED | FOREGROUND_GREEN; break; // BROWN case 7: fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; // LIGHTGRAY break; case 8: fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // DARKWHITE break; case 9: fg = FOREGROUND_BLUE | FOREGROUND_INTENSITY; break; case 10: fg = FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; case 11: fg = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; case 12: fg = FOREGROUND_RED | FOREGROUND_INTENSITY; break; case 13: fg = FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY; break; case 14: fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; case 15: fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; // WHITE break; } #elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS) textcolor(iColor); #elif defined LEM_UNIX && LEM_USES_NCURSES==1 switch (iColor) { case 0: attrset(COLOR_PAIR(1)); break; case 1: attrset(COLOR_PAIR(2)); break; case 2: attrset(COLOR_PAIR(3)); break; case 3: attrset(COLOR_PAIR(4)); break; case 4: attrset(COLOR_PAIR(5)); break; case 5: attrset(COLOR_PAIR(6)); break; case 6: attrset(COLOR_PAIR(7)); break; case 7: attrset(COLOR_PAIR(8)); break; case 8: attrset(0); break; case 9: attrset(COLOR_PAIR(2) | A_BOLD); break; case 10: attrset(COLOR_PAIR(3) | A_BOLD); break; case 11: attrset(COLOR_PAIR(4) | A_BOLD); break; case 12: attrset(COLOR_PAIR(5) | A_BOLD); break; case 13: attrset(COLOR_PAIR(6) | A_BOLD); break; case 14: attrset(COLOR_PAIR(7) | A_BOLD); break; case 15: attrset(COLOR_PAIR(8) | A_BOLD); break; } #endif return; } /**************************************************************** При выводе на терминал - установка текущего цвета фона символов. Цвет задается индексом. *****************************************************************/ void TtyStream::SetBackGroundColor(int iColor) { #if defined(LEM_BORLAND_3_1) && defined(LEM_DOS) textbackground(iColor); #endif return; } // *********************************************************************** // Режим мерцания символов - был доступен для MSDOS. Особой пользы от него // нет, но оставил метод для поддержки совместимости старых программ. // *********************************************************************** void TtyStream::SetBlinkMode(bool blinks) { #if defined(LEM_BORLAND_3_1) && defined(LEM_DOS) text_info ti; gettextinfo(&ti); int atr = ti.attribute; atr ^= BLINK; textattr(atr); #endif return; } // *********************************************************************** // Установка режима вывода символов с повышенной яркостью (белые). // *********************************************************************** void TtyStream::SetHighLightMode(void) { #if defined WIN_CUI fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; bg = 0; #elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS) highvideo(); #endif return; } // *********************************************************************** // Установка режима вывода символов с пониженной яркостью (темно-серые). // *********************************************************************** void TtyStream::SetLowLightMode(void) { #if defined WIN_CUI fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; bg = 0; #elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS) lowvideo(); #endif return; } // ********************************************************************* // Установка режима вывода символов обычного цвета (серебристо-серые). // ********************************************************************* void TtyStream::SetNormalMode(void) { #if defined WIN_CUI fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; bg = 0; // –ўҐв  д®­  Ё бЁ¬ў®«®ў Ї® 㬮«з ­Ёо. #elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS) // normvideo(); lowvideo(); #elif defined LEM_UNIX && LEM_USES_NCURSES==1 attrset(0); #endif return; } #if defined LEM_UNICODE_CONSOLE #if defined LEM_WINDOWS TtyUcs2Stream::TtyUcs2Stream(void) : TtyStream() {} int TtyUcs2Stream::Bits_Per_Char(void) const { return 16; } void TtyUcs2Stream::wput(wchar_t ch) { #if defined WIN_CUI wchar_t buf[1] = { ch }; DWORD dummy; BOOL res = SetConsoleTextAttribute(hOut, fg | bg); // set the current colors LEM_CHECKIT_Z(res != 0); res = WriteConsoleW(hOut, buf, 1, &dummy, NULL); // put the char LEM_CHECKIT_Z(res != 0); #else LEM_STOPIT; #endif } #endif #if defined LEM_LINUX || defined LEM_DARWIN TtyUtf8Stream::TtyUtf8Stream(void) : TtyStreamStd() {} void TtyUtf8Stream::put(char ch) { putchar(ch); if (ch == '\n') { putchar('\r'); } return; } void TtyUtf8Stream::wput(wchar_t ch) { if (!(0xffffff00 & ch)) putchar(ch); else { uint8_t utf8[8]; const int n8 = lem::UCS4_to_UTF8(ch, utf8); for (int i = 0; i < n8; i++) putchar(utf8[i + 1]); } if (ch == L'\n') { putchar('\r'); // refresh(); } } #endif #endif StdTtyStream::StdTtyStream(void) { stream = NULL; } StdTtyStream::StdTtyStream(ostream *s) :Stream(false, true) { stream = s; } void StdTtyStream::write(const void *src, pos_type size) { stream->write((const char*)src, size); } void StdTtyStream::put(char Ch) { stream->put(Ch); #if LEM_DEBUGGING==1 Assert(); #endif } lem::Stream::pos_type StdTtyStream::read(void * /*dest*/, pos_type /*size*/) { return 0; } int StdTtyStream::get(void) { return -1; } void StdTtyStream::Check(void) const { #if LEM_DEBUGGING==1 Assert(); #endif } void StdTtyStream::flush(void) { #if LEM_DEBUGGING==1 Assert(); #endif stream->flush(); } void StdTtyStream::close(void) { #if LEM_DEBUGGING==1 Assert(); #endif } bool StdTtyStream::eof(void) const { #if LEM_DEBUGGING==1 Assert(); #endif return false; } lem::Stream::pos_type StdTtyStream::tellp(void) const { #if LEM_DEBUGGING==1 Assert(); #endif return 0; } StdTtyStream::pos_type StdTtyStream::seekp(lem::Stream::off_type /*to*/, int /*whereto*/) { #if LEM_DEBUGGING==1 Assert(); #endif return (size_t)-1; } bool StdTtyStream::move(off_type /*offset*/) { #if LEM_DEBUGGING==1 Assert(); #endif return false; } lem::Stream::pos_type StdTtyStream::fsize(void) const { #if LEM_DEBUGGING==1 Assert(); #endif return 0; }
20.646575
90
0.551022
name212
d743e0d24f60ca8e1950c283cdab218ff20e6678
31,899
cpp
C++
iRODS/clients/icommands/src/iticket.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
null
null
null
iRODS/clients/icommands/src/iticket.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
7
2019-12-02T17:55:49.000Z
2019-12-02T17:55:59.000Z
iRODS/clients/icommands/src/iticket.cpp
benlazarine/irods
83f3c4a6f8f7fc6422a1e73a297b97796a961322
[ "BSD-3-Clause" ]
1
2019-12-02T05:44:10.000Z
2019-12-02T05:44:10.000Z
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* This is an interface to the Ticket management system. */ #include "irods_client_api_table.hpp" #include "irods_pack_table.hpp" #include "rods.h" #include "rodsClient.h" #include "irods_random.hpp" #define MAX_SQL 300 #define BIG_STR 3000 extern int get64RandomBytes( char *buf ); char cwd[BIG_STR]; int debug = 0; int longMode = 0; /* more detailed listing */ char zoneArgument[MAX_NAME_LEN + 2] = ""; rcComm_t *Conn; rodsEnv myEnv; int lastCommandStatus = 0; int printCount = 0; int printedRows = 0; int usage( char *subOpt ); void showRestrictions( char *inColumn ); /* print the results of a general query. */ void printResultsAndSubQuery( rcComm_t *Conn, int status, genQueryOut_t *genQueryOut, char *descriptions[], int subColumn, int dashOpt ) { int i, j; lastCommandStatus = status; if ( status == CAT_NO_ROWS_FOUND ) { lastCommandStatus = 0; } if ( status != 0 && status != CAT_NO_ROWS_FOUND ) { printError( Conn, status, "rcGenQuery" ); } else { if ( status == CAT_NO_ROWS_FOUND ) { if ( printCount == 0 ) { printf( "No rows found\n" ); } } else { for ( i = 0; i < genQueryOut->rowCnt; i++ ) { printedRows++; char *subCol = ""; if ( i > 0 && dashOpt > 0 ) { printf( "----\n" ); } for ( j = 0; j < genQueryOut->attriCnt; j++ ) { char *tResult; tResult = genQueryOut->sqlResult[j].value; tResult += i * genQueryOut->sqlResult[j].len; if ( subColumn == j ) { subCol = tResult; } if ( *descriptions[j] != '\0' ) { if ( strstr( descriptions[j], "time" ) != 0 ) { char localTime[TIME_LEN]; getLocalTimeFromRodsTime( tResult, localTime ); if ( strcmp( tResult, "0" ) == 0 || *tResult == '\0' ) { strcpy( localTime, "none" ); } printf( "%s: %s\n", descriptions[j], localTime ); } else { printf( "%s: %s\n", descriptions[j], tResult ); printCount++; } } } if ( subColumn >= 0 ) { showRestrictions( subCol ); } } } } } void showRestrictionsByHost( char *inColumn ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[10]; int i1b[10]; int i2a[10]; int i; char v1[MAX_NAME_LEN]; char *condVal[10]; int status; char *columnNames[] = {"restricted-to host"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ALLOWED_HOST; i1b[i++] = 0; genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; i2a[0] = COL_TICKET_ALLOWED_HOST_TICKET_ID; snprintf( v1, sizeof( v1 ), "='%s'", inColumn ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; genQueryInp.condInput.len = 0; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { printf( "No host restrictions (1)\n" ); return; } if ( status == CAT_NO_ROWS_FOUND ) { printf( "No host restrictions\n" ); return; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 0 ); } return; } void showRestrictionsByUser( char *inColumn ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[10]; int i1b[10]; int i2a[10]; int i; char v1[MAX_NAME_LEN]; char *condVal[10]; int status; char *columnNames[] = {"restricted-to user"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ALLOWED_USER_NAME; i1b[i++] = 0; genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; i2a[0] = COL_TICKET_ALLOWED_USER_TICKET_ID; snprintf( v1, sizeof( v1 ), "='%s'", inColumn ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; genQueryInp.condInput.len = 0; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { printf( "No user restrictions (1)\n" ); return; } if ( status == CAT_NO_ROWS_FOUND ) { printf( "No user restrictions\n" ); return; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 0 ); } return; } void showRestrictionsByGroup( char *inColumn ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[10]; int i1b[10]; int i2a[10]; int i; char v1[MAX_NAME_LEN]; char *condVal[10]; int status; char *columnNames[] = {"restricted-to group"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ALLOWED_GROUP_NAME; i1b[i++] = 0; genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; i2a[0] = COL_TICKET_ALLOWED_GROUP_TICKET_ID; snprintf( v1, sizeof( v1 ), "='%s'", inColumn ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; genQueryInp.condInput.len = 0; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { printf( "No group restrictions (1)\n" ); return; } if ( status == CAT_NO_ROWS_FOUND ) { printf( "No group restrictions\n" ); return; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 0 ); } return; } void showRestrictions( char *inColumn ) { showRestrictionsByHost( inColumn ); showRestrictionsByUser( inColumn ); showRestrictionsByGroup( inColumn ); return; } /* Via a general query, show the Tickets for this user */ int showTickets1( char *inOption, char *inName ) { genQueryInp_t genQueryInp; genQueryOut_t *genQueryOut; int i1a[20]; int i1b[20]; int i2a[20]; int i; char v1[MAX_NAME_LEN]; char *condVal[20]; int status; char *columnNames[] = {"id", "string", "ticket type", "obj type", "owner name", "owner zone", "uses count", "uses limit", "write file count", "write file limit", "write byte count", "write byte limit", "expire time", "collection name", "data collection"}; memset( &genQueryInp, 0, sizeof( genQueryInp_t ) ); printCount = 0; i = 0; i1a[i] = COL_TICKET_ID; i1b[i++] = 0; i1a[i] = COL_TICKET_STRING; i1b[i++] = 0; i1a[i] = COL_TICKET_TYPE; i1b[i++] = 0; i1a[i] = COL_TICKET_OBJECT_TYPE; i1b[i++] = 0; i1a[i] = COL_TICKET_OWNER_NAME; i1b[i++] = 0; i1a[i] = COL_TICKET_OWNER_ZONE; i1b[i++] = 0; i1a[i] = COL_TICKET_USES_COUNT; i1b[i++] = 0; i1a[i] = COL_TICKET_USES_LIMIT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_FILE_COUNT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_FILE_LIMIT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_BYTE_COUNT; i1b[i++] = 0; i1a[i] = COL_TICKET_WRITE_BYTE_LIMIT; i1b[i++] = 0; i1a[i] = COL_TICKET_EXPIRY_TS; i1b[i++] = 0; i1a[i] = COL_TICKET_COLL_NAME; i1b[i++] = 0; if ( strstr( inOption, "data" ) != 0 ) { i--; i1a[i] = COL_TICKET_DATA_NAME; columnNames[i] = "data-object name"; i1b[i++] = 0; i1a[i] = COL_TICKET_DATA_COLL_NAME; i1b[i++] = 0; } if ( strstr( inOption, "basic" ) != 0 ) { /* skip the COLL or DATA_NAME so it's just a query on the ticket tables */ i--; } genQueryInp.selectInp.inx = i1a; genQueryInp.selectInp.value = i1b; genQueryInp.selectInp.len = i; genQueryInp.condInput.len = 0; if ( inName != NULL && *inName != '\0' ) { if ( isInteger( inName ) == 1 ) { /* Could have an all-integer ticket but in most cases this is a good guess */ i2a[0] = COL_TICKET_ID; } else { i2a[0] = COL_TICKET_STRING; } snprintf( v1, sizeof( v1 ), "='%s'", inName ); condVal[0] = v1; genQueryInp.sqlCondInp.inx = i2a; genQueryInp.sqlCondInp.value = condVal; genQueryInp.sqlCondInp.len = 1; } genQueryInp.maxRows = 10; genQueryInp.continueInx = 0; if ( zoneArgument[0] != '\0' ) { addKeyVal( &genQueryInp.condInput, ZONE_KW, zoneArgument ); } status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == CAT_NO_ROWS_FOUND ) { i1a[0] = COL_USER_COMMENT; genQueryInp.selectInp.len = 1; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( status == 0 ) { return 0; } if ( status == CAT_NO_ROWS_FOUND ) { return 0; } } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 1 ); while ( status == 0 && genQueryOut->continueInx > 0 ) { genQueryInp.continueInx = genQueryOut->continueInx; status = rcGenQuery( Conn, &genQueryInp, &genQueryOut ); if ( genQueryOut->rowCnt > 0 ) { printf( "----\n" ); } printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 1 ); } return 0; } void showTickets( char *inName ) { printedRows = 0; showTickets1( "data", inName ); if ( printedRows > 0 ) { printf( "----\n" ); } showTickets1( "collection", inName ); if ( printedRows == 0 ) { /* try a more basic query in case the data obj or collection is gone */ showTickets1( "basic", inName ); if ( printedRows > 0 && inName != NULL && *inName != '\0' ) { printf( "Warning: the data-object or collection for this ticket no longer exists\n" ); } } } std::string makeFullPath( const char *inName ) { std::stringstream fullPathStream; if ( strlen( inName ) == 0 ) { return std::string(); } if ( *inName != '/' ) { fullPathStream << cwd << "/"; } fullPathStream << inName; return fullPathStream.str(); } /* Create, modify, or delete a ticket */ int doTicketOp( const char *arg1, const char *arg2, const char *arg3, const char *arg4, const char *arg5 ) { ticketAdminInp_t ticketAdminInp; int status; ticketAdminInp.arg1 = strdup( arg1 ); ticketAdminInp.arg2 = strdup( arg2 ); ticketAdminInp.arg3 = strdup( arg3 ); ticketAdminInp.arg4 = strdup( arg4 ); ticketAdminInp.arg5 = strdup( arg5 ); ticketAdminInp.arg6 = ""; status = rcTicketAdmin( Conn, &ticketAdminInp ); lastCommandStatus = status; free( ticketAdminInp.arg1 ); free( ticketAdminInp.arg2 ); free( ticketAdminInp.arg3 ); free( ticketAdminInp.arg4 ); free( ticketAdminInp.arg5 ); if ( status < 0 ) { if ( Conn->rError ) { rError_t *Err; rErrMsg_t *ErrMsg; int i, len; Err = Conn->rError; len = Err->len; for ( i = 0; i < len; i++ ) { ErrMsg = Err->errMsg[i]; rodsLog( LOG_ERROR, "Level %d: %s", i, ErrMsg->msg ); } } char *mySubName = NULL; const char *myName = rodsErrorName( status, &mySubName ); rodsLog( LOG_ERROR, "rcTicketAdmin failed with error %d %s %s", status, myName, mySubName ); free( mySubName ); } return status; } void makeTicket( char *newTicket ) { const int ticket_len = 15; // random_bytes must be (unsigned char[]) to guarantee that following // modulo result is positive (i.e. in [0, 61]) unsigned char random_bytes[ticket_len]; irods::getRandomBytes( random_bytes, ticket_len ); const char characterSet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; for ( int i = 0; i < ticket_len; ++i ) { const int ix = random_bytes[i] % sizeof(characterSet); newTicket[i] = characterSet[ix]; } newTicket[ticket_len] = '\0'; printf( "ticket:%s\n", newTicket ); } /* Prompt for input and parse into tokens */ void getInput( char *cmdToken[], int maxTokens ) { int lenstr, i; static char ttybuf[BIG_STR]; int nTokens; int tokenFlag; /* 1: start reg, 2: start ", 3: start ' */ char *cpTokenStart; char *stat; memset( ttybuf, 0, BIG_STR ); fputs( "iticket>", stdout ); stat = fgets( ttybuf, BIG_STR, stdin ); if ( stat == 0 ) { printf( "\n" ); rcDisconnect( Conn ); if ( lastCommandStatus != 0 ) { exit( 4 ); } exit( 0 ); } lenstr = strlen( ttybuf ); for ( i = 0; i < maxTokens; i++ ) { cmdToken[i] = ""; } cpTokenStart = ttybuf; nTokens = 0; tokenFlag = 0; for ( i = 0; i < lenstr; i++ ) { if ( ttybuf[i] == '\n' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; return; } if ( tokenFlag == 0 ) { if ( ttybuf[i] == '\'' ) { tokenFlag = 3; cpTokenStart++; } else if ( ttybuf[i] == '"' ) { tokenFlag = 2; cpTokenStart++; } else if ( ttybuf[i] == ' ' ) { cpTokenStart++; } else { tokenFlag = 1; } } else if ( tokenFlag == 1 ) { if ( ttybuf[i] == ' ' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; cpTokenStart = &ttybuf[i + 1]; tokenFlag = 0; } } else if ( tokenFlag == 2 ) { if ( ttybuf[i] == '"' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; cpTokenStart = &ttybuf[i + 1]; tokenFlag = 0; } } else if ( tokenFlag == 3 ) { if ( ttybuf[i] == '\'' ) { ttybuf[i] = '\0'; cmdToken[nTokens++] = cpTokenStart; cpTokenStart = &ttybuf[i + 1]; tokenFlag = 0; } } } } /* handle a command, return code is 0 if the command was (at least partially) valid, -1 for quitting, -2 for if invalid -3 if empty. */ int doCommand( char *cmdToken[] ) { if ( strcmp( cmdToken[0], "help" ) == 0 || strcmp( cmdToken[0], "h" ) == 0 ) { usage( cmdToken[1] ); return 0; } if ( strcmp( cmdToken[0], "quit" ) == 0 || strcmp( cmdToken[0], "q" ) == 0 ) { return -1; } if ( strcmp( cmdToken[0], "create" ) == 0 || strcmp( cmdToken[0], "make" ) == 0 || strcmp( cmdToken[0], "mk" ) == 0 ) { char myTicket[30]; if ( strlen( cmdToken[3] ) > 0 ) { snprintf( myTicket, sizeof( myTicket ), "%s", cmdToken[3] ); } else { makeTicket( myTicket ); } std::string fullPath = makeFullPath( cmdToken[2] ); doTicketOp( "create", myTicket, cmdToken[1], fullPath.c_str(), cmdToken[3] ); return 0; } if ( strcmp( cmdToken[0], "delete" ) == 0 ) { doTicketOp( "delete", cmdToken[1], cmdToken[2], cmdToken[3], cmdToken[4] ); return 0; } if ( strcmp( cmdToken[0], "mod" ) == 0 ) { doTicketOp( "mod", cmdToken[1], cmdToken[2], cmdToken[3], cmdToken[4] ); return 0; } if ( strcmp( cmdToken[0], "ls" ) == 0 ) { showTickets( cmdToken[1] ); return 0; } if ( strcmp( cmdToken[0], "ls-all" ) == 0 ) { printf( "Listing all of your tickets, even those for which the target collection\nor data-object no longer exists:\n" ); showTickets1( "basic", "" ); return 0; } if ( *cmdToken[0] != '\0' ) { printf( "unrecognized command, try 'help'\n" ); return -2; } return -3; } int main( int argc, char **argv ) { signal( SIGPIPE, SIG_IGN ); int status, i, j; rErrMsg_t errMsg; rodsArguments_t myRodsArgs; char *mySubName; int argOffset; int maxCmdTokens = 20; char *cmdToken[20]; int keepGoing; int firstTime; rodsLogLevel( LOG_ERROR ); status = parseCmdLineOpt( argc, argv, "vVhgrcGRCdulz:", 0, &myRodsArgs ); if ( status ) { printf( "Use -h for help.\n" ); exit( 1 ); } if ( myRodsArgs.help == True ) { usage( "" ); exit( 0 ); } if ( myRodsArgs.zone == True ) { strncpy( zoneArgument, myRodsArgs.zoneName, MAX_NAME_LEN ); } if ( myRodsArgs.longOption ) { longMode = 1; } argOffset = myRodsArgs.optind; if ( argOffset > 1 ) { if ( argOffset > 2 ) { if ( *argv[1] == '-' && *( argv[1] + 1 ) == 'z' ) { if ( *( argv[1] + 2 ) == '\0' ) { argOffset = 3; /* skip -z zone */ } else { argOffset = 2; /* skip -zzone */ } } else { argOffset = 1; /* Ignore the parseCmdLineOpt parsing as -d etc handled below*/ } } else { argOffset = 1; /* Ignore the parseCmdLineOpt parsing as -d etc handled below*/ } } status = getRodsEnv( &myEnv ); if ( status < 0 ) { rodsLog( LOG_ERROR, "main: getRodsEnv error. status = %d", status ); exit( 1 ); } strncpy( cwd, myEnv.rodsCwd, BIG_STR ); if ( strlen( cwd ) == 0 ) { strcpy( cwd, "/" ); } for ( i = 0; i < maxCmdTokens; i++ ) { cmdToken[i] = ""; } j = 0; for ( i = argOffset; i < argc; i++ ) { cmdToken[j++] = argv[i]; } #if defined(linux_platform) /* imeta cp -d TestFile1 -d TestFile3 comes in as: -d -d cp TestFile1 TestFile3 so switch it to: cp -d -d TestFile1 TestFile3 */ if ( cmdToken[0] != NULL && *cmdToken[0] == '-' ) { /* args were toggled, switch them back */ if ( cmdToken[1] != NULL && *cmdToken[1] == '-' ) { cmdToken[0] = argv[argOffset + 2]; cmdToken[1] = argv[argOffset]; cmdToken[2] = argv[argOffset + 1]; } else { cmdToken[0] = argv[argOffset + 1]; cmdToken[1] = argv[argOffset]; } } #else /* tested on Solaris, not sure other than Linux/Solaris */ /* imeta cp -d TestFile1 -d TestFile3 comes in as: cp -d TestFile1 -d TestFile3 so switch it to: cp -d -d TestFile1 TestFile3 */ if ( cmdToken[0] != NULL && cmdToken[1] != NULL && *cmdToken[1] == '-' && cmdToken[2] != NULL && cmdToken[3] != NULL && *cmdToken[3] == '-' ) { /* two args */ cmdToken[2] = argv[argOffset + 3]; cmdToken[3] = argv[argOffset + 2]; } #endif if ( strcmp( cmdToken[0], "help" ) == 0 || strcmp( cmdToken[0], "h" ) == 0 ) { usage( cmdToken[1] ); exit( 0 ); } if ( strcmp( cmdToken[0], "spass" ) == 0 ) { char scrambled[MAX_PASSWORD_LEN + 100]; if ( strlen( cmdToken[1] ) > MAX_PASSWORD_LEN - 2 ) { printf( "Password exceeds maximum length\n" ); } else { obfEncodeByKey( cmdToken[1], cmdToken[2], scrambled ); printf( "Scrambled form is:%s\n", scrambled ); } exit( 0 ); } // =-=-=-=-=-=-=- // initialize pluggable api table irods::api_entry_table& api_tbl = irods::get_client_api_table(); irods::pack_entry_table& pk_tbl = irods::get_pack_table(); init_api_table( api_tbl, pk_tbl ); Conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName, myEnv.rodsZone, 0, &errMsg ); if ( Conn == NULL ) { const char *myName = rodsErrorName( errMsg.status, &mySubName ); rodsLog( LOG_ERROR, "rcConnect failure %s (%s) (%d) %s", myName, mySubName, errMsg.status, errMsg.msg ); exit( 2 ); } status = clientLogin( Conn ); if ( status != 0 ) { if ( !debug ) { exit( 3 ); } } keepGoing = 1; firstTime = 1; while ( keepGoing ) { int status; status = doCommand( cmdToken ); if ( status == -1 ) { keepGoing = 0; } if ( firstTime ) { if ( status == 0 ) { keepGoing = 0; } if ( status == -2 ) { keepGoing = 0; lastCommandStatus = -1; } firstTime = 0; } if ( keepGoing ) { getInput( cmdToken, maxCmdTokens ); } } printErrorStack( Conn->rError ); rcDisconnect( Conn ); if ( lastCommandStatus != 0 ) { exit( 4 ); } exit( 0 ); } /* Print the main usage/help information. */ void usageMain() { char *msgs[] = { "Usage: iticket [-h] [command]", " -h This help", "Commands are:", " create read/write Object-Name [string] (create a new ticket)", " mod Ticket_string-or-id uses/expire string-or-none (modify restrictions)", " mod Ticket_string-or-id write-bytes-or-file number-or-0 (modify restrictions)", " mod Ticket_string-or-id add/remove host/user/group string (modify restrictions)", " ls [Ticket_string-or-id] (non-admins will see just your own)", " ls-all (list all your tickets, even with missing targets)", " delete ticket_string-or-id", " quit", " ", "Tickets are another way to provide access to iRODS data-objects (files) or", "collections (directories or folders). The 'iticket' command allows you", "to create, modify, list, and delete tickets. When you create a ticket", "its 15 character string is given to you which you can share with others.", "This is less secure than normal iRODS login-based access control, but", "is useful in some situations. See the 'ticket-based access' page on", "irods.org for more information.", " ", "A blank execute line invokes the interactive mode, where iticket", "prompts and executes commands until 'quit' or 'q' is entered.", "Like other unix utilities, a series of commands can be piped into it:", "'cat file1 | iticket' (maintaining one connection for all commands).", " ", "Use 'help command' for more help on a specific command.", "" }; int i; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { break; } printf( "%s\n", msgs[i] ); } printReleaseInfo( "iticket" ); } /* Print either main usage/help information, or some more specific information on particular commands. */ int usage( char *subOpt ) { int i; if ( *subOpt == '\0' ) { usageMain(); } else { if ( strcmp( subOpt, "create" ) == 0 ) { char *msgs[] = { " create read/write Object-Name [string] (create a new ticket)", "Create a new ticket for Object-Name, which is either a data-object (file)", "or a collection (directory). ", "Example: create read myFile", "The ticket string, which can be used for access, will be displayed.", "If 'string' is provided on the command line, it is the ticket-string to use", "as the ticket instead of a randomly generated string of characters.", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "mod" ) == 0 ) { char *msgs[] = { " mod Ticket-id uses/expire string-or-none", "or mod Ticket-id add/remove host/user/group string (modify restrictions)", "Modify a ticket to use one of the specialized options. By default a", "ticket can be used by anyone (and 'anonymous'), from any host, and any", "number of times, and for all time (until deleted). You can modify it to", "add (or remove) these types of restrictions.", " ", " 'mod Ticket-id uses integer-or-0' will make the ticket only valid", "the specified number of times. Use 0 to remove this restriction.", " ", " 'mod Ticket-id write-file integer-or-0' will make the write-ticket only", "valid for writing the specified number of times. Use 0 to remove this", "restriction.", " ", " 'mod Ticket-id write-byte integer-or-0' will make the write-ticket only", "valid for writing the specified number of bytes. Use 0 to remove this", "restriction.", " ", " 'mod Ticket-id add/remove user Username' will make the ticket only valid", "when used by that particular iRODS user. You can use multiple mod commands", "to add more users to the allowed list.", " ", " 'mod Ticket-id add/remove group Groupname' will make the ticket only valid", "when used by iRODS users in that particular iRODS group. You can use", "multiple mod commands to add more groups to the allowed list.", " ", " 'mod Ticket-id add/remove host Host/IP' will make the ticket only valid", "when used from that particular host computer. Host (full DNS name) will be", "converted to the IP address for use in the internal checks or you can enter", "the IP address itself. 'iticket ls' will display the IP addresses.", "You can use multiple mod commands to add more hosts to the list.", " ", " 'mod Ticket-id expire date.time-or-0' will make the ticket only valid", "before the specified date-time. You can cancel this expiration by using", "'0'. The time is year-mo-da.hr:min:sec, for example: 2012-05-07.23:00:00", " ", " The Ticket-id is either the ticket object number or the ticket-string", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "delete" ) == 0 ) { char *msgs[] = { " delete Ticket-string", "Remove a ticket from the system. Access will no longer be allowed", "via the ticket-string.", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "ls" ) == 0 ) { char *msgs[] = { " ls [Ticket_string-or-id]", "List the tickets owned by you or, for admin users, all tickets.", "Include a ticket-string or the ticket-id (object number) to list only one", "(in this case, a numeric string is assumed to be an id).", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "ls-all" ) == 0 ) { char *msgs[] = { " ls-all", "Similar to 'ls' (with no ticket string-or-id) but will list all of your", "tickets even if the target collection or data-object no longer exists.", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } if ( strcmp( subOpt, "quit" ) == 0 ) { char *msgs[] = { " Exits the interactive mode", "" }; for ( i = 0;; i++ ) { if ( strlen( msgs[i] ) == 0 ) { return 0; } printf( "%s\n", msgs[i] ); } } printf( "Sorry, either %s is an invalid command or the help has not been written yet\n", subOpt ); } return 0; }
30.731214
259
0.508354
cyverse
d7450f785a3e1c9e757e33c0116040be99ae4b96
18,666
cpp
C++
examples/pxScene2d/external/libnode-v6.9.0/deps/icu-small/source/common/unifiedcache.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
46
2017-09-07T14:59:22.000Z
2020-10-31T20:34:12.000Z
examples/pxScene2d/external/libnode-v6.9.0/deps/icu-small/source/common/unifiedcache.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/libnode-v6.9.0/deps/icu-small/source/common/unifiedcache.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
/* ****************************************************************************** * Copyright (C) 2015, International Business Machines Corporation and * others. All Rights Reserved. ****************************************************************************** * * File UNIFIEDCACHE.CPP ****************************************************************************** */ #include "uhash.h" #include "unifiedcache.h" #include "umutex.h" #include "mutex.h" #include "uassert.h" #include "ucln_cmn.h" static icu::UnifiedCache *gCache = NULL; static icu::SharedObject *gNoValue = NULL; static UMutex gCacheMutex = U_MUTEX_INITIALIZER; static UConditionVar gInProgressValueAddedCond = U_CONDITION_INITIALIZER; static icu::UInitOnce gCacheInitOnce = U_INITONCE_INITIALIZER; static const int32_t MAX_EVICT_ITERATIONS = 10; static int32_t DEFAULT_MAX_UNUSED = 1000; static int32_t DEFAULT_PERCENTAGE_OF_IN_USE = 100; U_CDECL_BEGIN static UBool U_CALLCONV unifiedcache_cleanup() { gCacheInitOnce.reset(); if (gCache) { delete gCache; gCache = NULL; } if (gNoValue) { delete gNoValue; gNoValue = NULL; } return TRUE; } U_CDECL_END U_NAMESPACE_BEGIN U_CAPI int32_t U_EXPORT2 ucache_hashKeys(const UHashTok key) { const CacheKeyBase *ckey = (const CacheKeyBase *) key.pointer; return ckey->hashCode(); } U_CAPI UBool U_EXPORT2 ucache_compareKeys(const UHashTok key1, const UHashTok key2) { const CacheKeyBase *p1 = (const CacheKeyBase *) key1.pointer; const CacheKeyBase *p2 = (const CacheKeyBase *) key2.pointer; return *p1 == *p2; } U_CAPI void U_EXPORT2 ucache_deleteKey(void *obj) { CacheKeyBase *p = (CacheKeyBase *) obj; delete p; } CacheKeyBase::~CacheKeyBase() { } static void U_CALLCONV cacheInit(UErrorCode &status) { U_ASSERT(gCache == NULL); ucln_common_registerCleanup( UCLN_COMMON_UNIFIED_CACHE, unifiedcache_cleanup); // gNoValue must be created first to avoid assertion error in // cache constructor. gNoValue = new SharedObject(); gCache = new UnifiedCache(status); if (gCache == NULL) { status = U_MEMORY_ALLOCATION_ERROR; } if (U_FAILURE(status)) { delete gCache; delete gNoValue; gCache = NULL; gNoValue = NULL; return; } // We add a softref because we want hash elements with gNoValue to be // elligible for purging but we don't ever want gNoValue to be deleted. gNoValue->addSoftRef(); } UnifiedCache *UnifiedCache::getInstance(UErrorCode &status) { umtx_initOnce(gCacheInitOnce, &cacheInit, status); if (U_FAILURE(status)) { return NULL; } U_ASSERT(gCache != NULL); return gCache; } UnifiedCache::UnifiedCache(UErrorCode &status) : fHashtable(NULL), fEvictPos(UHASH_FIRST), fItemsInUseCount(0), fMaxUnused(DEFAULT_MAX_UNUSED), fMaxPercentageOfInUse(DEFAULT_PERCENTAGE_OF_IN_USE), fAutoEvictedCount(0) { if (U_FAILURE(status)) { return; } U_ASSERT(gNoValue != NULL); fHashtable = uhash_open( &ucache_hashKeys, &ucache_compareKeys, NULL, &status); if (U_FAILURE(status)) { return; } uhash_setKeyDeleter(fHashtable, &ucache_deleteKey); } void UnifiedCache::setEvictionPolicy( int32_t count, int32_t percentageOfInUseItems, UErrorCode &status) { if (U_FAILURE(status)) { return; } if (count < 0 || percentageOfInUseItems < 0) { status = U_ILLEGAL_ARGUMENT_ERROR; return; } Mutex lock(&gCacheMutex); fMaxUnused = count; fMaxPercentageOfInUse = percentageOfInUseItems; } int32_t UnifiedCache::unusedCount() const { Mutex lock(&gCacheMutex); return uhash_count(fHashtable) - fItemsInUseCount; } int64_t UnifiedCache::autoEvictedCount() const { Mutex lock(&gCacheMutex); return fAutoEvictedCount; } int32_t UnifiedCache::keyCount() const { Mutex lock(&gCacheMutex); return uhash_count(fHashtable); } void UnifiedCache::flush() const { Mutex lock(&gCacheMutex); // Use a loop in case cache items that are flushed held hard references to // other cache items making those additional cache items eligible for // flushing. while (_flush(FALSE)); } #ifdef UNIFIED_CACHE_DEBUG #include <stdio.h> void UnifiedCache::dump() { UErrorCode status = U_ZERO_ERROR; const UnifiedCache *cache = getInstance(status); if (U_FAILURE(status)) { fprintf(stderr, "Unified Cache: Error fetching cache.\n"); return; } cache->dumpContents(); } void UnifiedCache::dumpContents() const { Mutex lock(&gCacheMutex); _dumpContents(); } // Dumps content of cache. // On entry, gCacheMutex must be held. // On exit, cache contents dumped to stderr. void UnifiedCache::_dumpContents() const { int32_t pos = UHASH_FIRST; const UHashElement *element = uhash_nextElement(fHashtable, &pos); char buffer[256]; int32_t cnt = 0; for (; element != NULL; element = uhash_nextElement(fHashtable, &pos)) { const SharedObject *sharedObject = (const SharedObject *) element->value.pointer; const CacheKeyBase *key = (const CacheKeyBase *) element->key.pointer; if (sharedObject->hasHardReferences()) { ++cnt; fprintf( stderr, "Unified Cache: Key '%s', error %d, value %p, total refcount %d, soft refcount %d\n", key->writeDescription(buffer, 256), key->creationStatus, sharedObject == gNoValue ? NULL :sharedObject, sharedObject->getRefCount(), sharedObject->getSoftRefCount()); } } fprintf(stderr, "Unified Cache: %d out of a total of %d still have hard references\n", cnt, uhash_count(fHashtable)); } #endif UnifiedCache::~UnifiedCache() { // Try our best to clean up first. flush(); { // Now all that should be left in the cache are entries that refer to // each other and entries with hard references from outside the cache. // Nothing we can do about these so proceed to wipe out the cache. Mutex lock(&gCacheMutex); _flush(TRUE); } uhash_close(fHashtable); } // Returns the next element in the cache round robin style. // On entry, gCacheMutex must be held. const UHashElement * UnifiedCache::_nextElement() const { const UHashElement *element = uhash_nextElement(fHashtable, &fEvictPos); if (element == NULL) { fEvictPos = UHASH_FIRST; return uhash_nextElement(fHashtable, &fEvictPos); } return element; } // Flushes the contents of the cache. If cache values hold references to other // cache values then _flush should be called in a loop until it returns FALSE. // On entry, gCacheMutex must be held. // On exit, those values with are evictable are flushed. If all is true // then every value is flushed even if it is not evictable. // Returns TRUE if any value in cache was flushed or FALSE otherwise. UBool UnifiedCache::_flush(UBool all) const { UBool result = FALSE; int32_t origSize = uhash_count(fHashtable); for (int32_t i = 0; i < origSize; ++i) { const UHashElement *element = _nextElement(); if (all || _isEvictable(element)) { const SharedObject *sharedObject = (const SharedObject *) element->value.pointer; uhash_removeElement(fHashtable, element); sharedObject->removeSoftRef(); result = TRUE; } } return result; } // Computes how many items should be evicted. // On entry, gCacheMutex must be held. // Returns number of items that should be evicted or a value <= 0 if no // items need to be evicted. int32_t UnifiedCache::_computeCountOfItemsToEvict() const { int32_t maxPercentageOfInUseCount = fItemsInUseCount * fMaxPercentageOfInUse / 100; int32_t maxUnusedCount = fMaxUnused; if (maxUnusedCount < maxPercentageOfInUseCount) { maxUnusedCount = maxPercentageOfInUseCount; } return uhash_count(fHashtable) - fItemsInUseCount - maxUnusedCount; } // Run an eviction slice. // On entry, gCacheMutex must be held. // _runEvictionSlice runs a slice of the evict pipeline by examining the next // 10 entries in the cache round robin style evicting them if they are eligible. void UnifiedCache::_runEvictionSlice() const { int32_t maxItemsToEvict = _computeCountOfItemsToEvict(); if (maxItemsToEvict <= 0) { return; } for (int32_t i = 0; i < MAX_EVICT_ITERATIONS; ++i) { const UHashElement *element = _nextElement(); if (_isEvictable(element)) { const SharedObject *sharedObject = (const SharedObject *) element->value.pointer; uhash_removeElement(fHashtable, element); sharedObject->removeSoftRef(); ++fAutoEvictedCount; if (--maxItemsToEvict == 0) { break; } } } } // Places a new value and creationStatus in the cache for the given key. // On entry, gCacheMutex must be held. key must not exist in the cache. // On exit, value and creation status placed under key. Soft reference added // to value on successful add. On error sets status. void UnifiedCache::_putNew( const CacheKeyBase &key, const SharedObject *value, const UErrorCode creationStatus, UErrorCode &status) const { if (U_FAILURE(status)) { return; } CacheKeyBase *keyToAdopt = key.clone(); if (keyToAdopt == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return; } keyToAdopt->fCreationStatus = creationStatus; if (value->noSoftReferences()) { _registerMaster(keyToAdopt, value); } uhash_put(fHashtable, keyToAdopt, (void *) value, &status); if (U_SUCCESS(status)) { value->addSoftRef(); } } // Places value and status at key if there is no value at key or if cache // entry for key is in progress. Otherwise, it leaves the current value and // status there. // On entry. gCacheMutex must not be held. value must be // included in the reference count of the object to which it points. // On exit, value and status are changed to what was already in the cache if // something was there and not in progress. Otherwise, value and status are left // unchanged in which case they are placed in the cache on a best-effort basis. // Caller must call removeRef() on value. void UnifiedCache::_putIfAbsentAndGet( const CacheKeyBase &key, const SharedObject *&value, UErrorCode &status) const { Mutex lock(&gCacheMutex); const UHashElement *element = uhash_find(fHashtable, &key); if (element != NULL && !_inProgress(element)) { _fetch(element, value, status); return; } if (element == NULL) { UErrorCode putError = U_ZERO_ERROR; // best-effort basis only. _putNew(key, value, status, putError); } else { _put(element, value, status); } // Run an eviction slice. This will run even if we added a master entry // which doesn't increase the unused count, but that is still o.k _runEvictionSlice(); } // Attempts to fetch value and status for key from cache. // On entry, gCacheMutex must not be held value must be NULL and status must // be U_ZERO_ERROR. // On exit, either returns FALSE (In this // case caller should try to create the object) or returns TRUE with value // pointing to the fetched value and status set to fetched status. When // FALSE is returned status may be set to failure if an in progress hash // entry could not be made but value will remain unchanged. When TRUE is // returned, caler must call removeRef() on value. UBool UnifiedCache::_poll( const CacheKeyBase &key, const SharedObject *&value, UErrorCode &status) const { U_ASSERT(value == NULL); U_ASSERT(status == U_ZERO_ERROR); Mutex lock(&gCacheMutex); const UHashElement *element = uhash_find(fHashtable, &key); while (element != NULL && _inProgress(element)) { umtx_condWait(&gInProgressValueAddedCond, &gCacheMutex); element = uhash_find(fHashtable, &key); } if (element != NULL) { _fetch(element, value, status); return TRUE; } _putNew(key, gNoValue, U_ZERO_ERROR, status); return FALSE; } // Gets value out of cache. // On entry. gCacheMutex must not be held. value must be NULL. status // must be U_ZERO_ERROR. // On exit. value and status set to what is in cache at key or on cache // miss the key's createObject() is called and value and status are set to // the result of that. In this latter case, best effort is made to add the // value and status to the cache. If createObject() fails to create a value, // gNoValue is stored in cache, and value is set to NULL. Caller must call // removeRef on value if non NULL. void UnifiedCache::_get( const CacheKeyBase &key, const SharedObject *&value, const void *creationContext, UErrorCode &status) const { U_ASSERT(value == NULL); U_ASSERT(status == U_ZERO_ERROR); if (_poll(key, value, status)) { if (value == gNoValue) { SharedObject::clearPtr(value); } return; } if (U_FAILURE(status)) { return; } value = key.createObject(creationContext, status); U_ASSERT(value == NULL || value->hasHardReferences()); U_ASSERT(value != NULL || status != U_ZERO_ERROR); if (value == NULL) { SharedObject::copyPtr(gNoValue, value); } _putIfAbsentAndGet(key, value, status); if (value == gNoValue) { SharedObject::clearPtr(value); } } void UnifiedCache::decrementItemsInUseWithLockingAndEviction() const { Mutex mutex(&gCacheMutex); decrementItemsInUse(); _runEvictionSlice(); } void UnifiedCache::incrementItemsInUse() const { ++fItemsInUseCount; } void UnifiedCache::decrementItemsInUse() const { --fItemsInUseCount; } // Register a master cache entry. // On entry, gCacheMutex must be held. // On exit, items in use count incremented, entry is marked as a master // entry, and value registered with cache so that subsequent calls to // addRef() and removeRef() on it correctly updates items in use count void UnifiedCache::_registerMaster( const CacheKeyBase *theKey, const SharedObject *value) const { theKey->fIsMaster = TRUE; ++fItemsInUseCount; value->registerWithCache(this); } // Store a value and error in given hash entry. // On entry, gCacheMutex must be held. Hash entry element must be in progress. // value must be non NULL. // On Exit, soft reference added to value. value and status stored in hash // entry. Soft reference removed from previous stored value. Waiting // threads notified. void UnifiedCache::_put( const UHashElement *element, const SharedObject *value, const UErrorCode status) const { U_ASSERT(_inProgress(element)); const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer; const SharedObject *oldValue = (const SharedObject *) element->value.pointer; theKey->fCreationStatus = status; if (value->noSoftReferences()) { _registerMaster(theKey, value); } value->addSoftRef(); UHashElement *ptr = const_cast<UHashElement *>(element); ptr->value.pointer = (void *) value; oldValue->removeSoftRef(); // Tell waiting threads that we replace in-progress status with // an error. umtx_condBroadcast(&gInProgressValueAddedCond); } void UnifiedCache::copyPtr(const SharedObject *src, const SharedObject *&dest) { if(src != dest) { if(dest != NULL) { dest->removeRefWhileHoldingCacheLock(); } dest = src; if(src != NULL) { src->addRefWhileHoldingCacheLock(); } } } void UnifiedCache::clearPtr(const SharedObject *&ptr) { if (ptr != NULL) { ptr->removeRefWhileHoldingCacheLock(); ptr = NULL; } } // Fetch value and error code from a particular hash entry. // On entry, gCacheMutex must be held. value must be either NULL or must be // included in the ref count of the object to which it points. // On exit, value and status set to what is in the hash entry. Caller must // eventually call removeRef on value. // If hash entry is in progress, value will be set to gNoValue and status will // be set to U_ZERO_ERROR. void UnifiedCache::_fetch( const UHashElement *element, const SharedObject *&value, UErrorCode &status) { const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer; status = theKey->fCreationStatus; // Since we have the cache lock, calling regular SharedObject methods // could cause us to deadlock on ourselves since they may need to lock // the cache mutex. UnifiedCache::copyPtr((const SharedObject *) element->value.pointer, value); } // Determine if given hash entry is in progress. // On entry, gCacheMutex must be held. UBool UnifiedCache::_inProgress(const UHashElement *element) { const SharedObject *value = NULL; UErrorCode status = U_ZERO_ERROR; _fetch(element, value, status); UBool result = _inProgress(value, status); // Since we have the cache lock, calling regular SharedObject methods // could cause us to deadlock on ourselves since they may need to lock // the cache mutex. UnifiedCache::clearPtr(value); return result; } // Determine if given hash entry is in progress. // On entry, gCacheMutex must be held. UBool UnifiedCache::_inProgress( const SharedObject *theValue, UErrorCode creationStatus) { return (theValue == gNoValue && creationStatus == U_ZERO_ERROR); } // Determine if given hash entry is eligible for eviction. // On entry, gCacheMutex must be held. UBool UnifiedCache::_isEvictable(const UHashElement *element) { const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer; const SharedObject *theValue = (const SharedObject *) element->value.pointer; // Entries that are under construction are never evictable if (_inProgress(theValue, theKey->fCreationStatus)) { return FALSE; } // We can evict entries that are either not a master or have just // one reference (The one reference being from the cache itself). return (!theKey->fIsMaster || (theValue->getSoftRefCount() == 1 && theValue->noHardReferences())); } U_NAMESPACE_END
33.693141
121
0.667202
madanagopaltcomcast
d745f1a35e3f706182f90a78fef4f4786234c637
5,642
cxx
C++
smtk/plugin/testing/cxx/UnitTestRegistry.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/plugin/testing/cxx/UnitTestRegistry.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/plugin/testing/cxx/UnitTestRegistry.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/plugin/Registry.h" #include "smtk/common/testing/cxx/helpers.h" #include <set> namespace { class Manager_1 { public: std::set<std::string> managed; }; class Manager_2 { public: std::set<std::string> managed; }; class Manager_3 { public: std::set<std::string> managed; }; class Registrar_1 { public: static constexpr const char* const type_name = "Registrar 1"; bool registerTo(const std::shared_ptr<Manager_1>& /*m*/) const; bool unregisterFrom(const std::shared_ptr<Manager_1>& /*m*/) const; bool registerTo(const std::shared_ptr<Manager_2>& /*m*/) const; void unregisterFrom(const std::shared_ptr<Manager_2>& /*m*/) const; void registerTo(const std::shared_ptr<Manager_3>& /*m*/) const; void unregisterFrom(const std::shared_ptr<Manager_3>& /*m*/) const; }; bool Registrar_1::registerTo(const std::shared_ptr<Manager_1>& m) const { auto inserted = m->managed.insert(type_name); test(inserted.second, "Double registering a registrar with a manager"); return true; } bool Registrar_1::unregisterFrom(const std::shared_ptr<Manager_1>& m) const { auto it = m->managed.find(type_name); test(it != m->managed.end(), "unregistering an unkown registrar from a manager"); m->managed.erase(it); return true; } bool Registrar_1::registerTo(const std::shared_ptr<Manager_2>& m) const { auto inserted = m->managed.insert(type_name); test(inserted.second, "Double registering a registrar with a manager"); return true; } void Registrar_1::unregisterFrom(const std::shared_ptr<Manager_2>& m) const { auto it = m->managed.find(type_name); test(it != m->managed.end(), "unregistering an unkown registrar from a manager"); m->managed.erase(it); } void Registrar_1::registerTo(const std::shared_ptr<Manager_3>& m) const { auto inserted = m->managed.insert(type_name); test(inserted.second, "Double registering a registrar with a manager"); } void Registrar_1::unregisterFrom(const std::shared_ptr<Manager_3>& m) const { auto it = m->managed.find(type_name); test(it != m->managed.end(), "unregistering an unkown registrar from a manager"); m->managed.erase(it); } class Registrar_2 { public: static constexpr const char* const type_name = "Registrar 2"; static int registerTo(const std::shared_ptr<Manager_1>& /*m*/); static bool unregisterFrom(const std::shared_ptr<Manager_1>& /*m*/); static bool registerTo(const std::shared_ptr<Manager_2>& /*m*/); static void unregisterFrom(const std::shared_ptr<Manager_2>& /*m*/); }; int Registrar_2::registerTo(const std::shared_ptr<Manager_1>& m) { auto inserted = m->managed.insert(type_name); test(inserted.second, "Double registering a registrar with a manager"); return 4; } bool Registrar_2::unregisterFrom(const std::shared_ptr<Manager_1>& m) { auto it = m->managed.find(type_name); test(it != m->managed.end(), "unregistering an unkown registrar from a manager"); m->managed.erase(it); return true; } bool Registrar_2::registerTo(const std::shared_ptr<Manager_2>& m) { auto inserted = m->managed.insert(type_name); test(inserted.second, "Double registering a registrar with a manager"); return true; } void Registrar_2::unregisterFrom(const std::shared_ptr<Manager_2>& m) { auto it = m->managed.find(type_name); test(it != m->managed.end(), "unregistering an unkown registrar from a manager"); m->managed.erase(it); } } // namespace int UnitTestRegistry(int /*unused*/, char** const /*unused*/) { auto manager_1 = std::make_shared<Manager_1>(); auto manager_2 = std::make_shared<Manager_2>(); auto manager_3 = std::make_shared<Manager_3>(); test( manager_1->managed.empty() && manager_2->managed.empty() && manager_3->managed.empty(), "New managers should not be managing anything"); { smtk::plugin::Registry<Registrar_1, Manager_1, Manager_2, Manager_3> registry_1( manager_1, manager_2, manager_3); test( manager_1->managed.size() == 1 && manager_2->managed.size() == 1 && manager_3->managed.size() == 1, "Managers should be managing one thing"); } test( manager_1->managed.empty() && manager_2->managed.empty() && manager_3->managed.empty(), "Cleared managers should not be managing anything"); smtk::plugin::Registry<Registrar_1, Manager_1, Manager_2, Manager_3> registry_2( manager_1, manager_2, manager_3); test( manager_1->managed.size() == 1 && manager_2->managed.size() == 1 && manager_3->managed.size() == 1, "Managers should be managing one thing again"); auto manager_22 = std::make_shared<Manager_2>(); auto manager_33 = std::make_shared<Manager_3>(); { smtk::plugin::Registry<Registrar_2, Manager_1, Manager_2, Manager_3> registry_3( manager_1, manager_22, manager_33); test(manager_1->managed.size() == 2, "Manager_1 should be managing two things"); test(manager_2->managed.size() == 1, "Manager_2 should be managing one thing"); test(manager_22->managed.size() == 1, "Manager_22 should be managing one thing"); test(manager_3->managed.size() == 1, "Manager_3 should be managing one thing"); test(manager_33->managed.empty(), "Manager_3 should not be managing anything"); } return 0; }
32.425287
91
0.691067
jcfr
d746477fdd68cacf8b6f38829672f52145c0bb66
5,111
hpp
C++
phonelibs/acado/include/acado/estimator/estimator.hpp
Neptos/openpilot
01914a1a91ade18bd7aead99e7d1bf38cd22ad89
[ "MIT" ]
116
2018-03-07T09:00:10.000Z
2020-04-06T18:37:45.000Z
phonelibs/acado/include/acado/estimator/estimator.hpp
Neptos/openpilot
01914a1a91ade18bd7aead99e7d1bf38cd22ad89
[ "MIT" ]
66
2020-04-09T20:27:57.000Z
2022-01-27T14:39:24.000Z
phonelibs/acado/include/acado/estimator/estimator.hpp
Neptos/openpilot
01914a1a91ade18bd7aead99e7d1bf38cd22ad89
[ "MIT" ]
154
2020-04-08T21:41:22.000Z
2022-03-17T21:05:33.000Z
/* * This file is part of ACADO Toolkit. * * ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization. * Copyright (C) 2008-2014 by Boris Houska, Hans Joachim Ferreau, * Milan Vukov, Rien Quirynen, KU Leuven. * Developed within the Optimization in Engineering Center (OPTEC) * under supervision of Moritz Diehl. All rights reserved. * * ACADO Toolkit is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * ACADO Toolkit 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 ACADO Toolkit; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ /** * \file include/acado/estimator/estimator.hpp * \author Hans Joachim Ferreau, Boris Houska */ #ifndef ACADO_TOOLKIT_ESTIMATOR_HPP #define ACADO_TOOLKIT_ESTIMATOR_HPP #include <acado/utils/acado_utils.hpp> #include <acado/simulation_environment/simulation_block.hpp> #include <acado/function/function.hpp> BEGIN_NAMESPACE_ACADO /** * \brief Base class for interfacing online state/parameter estimators. * * \ingroup UserInterfaces * * The class Estimator serves as a base class for interfacing online * state/parameter estimators. * * \author Hans Joachim Ferreau, Boris Houska */ class Estimator : public SimulationBlock { // // PUBLIC MEMBER FUNCTIONS: // public: /** Default constructor. */ Estimator( ); /** Constructor taking minimal sub-block configuration. */ Estimator( double _samplingTime ); /** Copy constructor (deep copy). */ Estimator( const Estimator& rhs ); /** Destructor. */ virtual ~Estimator( ); /** Assignment operator (deep copy). */ Estimator& operator=( const Estimator& rhs ); virtual Estimator* clone( ) const = 0; /** Initialization. */ virtual returnValue init( double startTime = 0.0, const DVector &x0_ = emptyConstVector, const DVector &p_ = emptyConstVector ); /** Executes next single step. */ virtual returnValue step( double currentTime, const DVector& _y ) = 0; /** Returns all estimator outputs. */ inline returnValue getOutputs( DVector& _x, /**< Estimated differential states. */ DVector& _xa, /**< Estimated algebraic states. */ DVector& _u, /**< Estimated previous controls. */ DVector& _p, /**< Estimated parameters. */ DVector& _w /**< Estimated disturbances. */ ) const; /** Returns estimated differential states. */ inline returnValue getX( DVector& _x /**< OUTPUT: estimated differential states. */ ) const; /** Returns estimated algebraic states. */ inline returnValue getXA( DVector& _xa /**< OUTPUT: estimated algebraic states. */ ) const; /** Returns estimated previous controls. */ inline returnValue getU( DVector& _u /**< OUTPUT: estimated previous controls. */ ) const; /** Returns estimated parameters. */ inline returnValue getP( DVector& _p /**< OUTPUT: estimated parameters. */ ) const; /** Returns estimated disturbances. */ inline returnValue getW( DVector& _w /**< OUTPUT: estimated disturbances. */ ) const; /** Returns number of estimated differential states. * \return Number of estimated differential states */ inline uint getNX( ) const; /** Returns number of estimated algebraic states. * \return Number of estimated algebraic states */ inline uint getNXA( ) const; /** Returns number of estimated previous controls. * \return Number of estimated previous controls */ inline uint getNU( ) const; /** Returns number of estimated parameters. * \return Number of estimated parameters */ inline uint getNP( ) const; /** Returns number of estimated disturbances. * \return Number of estimated disturbances */ inline uint getNW( ) const; /** Returns number of process outputs. * \return Number of process outputs */ inline uint getNY( ) const; // // PROTECTED MEMBER FUNCTIONS: // protected: // // DATA MEMBERS: // protected: DVector x; /**< Estimated differential state. */ DVector xa; /**< Estimated algebraic state. */ DVector u; /**< Estimated previous controls. */ DVector p; /**< Estimated parameters. */ DVector w; /**< Estimated disturbances. */ }; CLOSE_NAMESPACE_ACADO #include <acado/estimator/estimator.ipp> #endif // ACADO_TOOLKIT_ESTIMATOR_HPP /* * end of file */
28.713483
92
0.658384
Neptos
d746ebb5da20f0a352815e378faf61a85d2ae4df
12,073
cc
C++
fgl/include/OpenMesh/Tools/Smoother/SmootherT.cc
dmitriychunikhin/fgl
5d79c1e92e62d2d6e33413ee3f7e48b1c2322d4c
[ "BSD-2-Clause" ]
null
null
null
fgl/include/OpenMesh/Tools/Smoother/SmootherT.cc
dmitriychunikhin/fgl
5d79c1e92e62d2d6e33413ee3f7e48b1c2322d4c
[ "BSD-2-Clause" ]
null
null
null
fgl/include/OpenMesh/Tools/Smoother/SmootherT.cc
dmitriychunikhin/fgl
5d79c1e92e62d2d6e33413ee3f7e48b1c2322d4c
[ "BSD-2-Clause" ]
null
null
null
/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 808 $ * * $Date: 2013-02-20 13:25:03 +0100 (Wed, 20 Feb 2013) $ * * * \*===========================================================================*/ /** \file SmootherT.cc */ //============================================================================= // // CLASS SmootherT - IMPLEMENTATION // //============================================================================= #define OPENMESH_SMOOTHERT_C //== INCLUDES ================================================================= #include <OpenMesh/Core/Utils/vector_cast.hh> #include <OpenMesh/Tools/Smoother/SmootherT.hh> //== NAMESPACES =============================================================== namespace OpenMesh { namespace Smoother { //== IMPLEMENTATION ========================================================== template <class Mesh> SmootherT<Mesh>:: SmootherT(Mesh& _mesh) : mesh_(_mesh), skip_features_(false) { // request properties mesh_.request_vertex_status(); mesh_.request_face_normals(); mesh_.request_vertex_normals(); // custom properties mesh_.add_property(original_positions_); mesh_.add_property(original_normals_); mesh_.add_property(new_positions_); mesh_.add_property(is_active_); // default settings component_ = Tangential_and_Normal; continuity_ = C0; tolerance_ = -1.0; } //----------------------------------------------------------------------------- template <class Mesh> SmootherT<Mesh>:: ~SmootherT() { // free properties mesh_.release_vertex_status(); mesh_.release_face_normals(); mesh_.release_vertex_normals(); // free custom properties mesh_.remove_property(original_positions_); mesh_.remove_property(original_normals_); mesh_.remove_property(new_positions_); mesh_.remove_property(is_active_); } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: initialize(Component _comp, Continuity _cont) { typename Mesh::VertexIter v_it, v_end(mesh_.vertices_end()); // store smoothing settings component_ = _comp; continuity_ = _cont; // update normals mesh_.update_face_normals(); mesh_.update_vertex_normals(); // store original points & normals for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { mesh_.property(original_positions_, v_it) = mesh_.point(v_it); mesh_.property(original_normals_, v_it) = mesh_.normal(v_it); } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: set_active_vertices() { typename Mesh::VertexIter v_it, v_end(mesh_.vertices_end()); // is something selected? bool nothing_selected(true); for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.status(v_it).selected()) { nothing_selected = false; break; } // tagg all active vertices bool active; for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { active = ((nothing_selected || mesh_.status(v_it).selected()) && !mesh_.is_boundary(v_it) && !mesh_.status(v_it).locked()); if ( skip_features_ ) { active = active && !mesh_.status(v_it).feature(); typename Mesh::VertexOHalfedgeIter voh_it(mesh_,v_it); for ( ; voh_it ; ++voh_it ) { // If the edge is a feature edge, skip the current vertex while smoothing if ( mesh_.status(mesh_.edge_handle(voh_it.handle())).feature() ) active = false; typename Mesh::FaceHandle fh1 = mesh_.face_handle(voh_it.handle() ); typename Mesh::FaceHandle fh2 = mesh_.face_handle(mesh_.opposite_halfedge_handle(voh_it.handle() ) ); // If one of the faces is a feature, lock current vertex if ( fh1.is_valid() && mesh_.status( fh1 ).feature() ) active = false; if ( fh2.is_valid() && mesh_.status( fh2 ).feature() ) active = false; } } mesh_.property(is_active_, v_it) = active; } // C1: remove one ring of boundary vertices if (continuity_ == C1) { typename Mesh::VVIter vv_it; for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.is_boundary(v_it)) for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it) mesh_.property(is_active_, vv_it) = false; } // C2: remove two rings of boundary vertices if (continuity_ == C2) { typename Mesh::VVIter vv_it; for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { mesh_.status(v_it).set_tagged(false); mesh_.status(v_it).set_tagged2(false); } for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.is_boundary(v_it)) for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it) mesh_.status(v_it).set_tagged(true); for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) if (mesh_.status(v_it).tagged()) for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it) mesh_.status(v_it).set_tagged2(true); for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it) { if (mesh_.status(v_it).tagged2()) mesh_.property(is_active_, vv_it) = false; mesh_.status(v_it).set_tagged(false); mesh_.status(v_it).set_tagged2(false); } } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: set_relative_local_error(Scalar _err) { if (!mesh_.vertices_empty()) { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); // compute bounding box Point bb_min, bb_max; bb_min = bb_max = mesh_.point(v_it); for (++v_it; v_it!=v_end; ++v_it) { bb_min.minimize(mesh_.point(v_it)); bb_max.minimize(mesh_.point(v_it)); } // abs. error = rel. error * bounding-diagonal set_absolute_error(_err * (bb_max-bb_min).norm()); } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: set_absolute_local_error(Scalar _err) { tolerance_ = _err; } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: disable_local_error_check() { tolerance_ = -1.0; } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: smooth(unsigned int _n) { // mark active vertices set_active_vertices(); // smooth _n iterations while (_n--) { compute_new_positions(); if (component_ == Tangential) project_to_tangent_plane(); else if (tolerance_ >= 0.0) local_error_check(); move_points(); } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: compute_new_positions() { switch (continuity_) { case C0: compute_new_positions_C0(); break; case C1: compute_new_positions_C1(); break; case C2: break; } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: project_to_tangent_plane() { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); // Normal should be a vector type. In some environment a vector type // is different from point type, e.g. OpenSG! typename Mesh::Normal translation, normal; for (; v_it != v_end; ++v_it) { if (is_active(v_it)) { translation = new_position(v_it)-orig_position(v_it); normal = orig_normal(v_it); normal *= dot(translation, normal); translation -= normal; translation += vector_cast<typename Mesh::Normal>(orig_position(v_it)); set_new_position(v_it, translation); } } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: local_error_check() { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); typename Mesh::Normal translation; typename Mesh::Scalar s; for (; v_it != v_end; ++v_it) { if (is_active(v_it)) { translation = new_position(v_it) - orig_position(v_it); s = fabs(dot(translation, orig_normal(v_it))); if (s > tolerance_) { translation *= (tolerance_ / s); translation += vector_cast<NormalType>(orig_position(v_it)); set_new_position(v_it, translation); } } } } //----------------------------------------------------------------------------- template <class Mesh> void SmootherT<Mesh>:: move_points() { typename Mesh::VertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end()); for (; v_it != v_end; ++v_it) if (is_active(v_it)) mesh_.set_point(v_it, mesh_.property(new_positions_, v_it)); } //============================================================================= } // namespace Smoother } // namespace OpenMesh //=============================================================================
28.011601
109
0.495651
dmitriychunikhin
d74925529c06b5b049018b9b1fb8c6fb59cf5ca1
891
cpp
C++
LeetCode/Problems/Algorithms/#1048_LongestStringChain_sol2_dp_with_set_and_unordered_map_O(LNlogN+NL^2)_time_O(NL)_extra_space_64ms_20.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1048_LongestStringChain_sol2_dp_with_set_and_unordered_map_O(LNlogN+NL^2)_time_O(NL)_extra_space_64ms_20.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1048_LongestStringChain_sol2_dp_with_set_and_unordered_map_O(LNlogN+NL^2)_time_O(NL)_extra_space_64ms_20.6MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int longestStrChain(vector<string>& words) { set<pair<int, string>> lengthWordSet; unordered_map<string, int> dp; for(const string& WORD: words){ lengthWordSet.emplace(WORD.length(), WORD); dp[WORD] = 1; } int answer = 0; for(set<pair<int, string>>::const_reverse_iterator crit = lengthWordSet.crbegin(); crit != lengthWordSet.crend(); ++crit){ const string& WORD = crit->second; answer = max(dp[WORD], answer); for(int i = 0; i < (int)WORD.length(); ++i){ string nextWord = WORD.substr(0, i) + WORD.substr(i + 1); if(dp.count(nextWord)){ dp[nextWord] = max(1 + dp[WORD], dp[nextWord]); } } } return answer; } };
35.64
131
0.491582
Tudor67
d74a869695ab7d7bbc83137a4c4c78aa986ce401
497
cpp
C++
ZeroJudge/d578.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
ZeroJudge/d578.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
ZeroJudge/d578.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define _ ios::sync_with_stdio(0);cin.tie(0); using namespace std; int main(){ long long int N,M; while(~scanf("%lld %lld",&N,&M)&&N){ int cnt[1024][128]={0}; int RUN=N*M-1; char str[1024]; getchar(); while(RUN--){ fgets(str,1024,stdin); for(int i=0;str[i]!='\n';i++){ cnt[i][str[i]]++; } } for(int i=0;i<1024;i++){ for(int j=0;j<128;j++){ if(cnt[i][j]%M){ printf("%c",j); j=128; } } } printf("\n"); } return 0; }
17.75
45
0.511066
tico88612
d74aa64be238d773ac772d3fe286d5bca7ea3b59
5,096
cpp
C++
src/Table.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
src/Table.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
src/Table.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
/* Table.cpp By Jim Davies Jacobus Systems, Brighton & Hove, UK http://www.jacobus.co.uk Provided under the MIT license: https://github.com/jacobussystems/ArdJack/blob/master/LICENSE Copyright (c) 2019 James Davies, Jacobus Systems, Brighton & Hove, UK Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "pch.h" #ifdef ARDUINO #define _strlwr strlwr #else #include "stdafx.h" #include <typeinfo> #endif #include "Globals.h" #include "Log.h" #include "Table.h" #include "Utils.h" Table::Table() { ColumnCount = 0; HorzLineChar = '_'; LeftMargin = 3; TotalWidth = 0; VertLineChar = '|'; for (int i = 0; i < ARDJACK_MAX_TABLE_COLUMNS; i++) ColumnDefs[i] = NULL; } Table::~Table() { for (int i = 0; i < ARDJACK_MAX_TABLE_COLUMNS; i++) { if (NULL != ColumnDefs[i]) { delete ColumnDefs[i]; ColumnDefs[i] = NULL; } } ColumnCount = 0; } bool Table::AddColumn(const char* caption, int width, int align, int padding) { TableColumnDef* colDef = new TableColumnDef(); ColumnDefs[ColumnCount++] = colDef; colDef->Alignment = align; strcpy(colDef->Caption, caption); colDef->Padding = padding; colDef->Width = width; TotalWidth += width; return true; } char* Table::AddLeftMargin(char* text) { Utils::RepeatChar(text, ' ', LeftMargin); return text; } char* Table::Cell(char* text, const char* colText, int col) { text[0] = NULL; if (col >= ColumnCount) return text; TableColumnDef* colDef = ColumnDefs[col]; if (Utils::StringIsNullOrEmpty(colText)) { // There's no text. return Utils::RepeatChar(text, ' ', colDef->Width); } char format[22]; char padding[82]; char temp[102]; // Left-side padding. Utils::RepeatChar(padding, ' ', colDef->Padding); strcat(text, padding); // Align the column text. int textWidth = colDef->Width - 2 * colDef->Padding; switch (colDef->Alignment) { case ARDJACK_HORZ_ALIGN_CENTRE: { int remainder = textWidth - (NULL != colText) ? Utils::StringLen(colText) : 0; if (remainder <= 0) strcat(text, colText); else { int spaces = remainder / 2; Utils::RepeatChar(padding, ' ', spaces); strcat(text, padding); strcat(text, colText); Utils::RepeatChar(padding, ' ', remainder - spaces); strcat(text, padding); } } break; case ARDJACK_HORZ_ALIGN_LEFT: sprintf(format, "%%-%ds", textWidth); sprintf(temp, format, (NULL != colText) ? colText : ""); strcat(text, temp); break; case ARDJACK_HORZ_ALIGN_RIGHT: sprintf(format, "%%%ds", textWidth); sprintf(temp, format, (NULL != colText) ? colText : ""); strcat(text, temp); break; } if (col < ColumnCount - 1) { // Right-side padding. Utils::RepeatChar(padding, ' ', colDef->Padding); strcat(text, padding); } return text; } char* Table::Header(char* text) { text[0] = NULL; AddLeftMargin(text); char temp[82]; for (int col = 0; col < ColumnCount; col++) { TableColumnDef* colDef = ColumnDefs[col]; Cell(temp, colDef->Caption, col); strcat(text, temp); } return text; } char* Table::HorizontalLine(char* text) { text[0] = NULL; AddLeftMargin(text); // A horizontal line. char temp[202]; Utils::RepeatChar(temp, HorzLineChar, TotalWidth); strcat(text, temp); return text; } char* Table::Row(char* text, const char* col0, const char* col1, const char* col2, const char* col3, const char* col4, const char* col5, const char* col6, const char* col7, const char* col8, const char* col9, const char* col10, const char* col11) { text[0] = NULL; AddLeftMargin(text); if (strlen(col0) == 0) return text; char work[102]; int col = 0; strcat(text, Cell(work, col0, col++)); strcat(text, Cell(work, col1, col++)); strcat(text, Cell(work, col2, col++)); strcat(text, Cell(work, col3, col++)); strcat(text, Cell(work, col4, col++)); strcat(text, Cell(work, col5, col++)); strcat(text, Cell(work, col6, col++)); strcat(text, Cell(work, col7, col++)); strcat(text, Cell(work, col8, col++)); strcat(text, Cell(work, col9, col++)); strcat(text, Cell(work, col10, col++)); strcat(text, Cell(work, col11, col++)); return text; }
22.350877
114
0.683673
jacobussystems
d74deea9591e985dea2251071a1ad45d7d6bd4e6
598
cpp
C++
Codility_Challenges/PermMissingElem.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
1
2019-03-24T12:35:43.000Z
2019-03-24T12:35:43.000Z
Codility_Challenges/PermMissingElem.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
Codility_Challenges/PermMissingElem.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
/* A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. Your goal is to find that missing element. Write a function: int solution(int A[], int N); that, given a zero-indexed array A, returns the value of the missing element. */ // you can write to stdout for debugging purposes, e.g. // printf("this is a debug message\n"); int solution(int A[], int N) { // write your code in C99 int Sum=(N+1)*(N+2)/2; for(int i=0;i<N;i++) Sum=Sum-A[i]; return Sum; }
31.473684
171
0.673913
anishacharya
d74ef5b7b96345d05bde74f58bac90d4c0073d33
567
cpp
C++
src/npf/layout/ask.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
1
2021-07-16T04:25:02.000Z
2021-07-16T04:25:02.000Z
src/npf/layout/ask.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
4
2021-09-16T08:46:40.000Z
2022-03-12T05:12:20.000Z
src/npf/layout/ask.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
null
null
null
// // Created by Spud on 7/16/21. // #include "npf/layout/ask.hpp" void Ask::populateBlocks(const JSON_ARRAY &array) { // TODO Comments blocks = std::vector<int>(array.Size()); for (JSON_ARRAY_ENTRY &entry : array) { if (entry.IsInt()) { blocks.push_back(entry.GetInt()); } } } void Ask::populateNPF(JSON_OBJECT entry) { // TODO Comments POPULATE_ARRAY(entry, "blocks", populateBlocks(entry["blocks"].GetArray());) POPULATE_OBJECT(entry, "attribution", Attribution attr; attr.populateNPF(entry["attribution"].GetObj()); attribution = attr;) }
22.68
77
0.689594
yeSpud
d7525e11662834fddb8fcd586c8f3f21a6f03528
3,450
cpp
C++
dnn/src/rocm/pooling/opr_impl.cpp
googol-lab/MegEngine
e0193cc4431371719a6ddb0fa85f910c5583bfc8
[ "Apache-2.0" ]
1
2021-03-25T01:13:24.000Z
2021-03-25T01:13:24.000Z
dnn/src/rocm/pooling/opr_impl.cpp
googol-lab/MegEngine
e0193cc4431371719a6ddb0fa85f910c5583bfc8
[ "Apache-2.0" ]
1
2021-05-27T08:55:38.000Z
2021-05-27T08:55:38.000Z
dnn/src/rocm/pooling/opr_impl.cpp
googol-lab/MegEngine
e0193cc4431371719a6ddb0fa85f910c5583bfc8
[ "Apache-2.0" ]
null
null
null
/** * \file dnn/src/rocm/pooling/opr_impl.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "hcc_detail/hcc_defs_prologue.h" #include "src/rocm/pooling/opr_impl.h" #include "src/rocm/utils.h" namespace megdnn { namespace rocm { void PoolingForwardImpl::setup_descs(const TensorLayout &src, const TensorLayout &dst) { src_desc.set(src, param().format); dst_desc.set(dst, param().format); pooling_desc.set(this->param()); } void PoolingForwardImpl::exec(_megdnn_tensor_in src, _megdnn_tensor_out dst, _megdnn_workspace workspace) { check_exec(src.layout, dst.layout, workspace.size); auto handle = miopen_handle(this->handle()); setup_descs(src.layout, dst.layout); dt_float32 alpha = 1.0f, beta = 0.0f; miopen_check(miopenPoolingForward(handle, pooling_desc.desc, &alpha, src_desc.desc, src.raw_ptr, &beta, dst_desc.desc, dst.raw_ptr, false, nullptr, 0_z)); } void PoolingBackwardImpl::setup_descs(const TensorLayout& src, const TensorLayout& dst, const TensorLayout& diff, const TensorLayout& grad) { src_desc.set(src); dst_desc.set(dst); diff_desc.set(diff); grad_desc.set(grad); pooling_desc.set(this->param()); } void PoolingBackwardImpl::exec(_megdnn_tensor_in src, _megdnn_tensor_in dst, _megdnn_tensor_in diff, _megdnn_tensor_out grad, _megdnn_workspace workspace) { check_exec(src.layout, dst.layout, diff.layout, grad.layout, workspace.size); auto handle = miopen_handle(this->handle()); setup_descs(src.layout, dst.layout, diff.layout, grad.layout); float alpha = 1.0f, beta = 0.0f; if (param().mode == param::Pooling::Mode::MAX) { //! FIXME: when using max pooling opr, the backward opr need the indices //! of the forward opr which stored in workspace. We have to recompute //! the indices by calling miopenPoolingForward again. miopen_check(miopenPoolingForward(handle, pooling_desc.desc, &alpha, src_desc.desc, src.raw_ptr, &beta, dst_desc.desc, dst.raw_ptr, true, workspace.raw_ptr, workspace.size)); } miopen_check(miopenPoolingBackward( handle, pooling_desc.desc, &alpha, dst_desc.desc, dst.raw_ptr, diff_desc.desc, diff.raw_ptr, src_desc.desc, src.raw_ptr, &beta, grad_desc.desc, grad.raw_ptr, workspace.raw_ptr)); } size_t PoolingBackwardImpl::get_workspace_in_bytes(const TensorLayout& src, const TensorLayout& dst, const TensorLayout& diff, const TensorLayout& grad) { setup_descs(src, dst, diff, grad); size_t ws_size = 0_z; miopenPoolingGetWorkSpaceSize(dst_desc.desc, &ws_size); return ws_size; }; } // namespace rocm } // namespace megdnn // vim: syntax=cpp.doxygen
37.912088
89
0.631014
googol-lab
d75337db3fcf021e5b4f25798d76dac14a97140e
2,223
cpp
C++
Day_17/06_Top_View.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_17/06_Top_View.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_17/06_Top_View.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
// Problem Link: // https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1 // Recursive and Iterative // TC: O(n) // SC: O(n) #include <bits/stdc++.h> using namespace std; #define ll long long #define deb(x) cout << #x << ": " << x << "\n" class TreeNode { public: TreeNode *left; int val; TreeNode *right; TreeNode() { TreeNode(-1); } TreeNode(int _val) : left(NULL), val(_val), right(NULL) {} }; // Recusive void helper(TreeNode *root, map<int, pair<int, int>> &hash, int distance, int level) { if (root) { if (hash.find(distance) == hash.end() or level <= hash[distance].first) hash[distance] = {level, root->val}; helper(root->left, hash, distance - 1, level + 1); helper(root->right, hash, distance + 1, level + 1); } } vector<int> topView1(TreeNode *root) { vector<int> res{}; map<int, pair<int, int>> hash{}; helper(root, hash, 0, 0); for (auto i : hash) res.push_back(i.second.second); return res; } // Iterative vector<int> topView2(TreeNode *root) { vector<int> res{}; map<int, int> hash{}; queue<pair<TreeNode *, int>> qu; qu.push({root, 0}); while (!qu.empty()) { pair<TreeNode *, int> curr = qu.front(); qu.pop(); if (hash.find(curr.second) == hash.end()) hash[curr.second] = curr.first->val; if (curr.first->left) qu.push({curr.first->left, curr.second - 1}); if (curr.first->right) qu.push({curr.first->right, curr.second + 1}); } for (auto i : hash) res.push_back(i.second); return res; } void solve() { TreeNode *root = new TreeNode(10); root->left = new TreeNode(20); root->right = new TreeNode(30); root->left->left = new TreeNode(40); root->left->right = new TreeNode(60); vector<int> res; res = topView1(root); for (auto i : res) cout << i << " "; cout << endl; res = topView2(root); for (auto i : res) cout << i << " "; cout << endl; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
21.171429
84
0.549708
premnaaath
d759f3acebc967a441b587b809c6d3107b3612b8
400
cpp
C++
modules/06-point3.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
1
2022-03-07T09:14:07.000Z
2022-03-07T09:14:07.000Z
modules/06-point3.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
null
null
null
modules/06-point3.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
null
null
null
// 06-point3.cpp : Point type with global operator+ defined import std.core; using namespace std; struct Point{ int x{}, y{}; }; Point operator+ (const Point& lhs, const Point& rhs) { Point result; result.x = lhs.x + rhs.x; result.y = lhs.y + rhs.y; return result; } int main() { Point p1{ 100, 200 }, p2{ 200, -50 }, p3; p3 = p1 + p2; cout << "p3 = (" << p3.x << ',' << p3.y << ")\n"; }
18.181818
59
0.5775
cpp-tutor
d75d1281bb923484e384a772e6140080715ab209
17,039
cxx
C++
ALIGN/AliAlgSens.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1
2017-04-27T17:28:15.000Z
2017-04-27T17:28:15.000Z
ALIGN/AliAlgSens.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
3
2017-07-13T10:54:50.000Z
2018-04-17T19:04:16.000Z
ALIGN/AliAlgSens.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
5
2017-03-29T12:21:12.000Z
2018-01-15T15:52:24.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <stdio.h> #include <TClonesArray.h> #include "AliAlgSens.h" #include "AliAlgAux.h" #include "AliLog.h" #include "AliGeomManager.h" #include "AliExternalTrackParam.h" #include "AliAlgPoint.h" #include "AliAlgDet.h" #include "AliAlgDOFStat.h" ClassImp(AliAlgSens) using namespace AliAlgAux; using namespace TMath; //_________________________________________________________ AliAlgSens::AliAlgSens(const char* name,Int_t vid, Int_t iid) : AliAlgVol(name,iid) ,fSID(0) ,fDet(0) ,fMatClAlg() ,fMatClAlgReco() { // def c-tor SetVolID(vid); fAddError[0] = fAddError[1] = 0; fConstrChild = 0; // sensors don't have children } //_________________________________________________________ AliAlgSens::~AliAlgSens() { // d-tor } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame // parameters in TGeoHMatrix convention. // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; // variation matrix in tracking frame for variation in sensor LOCAL frame GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // Jacobian of position in sensor tracking frame (tra) vs parent volume LOCAL frame parameters. // NO check of parentship is done! // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // this is the matrix for transition from sensor to parent volume local frames: LOC=matRel*loc TGeoHMatrix matRel = parent->GetMatrixL2GIdeal().Inverse(); matRel *= GetMatrixL2GIdeal(); // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodLOC(matMod, delta, matRel); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is // tra' = tau*tra // // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING // frame parameters in TGeoHMatrix convention, i.e. the modified parameter is // tra' = tau*tra // // Result is stored in array deriv as linearized matrix 6x3 const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5}; double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3]; TGeoHMatrix matMod; // // 1st we need a matrix for transition between child and parent TRACKING frames // Let TRA,LOC are positions in tracking and local frame of parent, linked as LOC=T2L*TRA // and tra,loc are positions in tracking and local frame of child, linked as loc=t2l*tra // The loc and LOC are linked as LOC=R*loc, where R = L2G^-1*l2g, with L2G and l2g // local2global matrices for parent and child // // Then, TRA = T2L^-1*LOC = T2L^-1*R*loc = T2L^-1*R*t2l*tra // -> TRA = matRel*tra, with matRel = T2L^-1*L2G^-1 * l2g*t2l // Note that l2g*t2l are tracking to global matrices TGeoHMatrix matRel,t2gP; GetMatrixT2G(matRel); // t2g matrix of child parent->GetMatrixT2G(t2gP); // t2g matrix of parent matRel.MultiplyLeft(&t2gP.Inverse()); // memset(delta,0,kNDOFGeom*sizeof(double)); memset(deriv,0,kNDOFGeom*3*sizeof(double)); const double *tra = pnt->GetXYZTracking(); // for (int ip=kNDOFGeom;ip--;) { // if (!IsFreeDOF(ip)) continue; // double var = kDelta[ip]; delta[ip] -= var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos0); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos1); // varied position in tracking frame // delta[ip] += var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos2); // varied position in tracking frame // delta[ip] += 0.5*var; GetDeltaT2LmodTRA(matMod,delta,matRel); matMod.LocalToMaster(tra,pos3); // varied position in tracking frame // delta[ip] = 0; double *curd = deriv + ip*3; for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var; } // } //_________________________________________________________ void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const { // calculate point position derivatives in tracking frame of sensor // vs standard geometrical DOFs of its parent volume (if parent!=0) or sensor itself Frame_t frame = parent ? parent->GetVarFrame() : GetVarFrame(); switch(frame) { case kLOC : parent ? DPosTraDParGeomLOC(pnt,deriv,parent) : DPosTraDParGeomLOC(pnt,deriv); break; case kTRA : parent ? DPosTraDParGeomTRA(pnt,deriv,parent) : DPosTraDParGeomTRA(pnt,deriv); break; default : AliErrorF("Alignment frame %d is not implemented",parent->GetVarFrame()); break; } } //__________________________________________________________________ void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of LOCAL frame: // loc' = delta*loc = T2L'*tra = T2L'*T2L^-1*loc -> T2L' = delta*T2L Delta2Matrix(matMod, delta); matMod.Multiply(&GetMatrixT2L()); } //__________________________________________________________________ void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const { // prepare the sensitive module tracking2local matrix from its current T2L matrix // by applying local delta of modification of TRACKING frame: // loc' = T2L'*tra = T2L*delta*tra -> T2L' = T2L*delta Delta2Matrix(matMod, delta); matMod.MultiplyLeft(&GetMatrixT2L()); } //__________________________________________________________________ void AliAlgSens::AddChild(AliAlgVol*) { AliFatalF("Sensor volume cannot have childs: id=%d %s",GetVolID(),GetName()); } //__________________________________________________________________ Int_t AliAlgSens::Compare(const TObject* b) const { // compare VolIDs return GetUniqueID()<b->GetUniqueID() ? -1 : 1; } //__________________________________________________________________ void AliAlgSens::SetTrackingFrame() { // define tracking frame of the sensor // AliWarningF("Generic method called for %s",GetSymName()); double tra[3]={0},glo[3]; TGeoHMatrix t2g; GetMatrixT2G(t2g); t2g.LocalToMaster(tra,glo); fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); fAlp = ATan2(glo[1],glo[0]); AliAlgAux::BringToPiPM(fAlp); // } //____________________________________________ void AliAlgSens::Print(const Option_t *opt) const { // print info TString opts = opt; opts.ToLower(); printf("Lev:%2d IntID:%7d %s VId:%6d X:%8.4f Alp:%+.4f | Err: %.4e %.4e | Used Points: %d\n", CountParents(), GetInternalID(), GetSymName(), GetVolID(), fX, fAlp, fAddError[0],fAddError[1],fNProcPoints); printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {",fNDOFs,fFirstParGloID,fNDOFFree,fNDOFGeomFree); for (int i=0;i<kNDOFGeom;i++) printf("%d",IsFreeDOF(i) ? 1:0); printf("} in %s frame\n",fgkFrameName[fVarFrame]); // // // if (opts.Contains("par") && fParVals) { printf(" Lb: "); for (int i=0;i<fNDOFs;i++) printf("%10d ",GetParLab(i)); printf("\n"); printf(" Vl: "); for (int i=0;i<fNDOFs;i++) printf("%+9.3e ",GetParVal(i)); printf("\n"); printf(" Er: "); for (int i=0;i<fNDOFs;i++) printf("%+9.3e ",GetParErr(i)); printf("\n"); } // if (opts.Contains("mat")) { // print matrices printf("L2G ideal : "); GetMatrixL2GIdeal().Print(); printf("L2G misalign: "); GetMatrixL2G().Print(); printf("L2G RecoTime: "); GetMatrixL2GReco().Print(); printf("T2L : "); GetMatrixT2L().Print(); printf("ClAlg : "); GetMatrixClAlg().Print(); printf("ClAlgReco: "); GetMatrixClAlgReco().Print(); } // } //____________________________________________ void AliAlgSens::PrepareMatrixT2L() { // extract from geometry T2L matrix const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID()); if (!t2l) { Print("long"); AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName()); } SetMatrixT2L(*t2l); // } //____________________________________________ void AliAlgSens::PrepareMatrixClAlg() { // prepare alignment matrix in the LOCAL frame: delta = Gideal^-1 * G TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse(); ma *= GetMatrixL2G(); SetMatrixClAlg(ma); // } //____________________________________________ void AliAlgSens::PrepareMatrixClAlgReco() { // prepare alignment matrix used at reco time TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse(); ma *= GetMatrixL2GReco(); SetMatrixClAlgReco(ma); // } //____________________________________________ void AliAlgSens::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const { // update fDet->UpdatePointByTrackInfo(pnt,t); } //____________________________________________ void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent) const { // calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent // parent=0 means top detector object calibration // deriv[0]=deriv[1]=deriv[2]=0; } //______________________________________________________ Int_t AliAlgSens::FinalizeStat(AliAlgDOFStat* st) { // finalize statistics on processed points if (st) FillDOFStat(st); return fNProcPoints; } //_________________________________________________________________ void AliAlgSens::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix *cumulDelta) { // recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects // used during data reconstruction. // On top of what each volume does, also update misalignment matrix inverse // AliAlgVol::UpdateL2GRecoMatrices(algArr,cumulDelta); PrepareMatrixClAlgReco(); // } /* //_________________________________________________________________ AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*) { // dummy converter AliError("Generic method, must be implemented in specific sensor"); return 0; } */ //_________________________________________________________________ void AliAlgSens::ApplyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents // const AliAlgVol* vol = this; TGeoHMatrix deltaG; // create global combined delta: // DeltaG = deltaG_0*...*deltaG_j, where delta_i is global delta of each member of hierarchy while(vol) { TGeoHMatrix deltaGJ; vol->CreateAlignmenMatrix(deltaGJ); deltaG.MultiplyLeft(&deltaGJ); vol = vol->GetParent(); } // // update misaligned L2G matrix deltaG *= GetMatrixL2GIdeal(); SetMatrixL2G(deltaG); // // update local misalignment matrix PrepareMatrixClAlg(); // } /* //_________________________________________________________________ void AliAlgSens::ApplyAlignmentFromMPSol() { // apply to the tracking coordinates in the sensor frame the full chain // of alignments found by MP for this sensor and its parents double delta[kNDOFGeom]={0}; // TGeoHMatrix matMod; // // sensor proper variation GetParValGeom(delta); IsFrameTRA() ? GetDeltaT2LmodTRA(matMod,delta) : GetDeltaT2LmodLOC(matMod,delta); fMatClAlg.MultiplyLeft(&matMod); // AliAlgVol* parent = this; while ((parent==parent->GetParent())) { // this is the matrix for transition from sensor to parent volume frame parent->GetParValGeom(delta); TGeoHMatrix matRel,t2gP; if (parent->IsFrameTRA()) { GetMatrixT2G(matRel); // t2g matrix of child parent->GetMatrixT2G(t2gP); // t2g matrix of parent matRel.MultiplyLeft(&t2gP.Inverse()); GetDeltaT2LmodTRA(matMod, delta, matRel); } else { matRel = parent->GetMatrixL2GIdeal().Inverse(); matRel *= GetMatrixL2GIdeal(); GetDeltaT2LmodLOC(matMod, delta, matRel); } fMatClAlg.MultiplyLeft(&matMod); } // } */
34.98768
113
0.681671
AllaMaevskaya
d75f40295ae664eea93ed905f10f734d66c2221a
10,128
cpp
C++
src/Kernel/MEDimpl/Integrer_champ_med.cpp
cea-trust-platform/trust-code
c4f42d8f8602a8cc5e0ead0e29dbf0be8ac52f72
[ "BSD-3-Clause" ]
12
2021-06-30T18:50:38.000Z
2022-03-23T09:03:16.000Z
src/Kernel/MEDimpl/Integrer_champ_med.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
null
null
null
src/Kernel/MEDimpl/Integrer_champ_med.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
2
2021-10-04T09:19:39.000Z
2021-12-15T14:21:04.000Z
/**************************************************************************** * Copyright (c) 2015 - 2016, CEA * 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. * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // File: Integrer_champ_med.cpp // Directory: $TRUST_ROOT/src/Kernel/MEDimpl // Version: /main/9 // ////////////////////////////////////////////////////////////////////////////// #include <Integrer_champ_med.h> #include <Param.h> #include <Champ_Fonc_MED.h> #include <SFichier.h> Implemente_instanciable(Integrer_champ_med,"Integrer_champ_med",Interprete); // Description: // Simple appel a: Interprete::printOn(Sortie&) // Precondition: // Parametre: Sortie& os // Signification: un flot de sortie // Valeurs par defaut: // Contraintes: // Acces: entree/sortie // Retour: Sortie& // Signification: le flot de sortie modifie // Contraintes: // Exception: // Effets de bord: // Postcondition: la methode ne modifie pas l'objet Sortie& Integrer_champ_med::printOn(Sortie& os) const { return Interprete::printOn(os); } // Description: // Simple appel a: Interprete::readOn(Entree&) // Precondition: // Parametre: Entree& is // Signification: un flot d'entree // Valeurs par defaut: // Contraintes: // Acces: entree/sortie // Retour: Entree& // Signification: le flot d'entree modifie // Contraintes: // Exception: // Effets de bord: // Postcondition: Entree& Integrer_champ_med::readOn(Entree& is) { return Interprete::readOn(is); } void calcul_normal_norme(const ArrOfDouble& org,const ArrOfDouble& point1, const ArrOfDouble& point2,ArrOfDouble& normal); double calcul_surface_triangle(const ArrOfDouble& origine,const ArrOfDouble& point1, const ArrOfDouble& point2) { double normal0=(point1(1)-origine(1))*(point2(2)-origine(2))-((point2(1)-origine(1))*(point1(2)-origine(2))); double normal1=(point1(2)-origine(2))*(point2(0)-origine(0))-((point2(2)-origine(2))*(point1(0)-origine(0))); double normal2=(point1(0)-origine(0))*(point2(1)-origine(1))-((point2(0)-origine(0))*(point1(1)-origine(1))); double res=normal0*normal0+ normal1*normal1 + normal2*normal2 ; return sqrt(res)/2.; } double portion_surface_elem(const ArrOfDouble& pointA,const ArrOfDouble& pointB, const ArrOfDouble& pointC,const double& z) { if (z<=pointA(2)) return 0; if (z>pointC(2)) return calcul_surface_triangle(pointA,pointB,pointC); ArrOfDouble pointD(3); // le point D est sur AC a hauteur de B. pointD(2)=pointB(2); double lambda=(pointB(2)-pointA(2))/(pointC(2)-pointA(2)); for (int i=0; i<2; i++) pointD(i)=pointA(i)+lambda*(pointC(i)-pointA(i)); if (z<=pointB(2)) { // on calcul la surface du triangle inferieur // et on prend la proportion... double surf_inf=calcul_surface_triangle(pointA,pointB,pointD); double rap=1; if (pointB(2)!=pointA(2)) rap=(z-pointA(2))/(pointB(2)-pointA(2)); return surf_inf*rap*rap; } else { // on calcul la surface du triangle inferieur // et on prend la proportion... // et on retire a la surface totale double surf_sup=calcul_surface_triangle(pointB,pointD,pointC); double rap=(z-pointC(2))/(pointB(2)-pointC(2)); double surf_tot=calcul_surface_triangle(pointA,pointB,pointC); return surf_tot-surf_sup*rap*rap; } } double portion_surface(const ArrOfDouble& point0,const ArrOfDouble& point1, const ArrOfDouble& point2,const double& zmin,const double& zmax) { return portion_surface_elem(point0,point1,point2,zmax)- portion_surface_elem(point0,point1,point2,zmin); } static True_int fonction_tri_data(const void *ptr1, const void *ptr2) { const double * tab1 = (const double *) ptr1; const double * tab2 = (const double *) ptr2; double delta=(tab1[0] - tab2[0]); if (delta>0) return 1; else if (delta<0) return -1; return 0; } // Description: // Fonction principale de l'interprete. // Precondition: // Parametre: Entree& is // Signification: un flot d'entree // Valeurs par defaut: // Contraintes: // Acces: entree/sortie // Retour: Entree& // Signification: le flot d'entree // Contraintes: // Exception: // Effets de bord: // Postcondition: Entree& Integrer_champ_med::interpreter(Entree& is) { Motcle nom_methode; Nom nom_fichier("integrale"); Nom nom_champ_fonc_med; double zmin=0,zmax=0; int nb_tranche=1; Param param(que_suis_je()); param.ajouter("champ_med",&nom_champ_fonc_med,Param::REQUIRED); param.ajouter("methode",&nom_methode,Param::REQUIRED); param.ajouter("zmin",&zmin); param.ajouter("zmax",&zmax); param.ajouter("nb_tranche",&nb_tranche); param.ajouter("fichier_sortie",&nom_fichier); param.lire_avec_accolades_depuis(is); if ((nom_methode!="integrale_en_z")&&(nom_methode!="debit_total")) { Cerr<<"method "<<nom_methode <<" not coded yet "<<finl; } // on recupere le domaine if(! sub_type(Champ_Fonc_MED, objet(nom_champ_fonc_med))) { Cerr << nom_champ_fonc_med << " type is " << objet(nom_champ_fonc_med).que_suis_je() << finl; Cerr << "only the objects of type Champ_Fonc_MED can be meshed" << finl; exit(); } Champ_Fonc_MED& champ=ref_cast(Champ_Fonc_MED, objet(nom_champ_fonc_med)); const Zone& zone=champ.zone_dis_base().zone(); const DoubleTab& coord=zone.domaine().les_sommets(); // on fait une coie pour les modifier IntTab les_elems_mod=zone.les_elems(); const IntTab& les_elems=zone.les_elems(); ArrOfDouble normal(3); const DoubleTab& valeurs= champ.valeurs(); assert(valeurs.dimension(0)==zone.nb_elem()); assert(valeurs.dimension(1)==3); double dz=(zmax-zmin)/nb_tranche; ArrOfDouble res(nb_tranche),pos(nb_tranche),surface(nb_tranche); int nb_elem=les_elems.dimension(0); Cerr<<" Field integration using the method "<<nom_methode<<" on the domain "<<zone.domaine().le_nom() <<finl; if (nom_methode=="debit_total") { nb_tranche=1; zmax=DMAXFLOAT/2.; zmin=-zmax; dz=(zmax-zmin); pos(0)=0; } //if (nom_methode=="integrale_en_z") { // Etape 1 on reordonne les triangles pour classeren z les sommets for (int elem=0; elem<nb_elem; elem++) { DoubleTab zz(3,2); for (int i=0; i<3; i++) { int s=les_elems(elem,i); zz(i,1)=s; zz(i,0)=coord(s,2); } qsort(zz.addr(),3,sizeof(double) * 2 , fonction_tri_data); for (int i=0; i<3; i++) { int ss=(int)zz(i,1); // if (ss!=les_elems(elem,i)) Cerr<<" coucou" <<elem<<finl; les_elems_mod(elem,i)=ss; } } // ArrOfDouble point0(3),point1(3),point2(3); for (int elem=0; elem<nb_elem; elem++) { for (int i=0; i<3; i++) { point0(i)=coord(les_elems(elem,0),i); point1(i)=coord(les_elems(elem,1),i); point2(i)=coord(les_elems(elem,2),i); } calcul_normal_norme(point0,point1, point2, normal); for (int i=0; i<3; i++) { point0(i)=coord(les_elems_mod(elem,0),i); point1(i)=coord(les_elems_mod(elem,1),i); point2(i)=coord(les_elems_mod(elem,2),i); } for (int tranche=0; tranche<nb_tranche; tranche++) { double zminl=(zmin)+(zmax-zmin)/nb_tranche*tranche; double zmaxl=zminl+dz; pos(tranche)=(zminl+zmaxl)/2.; double z0=coord(les_elems_mod(elem,0),2); if (z0<=zmaxl) { double z2=coord(les_elems_mod(elem,2),2); if (z2>=zminl) { double portion=portion_surface(point0,point1,point2,zminl,zmaxl); double prod_scal=0; for (int i=0; i<3; i++) prod_scal+=valeurs(elem,i)*normal(i); res(tranche)+=portion*prod_scal; surface(tranche)+=portion; } } } } } double trace=0; SFichier so(nom_fichier); for (int nb=0; nb<nb_tranche; nb++) { trace+=res(nb); if (surface(nb)!=0) res(nb)/=surface(nb); else assert(res(nb)==0); } Cout<<"# overall balance "<<trace<<finl; so<<"# bilan global "<<trace<<finl; so<<"# position, valeur moyenne, surface, flux"<<finl; for (int nb=0; nb<nb_tranche; nb++) so << pos(nb)<<" "<<res(nb)<<" "<<surface(nb)<<" "<<res(nb)*surface(nb)<<finl; return is; }
34.10101
260
0.630825
cea-trust-platform
d76039ede79217000084ddf0cc1897ac8d06ac15
1,856
hpp
C++
lib/primitive/src/thread/Task.hpp
tkeycoin/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
3
2020-01-24T04:45:14.000Z
2020-06-30T13:49:58.000Z
lib/primitive/src/thread/Task.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-06-18T15:51:36.000Z
2020-06-20T17:25:45.000Z
lib/primitive/src/thread/Task.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-10-20T06:50:13.000Z
2020-10-20T06:50:13.000Z
// Copyright (c) 2017-2019 Tkeycoin Dao. All rights reserved. // Copyright (c) 2019-2020 TKEY DMCC LLC & Tkeycoin Dao. All rights reserved. // Website: www.tkeycoin.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. // // Task.hpp #pragma once #include <functional> #include <chrono> #include <ucontext.h> #include "../utils/Shareable.hpp" class Task final { public: using Func = std::function<void()>; using Clock = std::chrono::steady_clock; using Duration = Clock::duration; using Time = Clock::time_point; private: Func _function; Time _until; const char* _label; mutable ucontext_t* _parentTaskContext; public: explicit Task(Func&& function, Time until, const char* label = "-"); virtual ~Task() = default; // Разрешаем перемещение Task(Task&& that) noexcept; Task& operator=(Task&& that) noexcept; // Запрещаем любое копирование Task(const Task&) = delete; Task& operator=(const Task&) = delete; // Планирование времени const Time& until() const { return _until; } // Метка задачи (имя, название и т.п., для отладки) const char* label() const { return _label; } // Сравнение по времени bool operator<(const Task &that) const { return this->_until > that._until; } // Исполнение void execute(); // Пустышка (остаток от перемещения) bool isDummy() const { return !_function; } };
22.361446
78
0.706897
tkeycoin
d762c3a4125cc44871fbc25d7c1e6a4bd27167c5
3,852
cpp
C++
SIRCommon/ShooterRecord.cpp
sbweeden/signinregister
bf6741f71eefb4ad860c83473f84417a9cabbd73
[ "MIT" ]
null
null
null
SIRCommon/ShooterRecord.cpp
sbweeden/signinregister
bf6741f71eefb4ad860c83473f84417a9cabbd73
[ "MIT" ]
null
null
null
SIRCommon/ShooterRecord.cpp
sbweeden/signinregister
bf6741f71eefb4ad860c83473f84417a9cabbd73
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "ShooterRecord.h" #include "Msg.h" #include "Resource.h" #define SEPARATOR ";" ShooterRecord::ShooterRecord( LPCTSTR membership_number /* = NULL */, LPCTSTR shooter_name /* = NULL */, LPCTSTR license /* = NULL */, LPCTSTR club /* = NULL */, LPCTSTR category /* = NULL */, __time64_t license_expiry_time /* = 0 */) : m_membership_number(membership_number), m_shooter_name(shooter_name), m_license(license), m_club(club), m_category(category), m_license_expiry_time(license_expiry_time) { } ShooterRecord::ShooterRecord( const ShooterRecord& rec) : m_membership_number(rec.m_membership_number), m_shooter_name(rec.m_shooter_name), m_license(rec.m_license), m_club(rec.m_club), m_category(rec.m_category), m_license_expiry_time(rec.m_license_expiry_time) { } ShooterRecord::~ShooterRecord(void) { } bool ShooterRecord::operator==(const ShooterRecord& rec) const { return ( m_membership_number == rec.m_membership_number && m_shooter_name == rec.m_shooter_name && m_license == rec.m_license && m_club == rec.m_club && m_category == rec.m_category && m_license_expiry_time == rec.m_license_expiry_time ); } CStringA ShooterRecord::ToAsciiString() const { CStringA result; char buf[256]; result += m_membership_number; result += SEPARATOR; result += m_shooter_name; result += SEPARATOR; result += m_license; result += SEPARATOR; result += m_club; result += SEPARATOR; result += m_category; if (!_i64toa_s(m_license_expiry_time, buf, 256, 10)) { result += SEPARATOR; result += buf; } return result; } void ShooterRecord::FromAsciiString(const char * str) { CStringA s(str); CStringA token; int curPos = 0; bool parseError = false; if ( !parseError ) { // parse membership number token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_membership_number = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Membership Number"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse shooter name token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_shooter_name = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Shooter Name"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse license token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_license = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("License"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse club token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_club = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Club"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { // parse category token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_category = token; } else { parseError = true; CString wholestr(str); ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Category"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); } } if ( !parseError ) { token = s.Tokenize(SEPARATOR, curPos); if ( curPos > 0 ) { m_license_expiry_time = _atoi64((const char *) token); } // optional - don't consider this a failure //else //{ // parseError = true; // CString wholestr(str); // ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("License Expiry Time"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK); //} } } CString ShooterRecord::ToSearchResultString() const { CString result; result.Format(_T("%-25s %-16s %-20s"), m_shooter_name, m_membership_number, m_club ); return result; }
21.281768
118
0.678089
sbweeden
d7637633be8552f113c0fe6ee190722bd318a079
29,874
cpp
C++
sdk/private/eventmanager.cpp
faming-wang/QTeamSpeak3
41f6161cb87be7029c5d91ab4a33062d91445c64
[ "Apache-2.0" ]
2
2021-12-28T15:49:43.000Z
2022-03-27T08:05:12.000Z
sdk/private/eventmanager.cpp
faming-wang/QTeamSpeak3
41f6161cb87be7029c5d91ab4a33062d91445c64
[ "Apache-2.0" ]
null
null
null
sdk/private/eventmanager.cpp
faming-wang/QTeamSpeak3
41f6161cb87be7029c5d91ab4a33062d91445c64
[ "Apache-2.0" ]
null
null
null
#include "eventmanager_p.h" #include "cachemanager_p.h" #include "interfacemanager_p.h" #include "client.h" #include "channel.h" #include "connection.h" #include "exception.h" #include "teamspeakevents.h" namespace TeamSpeakSdk { class EventManagerPrivate { public: EventManagerPrivate() { memset(&clientUIFunctions, 0, sizeof(struct ClientUIFunctions)); } ~EventManagerPrivate() { } ClientUIFunctions clientUIFunctions; // ClientUIFunctionsRare clientUIRareFunctions; }; static EventManager* m_instance = Q_NULLPTR; static EventManagerPrivate* d = Q_NULLPTR; EventManager* EventManager::instance() { return m_instance; } EventManager::~EventManager() { m_instance = Q_NULLPTR; delete d;d = Q_NULLPTR; } EventManager::EventManager(QObject* parent) : QObject(parent) { d = new EventManagerPrivate; d->clientUIFunctions.onConnectStatusChangeEvent = onConnectStatusChangeEventWrapper; d->clientUIFunctions.onServerProtocolVersionEvent = onServerProtocolVersionEventWrapper; d->clientUIFunctions.onNewChannelEvent = onNewChannelEventWrapper; d->clientUIFunctions.onNewChannelCreatedEvent = onNewChannelCreatedEventWrapper; d->clientUIFunctions.onDelChannelEvent = onDelChannelEventWrapper; d->clientUIFunctions.onChannelMoveEvent = onChannelMoveEventWrapper; d->clientUIFunctions.onUpdateChannelEvent = onUpdateChannelEventWrapper; d->clientUIFunctions.onUpdateChannelEditedEvent = onUpdateChannelEditedEventWrapper; d->clientUIFunctions.onUpdateClientEvent = onUpdateClientEventWrapper; d->clientUIFunctions.onClientMoveEvent = onClientMoveEventWrapper; d->clientUIFunctions.onClientMoveSubscriptionEvent = onClientMoveSubscriptionEventWrapper; d->clientUIFunctions.onClientMoveTimeoutEvent = onClientMoveTimeoutEventWrapper; d->clientUIFunctions.onClientMoveMovedEvent = onClientMoveMovedEventWrapper; d->clientUIFunctions.onClientKickFromChannelEvent = onClientKickFromChannelEventWrapper; d->clientUIFunctions.onClientKickFromServerEvent = onClientKickFromServerEventWrapper; d->clientUIFunctions.onClientIDsEvent = onClientIDsEventWrapper; d->clientUIFunctions.onClientIDsFinishedEvent = onClientIDsFinishedEventWrapper; d->clientUIFunctions.onServerEditedEvent = onServerEditedEventWrapper; d->clientUIFunctions.onServerUpdatedEvent = onServerUpdatedEventWrapper; d->clientUIFunctions.onServerErrorEvent = onServerErrorEventWrapper; d->clientUIFunctions.onServerStopEvent = onServerStopEventWrapper; d->clientUIFunctions.onTextMessageEvent = onTextMessageEventWrapper; d->clientUIFunctions.onTalkStatusChangeEvent = onTalkStatusChangeEventWrapper; d->clientUIFunctions.onIgnoredWhisperEvent = onIgnoredWhisperEventWrapper; d->clientUIFunctions.onConnectionInfoEvent = onConnectionInfoEventWrapper; d->clientUIFunctions.onServerConnectionInfoEvent = onServerConnectionInfoEventWrapper; d->clientUIFunctions.onChannelSubscribeEvent = onChannelSubscribeEventWrapper; d->clientUIFunctions.onChannelSubscribeFinishedEvent = onChannelSubscribeFinishedEventWrapper; d->clientUIFunctions.onChannelUnsubscribeEvent = onChannelUnsubscribeEventWrapper; d->clientUIFunctions.onChannelUnsubscribeFinishedEvent = onChannelUnsubscribeFinishedEventWrapper; d->clientUIFunctions.onChannelDescriptionUpdateEvent = onChannelDescriptionUpdateEventWrapper; d->clientUIFunctions.onChannelPasswordChangedEvent = onChannelPasswordChangedEventWrapper; d->clientUIFunctions.onPlaybackShutdownCompleteEvent = onPlaybackShutdownCompleteEventWrapper; d->clientUIFunctions.onSoundDeviceListChangedEvent = onSoundDeviceListChangedEventWrapper; d->clientUIFunctions.onEditPlaybackVoiceDataEvent = onEditPlaybackVoiceDataEventWrapper; d->clientUIFunctions.onEditPostProcessVoiceDataEvent = onEditPostProcessVoiceDataEventWrapper; d->clientUIFunctions.onEditMixedPlaybackVoiceDataEvent = onEditMixedPlaybackVoiceDataEventWrapper; d->clientUIFunctions.onEditCapturedVoiceDataEvent = onEditCapturedVoiceDataEventWrapper; d->clientUIFunctions.onCustom3dRolloffCalculationClientEvent = onCustom3dRolloffCalculationClientEventWrapper; d->clientUIFunctions.onCustom3dRolloffCalculationWaveEvent = onCustom3dRolloffCalculationWaveEventWrapper; d->clientUIFunctions.onUserLoggingMessageEvent = onUserLoggingMessageEventWrapper; d->clientUIFunctions.onProvisioningSlotRequestResultEvent = onProvisioningSlotRequestResultEventWrapper; d->clientUIFunctions.onCheckServerUniqueIdentifierEvent = onCheckServerUniqueIdentifierEventWrapper; d->clientUIFunctions.onFileTransferStatusEvent = onFileTransferStatusEventWrapper; d->clientUIFunctions.onFileListEvent = onFileListEventWrapper; d->clientUIFunctions.onFileListFinishedEvent = onFileListFinishedEventWrapper; d->clientUIFunctions.onFileInfoEvent = onFileInfoEventWrapper; d->clientUIFunctions.onCustomPacketEncryptEvent = onCustomPacketEncryptEventWrapper; d->clientUIFunctions.onCustomPacketDecryptEvent = onCustomPacketDecryptEventWrapper; d->clientUIFunctions.onClientPasswordEncrypt = onClientPasswordEncryptEventWrapper; m_instance = this; } ClientUIFunctions* EventManager::clientUIFunctions() { return &d->clientUIFunctions; } ClientUIFunctionsRare* EventManager::clientUIFunctionsRare() { return nullptr; } void EventManager::onConnectStatusChangeEventWrapper(uint64 serverId, int newStatus, uint errorNumber) { auto server = Library::getServer(serverId); auto event = new ConnectStatusChangedEvent; event->newStatus = static_cast<ConnectStatus>(newStatus); event->errorNumber = ReturnCode(errorNumber); QCoreApplication::postEvent(server, event); } void EventManager::onServerProtocolVersionEventWrapper(uint64 serverId, int protocolVersion) { auto server = Library::getServer(serverId); auto event = new ServerProtocolVersionEvent; event->protocolVersion = protocolVersion; QCoreApplication::postEvent(server, event); } void EventManager::onNewChannelEventWrapper(uint64 serverId, uint64 channelID, uint64 channelParentID) { auto server = Library::getServer(serverId); auto event = new NewChannelEvent; event->channel = server->getChannel(channelID); event->channelParent = server->getChannel(channelParentID); QCoreApplication::postEvent(server, event); } void EventManager::onNewChannelCreatedEventWrapper(uint64 serverId, uint64 channelID, uint64 channelParentID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new NewChannelCreatedEvent; event->channel = server->getChannel(channelID); event->channelParent = server->getChannel(channelParentID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onDelChannelEventWrapper(uint64 serverId, uint64 channelID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ChannelDeletedEvent; event->channel = server->getChannel(channelID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onChannelMoveEventWrapper(uint64 serverId, uint64 channelID, uint64 newChannelParentID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ChannelMovedEvent; event->channel = server->getChannel(channelID); event->newChannelParent = server->getChannel(newChannelParentID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onUpdateChannelEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelUpdatedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onUpdateChannelEditedEventWrapper(uint64 serverId, uint64 channelID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ChannelEditedEvent; event->channel = server->getChannel(channelID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onUpdateClientEventWrapper(uint64 serverId, uint16 clientID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ClientUpdatedEvent; event->client = server->getClient(clientID); event->invoker = server->getClient(invokerID); event->invokerName = utils::to_string(invokerName); event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, const char* moveMessage) { auto server = Library::getServer(serverId); auto event = new ClientMovedEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->moveMessage = utils::to_string(moveMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveSubscriptionEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility) { auto server = Library::getServer(serverId); auto event = new SubscriptionClientMovedEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveTimeoutEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, const char* timeoutMessage) { auto server = Library::getServer(serverId); auto event = new ClientMoveTimeoutEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->timeoutMessage = utils::to_string(timeoutMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientMoveMovedEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 moverID, const char* moverName, const char* moverUniqueIdentifier, const char* moveMessage) { auto server = Library::getServer(serverId); auto event = new ClientMoverMovedEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->mover = server->getClient(moverID); event->moverName = utils::to_string(moverName); event->moverUniqueIdentifier = utils::to_string(moverUniqueIdentifier); event->moveMessage = utils::to_string(moveMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientKickFromChannelEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 kickerID, const char* kickerName, const char* kickerUniqueIdentifier, const char* kickMessage) { auto server = Library::getServer(serverId); auto event = new ClientKickFromChannelEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->kicker = server->getClient(kickerID); event->kickerName = utils::to_string(kickerName); event->kickerUniqueIdentifier = utils::to_string(kickerUniqueIdentifier); event->kickMessage = utils::to_string(kickMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientKickFromServerEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 kickerID, const char* kickerName, const char* kickerUniqueIdentifier, const char* kickMessage) { auto server = Library::getServer(serverId); auto event = new ClientKickFromServerEvent; event->client = server->getClient(clientID); event->oldChannel = server->getChannel(oldChannelID); event->newChannel = server->getChannel(newChannelID); event->visibility = static_cast<Visibility>(visibility); event->kicker = server->getClient(kickerID); event->kickerName = utils::to_string(kickerName); event->kickerUniqueIdentifier = utils::to_string(kickerUniqueIdentifier); event->kickMessage = utils::to_string(kickMessage); QCoreApplication::postEvent(server, event); } void EventManager::onClientIDsEventWrapper(uint64 serverId, const char* uniqueClientIdentifier, uint16 clientID, const char* clientName) { auto server = Library::getServer(serverId); auto event = new ClientIDsReceivedEvent; event->client = server->getClient(clientID); event->clientName = utils::to_string(clientName); event->uniqueClientIdentifier = utils::to_string(uniqueClientIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onClientIDsFinishedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ClientIDsFinishedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onServerEditedEventWrapper(uint64 serverId, uint16 editerID, const char* editerName, const char* editerUniqueIdentifier) { auto server = Library::getServer(serverId); auto event = new ServerEditedEvent; event->editer = server->getClient(editerID); event->editerName = utils::to_string(editerName); event->editerUniqueIdentifier = utils::to_string(editerUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onServerUpdatedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ServerUpdatedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onServerErrorEventWrapper(uint64 serverId, const char* errorMessage, uint error, const char* returnCode, const char* extraMessage) { auto server = Library::getServer(serverId); auto event = new ServerErrorEvent; event->error = static_cast<ReturnCode>(error); event->returnCode = utils::to_string(returnCode); event->errorMessage = utils::to_string(errorMessage); event->extraMessage = utils::to_string(extraMessage); QCoreApplication::postEvent(server, event); } void EventManager::onServerStopEventWrapper(uint64 serverId, const char* shutdownMessage) { auto server = Library::getServer(serverId); auto event = new ServerStopEvent; event->shutdownMessage = utils::to_string(shutdownMessage); QCoreApplication::postEvent(server, event); } void EventManager::onTextMessageEventWrapper(uint64 serverId, uint16 targetMode, uint16 toID, uint16 fromID, const char* fromName, const char* fromUniqueIdentifier, const char* message) { auto server = Library::getServer(serverId); auto event = new TextMessageEvent; event->from = server->getClient(fromID); event->targetMode = static_cast<TargetMode>(targetMode); switch (event->targetMode) { case TargetMode::Client: event->to = server->getClient(toID); break; case TargetMode::Channel: case TargetMode::Server: default: event->to = Q_NULLPTR; break; } event->message = utils::to_string(message); event->fromName = utils::to_string(fromName); event->fromUniqueIdentifier = utils::to_string(fromUniqueIdentifier); QCoreApplication::postEvent(server, event); } void EventManager::onTalkStatusChangeEventWrapper(uint64 serverId, int status, int isReceivedWhisper, uint16 clientID) { auto server = Library::getServer(serverId); auto event = new TalkStatusChangeEvent; event->client = server->getClient(clientID); event->status = static_cast<TalkStatus>(status); event->isReceivedWhisper = isReceivedWhisper != 0; QCoreApplication::postEvent(server, event); } void EventManager::onIgnoredWhisperEventWrapper(uint64 serverId, uint16 clientID) { auto server = Library::getServer(serverId); auto event = new WhisperIgnoredEvent; event->client = server->getClient(clientID); QCoreApplication::postEvent(server, event); } void EventManager::onConnectionInfoEventWrapper(uint64 serverId, uint16 clientID) { auto server = Library::getServer(serverId); auto event = new ConnectionInfoEvent; event->client = server->getClient(clientID); QCoreApplication::postEvent(server, event); } void EventManager::onServerConnectionInfoEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ServerConnectionInfoEvent; QCoreApplication::postEvent(server, event); } void EventManager::onChannelSubscribeEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelSubscribedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onChannelSubscribeFinishedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ChannelSubscribesFinishedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onChannelUnsubscribeEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelUnsubscribedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onChannelUnsubscribeFinishedEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new ChannelUnsubscribesFinishedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onChannelDescriptionUpdateEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelDescriptionUpdatedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onChannelPasswordChangedEventWrapper(uint64 serverId, uint64 channelID) { auto server = Library::getServer(serverId); auto event = new ChannelPasswordChangedEvent; event->channel = server->getChannel(channelID); QCoreApplication::postEvent(server, event); } void EventManager::onPlaybackShutdownCompleteEventWrapper(uint64 serverId) { auto server = Library::getServer(serverId); auto event = new PlaybackShutdownCompletedEvent; QCoreApplication::postEvent(server, event); } void EventManager::onSoundDeviceListChangedEventWrapper(const char* modeID, int playOrCap) { auto event = new SoundDeviceListChangedEvent; event->modeID = utils::to_string(modeID); event->playOrCap = playOrCap != 0; QCoreApplication::postEvent(Library::instance(), event); } void EventManager::onUserLoggingMessageEventWrapper(const char* logmessage, int logLevel, const char* logChannel, uint64 logID, const char* logTime, const char* completeLogString) { auto server = Library::getServer(logID); auto event = new UserLoggingMessageEvent; event->logLevel = static_cast<LogLevel>(logLevel); event->logmessage = utils::to_string(logmessage); event->logChannel = utils::to_string(logChannel); event->logTime = utils::to_string(logTime); event->completeLogString = utils::to_string(completeLogString); QCoreApplication::postEvent(Library::instance(), event); } void EventManager::onFileTransferStatusEventWrapper(uint16 transferID, uint status, const char* statusMessage, uint64 remotefileSize, uint64 serverId) { auto server = Library::getServer(serverId); auto event = new FileTransferStatusReceivedEvent; event->transfer = server->getTransfer(transferID); event->status = static_cast<ReturnCode>(status); event->statusMessage = utils::to_string(statusMessage); event->remotefileSize = remotefileSize; QCoreApplication::postEvent(server, event); } void EventManager::onFileListEventWrapper(uint64 serverId, uint64 channelID, const char* path, const char* name, uint64 size, uint64 datetime, int type, uint64 incompletesize, const char* returnCode) { auto server = Library::getServer(serverId); auto event = new FileListReceivedEvent; event->channel = server->getChannel(channelID); event->path = utils::to_string(path); event->name = utils::to_string(name); event->size = size; event->incompletesize = incompletesize; event->type = static_cast<FileListType>(type); event->datetime = utils::to_date_time(datetime); event->returnCode = utils::to_string(returnCode); QCoreApplication::postEvent(server, event); } void EventManager::onFileListFinishedEventWrapper(uint64 serverId, uint64 channelID, const char* path) { auto server = Library::getServer(serverId); auto event = new FileListFinishedEvent; event->channel = server->getChannel(channelID); event->path = utils::to_string(path); QCoreApplication::postEvent(server, event); } void EventManager::onFileInfoEventWrapper(uint64 serverId, uint64 channelID, const char* name, uint64 size, uint64 datetime) { auto server = Library::getServer(serverId); auto event = new FileInfoReceivedEvent; event->channel = server->getChannel(channelID); event->name = utils::to_string(name); event->size = size; event->datetime = utils::to_date_time(datetime); QCoreApplication::postEvent(server, event); } void EventManager::onEditPlaybackVoiceDataEventWrapper(uint64 serverId, uint16 clientID, short* samples, int sampleCount, int channels) { auto handler = Library::editPlaybackVoiceDataHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto client = server->getClient(clientID); auto vector = utils::make_vector<short>(samples, sampleCount); auto result = handler(client, vector, channels); utils::copy_vector(result, samples); } void EventManager::onEditPostProcessVoiceDataEventWrapper( uint64 serverId, uint16 clientID, short* samples, int sampleCount, int channels, const uint* channelSpeakers, uint* channelFillMask) { auto handler = Library::editPostProcessVoiceDataHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto client = server->getClient(clientID); auto vector_samples = utils::make_vector<short>(samples, sampleCount); auto vector_speakers = utils::make_vector<Speakers>(channelSpeakers, channels); auto result = handler(client, vector_samples, vector_speakers, (Speakers*)channelFillMask); if (0 != *channelFillMask) utils::copy_vector(result, samples); } void EventManager::onEditMixedPlaybackVoiceDataEventWrapper( uint64 serverId, short* samples, int sampleCount, int channels, const uint* channelSpeakers, uint* channelFillMask) { auto handler = Library::editMixedPlaybackVoiceDataHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto vector_samples = utils::make_vector<short>(samples, sampleCount * channels); auto vector_speakers = utils::make_vector<Speakers>(channelSpeakers, channels); auto result = handler(server, vector_samples, vector_speakers, (Speakers*)channelFillMask); if (0 != *channelFillMask) utils::copy_vector(result, samples); } void EventManager::onEditCapturedVoiceDataEventWrapper(uint64 serverId, short* samples, int sampleCount, int channels, int* bytes) { auto handler = Library::editCapturedVoiceDataHandler(); if (!handler) return; // TODO: handler call bool edited = (*bytes & 1) == 1; bool cancel = (*bytes & 2) == 0; auto server = Library::getServer(serverId); auto vector_samples = utils::make_vector<short>(samples, sampleCount); auto result = handler(server, vector_samples, channels, edited, cancel); if (edited && cancel == false) utils::copy_vector(result, samples); *bytes = (edited ? 1 : 0) | (cancel ? 0 : 2); } void EventManager::onCustom3dRolloffCalculationClientEventWrapper(uint64 serverId, uint16 clientID, float distance, float* volume) { auto handler = Library::custom3dRolloffCalculationClientHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto client = server->getClient(clientID); handler(client, distance, volume); } void EventManager::onCustom3dRolloffCalculationWaveEventWrapper(uint64 serverId, uint64 waveHandle, float distance, float* volume) { auto handler = Library::custom3dRolloffCalculationWaveHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto wave = server->getWaveHandle(waveHandle); handler(wave, distance, volume); } void EventManager::onProvisioningSlotRequestResultEventWrapper( uint error, uint64 requestHandle, const char* connectionKey) { auto key = utils::to_string(connectionKey); } void EventManager::onCheckServerUniqueIdentifierEventWrapper(uint64 serverId, const char* serverUniqueIdentifier, int* cancelConnect) { auto handler = Library::checkUniqueIdentifierHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto uniqueIdentifier = utils::to_string(serverUniqueIdentifier); auto result = handler(server, uniqueIdentifier); *cancelConnect = result; } #define CUSTOM_CRYPT_KEY 123 void EventManager::onCustomPacketEncryptEventWrapper(char** dataToSend, uint* sizeOfData) { auto handler = Library::customPacketEncryptHandler(); if (!handler) { #if defined(CUSTOM_CRYPT_KEY) for (uint i = 0; i < *sizeOfData; ++i) { (*dataToSend)[i] ^= CUSTOM_CRYPT_KEY; } #endif } else { // TODO: handler call } } void EventManager::onCustomPacketDecryptEventWrapper(char** dataReceived, uint* dataReceivedSize) { auto handler = Library::customPacketDecryptHandler(); if (!handler) { #if defined(CUSTOM_CRYPT_KEY) for (uint i = 0; i < *dataReceivedSize; ++i) { (*dataReceived)[i] ^= CUSTOM_CRYPT_KEY; } #endif } else { // TODO: handler call } } void EventManager::onClientPasswordEncryptEventWrapper(uint64 serverId, const char* plaintext, char* encryptedText, int encryptedTextByteSize) { auto handler = Library::clientPasswordEncryptHandler(); if (!handler) return; // TODO: handler call auto server = Library::getServer(serverId); auto text = utils::to_byte(plaintext); auto result = handler(server, text, encryptedTextByteSize - 1); ::memcpy(encryptedText, result.data(), result.size()); } void __init_event_manager() { (void) new EventManager(qApp); } Q_COREAPP_STARTUP_FUNCTION(__init_event_manager) } // namespace TeamSpeakSdk
42.254597
248
0.726451
faming-wang
d766a0318ae5854a75c375505dcd6f0932a806d9
1,182
cpp
C++
Codechef/chefchal.cpp
ujjwalgulecha/Coding
d04c19d8f673749a00c85cd5e8935960fb7e8b16
[ "MIT" ]
null
null
null
Codechef/chefchal.cpp
ujjwalgulecha/Coding
d04c19d8f673749a00c85cd5e8935960fb7e8b16
[ "MIT" ]
1
2018-02-14T16:00:44.000Z
2021-10-17T16:32:50.000Z
Codechef/chefchal.cpp
ujjwalgulecha/Coding
d04c19d8f673749a00c85cd5e8935960fb7e8b16
[ "MIT" ]
null
null
null
<<<<<<< HEAD #include<iostream> using namespace std; int main() { int a[100001],i,j,n; cin>>n;int ct=0; int flag[100001]={0}; for(i=0;i<n;i++) cin>>a[i]; for(i=1;i<n;i++) { if(flag[i]==0&&((a[i+1]-a[i])!=(a[i]-a[i-1]))||flag[i-1]==-1) { ct++; flag[i]=1; } else flag[i]=-1; } cout<<ct<<endl; for(j=0;j<n;j++) { if(flag[i])cout<<a[i]<<" "; } cout<<endl; return 0; } ======= #include<iostream> using namespace std; int main() { int a[100001],i,j,n; cin>>n;int ct=0; int flag[100001]={0}; for(i=0;i<n;i++) cin>>a[i]; for(i=1;i<n;i++) { if(flag[i]==0&&((a[i+1]-a[i])!=(a[i]-a[i-1]))||flag[i-1]==-1) { ct++; flag[i]=1; } else flag[i]=-1; } cout<<ct<<endl; for(j=0;j<n;j++) { if(flag[i])cout<<a[i]<<" "; } cout<<endl; return 0; } >>>>>>> efd4245fe427ffeefe49c72470b81a015d8dcf82
20.37931
73
0.351946
ujjwalgulecha
d76945ee00b8639a631774d8377a1473c992a5f6
314
cpp
C++
code/client/src/sdk/ue/sys/core/i_core.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
16
2021-10-08T17:47:04.000Z
2022-03-28T13:26:37.000Z
code/client/src/sdk/ue/sys/core/i_core.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2022-01-19T08:11:57.000Z
2022-01-29T19:02:24.000Z
code/client/src/sdk/ue/sys/core/i_core.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2021-10-09T11:15:08.000Z
2022-01-27T22:42:26.000Z
#include "i_core.h" #include "../../../patterns.h" #include <utils/hooking/hooking.h> namespace SDK { namespace ue::sys::core { C_Core *I_Core::GetInstance() { return hook::this_call<C_Core *>(gPatterns.I_Core__GetInstance); } } // namespace ue::sys::core } // namespace SDK
22.428571
76
0.61465
mufty
d76a3f4b3a02f77886bcb78b79c0e41808f40084
372
cpp
C++
chapters/3/3-40.cpp
Raymain1944/CPPLv1
96e5fd5347a336870fc868206ebfe44f88ce69eb
[ "Apache-2.0" ]
null
null
null
chapters/3/3-40.cpp
Raymain1944/CPPLv1
96e5fd5347a336870fc868206ebfe44f88ce69eb
[ "Apache-2.0" ]
null
null
null
chapters/3/3-40.cpp
Raymain1944/CPPLv1
96e5fd5347a336870fc868206ebfe44f88ce69eb
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstring> using std::cin; using std::cout; using std::endl; using std::cerr; using std::begin; using std::end; using std::strcmp; using std::strcpy; using std::strcat; int main() { const char a[] = "A test"; const char b[] = "about it"; char c[16]; strcpy(c, a); strcat(c, " "); strcat(c, b); cout << c << endl; }
21.882353
66
0.591398
Raymain1944
d76e2eafafe42cf341cc63b6100c6b6c250e3bae
1,122
hxx
C++
opencascade/Prs3d_DatumAttribute.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Prs3d_DatumAttribute.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/Prs3d_DatumAttribute.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Copyright (c) 2016 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Prs3d_DatumAttribute_HeaderFile #define _Prs3d_DatumAttribute_HeaderFile //! Enumeration defining a part of datum aspect, see Prs3d_Datum. enum Prs3d_DatumAttribute { Prs3d_DA_XAxisLength = 0, Prs3d_DA_YAxisLength, Prs3d_DA_ZAxisLength, Prs3d_DP_ShadingTubeRadiusPercent, Prs3d_DP_ShadingConeRadiusPercent, Prs3d_DP_ShadingConeLengthPercent, Prs3d_DP_ShadingOriginRadiusPercent, Prs3d_DP_ShadingNumberOfFacettes }; #endif // _Prs3d_DatumAttribute_HeaderFile
36.193548
81
0.811943
valgur
d772d7f0302d2b76fc471771253741f96497c7ae
4,732
cpp
C++
MSP2007/TaskBaseline_C.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
MSP2007/TaskBaseline_C.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
MSP2007/TaskBaseline_C.cpp
jluzardo1971/ActiveGanttVC
4748cb4d942551dc64c9017f279c90969cdcc634
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------------------- // COPYRIGHT NOTICE // ---------------------------------------------------------------------------------------- // // The Source Code Store LLC // ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC // ActiveX Control // Copyright (c) 2002-2017 The Source Code Store LLC // // All Rights Reserved. No parts of this file may be reproduced, modified or transmitted // in any form or by any means without the written permission of the author. // // ---------------------------------------------------------------------------------------- #include "stdafx.h" #include "clsXML.h" #include "TaskBaseline_C.h" IMPLEMENT_DYNCREATE(TaskBaseline_C, CCmdTarget) //{5A5680D4-68DB-421F-972C-16C1C2B35985} static const IID IID_ITaskBaseline_C = { 0x5A5680D4, 0x68DB, 0x421F, { 0x97, 0x2C, 0x16, 0xC1, 0xC2, 0xB3, 0x59, 0x85} }; //{C8E849CD-4B77-47AF-97E1-56281F8FB6F1} IMPLEMENT_OLECREATE_FLAGS(TaskBaseline_C, "MSP2007.TaskBaseline_C", afxRegApartmentThreading, 0xC8E849CD, 0x4B77, 0x47AF, 0x97, 0xE1, 0x56, 0x28, 0x1F, 0x8F, 0xB6, 0xF1) BEGIN_DISPATCH_MAP(TaskBaseline_C, CCmdTarget) DISP_PROPERTY_EX_ID(TaskBaseline_C, "Count", 1, odl_GetCount, SetNotSupported, VT_I4) DISP_PROPERTY_PARAM_ID(TaskBaseline_C, "Item", 2, odl_Item, SetNotSupported, VT_DISPATCH, VTS_BSTR) DISP_FUNCTION_ID(TaskBaseline_C, "Add", 3, odl_Add, VT_DISPATCH, VTS_NONE) DISP_FUNCTION_ID(TaskBaseline_C, "Clear", 4, odl_Clear, VT_EMPTY, VTS_NONE) DISP_FUNCTION_ID(TaskBaseline_C, "Remove", 5, odl_Remove, VT_EMPTY, VTS_BSTR) DISP_FUNCTION_ID(TaskBaseline_C, "IsNull", 6, IsNull, VT_BOOL, VTS_NONE) DISP_FUNCTION_ID(TaskBaseline_C, "Initialize", 7, Initialize, VT_EMPTY, VTS_NONE) DISP_DEFVALUE(TaskBaseline_C, "Item") END_DISPATCH_MAP() BEGIN_INTERFACE_MAP(TaskBaseline_C, CCmdTarget) INTERFACE_PART(TaskBaseline_C, IID_ITaskBaseline_C, Dispatch) END_INTERFACE_MAP() BEGIN_MESSAGE_MAP(TaskBaseline_C, CCmdTarget) END_MESSAGE_MAP() TaskBaseline_C::TaskBaseline_C() { EnableAutomation(); AfxOleLockApp(); InitVars(); } void TaskBaseline_C::Initialize(void) { InitVars(); } void TaskBaseline_C::InitVars(void) { mp_oCollection = new clsCollectionBase("TaskBaseline"); } TaskBaseline_C::~TaskBaseline_C() { delete mp_oCollection; AfxOleUnlockApp(); } void TaskBaseline_C::OnFinalRelease() { CCmdTarget::OnFinalRelease(); } LONG TaskBaseline_C::odl_GetCount(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return GetCount(); } LONG TaskBaseline_C::GetCount(void) { return mp_oCollection->m_lCount(); } IDispatch* TaskBaseline_C::odl_Item(LPCTSTR Index) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return Item(Index)->GetIDispatch(TRUE); } IDispatch* TaskBaseline_C::odl_Add(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return Add()->GetIDispatch(TRUE); } void TaskBaseline_C::odl_Clear(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); Clear(); } void TaskBaseline_C::odl_Remove(LPCTSTR Index) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); Remove(Index); } BOOL TaskBaseline_C::IsNull(void) { BOOL bReturn = TRUE; if (GetCount() > 0) { bReturn = FALSE; } return bReturn; } TaskBaseline* TaskBaseline_C::Item(CString Index) { TaskBaseline *oTaskBaseline; oTaskBaseline = (TaskBaseline*)mp_oCollection->m_oItem(Index, MP_ITEM_1, MP_ITEM_2, MP_ITEM_3, MP_ITEM_4); return oTaskBaseline; } TaskBaseline* TaskBaseline_C::Add() { mp_oCollection->SetAddMode(TRUE); TaskBaseline* oTaskBaseline = new TaskBaseline(); oTaskBaseline->mp_oCollection = mp_oCollection; mp_oCollection->m_Add(oTaskBaseline, _T(""), MP_ADD_1, MP_ADD_2, FALSE, MP_ADD_3); return oTaskBaseline; } void TaskBaseline_C::Clear(void) { mp_oCollection->m_Clear(); } void TaskBaseline_C::Remove(CString Index) { mp_oCollection->m_Remove(Index, MP_REMOVE_1, MP_REMOVE_2, MP_REMOVE_3, MP_REMOVE_4); } void TaskBaseline_C::ReadObjectProtected(clsXML &oXML) { LONG lIndex; for (lIndex = 1; lIndex <= oXML.ReadCollectionCount(); lIndex++) { if (oXML.GetCollectionObjectName(lIndex) == "Baseline") { TaskBaseline* oTaskBaseline = new TaskBaseline(); oTaskBaseline->SetXML(oXML.ReadCollectionObject(lIndex)); mp_oCollection->SetAddMode(TRUE); CString sKey = _T(""); oTaskBaseline->mp_oCollection = mp_oCollection; mp_oCollection->m_Add(oTaskBaseline, sKey, MP_ADD_1, MP_ADD_2, FALSE, MP_ADD_3); } } } void TaskBaseline_C::WriteObjectProtected(clsXML &oXML) { LONG lIndex; TaskBaseline* oTaskBaseline; for (lIndex = 1; lIndex <= GetCount(); lIndex++) { oTaskBaseline = (TaskBaseline*) mp_oCollection->m_oReturnArrayElement(lIndex); oXML.WriteObject(oTaskBaseline->GetXML()); } }
27.835294
169
0.720837
jluzardo1971
d772e4b3b4ca79c133cdc841b9364964ecb9e5d8
2,609
cpp
C++
orbsvcs/Event/EC_Masked_Type_Filter.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
orbsvcs/Event/EC_Masked_Type_Filter.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
orbsvcs/Event/EC_Masked_Type_Filter.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
// $Id: EC_Masked_Type_Filter.cpp 1861 2011-08-31 16:18:08Z mesnierp $ #include "orbsvcs/Event/EC_Masked_Type_Filter.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_EC_Masked_Type_Filter:: TAO_EC_Masked_Type_Filter (CORBA::ULong source_mask, CORBA::ULong type_mask, CORBA::ULong source_value, CORBA::ULong type_value) : source_mask_ (source_mask), type_mask_ (type_mask), source_value_ (source_value), type_value_ (type_value) { } TAO_EC_Masked_Type_Filter::~TAO_EC_Masked_Type_Filter (void) { } TAO_EC_Filter::ChildrenIterator TAO_EC_Masked_Type_Filter::begin (void) const { return 0; } TAO_EC_Filter::ChildrenIterator TAO_EC_Masked_Type_Filter::end (void) const { return 0; } int TAO_EC_Masked_Type_Filter::size (void) const { return 0; } int TAO_EC_Masked_Type_Filter::filter (const RtecEventComm::EventSet& event, TAO_EC_QOS_Info& qos_info) { if (event.length () != 1) return 0; if ((event[0].header.type & this->type_mask_) != this->type_value_ || (event[0].header.source & this->source_mask_) != this->source_value_) return 0; if (this->parent () != 0) { this->parent ()->push (event, qos_info); } return 1; } int TAO_EC_Masked_Type_Filter::filter_nocopy (RtecEventComm::EventSet& event, TAO_EC_QOS_Info& qos_info) { if (event.length () != 1) return 0; if ((event[0].header.type & this->type_mask_) != this->type_value_ || (event[0].header.source & this->source_mask_) != this->source_value_) return 0; if (this->parent () != 0) { this->parent ()->push_nocopy (event, qos_info); } return 1; } void TAO_EC_Masked_Type_Filter::push (const RtecEventComm::EventSet &, TAO_EC_QOS_Info &) { } void TAO_EC_Masked_Type_Filter::push_nocopy (RtecEventComm::EventSet &, TAO_EC_QOS_Info &) { } void TAO_EC_Masked_Type_Filter::clear (void) { } CORBA::ULong TAO_EC_Masked_Type_Filter::max_event_size (void) const { return 1; } int TAO_EC_Masked_Type_Filter::can_match ( const RtecEventComm::EventHeader& header) const { if ((header.type & this->type_mask_) == this->type_value_ && (header.source & this->source_mask_) == this->source_value_) return 1; return 0; } int TAO_EC_Masked_Type_Filter::add_dependencies ( const RtecEventComm::EventHeader&, const TAO_EC_QOS_Info &) { return 0; } TAO_END_VERSIONED_NAMESPACE_DECL
21.385246
78
0.648141
binary42
d773f76cdfc1d99ccae3c7e81390fb8b6e73a662
5,899
cpp
C++
test_conformance/commonfns/test_mix.cpp
kbenzie/OpenCL-CTS
efaf0240350419b701b028f281690258e38cf71c
[ "Apache-2.0" ]
1
2020-08-11T11:53:04.000Z
2020-08-11T11:53:04.000Z
test_conformance/commonfns/test_mix.cpp
kbenzie/OpenCL-CTS
efaf0240350419b701b028f281690258e38cf71c
[ "Apache-2.0" ]
3
2020-03-25T07:42:27.000Z
2020-04-02T13:23:42.000Z
test_conformance/commonfns/test_mix.cpp
kbenzie/OpenCL-CTS
efaf0240350419b701b028f281690258e38cf71c
[ "Apache-2.0" ]
1
2020-03-24T10:50:01.000Z
2020-03-24T10:50:01.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. // #include "harness/compat.h" #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "procs.h" const char *mix_kernel_code = "__kernel void test_mix(__global float *srcA, __global float *srcB, __global float *srcC, __global float *dst)\n" "{\n" " int tid = get_global_id(0);\n" "\n" " dst[tid] = mix(srcA[tid], srcB[tid], srcC[tid]);\n" "}\n"; #define MAX_ERR 1e-3 float verify_mix(float *inptrA, float *inptrB, float *inptrC, float *outptr, int n) { float r, delta, max_err = 0.0f; int i; for (i=0; i<n; i++) { r = inptrA[i] + ((inptrB[i] - inptrA[i]) * inptrC[i]); delta = fabsf(r - outptr[i]) / r; if(delta > max_err) max_err = delta; } return max_err; } int test_mix(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements) { cl_mem streams[4]; cl_float *input_ptr[3], *output_ptr, *p; cl_program program; cl_kernel kernel; void *values[4]; size_t lengths[1]; size_t threads[1]; float max_err; int err; int i; MTdata d; input_ptr[0] = (cl_float*)malloc(sizeof(cl_float) * num_elements); input_ptr[1] = (cl_float*)malloc(sizeof(cl_float) * num_elements); input_ptr[2] = (cl_float*)malloc(sizeof(cl_float) * num_elements); output_ptr = (cl_float*)malloc(sizeof(cl_float) * num_elements); streams[0] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[0]) { log_error("clCreateBuffer failed\n"); return -1; } streams[1] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[1]) { log_error("clCreateBuffer failed\n"); return -1; } streams[2] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[2]) { log_error("clCreateBuffer failed\n"); return -1; } streams[3] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[3]) { log_error("clCreateBuffer failed\n"); return -1; } p = input_ptr[0]; d = init_genrand( gRandomSeed ); for (i=0; i<num_elements; i++) { p[i] = (float) genrand_real1(d); } p = input_ptr[1]; for (i=0; i<num_elements; i++) { p[i] = (float) genrand_real1(d); } p = input_ptr[2]; for (i=0; i<num_elements; i++) { p[i] = (float) genrand_real1(d); } free_mtdata(d); d = NULL; err = clEnqueueWriteBuffer( queue, streams[0], true, 0, sizeof(cl_float)*num_elements, (void *)input_ptr[0], 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clWriteArray failed\n"); return -1; } err = clEnqueueWriteBuffer( queue, streams[1], true, 0, sizeof(cl_float)*num_elements, (void *)input_ptr[1], 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clWriteArray failed\n"); return -1; } err = clEnqueueWriteBuffer( queue, streams[2], true, 0, sizeof(cl_float)*num_elements, (void *)input_ptr[2], 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clWriteArray failed\n"); return -1; } lengths[0] = strlen(mix_kernel_code); err = create_single_kernel_helper( context, &program, &kernel, 1, &mix_kernel_code, "test_mix" ); test_error( err, "Unable to create test kernel" ); values[0] = streams[0]; values[1] = streams[1]; values[2] = streams[2]; values[3] = streams[3]; err = clSetKernelArg(kernel, 0, sizeof streams[0], &streams[0] ); err |= clSetKernelArg(kernel, 1, sizeof streams[1], &streams[1] ); err |= clSetKernelArg(kernel, 2, sizeof streams[2], &streams[2] ); err |= clSetKernelArg(kernel, 3, sizeof streams[3], &streams[3] ); if (err != CL_SUCCESS) { log_error("clSetKernelArgs failed\n"); return -1; } threads[0] = (size_t)num_elements; err = clEnqueueNDRangeKernel( queue, kernel, 1, NULL, threads, NULL, 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clEnqueueNDRangeKernel failed\n"); return -1; } err = clEnqueueReadBuffer( queue, streams[3], true, 0, sizeof(cl_float)*num_elements, (void *)output_ptr, 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clEnqueueReadBuffer failed\n"); return -1; } max_err = verify_mix(input_ptr[0], input_ptr[1], input_ptr[2], output_ptr, num_elements); if (max_err > MAX_ERR) { log_error("MIX test failed %g max err\n", max_err); err = -1; } else { log_info("MIX test passed %g max err\n", max_err); err = 0; } clReleaseMemObject(streams[0]); clReleaseMemObject(streams[1]); clReleaseMemObject(streams[2]); clReleaseMemObject(streams[3]); clReleaseKernel(kernel); clReleaseProgram(program); free(input_ptr[0]); free(input_ptr[1]); free(input_ptr[2]); free(output_ptr); return err; }
30.096939
129
0.612646
kbenzie
d7744a654c01ba213de2bc532a8a412b02565e64
2,349
cpp
C++
src/C/Security-57031.40.6/Security/libsecurity_cdsa_client/lib/signclient.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/Security-57031.40.6/Security/libsecurity_cdsa_client/lib/signclient.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/Security-57031.40.6/Security/libsecurity_cdsa_client/lib/signclient.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. * * The contents of this file constitute Original Code as defined in and are * subject to the Apple Public Source License Version 1.2 (the 'License'). * You may not use this file except in compliance with the License. Please obtain * a copy of the License at http://www.apple.com/publicsource and read it before * using this file. * * This Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the * specific language governing rights and limitations under the License. */ // // signclient - client interface to CSSM sign/verify contexts // #include <security_cdsa_client/signclient.h> using namespace CssmClient; // // Common features of signing and verify contexts // void SigningContext::activate() { StLock<Mutex> _(mActivateMutex); if (!mActive) { check(CSSM_CSP_CreateSignatureContext(attachment()->handle(), mAlgorithm, cred(), mKey, &mHandle)); mActive = true; } } // // Signing // void Sign::sign(const CssmData *data, uint32 count, CssmData &signature) { unstaged(); check(CSSM_SignData(handle(), data, count, mSignOnly, &signature)); } void Sign::init() { check(CSSM_SignDataInit(handle())); mStaged = true; } void Sign::sign(const CssmData *data, uint32 count) { staged(); check(CSSM_SignDataUpdate(handle(), data, count)); } void Sign::operator () (CssmData &signature) { staged(); check(CSSM_SignDataFinal(handle(), &signature)); mStaged = false; } // // Verifying // void Verify::verify(const CssmData *data, uint32 count, const CssmData &signature) { unstaged(); check(CSSM_VerifyData(handle(), data, count, mSignOnly, &signature)); } void Verify::init() { check(CSSM_VerifyDataInit(handle())); mStaged = true; } void Verify::verify(const CssmData *data, uint32 count) { staged(); check(CSSM_VerifyDataUpdate(handle(), data, count)); } void Verify::operator () (const CssmData &signature) { staged(); check(CSSM_VerifyDataFinal(handle(), &signature)); mStaged = false; }
23.969388
82
0.725841
GaloisInc
d77648414a09632cd2856262e6251f30469035f6
2,172
hpp
C++
lib/appbase/common/ChatterinoSetting.hpp
holysnipz/chatterino2
230ade2d1b8eb8b1cb1e0aba6eb3994c498bf7a8
[ "MIT" ]
null
null
null
lib/appbase/common/ChatterinoSetting.hpp
holysnipz/chatterino2
230ade2d1b8eb8b1cb1e0aba6eb3994c498bf7a8
[ "MIT" ]
null
null
null
lib/appbase/common/ChatterinoSetting.hpp
holysnipz/chatterino2
230ade2d1b8eb8b1cb1e0aba6eb3994c498bf7a8
[ "MIT" ]
null
null
null
#pragma once #include <QString> #include <pajlada/settings.hpp> namespace AB_NAMESPACE { void _registerSetting(std::weak_ptr<pajlada::Settings::SettingData> setting); template <typename Type> class ChatterinoSetting : public pajlada::Settings::Setting<Type> { public: ChatterinoSetting(const std::string &path) : pajlada::Settings::Setting<Type>(path) { _registerSetting(this->getData()); } ChatterinoSetting(const std::string &path, const Type &defaultValue) : pajlada::Settings::Setting<Type>(path, defaultValue) { _registerSetting(this->getData()); } template <typename T2> ChatterinoSetting &operator=(const T2 &newValue) { this->setValue(newValue); return *this; } ChatterinoSetting &operator=(Type &&newValue) noexcept { pajlada::Settings::Setting<Type>::operator=(newValue); return *this; } using pajlada::Settings::Setting<Type>::operator==; using pajlada::Settings::Setting<Type>::operator!=; using pajlada::Settings::Setting<Type>::operator Type; }; using BoolSetting = ChatterinoSetting<bool>; using FloatSetting = ChatterinoSetting<float>; using DoubleSetting = ChatterinoSetting<double>; using IntSetting = ChatterinoSetting<int>; using StringSetting = ChatterinoSetting<std::string>; using QStringSetting = ChatterinoSetting<QString>; template <typename Enum> class EnumSetting : public ChatterinoSetting<typename std::underlying_type<Enum>::type> { using Underlying = typename std::underlying_type<Enum>::type; public: using ChatterinoSetting<Underlying>::ChatterinoSetting; EnumSetting(const std::string &path, const Enum &defaultValue) : ChatterinoSetting<Underlying>(path, Underlying(defaultValue)) { _registerSetting(this->getData()); } template <typename T2> EnumSetting<Enum> &operator=(Enum newValue) { this->setValue(Underlying(newValue)); return *this; } operator Enum() { return Enum(this->getValue()); } Enum getEnum() { return Enum(this->getValue()); } }; } // namespace AB_NAMESPACE
24.404494
77
0.683241
holysnipz
d77761ec69c113779be974a469d59945e8e4b24c
77,846
hh
C++
src/mesh/Mesh.hh
jloveric/jali
635d46983acb66c824fabb0947803f5787356dc9
[ "BSD-3-Clause" ]
null
null
null
src/mesh/Mesh.hh
jloveric/jali
635d46983acb66c824fabb0947803f5787356dc9
[ "BSD-3-Clause" ]
null
null
null
src/mesh/Mesh.hh
jloveric/jali
635d46983acb66c824fabb0947803f5787356dc9
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2019, Triad National Security, LLC All rights reserved. Copyright 2019. Triad National Security, LLC. This software was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy. All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so This is open source software distributed under the 3-clause BSD license. 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 Triad National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, 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 TRIAD NATIONAL SECURITY, LLC 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 TRIAD NATIONAL SECURITY, LLC 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. */ #ifndef _JALIMESH_H_ #define _JALIMESH_H_ #include <mpi.h> #include <memory> #include <vector> #include <array> #include <string> #include <algorithm> #include <cassert> #include <typeinfo> #include "MeshDefs.hh" #include "Point.hh" #include "GeometricModel.hh" #include "Region.hh" #include "LabeledSetRegion.hh" #include "Geometry.hh" #include "MeshTile.hh" #include "MeshSet.hh" #define JALI_CACHE_VARS 1 // Switch to 0 to turn caching off //! \mainpage Jali //! //! Jali is a parallel unstructured mesh infrastructure library for //! multiphysics applications. It simplifies the process of importing, //! querying, manipulating and exporting unstructured mesh information //! for physics and numerical methods developers. Jali is capable of //! representing arbitrarily complex polytopal meshes in 2D and 3D. It //! can answer topological queries about cells, faces, edges and nodes //! as well subcell entities called corners and wedges //! (iotas). Additionally, Jali can answer geometric queries about the //! entities it supports. It can handle distributed meshes scalably //! upto thousands of processors. Jali is built upon the open source //! unstructured mesh infrastructure library, MSTK, developed at Los //! Alamos National Laboratory since 2004 or the built-in regular mesh //! infrastructure class called Simple mesh. //! //! In addition, to the mesh representation, the Jali library also //! includes a rudimentary geometric model representation consisting of //! simple geometric regions. Geometric regions are used to create mesh //! sets (sets of cells, sets of faces, etc.) for specification of //! material properties, boundary conditions and initial conditions. //! //! Finally, the Jali library contains a simple state manager for //! storing and retrieving field data on mesh entities. Currently, the //! state manager does not have any capability to synchronize data //! across processors. //! //! The main classes of relevance to developers in the Jali package are: //! - Jali::Mesh in file Mesh.hh //! - Jali::MeshFactory in file MeshFactory.hh //! - Jali::State in file JaliState.h //! - JaliGeometry::GeometricModel in file GeometricModel.hh //! . // RegionFactory will get included once we decide on a way to read XML // input files and generate parameter lists // - JaliGeometry::RegionFactory in file RegionFactory.hh namespace Jali { //! \class Mesh.hh //! \brief Base mesh class //! //! Use the associated mesh factory to create an instance of a //! derived class based on a particular mesh framework (like MSTK, //! STKmesh etc.) //! //! **** IMPORTANT NOTE ABOUT CONSTANTNESS OF THIS CLASS **** //! Instantiating a const version of this class only guarantees that //! the underlying mesh topology and geometry does not change (the //! public interfaces conforms strictly to this definition). However, //! for purposes of memory savings we use lazy initialization and //! caching of face data, edge data, geometry quantities, columns //! etc., which means that these data may still change. We also //! cannot initialize the cached quantities in the constructor since //! they depend on initialization of data structures in the derived //! class - however, the base class gets constructed before the //! derived class gets constructed so it is not possible without more //! obscure acrobatics. This is why some of the caching data //! declarations are declared with the keyword 'mutable' and routines //! that modify the mutable data are declared with a constant //! qualifier. //! class Mesh { public: //! \brief constructor //! //! constructor - cannot call directly. Code must set mesh framework //! preference to one of the available mesh frameworks (MSTK or Simple) //! and call the mesh_factory to make a mesh. If it is absolutely //! necessary, one can call the constructor of one of the available //! mesh frameworks directly Mesh(const bool request_faces = true, const bool request_edges = false, const bool request_sides = false, const bool request_wedges = false, const bool request_corners = false, const int num_tiles_ini = 0, const int num_ghost_layers_tile = 0, const int num_ghost_layers_distmesh = 1, const bool request_boundary_ghosts = false, const Partitioner_type partitioner = Partitioner_type::METIS, const JaliGeometry::Geom_type geom_type = JaliGeometry::Geom_type::CARTESIAN, const MPI_Comm incomm = MPI_COMM_WORLD) : space_dim_(3), manifold_dim_(3), mesh_type_(Mesh_type::GENERAL), cell_geometry_precomputed(false), face_geometry_precomputed(false), edge_geometry_precomputed(false), side_geometry_precomputed(false), corner_geometry_precomputed(false), faces_requested(request_faces), edges_requested(request_edges), sides_requested(request_sides), wedges_requested(request_wedges), corners_requested(request_corners), num_tiles_ini_(num_tiles_ini), num_ghost_layers_tile_(num_ghost_layers_tile), num_ghost_layers_distmesh_(num_ghost_layers_distmesh), boundary_ghosts_requested_(request_boundary_ghosts), partitioner_pref_(partitioner), cell2face_info_cached(false), face2cell_info_cached(false), cell2edge_info_cached(false), face2edge_info_cached(false), side_info_cached(false), wedge_info_cached(false), corner_info_cached(false), type_info_cached(false), geometric_model_(NULL), comm(incomm), geomtype(geom_type) { if (corners_requested) // corners are defined in terms of wedges wedges_requested = true; if (wedges_requested) // wedges are defined in terms of sides sides_requested = true; if (sides_requested) { faces_requested = true; edges_requested = true; } } //! destructor //! //! destructor - must be virtual to downcast base class to derived class //! (I don't understand why but the stackoverflow prophets say so) virtual ~Mesh() {} //! MPI communicator being used inline MPI_Comm get_comm() const { return comm; } // Geometric type for the mesh - CARTESIAN, CYLINDRICAL, or SPHERICAL inline JaliGeometry::Geom_type geom_type() const { return geomtype; } //! Set/get the space dimension of points //! often invoked by the constructor of a derived mesh class void set_space_dimension(const unsigned int dim) { space_dim_ = dim; } unsigned int space_dimension() const { return space_dim_; } //! Set/get the manifold dimension - //! often invoked by the constructor of a derived mesh class void set_manifold_dimension(const unsigned int dim) { manifold_dim_ = dim; // 3 is solid mesh, 2 is surface mesh, 1 is wire mesh } unsigned int manifold_dimension() const { return manifold_dim_; } //! Set the pointer to a geometric model underpinning the mesh //! Typically, set by the constructor of a derived mesh class inline void set_geometric_model(const JaliGeometry::GeometricModelPtr &gm) { geometric_model_ = gm; } //! Return a pointer to a geometric model underpinning the mesh The //! geometric model consists of regions that are used to define mesh //! sets inline JaliGeometry::GeometricModelPtr geometric_model() const { return geometric_model_; } //! Set mesh type - Mesh_type::RECTANGULAR or Mesh_type::GENERAL inline void set_mesh_type(const Mesh_type mesh_type) { mesh_type_ = mesh_type; } //! Get mesh type - Mesh_type::RECTANGULAR or Mesh_type::GENERAL inline Mesh_type mesh_type() const { return mesh_type_; } //! Get type of entity - PARALLEL_OWNED, PARALLEL_GHOST, BOUNDARY_GHOST Entity_type entity_get_type(const Entity_kind kind, const Entity_ID entid) const; //! Parent entity in the source mesh if mesh was derived from another mesh virtual Entity_ID entity_get_parent(const Entity_kind kind, const Entity_ID entid) const; //! Get cell type - UNKNOWN, TRI, QUAD, POLYGON, TET, PRISM, PYRAMID, HEX, //! POLYHED //! See MeshDefs.hh virtual Cell_type cell_get_type(const Entity_ID cellid) const = 0; // // General mesh information // ------------------------- // //! Number of entities of any kind (cell, face, node) and in a //! particular category (PARALLEL_OWNED, PARALLEL_GHOST, ALL) unsigned int num_entities(const Entity_kind kind, const Entity_type type) const; //! Number of nodes of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_nodes() const; //! Number of edges of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_edges() const; //! Number of faces of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_faces() const; //! Number of sides of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_sides() const; //! Number of wedges of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_wedges() const; //! Number of corners of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_corners() const; //! Number of cells of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_cells() const; //! Global ID of any entity virtual Entity_ID GID(const Entity_ID lid, const Entity_kind kind) const = 0; //! List of references to mesh tiles (collections of mesh cells) // Don't want to make the vector contain const references to tiles // because the tiles may be asked to add or remove some entities const std::vector<std::shared_ptr<MeshTile>> & tiles() { return meshtiles; } //! Number of mesh tiles (on a compute node) int num_tiles() const {return meshtiles.size();} //! Nodes of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & nodes() const; //! Edges of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & edges() const; //! Faces of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & faces() const; //! Sides of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & sides() const; //! Wedges of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & wedges() const; //! Corners of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & corners() const; //! Cells of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & cells() const; // Master tile ID for entities int master_tile_ID_of_node(Entity_ID const nodeid) const { return tiles_initialized_ ? node_master_tile_ID_[nodeid] : -1; } int master_tile_ID_of_edge(Entity_ID const edgeid) const { return tiles_initialized_ ? edge_master_tile_ID_[edgeid] : -1; } int master_tile_ID_of_face(Entity_ID const faceid) const { return tiles_initialized_ ? face_master_tile_ID_[faceid] : -1; } int master_tile_ID_of_cell(Entity_ID const cellid) const { return tiles_initialized_ ? cell_master_tile_ID_[cellid] : -1; } int master_tile_ID_of_side(Entity_ID const sideid) const { return (tiles_initialized_ ? cell_master_tile_ID_[side_get_cell(sideid)] : -1); } int master_tile_ID_of_wedge(Entity_ID const wedgeid) const { return (tiles_initialized_ ? cell_master_tile_ID_[wedge_get_cell(wedgeid)] : -1); } int master_tile_ID_of_corner(Entity_ID const cornerid) const { return (tiles_initialized_ ? cell_master_tile_ID_[corner_get_cell(cornerid)] : -1); } // // Mesh Entity Adjacencies //------------------------- // Downward Adjacencies //--------------------- //! Get number of faces in a cell unsigned int cell_get_num_faces(const Entity_ID cellid) const; //! Get faces of a cell. //! //! The Google coding guidelines regarding function arguments is purposely //! violated here to allow for a default input argument //! //! On a distributed mesh, this will return all the faces of the //! cell, OWNED or GHOST. If ordered = true, the faces will be //! returned in a standard order according to Exodus II convention //! for standard cells; in all other situations (ordered = false or //! non-standard cells), the list of faces will be in arbitrary order void cell_get_faces(const Entity_ID cellid, Entity_ID_List *faceids, const bool ordered = false) const; //! Get faces of a cell and directions in which the cell uses the face //! //! The Google coding guidelines regarding function arguments is purposely //! violated here to allow for a default input argument //! //! On a distributed mesh, this will return all the faces of the //! cell, OWNED or GHOST. If ordered = true, the faces will be //! returned in a standard order according to Exodus II convention //! for standard cells; in all other situations (ordered = false or //! non-standard cells), the list of faces will be in arbitrary order //! //! In 3D, direction is 1 if face normal points out of cell //! and -1 if face normal points into cell //! In 2D, direction is 1 if face/edge is defined in the same //! direction as the cell polygon, and -1 otherwise void cell_get_faces_and_dirs(const Entity_ID cellid, Entity_ID_List *faceids, std::vector<dir_t> *facedirs, const bool ordered = false) const; //! Get edges of a cell (in no particular order) void cell_get_edges(const Entity_ID cellid, Entity_ID_List *edgeids) const; //! Get edges and dirs of a 2D cell. This is to make the code cleaner //! for integrating over the cell in 2D where faces and edges are //! identical but integrating over the cells using face information //! is more cumbersome (one would have to take the face normals, //! rotate them and then get a consistent edge vector) void cell_2D_get_edges_and_dirs(const Entity_ID cellid, Entity_ID_List *edgeids, std::vector<dir_t> *edge_dirs) const; //! Get nodes of a cell (in no particular order) virtual void cell_get_nodes(const Entity_ID cellid, Entity_ID_List *nodeids) const = 0; //! Get edges of a face and directions in which the face uses the edges //! //! On a distributed mesh, this will return all the edges of the //! face, OWNED or GHOST. If ordered = true, the edges will be //! returned in a ccw order around the face as it is naturally defined. //! //! IMPORTANT NOTE IN 2D CELLS: In meshes where the cells are two //! dimensional, faces and edges are identical. For such cells, this //! operator will return a single edge and a direction of 1. However, //! this direction cannot be relied upon to compute, say, a contour //! integral around the 2D cell. void face_get_edges_and_dirs(const Entity_ID faceid, Entity_ID_List *edgeids, std::vector<dir_t> *edgedirs, const bool ordered = false) const; //! Get the local index of a face edge in a cell edge list //! Example: //! //! face_get_edges(face=5) --> {20, 21, 35, 9, 10} //! cell_get_edges(cell=18) --> {1, 2, 3, 5, 8, 9, 10, 13, 21, 35, 20, 37, 40} //! face_to_cell_edge_map(face=5,cell=18) --> {10, 8, 9, 5, 6} void face_to_cell_edge_map(const Entity_ID faceid, const Entity_ID cellid, std::vector<int> *map) const; //! Get nodes of face //! On a distributed mesh, all nodes (OWNED or GHOST) of the face //! are returned //! In 3D, the nodes of the face are returned in ccw order consistent //! with the face normal //! In 2D, nfnodes is 2 virtual void face_get_nodes(const Entity_ID faceid, Entity_ID_List *nodeids) const = 0; //! Get nodes of edge void edge_get_nodes(const Entity_ID edgeid, Entity_ID *nodeid0, Entity_ID *nodeid1) const; //! Get sides of a cell (in no particular order) void cell_get_sides(const Entity_ID cellid, Entity_ID_List *sideids) const; //! Get wedges of cell (in no particular order) void cell_get_wedges(const Entity_ID cellid, Entity_ID_List *wedgeids) const; //! Get corners of cell (in no particular order) void cell_get_corners(const Entity_ID cellid, Entity_ID_List *cornerids) const; //! Get corner at cell and node combination Entity_ID cell_get_corner_at_node(const Entity_ID cellid, const Entity_ID nodeid) const; //! Face of a side Entity_ID side_get_cell(const Entity_ID sideid) const; //! Face of a side Entity_ID side_get_face(const Entity_ID sideid) const; //! Edge of a side Entity_ID side_get_edge(const Entity_ID sideid) const; //! Sense in which side is using its edge (i.e. do p0, p1 of side, //! edge match or not) int side_get_edge_use(const Entity_ID sideid) const; //! Node of a side (each edge of a side has two nodes - inode (0,1) //! indicates which one to return) Entity_ID side_get_node(const Entity_ID sideid, int inode) const; //! Wedge of a side //! Each side points to two wedges - iwedge (0, 1) //! indicates which one to return; the wedge returned will be //! consistent with the node returned by side_get_node. //! So, side_get_node(s,i) = wedge_get_node(side_get_wedge(s,i)) Entity_ID side_get_wedge(const Entity_ID sideid, int iwedge) const; //! Face of a wedge Entity_ID wedge_get_face(const Entity_ID wedgeid) const; //! Edge of a wedge Entity_ID wedge_get_edge(const Entity_ID wedgeid) const; //! Node of a wedge Entity_ID wedge_get_node(const Entity_ID wedgeid) const; //! Node of a corner Entity_ID corner_get_node(const Entity_ID cornerid) const; //! Wedges of a corner void corner_get_wedges(const Entity_ID cornerid, Entity_ID_List *wedgeids) const; //! Face get facets (or should we return a vector of standard pairs //! containing the wedge and a facet index?) void face_get_facets(const Entity_ID faceid, Entity_ID_List *facetids) const; // Upward adjacencies //------------------- //! Cells of type 'type' connected to a node - The order of cells //! is not guaranteed to be the same for corresponding nodes on //! different processors virtual void node_get_cells(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *cellids) const = 0; //! Faces of type 'type' connected to a node - The order of faces //! is not guaranteed to be the same for corresponding nodes on //! different processors virtual void node_get_faces(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *faceids) const = 0; //! Wedges connected to a node - The wedges are returned in no //! particular order. Also, the order of nodes is not guaranteed to //! be the same for corresponding nodes on different processors void node_get_wedges(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *wedgeids) const; //! Corners connected to a node - The corners are returned in no //! particular order. Also, the order of corners is not guaranteed to //! be the same for corresponding nodes on different processors void node_get_corners(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *cornerids) const; //! Get faces of type of a particular cell that are connected to the //! given node - The order of faces is not guarnateed to be the same //! for corresponding nodes on different processors virtual void node_get_cell_faces(const Entity_ID nodeid, const Entity_ID cellid, const Entity_type type, Entity_ID_List *faceids) const = 0; //! Cells connected to a face - The cells are returned in no //! particular order. Also, the order of cells is not guaranteed to //! be the same for corresponding faces on different processors void face_get_cells(const Entity_ID faceid, const Entity_type type, Entity_ID_List *cellids) const; //! Cell of a wedge Entity_ID wedge_get_cell(const Entity_ID wedgeid) const; //! Side of a wedge Entity_ID wedge_get_side(const Entity_ID wedgeid) const; //! Corner of a wedge Entity_ID wedge_get_corner(const Entity_ID wedgeid) const; //! wedges of a facet // void wedges_of_a_facet (const Entity_ID facetid, Entity_ID_List *wedgeids) // const; //! Cell of a corner Entity_ID corner_get_cell(const Entity_ID cornerid) const; // Same level adjacencies //----------------------- //! Face connected neighboring cells of given cell of a particular type //! (e.g. a hex has 6 face neighbors) //! //! The order in which the cellids are returned cannot be //! guaranteed in general except when type = ALL, in which case //! the cellids will correcpond to cells across the respective //! faces given by cell_get_faces virtual void cell_get_face_adj_cells(const Entity_ID cellid, const Entity_type type, Entity_ID_List *fadj_cellids) const = 0; //! Node connected neighboring cells of given cell //! (a hex in a structured mesh has 26 node connected neighbors) //! The cells are returned in no particular order virtual void cell_get_node_adj_cells(const Entity_ID cellid, const Entity_type type, Entity_ID_List *cellids) const = 0; //! Opposite side in neighboring cell of a side. The two sides share //! facet 0 of wedge comprised of nodes 0,1 of the common edge and //! center point of the common face in 3D, and nodes 0,1 of the //! common edge in 2D. At boundaries, this routine returns -1 Entity_ID side_get_opposite_side(const Entity_ID wedgeid) const; //! Opposite wedge in neighboring cell of a wedge. The two wedges //! share facet 0 of wedge comprised of the node, center point of //! the common edge and center point of the common face in 3D, and //! node and edge center in 2D. At boundaries, this routine returns //! -1 Entity_ID wedge_get_opposite_wedge(const Entity_ID wedgeid) const; //! adjacent wedge along edge in the same cell. The two wedges share //! facet 1 of wedge comprised of edge center, face center and zone center //! in 3D, and node and zone center in 2D Entity_ID wedge_get_adjacent_wedge(const Entity_ID wedgeid) const; // // Mesh entity geometry //-------------- // //! Node coordinates // Preferred operator virtual void node_get_coordinates(const Entity_ID nodeid, JaliGeometry::Point *ncoord) const = 0; virtual void node_get_coordinates(const Entity_ID nodeid, std::array<double, 3> *ncoord) const; virtual void node_get_coordinates(const Entity_ID nodeid, std::array<double, 2> *ncoord) const; virtual void node_get_coordinates(const Entity_ID nodeid, double *ncoord) const; //! Face coordinates - conventions same as face_to_nodes call //! Number of nodes is the vector size divided by number of spatial dimensions virtual void face_get_coordinates(const Entity_ID faceid, std::vector<JaliGeometry::Point> *fcoords) const = 0; //! Coordinates of cells in standard order (Exodus II convention) //! //! STANDARD CONVENTION WORKS ONLY FOR STANDARD CELL TYPES IN 3D //! For a general polyhedron this will return the node coordinates in //! arbitrary order //! Number of nodes is vector size divided by number of spatial dimensions virtual void cell_get_coordinates(const Entity_ID cellid, std::vector<JaliGeometry::Point> *ccoords) const = 0; //! Coordinates of side //! //! The coordinates will be returned in a fixed //! order - If posvol_order is true, the node coordinates will be //! ordered such that they will result in a +ve volume calculation; //! otherwise, they will be returned in the natural order in which //! they are defined for the side. For sides, the natural order //! automatically gives positive volume for 2D and 3D - its only in //! 1D that some side coordinates have to be reordered (see wedges //! below for which one wedge of each side will give a -ve volume if //! the natural coordinate order is used) void side_get_coordinates(const Entity_ID sideid, std::vector<JaliGeometry::Point> *scoords, bool posvol_order = false) const; //! Coordinates of wedge //! //! If posvol_order = true, then the coordinates will be returned //! in an order that will result in a positive volume (in 3D this assumes //! that the computation for volume is done as (V01 x V02).V03 where V0i //! is a vector from coordinate 0 to coordinate i of the tet). If posvol_order //! is false, the coordinates will be returned in a fixed order - in 2D, //! this is node point, edge/face center, cell center and in 3D, this is //! node point, edge center, face center, cell center //! //! By default the coordinates are returned in the natural order //! (posvol_order = false) void wedge_get_coordinates(const Entity_ID wedgeid, std::vector<JaliGeometry::Point> *wcoords, bool posvol_order = false) const; //! Coordinates of corner points. In 2D, these are ordered in a ccw //! manner. In 3D, they are not ordered in any particular way and //! this routine may not be too useful since the topology of the //! corner is not guaranteed to be standard like in 2D. Its better //! to work with the wedges of the corner void corner_get_coordinates(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *cncoords) const; //! Get a facetized description of corner geometry in 3D. The facet //! points index into the pointcoords vector. Each facet is //! guaranteed to have its points listed such that its normal points //! out of the corner void corner_get_facetization(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *pointcoords, std::vector<std::array<Entity_ID, 3>> *facetpoints) const; //! "facets" (line segments) describing a corner in 2D. The facet points are //! (0,1) (1,2) (2,3) and (3,4) referring to the point coordinates. They are //! guaranteed to be in ccw order around the quadrilateral corner void corner_get_facetization(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *pointcoords, std::vector<std::array<Entity_ID, 2>> *facetpoints) const; // "facets" (points - node and cell center) describing a corner in 1D :) void corner_get_facetization(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *pointcoords, std::vector<std::array<Entity_ID, 1>> *facetpoints) const; // Mesh entity geometry //-------------- // //! Volume/Area of cell double cell_volume(const Entity_ID cellid, const bool recompute = false) const; //! Area/length of face double face_area(const Entity_ID faceid, const bool recompute = false) const; //! Length of edge double edge_length(const Entity_ID edgeid, const bool recompute = false) const; //! Volume of side double side_volume(const Entity_ID sideid, const bool recompute = false) const; //! Volume of wedge double wedge_volume(const Entity_ID wedgeid, const bool recompute = false) const; //! Volume of a corner double corner_volume(const Entity_ID cornerid, const bool recompute = false) const; //! Centroid of cell JaliGeometry::Point cell_centroid(const Entity_ID cellid, const bool recompute = false) const; //! Centroid of face JaliGeometry::Point face_centroid(const Entity_ID faceid, const bool recompute = false) const; //! Centroid/center of edge(never cached) JaliGeometry::Point edge_centroid(const Entity_ID edgeid) const; //! Normal to face //! The vector is normalized and then weighted by the area of the face //! //! If recompute is TRUE, then the normal is recalculated using current //! face coordinates but not stored. (If the recomputed normal must be //! stored, then call recompute_geometric_quantities). //! //! If cellid is not specified, the normal is the natural normal of //! the face. This means that at boundaries, the normal may point in //! or out of the domain depending on how the face is defined. On the //! other hand, if cellid is specified, the normal is the outward //! normal with respect to the cell. In planar and solid meshes, the //! normal with respect to the cell on one side of the face is just //! the negative of the normal with respect to the cell on the other //! side. In general surfaces meshes, this will not be true at C1 //! discontinuities //! if cellid is specified, then orientation returns the direction of //! the natural normal of the face with respect to the cell (1 is //! pointing out of the cell and -1 pointing in) JaliGeometry::Point face_normal(const Entity_ID faceid, const bool recompute = false, const Entity_ID cellid = -1, int *orientation = NULL) const; //! Edge vector - not normalized (or normalized and weighted by length //! of the edge) //! //! If recompute is TRUE, then the vector is recalculated using current //! edge coordinates but not stored. (If the recomputed vector must be //! stored, then call recompute_geometric_quantities). //! //! If pointid is specified, the vector is the natural direction of //! the edge (from point0 to point1). On the other hand, if pointid //! is specified (has to be a point of the face), the vector is from //! specified point to opposite point of edge. //! //! if pointid is specified, then orientation returns the direction of //! the natural direction of the edge with respect to the point (1 is //! away from the point and -1 is towards) JaliGeometry::Point edge_vector(const Entity_ID edgeid, const bool recompute = false, const Entity_ID pointid = -1, int *orientation = NULL) const; //! Point in cell? bool point_in_cell(const JaliGeometry::Point &p, const Entity_ID cellid) const; //! Outward normal to facet of side that is shared with side from //! neighboring cell. //! //! The vector is normalized and then weighted by the area of the //! face. If recompute is TRUE, then the normal is recalculated //! using current wedge coordinates but not stored. (If the //! recomputed normal must be stored, then call //! recompute_geometric_quantities). //! //! Normals of other facets are typically not used in discretizations JaliGeometry::Point side_facet_normal(const Entity_ID sideid, const bool recompute = false) const; //! Outward normal to facet of wedge. //! //! The vector is normalized and then weighted by the area of the //! face Typically, one would ask for only facet 0 (shared with //! wedge from neighboring cell) and facet 1 (shared with adjacent //! wedge in the same side). If recompute is TRUE, then the normal //! is recalculated using current wedge coordinates but not //! stored. (If the recomputed normal must be stored, then call //! recompute_geometric_quantities). //! //! Normals of other facets are typically not used in discretizations JaliGeometry::Point wedge_facet_normal(const Entity_ID wedgeid, const unsigned int which_facet, const bool recompute = false) const; // // Mesh modification //------------------- //! Set coordinates of node virtual void node_set_coordinates(const Entity_ID nodeid, const JaliGeometry::Point ncoord) = 0; virtual void node_set_coordinates(const Entity_ID nodeid, const double *ncoord) = 0; //! Update geometric quantities (volumes, normals, centroids, etc.) //! and cache them - called for initial caching or for update after //! mesh modification void update_geometric_quantities(); // // Mesh Sets for ICs, BCs, Material Properties and whatever else //-------------------------------------------------------------- // //! Number of sets int num_sets(const Entity_kind kind = Entity_kind::ANY_KIND) const; //! Return a list of sets on entities of 'kind' std::vector<std::shared_ptr<MeshSet>> sets(const Entity_kind kind) const; //! Return a list of all sets std::vector<std::shared_ptr<MeshSet>> const& sets() const; //! Is this is a valid name of a geometric region defined on for //! containing entities of 'kind' bool valid_region_name(const std::string setname, const Entity_kind kind) const; // Find a meshset containing entities of 'kind' defined on a // geometric region 'regname' (non-const version - create the set if // it is missing, it is requested through the create_if_missing flag // and it corresponds to a valid region). std::shared_ptr<MeshSet> find_meshset_from_region(std::string regname, Entity_kind kind, bool create_if_missing); // Find a meshset containing entities of 'kind' defined on a geometric // region 'regname' (const version - do nothing if it is missing). std::shared_ptr<MeshSet> find_meshset_from_region(std::string setname, Entity_kind kind) const; //! Find a meshset with 'setname' containing entities of 'kind' std::shared_ptr<MeshSet> find_meshset(const std::string setname, const Entity_kind kind) const; //! Get number of entities of 'type' in set (non-const version - //! create the set if it is missing and it corresponds to a valid //! region). unsigned int get_set_size(const std::string setname, const Entity_kind kind, const Entity_type type); //! Get number of entities of 'type' in set (const version - return //! 0 if the set does not exist) unsigned int get_set_size(const std::string setname, const Entity_kind kind, const Entity_type type) const; //! Get entities of 'type' in set (non-const version - create the //! set if it is missing and it corresponds to a valid region). void get_set_entities(const std::string setname, const Entity_kind kind, const Entity_type type, Entity_ID_List *entids); //! Get entities of 'type' in set (const version - return empty list //! if the set does not exist) void get_set_entities(const std::string setname, const Entity_kind kind, const Entity_type type, Entity_ID_List *entids) const; //! \brief Export to Exodus II file //! Export mesh to Exodus II file. If with_fields is true, the fields in //! JaliState are also exported out. virtual void write_to_exodus_file(const std::string exodusfilename, const bool with_fields = true) const {} //! \brief Export to GMV file //! Export mesh to GMV file. If with_fields is true, the fields in //! JaliState are also exported out. virtual void write_to_gmv_file(const std::string gmvfilename, const bool with_fields = true) const {} //! \brief Precompute and cache corners, wedges, edges, cells // WHY IS THIS VIRTUAL? virtual void cache_extra_variables(); protected: int compute_cell_geometric_quantities() const; int compute_face_geometric_quantities() const; int compute_edge_geometric_quantities() const; int compute_side_geometric_quantities() const; int compute_corner_geometric_quantities() const; // get faces of a cell and directions in which it is used - this function // is implemented in each mesh framework. The results are cached in // the base class virtual void cell_get_faces_and_dirs_internal(const Entity_ID cellid, Entity_ID_List *faceids, std::vector<dir_t> *face_dirs, const bool ordered = false) const = 0; // Cells connected to a face - this function is implemented in each // mesh framework. The results are cached in the base class virtual void face_get_cells_internal(const Entity_ID faceid, const Entity_type type, Entity_ID_List *cellids) const = 0; // edges of a face - this function is implemented in each mesh // framework. The results are cached in the base class virtual void face_get_edges_and_dirs_internal(const Entity_ID faceid, Entity_ID_List *edgeids, std::vector<dir_t> *edge_dirs, const bool ordered = true) const = 0; // edges of a cell - this function is implemented in each mesh // framework. The results are cached in the base class. virtual void cell_get_edges_internal(const Entity_ID cellid, Entity_ID_List *edgeids) const = 0; // edges and directions of a 2D cell - this function is implemented // in each mesh framework. The results are cached in the base class. virtual void cell_2D_get_edges_and_dirs_internal(const Entity_ID cellid, Entity_ID_List *edgeids, std::vector<dir_t> *edge_dirs) const = 0; // get nodes of an edge - virtual function that will be implemented // in each mesh framework. The results are cached in the base class virtual void edge_get_nodes_internal(const Entity_ID edgeid, Entity_ID *enode0, Entity_ID *enode1) const = 0; //! Some functionality for mesh sets void init_sets(); void add_set(std::shared_ptr<MeshSet> set); //! build a mesh set std::shared_ptr<MeshSet> build_set_from_region(const std::string setname, const Entity_kind kind, const bool build_reverse_map = true); //! get labeled set entities // // Labeled sets are pre-existing mesh sets with a "name" in the mesh // as read from a file. Each mesh framework may have its own way of // retrieving these sets and so this is implemented in the derived class virtual void get_labeled_set_entities(const JaliGeometry::LabeledSetRegionPtr rgn, const Entity_kind kind, Entity_ID_List *owned_entities, Entity_ID_List *ghost_entities) const = 0; //! \brief Get info about mesh fields on a particular type of entity //! Get info about the number of fields, their names and their types //! on a particular type of entity on the mesh - DESIGNED TO BE //! CALLED ONLY BY THE JALI STATE MANAGER FOR INITIALIZATION OF MESH //! STATE FROM THE MESH FILE virtual void get_field_info(Entity_kind on_what, int *num, std::vector<std::string> *varnames, std::vector<std::string> *vartypes) const {*num = 0;} //! \brief Retrieve a field on the mesh - cannot template virtual funcs //! Retrieve a field on the mesh. If the return value is false, it //! could be that (1) the field does not exist (2) it exists but is //! associated with a different type of entity (3) the variable type //! sent in was the wrong type (int instead of double or double //! instead of std::array<double,2> or std::array<double,2> instead //! of std::array<double,3> etc - DESIGNED TO BE CALLED ONLY BY THE //! JALI STATE MANAGER FOR INITIALIZATION OF MESH STATE FROM THE //! MESH FILE virtual bool get_field(std::string field_name, Entity_kind on_what, int *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, double *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)2> *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)3> *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)6> *data) const {return false;} //! \brief Store a field on the mesh - cannot template as its virtual //! Store a field on the mesh. If the return value is false, it //! means that the mesh already has a field of that name but its of //! a different type or its on a different type of entity - DESIGNED //! TO BE CALLED ONLY BY THE JALI STATE MANAGER FOR INITIALIZATION //! OF MESH STATE FROM THE MESH FILE virtual bool store_field(std::string field_name, Entity_kind on_what, int *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, double *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)2> *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)3> *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)6> *data) {return false;} // The following methods are declared const since they do not modify the // mesh but just modify cached variables declared as mutable int compute_cell_geometry(const Entity_ID cellid, double *volume, JaliGeometry::Point *centroid) const; int compute_face_geometry(const Entity_ID faceid, double *area, JaliGeometry::Point *centroid, JaliGeometry::Point *normal0, JaliGeometry::Point *normal1) const; int compute_edge_geometry(const Entity_ID edgeid, double *length, JaliGeometry::Point *edge_vector, JaliGeometry::Point *centroid) const; // The outward_facet_normal is the area-weighted normal of the side // that lies on the boundary of the cell. This normal points out of // the cell. The mid_facet_normal is the normal of the common facet // between the two wedges of the side. This normal points out of // wedge 0 of the side and into wedge 1 void compute_side_geometry(const Entity_ID sideid, double *volume, JaliGeometry::Point *outward_facet_normal, JaliGeometry::Point *mid_facet_normal) const; void compute_corner_geometry(const Entity_ID cornerid, double *volume) const; void cache_type_info() const; void cache_cell2face_info() const; void cache_face2cell_info() const; void cache_cell2edge_info() const; void cache_face2edge_info() const; void cache_edge2node_info() const; void cache_side_info() const; void cache_wedge_info() const; void cache_corner_info() const; void build_tiles(); void add_tile(std::shared_ptr<MeshTile> tile2add); void init_tiles(); int get_new_tile_ID() const { return meshtiles.size(); } // Set master tile ID for entities void set_master_tile_ID_of_node(Entity_ID const nodeid, int const tileid) { node_master_tile_ID_[nodeid] = tileid; } void set_master_tile_ID_of_edge(Entity_ID const edgeid, int const tileid) { edge_master_tile_ID_[edgeid] = tileid; } void set_master_tile_ID_of_face(Entity_ID const faceid, int const tileid) { face_master_tile_ID_[faceid] = tileid; } void set_master_tile_ID_of_cell(Entity_ID const cellid, int const tileid) { cell_master_tile_ID_[cellid] = tileid; } void set_master_tile_ID_of_wedge(Entity_ID const wedgeid, int const tileid) {} void set_master_tile_ID_of_side(Entity_ID const sideid, int const tileid) {} void set_master_tile_ID_of_corner(Entity_ID const cornerid, int const tileid) {} //! @brief Get the partitioning of a regular mesh such that each //! partition is a rectangular block //! //! @param dim Dimension of problem - 1, 2 or 3 //! @param domain 2*dim values for min/max of domain //! (xmin, xmax, ymin, ymax, zmin, zmax) //! @param num_cells_in_dir number of cells in each direction //! @param num_blocks_requested number of blocks requested //! @param blocklimits min/max limits for each block //! @param blocknumcells num cells in each direction for blocks //! //! Returns 1 if successful, 0 otherwise int block_partition_regular_mesh(int const dim, double const * const domain, int const * const num_cells_in_dir, int const num_blocks_requested, std::vector<std::array<double, 6>> *blocklimits, std::vector<std::array<int, 3>> *blocknumcells); // Data unsigned int manifold_dim_, space_dim_; JaliGeometry::Geom_type geomtype = JaliGeometry::Geom_type::CARTESIAN; MPI_Comm comm; // MeshTile data (A meshtile is a list of cell indices that will be // processed together) const int num_tiles_ini_; const int num_ghost_layers_tile_; const int num_ghost_layers_distmesh_; const bool boundary_ghosts_requested_; const Partitioner_type partitioner_pref_; bool tiles_initialized_ = false; std::vector<std::shared_ptr<MeshTile>> meshtiles; std::vector<int> node_master_tile_ID_, edge_master_tile_ID_; std::vector<int> face_master_tile_ID_, cell_master_tile_ID_; // MeshSets (collection of entities of a particular kind) bool meshsets_initialized_ = false; std::vector<std::shared_ptr<MeshSet>> meshsets_; // Some geometric quantities mutable std::vector<double> cell_volumes, face_areas, edge_lengths, side_volumes, corner_volumes; mutable std::vector<JaliGeometry::Point> cell_centroids, face_centroids, face_normal0, face_normal1, edge_vectors, edge_centroids; // outward facing normal from side to side in adjacent cell mutable std::vector<JaliGeometry::Point> side_outward_facet_normal; // Normal of the common facet of the two wedges - normal points out // of wedge 0 of side into wedge 1 mutable std::vector<JaliGeometry::Point> side_mid_facet_normal; // Entity lists mutable std::vector<int> nodeids_owned_, nodeids_ghost_, nodeids_all_; mutable std::vector<int> edgeids_owned_, edgeids_ghost_, edgeids_all_; mutable std::vector<int> faceids_owned_, faceids_ghost_, faceids_all_; mutable std::vector<int> sideids_owned_, sideids_ghost_, sideids_boundary_ghost_, sideids_all_; mutable std::vector<int> wedgeids_owned_, wedgeids_ghost_, wedgeids_boundary_ghost_, wedgeids_all_; mutable std::vector<int> cornerids_owned_, cornerids_ghost_, cornerids_boundary_ghost_, cornerids_all_; mutable std::vector<int> cellids_owned_, cellids_ghost_, cellids_boundary_ghost_, cellids_all_; std::vector<int> dummy_list_; // for unspecialized cases // Type info for essential entities - sides, wedges and corners will // get their type from their owning cell mutable std::vector<Entity_type> cell_type; mutable std::vector<Entity_type> face_type; // if faces requested mutable std::vector<Entity_type> edge_type; // if edges requested mutable std::vector<Entity_type> node_type; // Some standard topological relationships that are cached. The rest // are computed on the fly or obtained from the derived class mutable std::vector<Entity_ID_List> cell_face_ids; mutable std::vector<std::vector<dir_t>> cell_face_dirs; mutable std::vector<Entity_ID_List> face_cell_ids; mutable std::vector<Entity_ID_List> cell_edge_ids; mutable std::vector<Entity_ID_List> face_edge_ids; mutable std::vector<std::vector<dir_t>> face_edge_dirs; mutable std::vector<std::array<Entity_ID, 2>> edge_node_ids; // cell_2D_edge_dirs is an unusual topological relationship // requested by MHD discretization - It has no equivalent in 3D mutable std::vector<std::vector<dir_t>> cell_2D_edge_dirs; // Topological relationships involving standard and non-standard // entities (sides, corners and wedges). The non-standard entities // may be required for polyhedral elements and more accurate // discretizations. // // 1D: // A side is a line segment from a node to the cell. Wedges and // corners are the same as sides. // // 2D: // A side is a triangle formed by the two nodes of an edge/face and // the cell center. A wedge is half of a side formed by one node of // the edge, the edge center and the cell center. A corner is a // quadrilateral formed by the two wedges in a cell at a node // // 3D: // A side is a tet formed by the two nodes of an edge, a face center // and a cell center. A wedge is half a side, formed by a node of // the edge, the edge center, the face center and the cell center. A // corner is formed by all the wedges of a cell at a node. // Sides mutable std::vector<Entity_ID> side_cell_id; mutable std::vector<Entity_ID> side_face_id; mutable std::vector<Entity_ID> side_edge_id; mutable std::vector<bool> side_edge_use; // true: side, edge - p0, p1 match mutable std::vector<std::array<Entity_ID, 2>> side_node_ids; mutable std::vector<Entity_ID> side_opp_side_id; // Wedges - most wedge info is derived from sides mutable std::vector<Entity_ID> wedge_corner_id; // some other one-many adjacencies mutable std::vector<std::vector<Entity_ID>> cell_side_ids; mutable std::vector<std::vector<Entity_ID>> cell_corner_ids; // mutable std::vector<std::vector<Entity_ID>> edge_side_ids; mutable std::vector<std::vector<Entity_ID>> node_corner_ids; mutable std::vector<std::vector<Entity_ID>> corner_wedge_ids; // Rectangular or general mutable Mesh_type mesh_type_; // flags to indicate what data is current mutable bool faces_requested, edges_requested, sides_requested, wedges_requested, corners_requested; mutable bool type_info_cached; mutable bool cell2face_info_cached, face2cell_info_cached; mutable bool cell2edge_info_cached, face2edge_info_cached; mutable bool edge2node_info_cached; mutable bool side_info_cached, wedge_info_cached, corner_info_cached; mutable bool cell_geometry_precomputed, face_geometry_precomputed, edge_geometry_precomputed, side_geometry_precomputed, corner_geometry_precomputed; // Pointer to geometric model that contains descriptions of // geometric regions - These geometric regions are used to define // entity sets for properties, boundary conditions etc. JaliGeometry::GeometricModelPtr geometric_model_; //! Make the State class a friend so that it can access protected //! methods for retrieving and storing mesh fields friend class State; //! Make the MeshTile class a friend so it can access protected functions //! for getting a new tile ID friend class MeshTile; // Make the make_meshtile function a friend so that it can access // the protected functions init_tiles and add_tile friend std::shared_ptr<MeshTile> make_meshtile(Mesh& parent_mesh, std::vector<Entity_ID> const& cells, int const num_ghost_layers_tile, bool const request_faces, bool const request_edges, bool const request_sides, bool const request_wedges, bool const request_corners); // Make the make_meshset function a friend so that it can access the // protected functions init_sets and add_set friend std::shared_ptr<MeshSet> make_meshset(std::string const& name, Mesh& parent_mesh, Entity_kind const& kind, Entity_ID_List const& entityids_owned, Entity_ID_List const& entityids_ghost, bool build_reverse_map); private: /// Method to get partitioning of a mesh into num parts void get_partitioning(int const num_parts, Partitioner_type const parttype, std::vector<std::vector<int>> *partitions); /// Method to get crude partitioning by chopping up the index space void get_partitioning_by_index_space(int const num_parts, std::vector<std::vector<int>> *partitions); /// Method to get crude partitioning by subdivision into rectangular blocks void get_partitioning_by_blocks(int const num_parts, std::vector<std::vector<int>> *partitions); /// Method to get partitioning of a mesh into num parts using METIS #ifdef Jali_HAVE_METIS void get_partitioning_with_metis(int const num_parts, std::vector<std::vector<int>> *partitions); #endif /// Method to get partitioning of a mesh into num parts using ZOLTAN #ifdef Jali_HAVE_ZOLTAN void get_partitioning_with_zoltan(int const num_parts, std::vector<std::vector<int>> *partitions); #endif }; // End class Mesh // Templated version of num_entities with specializations on enum template<Entity_type type> inline unsigned int Mesh::num_nodes() const { std::cerr << "num_nodes: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_nodes<Entity_type::PARALLEL_OWNED>() const { return nodeids_owned_.size(); } template<> inline unsigned int Mesh::num_nodes<Entity_type::PARALLEL_GHOST>() const { return nodeids_ghost_.size(); } template<> inline unsigned int Mesh::num_nodes<Entity_type::ALL>() const { return num_nodes<Entity_type::PARALLEL_OWNED>() + num_nodes<Entity_type::PARALLEL_GHOST>(); } template<Entity_type type> inline unsigned int Mesh::num_edges() const { std::cerr << "num_edges: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_edges<Entity_type::PARALLEL_OWNED>() const { return edgeids_owned_.size(); } template<> inline unsigned int Mesh::num_edges<Entity_type::PARALLEL_GHOST>() const { return edgeids_ghost_.size(); } template<> inline unsigned int Mesh::num_edges<Entity_type::ALL>() const { return num_edges<Entity_type::PARALLEL_OWNED>() + num_edges<Entity_type::PARALLEL_GHOST>(); } template<Entity_type type> inline unsigned int Mesh::num_faces() const { std::cerr << "num_faces: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_faces<Entity_type::PARALLEL_OWNED>() const { return faceids_owned_.size(); } template<> inline unsigned int Mesh::num_faces<Entity_type::PARALLEL_GHOST>() const { return faceids_ghost_.size(); } template<> inline unsigned int Mesh::num_faces<Entity_type::ALL>() const { return (num_faces<Entity_type::PARALLEL_OWNED>() + num_faces<Entity_type::PARALLEL_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_sides() const { std::cerr << "num_sides: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_sides<Entity_type::PARALLEL_OWNED>() const { return sideids_owned_.size(); } template<> inline unsigned int Mesh::num_sides<Entity_type::PARALLEL_GHOST>() const { return sideids_ghost_.size(); } template<> inline unsigned int Mesh::num_sides<Entity_type::BOUNDARY_GHOST>() const { return sideids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_sides<Entity_type::ALL>() const { return (num_sides<Entity_type::PARALLEL_OWNED>() + num_sides<Entity_type::PARALLEL_GHOST>() + num_sides<Entity_type::BOUNDARY_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_wedges() const { std::cerr << "num_wedges: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_wedges<Entity_type::PARALLEL_OWNED>() const { return wedgeids_owned_.size(); } template<> inline unsigned int Mesh::num_wedges<Entity_type::PARALLEL_GHOST>() const { return wedgeids_ghost_.size(); } template<> inline unsigned int Mesh::num_wedges<Entity_type::BOUNDARY_GHOST>() const { return wedgeids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_wedges<Entity_type::ALL>() const { return (num_wedges<Entity_type::PARALLEL_OWNED>() + num_wedges<Entity_type::PARALLEL_GHOST>() + num_wedges<Entity_type::BOUNDARY_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_corners() const { std::cerr << "num_corners: Not defined for type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_corners<Entity_type::PARALLEL_OWNED>() const { return cornerids_owned_.size(); } template<> inline unsigned int Mesh::num_corners<Entity_type::PARALLEL_GHOST>() const { return cornerids_ghost_.size(); } template<> inline unsigned int Mesh::num_corners<Entity_type::BOUNDARY_GHOST>() const { return cornerids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_corners<Entity_type::ALL>() const { return (num_corners<Entity_type::PARALLEL_OWNED>() + num_corners<Entity_type::PARALLEL_GHOST>() + num_corners<Entity_type::BOUNDARY_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_cells() const { std::cerr << "num_cells: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_cells<Entity_type::PARALLEL_OWNED>() const { return cellids_owned_.size(); } template<> inline unsigned int Mesh::num_cells<Entity_type::PARALLEL_GHOST>() const { return cellids_ghost_.size(); } template<> inline unsigned int Mesh::num_cells<Entity_type::BOUNDARY_GHOST>() const { return cellids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_cells<Entity_type::ALL>() const { return (num_cells<Entity_type::PARALLEL_OWNED>() + num_cells<Entity_type::PARALLEL_GHOST>() + num_cells<Entity_type::BOUNDARY_GHOST>()); } inline unsigned int Mesh::num_entities(const Entity_kind kind, const Entity_type type) const { switch (kind) { case Entity_kind::NODE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_nodes<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_nodes<Entity_type::PARALLEL_GHOST>(); case Entity_type::ALL: return num_nodes<Entity_type::ALL>(); default: return 0; } case Entity_kind::EDGE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_edges<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_edges<Entity_type::PARALLEL_GHOST>(); case Entity_type::ALL: return num_edges<Entity_type::ALL>(); default: return 0; } case Entity_kind::FACE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_faces<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_faces<Entity_type::PARALLEL_GHOST>(); case Entity_type::ALL: return num_faces<Entity_type::ALL>(); default: return 0; } case Entity_kind::SIDE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_sides<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_sides<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_sides<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_sides<Entity_type::ALL>(); default: return 0; } case Entity_kind::WEDGE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_wedges<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_wedges<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_wedges<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_wedges<Entity_type::ALL>(); default: return 0; } case Entity_kind::CORNER: switch (type) { case Entity_type::PARALLEL_OWNED: return num_corners<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_corners<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_corners<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_corners<Entity_type::ALL>(); default: return 0; } case Entity_kind::CELL: switch (type) { case Entity_type::PARALLEL_OWNED: return num_cells<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_cells<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_cells<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_cells<Entity_type::ALL>(); default: return 0; } default: return 0; } } // templated version of functions returning entity lists (default // implementation prints error message - meaningful values returned // through template specialization) template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::nodes() const { std::cerr << "Mesh::nodes() - " << "Meaningless to query for list of nodes of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::nodes<Entity_type::PARALLEL_OWNED>() const { return nodeids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::nodes<Entity_type::PARALLEL_GHOST>() const { return nodeids_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::nodes<Entity_type::ALL>() const { return nodeids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::edges() const { std::cerr << "Mesh::edges() - " << "Meaningless to query for list of edges of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::edges<Entity_type::PARALLEL_OWNED>() const { return edgeids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::edges<Entity_type::PARALLEL_GHOST>() const { return edgeids_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::edges<Entity_type::ALL>() const { return edgeids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::faces() const { std::cerr << "Mesh::faces() - " << "Meaningless to query for list of faces of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::faces<Entity_type::PARALLEL_OWNED>() const { return faceids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::faces<Entity_type::PARALLEL_GHOST>() const { return faceids_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::faces<Entity_type::ALL>() const { return faceids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::sides() const { std::cerr << "Mesh::sides() - " << "Meaningless to query for list of sides of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::sides<Entity_type::PARALLEL_OWNED>() const { return sideids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::sides<Entity_type::PARALLEL_GHOST>() const { return sideids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::sides<Entity_type::BOUNDARY_GHOST>() const { return sideids_boundary_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::sides<Entity_type::ALL>() const { return sideids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::wedges() const { std::cerr << "Mesh::wedges() - " << "Meaningless to query for list of wedges of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::PARALLEL_OWNED>() const { return wedgeids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::PARALLEL_GHOST>() const { return wedgeids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::BOUNDARY_GHOST>() const { return wedgeids_boundary_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::ALL>() const { return wedgeids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::corners() const { std::cerr << "Mesh::corners() - " << "Meaningless to query for list of corners of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::PARALLEL_OWNED>() const { return cornerids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::PARALLEL_GHOST>() const { return cornerids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::BOUNDARY_GHOST>() const { return cornerids_boundary_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::ALL>() const { return cornerids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::cells() const { std::cerr << "Mesh::cells() - " << "Meaningless to query for list of cells of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::PARALLEL_OWNED>() const { return cellids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::PARALLEL_GHOST>() const { return cellids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::BOUNDARY_GHOST>() const { return cellids_boundary_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::ALL>() const { return cellids_all_; } // Inline functions of the Mesh class inline void Mesh::cell_get_faces(const Entity_ID cellid, Entity_ID_List *faceids, const bool ordered) const { cell_get_faces_and_dirs(cellid, faceids, NULL, ordered); } inline void Mesh::edge_get_nodes(const Entity_ID edgeid, Entity_ID *nodeid0, Entity_ID *nodeid1) const { #ifdef JALI_CACHE_VARS *nodeid0 = edge_node_ids[edgeid][0]; *nodeid1 = edge_node_ids[edgeid][1]; #else edge_get_nodes_internal(edgeid, nodeid0, nodeid1); #endif } inline Entity_ID Mesh::side_get_wedge(const Entity_ID sideid, int iwedge) const { assert(wedges_requested); return (iwedge ? 2*sideid + 1 : 2*sideid); } inline Entity_ID Mesh::side_get_face(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_face_id[sideid]; } inline Entity_ID Mesh::side_get_edge(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_edge_id[sideid]; } inline int Mesh::side_get_edge_use(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return static_cast<int>(side_edge_use[sideid]); } inline Entity_ID Mesh::side_get_cell(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_cell_id[sideid]; } inline Entity_ID Mesh::side_get_node(const Entity_ID sideid, const int inode) const { assert(sides_requested); assert(side_info_cached && edge2node_info_cached); assert(inode == 0 || inode == 1); Entity_ID edgeid = side_edge_id[sideid]; Entity_ID enodes[2]; edge_get_nodes(edgeid, &enodes[0], &enodes[1]); bool use = side_edge_use[sideid]; return (use ? enodes[inode] : enodes[!inode]); } inline Entity_ID Mesh::side_get_opposite_side(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_opp_side_id[sideid]; } inline Entity_ID Mesh::wedge_get_cell(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); int sideid = wedgeid/2; // which side does wedge belong to return side_get_cell(sideid); } inline Entity_ID Mesh::wedge_get_face(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); return side_get_face(sideid); } inline Entity_ID Mesh::wedge_get_edge(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); return side_get_edge(sideid); } inline Entity_ID Mesh::wedge_get_node(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); int iwedge = wedgeid%2; // Is it wedge 0 or wedge 1 of side return side_get_node(sideid, iwedge); } inline Entity_ID Mesh::wedge_get_corner(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached && wedge_info_cached); return wedge_corner_id[wedgeid]; } inline Entity_ID Mesh::wedge_get_adjacent_wedge(Entity_ID const wedgeid) const { assert(wedges_requested); // Wedges come in pairs; their IDs are (2*sideid) and (2*sideid+1) // If the wedge ID is an odd number, then the adjacent wedge ID is // wedge ID minus one; If it is an even number, the adjacent wedge // ID is wedge ID plus one return (wedgeid%2 ? wedgeid - 1 : wedgeid + 1); } inline Entity_ID Mesh::wedge_get_opposite_wedge(Entity_ID const wedgeid) const { assert(wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); int iwedge = wedgeid%2; // Is it wedge 0 or wedge 1 of side Entity_ID oppsideid = side_opp_side_id[sideid]; if (oppsideid == -1) return -1; else { // if wedge is wedge 0 of side, the opposite wedge will be wedge 1 // of the opposite side Entity_ID adjwedgeid = iwedge ? 2*oppsideid : 2*oppsideid + 1; return adjwedgeid; } } inline void Mesh::corner_get_wedges(const Entity_ID cornerid, Entity_ID_List *cwedges) const { assert(corners_requested); assert(corner_info_cached); int nwedges = corner_wedge_ids[cornerid].size(); (*cwedges).resize(nwedges); std::copy(corner_wedge_ids[cornerid].begin(), corner_wedge_ids[cornerid].end(), cwedges->begin()); } inline Entity_ID Mesh::corner_get_node(const Entity_ID cornerid) const { assert(corners_requested); assert(corner_info_cached && side_info_cached); assert(corner_wedge_ids[cornerid].size()); // Instead of calling corner_get_wedges which involves a list copy, // we will directly access the first element of the corner_wedge_ids // array Entity_ID w0 = corner_wedge_ids[cornerid][0]; return wedge_get_node(w0); } inline Entity_ID Mesh::corner_get_cell(const Entity_ID cornerid) const { assert(corners_requested); assert(corner_info_cached && side_info_cached); assert(corner_wedge_ids[cornerid].size()); // Instead of calling corner_get_wedges which involves a list copy, // we will directly access the first element of the corner_wedge_ids // array Entity_ID w0 = corner_wedge_ids[cornerid][0]; return wedge_get_cell(w0); } // Inefficient fallback implementation - hopefully the derived class // has a more direct implementation inline void Mesh::node_get_coordinates(const Entity_ID nodeid, std::array<double, 3> *ncoord) const { assert(space_dim_ == 3); JaliGeometry::Point p; node_get_coordinates(nodeid, &p); (*ncoord)[0] = p[0]; (*ncoord)[1] = p[1]; (*ncoord)[2] = p[2]; } // Inefficient fallback implementation - hopefully the derived class // has a more direct implementation inline void Mesh::node_get_coordinates(const Entity_ID nodeid, std::array<double, 2> *ncoord) const { assert(space_dim_ == 2); JaliGeometry::Point p; node_get_coordinates(nodeid, &p); (*ncoord)[0] = p[0]; (*ncoord)[1] = p[1]; } // Inefficient fallback implementation - hopefully the derived class // has a more direct implementation inline void Mesh::node_get_coordinates(const Entity_ID nodeid, double *ncoord) const { assert(space_dim_ == 1); JaliGeometry::Point p; node_get_coordinates(nodeid, &p); *ncoord = p[0]; } } // end namespace Jali #endif /* _JALI_MESH_H_ */
34.924181
86
0.685469
jloveric
d7782ced05b4c171b035adfc673a35ae444f7135
9,671
cpp
C++
src/gui/MainWindow.cpp
guerinoni/tino
0cdd464db7135f7abd427f7b9dc0e03f8e48ef28
[ "MIT" ]
1
2020-03-22T22:14:43.000Z
2020-03-22T22:14:43.000Z
src/gui/MainWindow.cpp
marsiliano/tino
0cdd464db7135f7abd427f7b9dc0e03f8e48ef28
[ "MIT" ]
17
2019-11-20T09:51:45.000Z
2020-04-16T06:43:14.000Z
src/gui/MainWindow.cpp
marsiliano/tino
0cdd464db7135f7abd427f7b9dc0e03f8e48ef28
[ "MIT" ]
3
2019-07-02T14:37:29.000Z
2019-11-13T15:38:26.000Z
#include "MainWindow.hpp" #include "ui_MainWindow.h" #include "ConfigViewFactory.hpp" #include "DialogAbout.hpp" #include "DialogSerialSettings.hpp" #include "MdiChild.hpp" #include "../parser/ConfigParser.hpp" #include "../core/Element.hpp" #include <QDockWidget> #include <QFileDialog> #include <QMdiSubWindow> #include <QMessageBox> #include <QSettings> #include <QStandardItemModel> #include <QStandardPaths> #include <QToolBar> #include <QTreeView> #include <QtDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("Tino"); this->setWindowIcon(QIcon(":/logos/vector/isolated-layout.svg")); createActions(); createMenuBar(); createToolBar(); loadSettings(); connect(this, &MainWindow::importFinished, this, &MainWindow::createConfigView); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { QSettings settings("Tino"); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); QMainWindow::closeEvent(event); } void MainWindow::selectFile() { const auto filename = QFileDialog::getOpenFileName(this, tr("Open Config File"), m_importFilePath, tr("Config File (*.json)")); auto result = importConfig(filename); if (result.error) { QMessageBox::warning(this, tr("Load configuration"), tr(result.message.toUtf8().constData())); } } void MainWindow::createConfigView() { ui->mdiArea->closeAllSubWindows(); m_configViewDock.reset(ConfigViewFactory().makeConfigView(m_config->protocol)); m_configViewDock->setObjectName("ConfigView"); m_configViewDock->setFeatures(m_configViewDock->features() & ~QDockWidget::DockWidgetClosable); addDockWidget(Qt::DockWidgetArea::LeftDockWidgetArea, m_configViewDock.get(), Qt::Orientation::Vertical); auto tree = dynamic_cast<QTreeView *>(m_configViewDock->widget()); tree->setContextMenuPolicy(Qt::CustomContextMenu); connect(tree, &QTreeView::customContextMenuRequested, this, &MainWindow::customConfigViewContextMenu); } void MainWindow::customConfigViewContextMenu(const QPoint &point) { auto tree = dynamic_cast<QTreeView *>(m_configViewDock->widget()); QModelIndex index = tree->indexAt(point); if (!index.isValid()) { qWarning() << "index not valid" << index; return; } if (index.parent() != tree->rootIndex()) { qWarning() << "Not a root index"; return; } auto sModel = qobject_cast<QStandardItemModel *>(tree->model()); auto item = sModel->itemFromIndex(index); const auto protocolItemMenu = new QMenu(this); const auto view = new QAction("View", protocolItemMenu); view->setEnabled(item->accessibleText() == ConfigViewFactory::guiCreatable); connect(view, &QAction::triggered, this, [&]() { createWidgetRequested(item); }); protocolItemMenu->addAction(view); protocolItemMenu->exec(tree->viewport()->mapToGlobal(point)); } void MainWindow::connectClient() { if (!m_modbus->connectModbus(m_config->settings)) { QMessageBox::critical(this, tr("Tino"), tr("Modbus connection failed.")); return; } m_actions[Actions::Connect]->setEnabled(false); m_actions[Actions::Disconnect]->setEnabled(true); } void MainWindow::disconnectClient() { m_modbus->disconnectModbus(); m_actions[Actions::Connect]->setEnabled(true); m_actions[Actions::Disconnect]->setEnabled(false); const auto list = ui->mdiArea->subWindowList(); std::for_each(std::cbegin(list), std::cend(list), [](const auto &w) { auto mdiChild = dynamic_cast<MdiChild *>(w->widget()); mdiChild->resetToDefault(); }); } void MainWindow::createActions() { m_actions[Actions::Open] = std::make_unique<QAction>(tr("Open File...")); m_actions[Actions::Open]->setIcon(QIcon(":/flat/folder.png")); connect(m_actions[Actions::Open].get(), &QAction::triggered, this, &MainWindow::selectFile); m_actions[Actions::Connect] = std::make_unique<QAction>(tr("Connect")); m_actions[Actions::Connect]->setIcon(QIcon(":/flat/connected.png")); m_actions[Actions::Connect]->setEnabled(false); connect(m_actions[Actions::Connect].get(), &QAction::triggered, this, &MainWindow::connectClient); m_actions[Actions::Disconnect] = std::make_unique<QAction>(tr("Disconnect")); m_actions[Actions::Disconnect]->setIcon(QIcon(":/flat/disconnected.png")); m_actions[Actions::Disconnect]->setEnabled(false); connect(m_actions[Actions::Disconnect].get(), &QAction::triggered, this, &MainWindow::disconnectClient); m_actions[Actions::Settings] = std::make_unique<QAction>(tr("Setting...")); m_actions[Actions::Settings]->setIcon(QIcon(":/flat/settings.png")); m_actions[Actions::Settings]->setEnabled(false); connect(m_actions[Actions::Settings].get(), &QAction::triggered, this, [&]() { DialogSerialSettings(&m_config->settings).exec(); }); m_actions[Actions::About] = std::make_unique<QAction>(tr("About...")); m_actions[Actions::About]->setIcon(QIcon(":/flat/info.png")); connect(m_actions[Actions::About].get(), &QAction::triggered, this, []() { DialogAbout().exec(); }); m_actions[Actions::Quit] = std::make_unique<QAction>(tr("Quit")); m_actions[Actions::Quit]->setIcon(QIcon(":/flat/quit.png")); m_actions[Actions::Quit]->setShortcut(QKeySequence::StandardKey::Quit); connect(m_actions[Actions::Quit].get(), &QAction::triggered, this, []() { QApplication::exit(); }); } void MainWindow::createMenuBar() { const auto file = new QMenu("File", ui->menuBar); file->addAction(m_actions[Actions::Open].get()); file->addAction(m_actions[Actions::Quit].get()); ui->menuBar->addMenu(file); const auto comMenu = new QMenu(tr("Communication"), ui->menuBar); comMenu->addAction(m_actions[Actions::Connect].get()); comMenu->addAction(m_actions[Actions::Disconnect].get()); comMenu->addSeparator(); comMenu->addAction(m_actions[Actions::Settings].get()); ui->menuBar->addMenu(comMenu); const auto help = new QMenu("Help", ui->menuBar); help->addAction(m_actions[Actions::About].get()); ui->menuBar->addMenu(help); } void MainWindow::createToolBar() { m_toolbar = new QToolBar(this); m_toolbar->setObjectName("toolbar"); m_toolbar->setMovable(false); addToolBar(Qt::ToolBarArea::TopToolBarArea, m_toolbar); m_toolbar->addAction(m_actions[Actions::Open].get()); m_toolbar->addAction(m_actions[Actions::Connect].get()); m_toolbar->addAction(m_actions[Actions::Disconnect].get()); m_toolbar->addAction(m_actions[Actions::Settings].get()); } MainWindow::Error MainWindow::importConfig(const QString &filename) { if (filename.isNull() || filename.isEmpty()) { return Error{true, "Filename not valid!"}; } ConfigParser parser; m_config = std::make_unique<Configuration>(parser.parse(filename)); if (m_config == nullptr) { return Error{true, "Parsing configuration error!"}; } m_modbus = std::make_unique<ModbusCom>(m_config->protocol); connect(m_modbus.get(), &ModbusCom::updateGui, this, [this](int address) { const auto list = ui->mdiArea->subWindowList(); for (const auto &w : list) { auto mdi = dynamic_cast<MdiChild *>(w->widget()); // FIXME: maybe some ValueWidget are not refreshed if (mdi->hasElementWithAddress(address)) { mdi->updateGuiElemets(); return; } } }); m_actions[Actions::Connect]->setEnabled(true); m_actions[Actions::Disconnect]->setEnabled(false); m_actions[Actions::Settings]->setEnabled(true); emit importFinished({}); m_importFilePath = filename; saveSettings(); return {}; } void MainWindow::createWidgetRequested(QStandardItem *item) { const auto whatsThis = item->whatsThis(); const auto blockId = whatsThis.split('_').at(1).toInt(); const auto block = m_config->protocol.blocks.at(blockId); if (setFocusIfAlreadyExists(block)) { return; } const auto child = new MdiChild(block); connect(child, &MdiChild::updateModbus, m_modbus.get(), &ModbusCom::writeRegister); ui->mdiArea->addSubWindow(child); child->show(); } void MainWindow::saveSettings() { QSettings settings("Tino"); settings.setValue("importFilePath", m_importFilePath); } void MainWindow::loadSettings() { QSettings settings("Tino"); auto desktop = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); m_importFilePath = settings.value("importFilePath", desktop).toString(); restoreGeometry(settings.value("geometry").toByteArray()); restoreState(settings.value("windowState").toByteArray()); } bool MainWindow::setFocusIfAlreadyExists(const Block &block) const { const auto list = ui->mdiArea->subWindowList(); const auto it = std::find_if(std::cbegin(list), std::cend(list), [&](const auto &k) { return k->windowTitle() == block.description; }); if (it == list.cend()) { return false; } list.at(std::distance(std::cbegin(list), it))->setFocus(); return true; }
32.783051
99
0.656292
guerinoni
d778d577ea8efc1b356df1d7c017ecdf3188106a
6,221
cpp
C++
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "LibWebRTCSocketFactory.h" #if USE(LIBWEBRTC) #include "NetworkProcessConnection.h" #include "NetworkRTCMonitorMessages.h" #include "NetworkRTCProviderMessages.h" #include "WebProcess.h" #include "WebRTCSocket.h" #include <wtf/MainThread.h> namespace WebKit { uint64_t LibWebRTCSocketFactory::s_uniqueSocketIdentifier = 0; uint64_t LibWebRTCSocketFactory::s_uniqueResolverIdentifier = 0; static inline rtc::SocketAddress prepareSocketAddress(const rtc::SocketAddress& address, bool disableNonLocalhostConnections) { auto result = RTCNetwork::isolatedCopy(address); if (disableNonLocalhostConnections) result.SetIP("127.0.0.1"); return result; } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateServerTcpSocket(const rtc::SocketAddress& address, uint16_t minPort, uint16_t maxPort, int options) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ServerTCP, address, rtc::SocketAddress()); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), address = prepareSocketAddress(address, m_disableNonLocalhostConnections), minPort, maxPort, options]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateServerTCPSocket(identifier, RTCNetwork::SocketAddress(address), minPort, maxPort, options), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateUdpSocket(const rtc::SocketAddress& address, uint16_t minPort, uint16_t maxPort) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::UDP, address, rtc::SocketAddress()); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), address = prepareSocketAddress(address, m_disableNonLocalhostConnections), minPort, maxPort]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateUDPSocket(identifier, RTCNetwork::SocketAddress(address), minPort, maxPort), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateClientTcpSocket(const rtc::SocketAddress& localAddress, const rtc::SocketAddress& remoteAddress, const rtc::ProxyInfo&, const std::string&, int options) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ClientTCP, localAddress, remoteAddress); socket->setState(LibWebRTCSocket::STATE_CONNECTING); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), localAddress = prepareSocketAddress(localAddress, m_disableNonLocalhostConnections), remoteAddress = prepareSocketAddress(remoteAddress, m_disableNonLocalhostConnections), options]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateClientTCPSocket(identifier, RTCNetwork::SocketAddress(localAddress), RTCNetwork::SocketAddress(remoteAddress), options), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::createNewConnectionSocket(LibWebRTCSocket& serverSocket, uint64_t newConnectionSocketIdentifier, const rtc::SocketAddress& remoteAddress) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ServerConnectionTCP, serverSocket.localAddress(), remoteAddress); socket->setState(LibWebRTCSocket::STATE_CONNECTED); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), newConnectionSocketIdentifier]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::WrapNewTCPConnection(identifier, newConnectionSocketIdentifier), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } void LibWebRTCSocketFactory::detach(LibWebRTCSocket& socket) { ASSERT(m_sockets.contains(socket.identifier())); m_sockets.remove(socket.identifier()); } rtc::AsyncResolverInterface* LibWebRTCSocketFactory::CreateAsyncResolver() { auto resolver = std::make_unique<LibWebRTCResolver>(++s_uniqueResolverIdentifier); auto* resolverPointer = resolver.get(); m_resolvers.set(resolverPointer->identifier(), WTFMove(resolver)); return resolverPointer; } } // namespace WebKit #endif // USE(LIBWEBRTC)
48.224806
250
0.756631
mlcldh
d779d8f0b194753a162cd7d6a24f749908c204ab
4,685
hpp
C++
engine/src/engine/physics/LevelContactListener.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
1
2018-08-14T05:45:29.000Z
2018-08-14T05:45:29.000Z
engine/src/engine/physics/LevelContactListener.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
engine/src/engine/physics/LevelContactListener.hpp
CaptureTheBanana/CaptureTheBanana
1398bedc80608e502c87b880c5b57d272236f229
[ "MIT" ]
null
null
null
// This file is part of CaptureTheBanana++. // // Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md) // This file is licensed under the MIT license; see LICENSE file in the root of this // project for details. #ifndef ENGINE_PHYSICS_LEVELCONTACTLISTENER_HPP #define ENGINE_PHYSICS_LEVELCONTACTLISTENER_HPP #include <Box2D/Box2D.h> namespace ctb { namespace engine { class Player; class Bot; class Door; class Fist; class Flag; class PhysicalObject; class PhysicalRenderable; class Projectile; /** * @brief Class, that handles special behavior for certain objects */ class LevelContactListener : public b2ContactListener { public: /** * @brief Constructor */ LevelContactListener(); ~LevelContactListener() override = default; /** * @brief What should happen at the beginning of a contact of two certain objects? * * @param contact all necessary contact information */ void BeginContact(b2Contact* contact) override; /** * @brief What should happen at the end of a contatc of two certain objects? * * @param contact all necessary contact information */ void EndContact(b2Contact* contact) override; /** * @brief What should happen before two certain objects are in contact? * * @param contact all necessary contact information * @param oldManifold for two touching convex shapes */ void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; /** * @brief Should be called after every step of the b2World. * Does tasks, that cannot be done during the normal contact events, * because in BeginContact, EndContact and PreContact the beWorld is locked */ virtual void update(); private: /** * @brief What should happen, if an player reaches the right door with the banana? * * @param contact all necessary contact information * @param player who reached the door * @param door which was reached */ void doorReached(b2Contact* contact, Player* player, Door* door); /** * @brief Makes, that the given player is the owner of the given flag * * @param player who whould be the owner of the flag * @param flag who should be owned by the player */ void flagOwned(Player* player, Flag* flag); /** * @brief Proves, if the given flag is owned by an player * * @param obj must be a flag * * @return Is the flag in use? */ bool isFlagInUse(PhysicalObject* obj); /** * @brief What should happen, if an player collides with a bot? * * @param player who is colliding * @param bot who is colliding */ void collidedBotPlayer(Player* player, Bot* bot); /** * @brief Perform a melee attack on an other player with a cooldown * * @param attacking the attacking player * @param hurt the player, who is attacked */ void meleeWithCooldown(Player* attacking, Player* hurt); /** * @brief What should happen, if an player collects a flag * * @param player who is colliding with a flag * @param flag which is colliding with an player */ void collectFlag(Player* player, Flag* flag); /** * @brief What should happen, if an player collides with a weapon * * @param player who is colliding with a weapon * @param weapon which is colliding with an player * @param contact information about the collision */ void collisionPlayerWeapon(Player* player, Fist* weapon, b2Contact* contact); /** * @brief What should happen, if a projectile collides with an other PhysicalObject * * @param projectile which is colliding with a PhysicalObject * @param obj which is colliding with a projectile * @param contact information about the collision */ void collisionWithProjectile(Projectile* projectile, PhysicalObject* obj, b2Contact* contact); /** * @brief Method for ignoring the contact betwen a door and an player * * @param door which is colliding with an player * @param player which is colliding with a door * @param contact information about the collision */ void doorIgnoring(Door* door, Player* player, b2Contact* contact); /// Reference to the first object, which is collided for the update method PhysicalRenderable* m_a; /// Reference to the second object, which is collided for the update method PhysicalRenderable* m_b; /// Reference to an player for the update method Player* m_player; }; } // namespace engine } // namespace ctb #endif
28.742331
98
0.672785
CaptureTheBanana
d77cd5d06cd6bbacb5195297de4e66ce3070345d
536
cpp
C++
src/Extensions/src/extensions/entitycomponentsystem/detail/filter.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/Extensions/src/extensions/entitycomponentsystem/detail/filter.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/Extensions/src/extensions/entitycomponentsystem/detail/filter.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/extensions/entitycomponentsystem/detail/filter.h> namespace BABYLON { namespace Extensions { namespace ECS { namespace detail { bool Filter::doesPassFilter(const ComponentTypeList& componentTypeList) const { for (std::size_t i = 0; i < m_requires.size(); ++i) { if (m_requires[i] && !componentTypeList[i]) { return false; } } return !(m_excludes & componentTypeList).any(); } } // end of namespace detail } // end of namespace ECS } // end of namespace Extensions } // end of namespace BABYLON
23.304348
77
0.705224
sacceus
d780723d2d263f31f784eba9d2863690464d25b1
2,815
cpp
C++
Main/Main.cpp
ArclightEngine/ArclightEngine
f39eb0f22842eb94967982388f73ba942ebfd355
[ "MIT" ]
2
2021-10-05T03:27:03.000Z
2021-12-14T02:56:25.000Z
Main/Main.cpp
ArclightEngine/ArclightEngine
f39eb0f22842eb94967982388f73ba942ebfd355
[ "MIT" ]
7
2021-09-30T01:22:25.000Z
2022-01-07T01:33:07.000Z
Main/Main.cpp
ArclightEngine/ArclightEngine
f39eb0f22842eb94967982388f73ba942ebfd355
[ "MIT" ]
null
null
null
#include <assert.h> #include <Arclight/Core/Application.h> #include <Arclight/Core/Input.h> #include <Arclight/Core/Logger.h> #include <Arclight/Core/ResourceManager.h> #include <Arclight/Core/ThreadPool.h> #include <Arclight/Core/Timer.h> #include <Arclight/Graphics/Rendering/Renderer.h> #include <Arclight/Platform/Platform.h> #include <Arclight/State/StateManager.h> #include <Arclight/Window/WindowContext.h> #ifdef ARCLIGHT_PLATFORM_UNIX #include <dlfcn.h> #include <unistd.h> #endif #ifdef ARCLIGHT_PLATFORM_WINDOWS #include <windows.h> #endif #include <chrono> #include <vector> using namespace Arclight; bool isRunning = true; #ifdef ARCLIGHT_SINGLE_EXECUTABLE extern "C" void game_init(); #endif #if defined(ARCLIGHT_PLATFORM_WINDOWS) int wmain(int argc, wchar_t** argv) { #else int main(int argc, char** argv) { #endif Platform::Initialize(); Logger::Debug("Using renderer: {}", Rendering::Renderer::instance()->get_name()); #if defined(ARCLIGHT_PLATFORM_WASM) void (*InitFunc)(void) = game_init; #elif defined(ARCLIGHT_PLATFORM_UNIX) if (argc >= 2) { chdir(argv[1]); } char cwd[4096]; getcwd(cwd, 4096); std::string gamePath = std::string(cwd) + "/" + "game.so"; Logger::Debug("Loading game executable: {}", gamePath); void* game = dlopen(gamePath.c_str(), RTLD_GLOBAL | RTLD_NOW); if (!game) { // Try Build/game.so instead gamePath = std::string(cwd) + "/Build/" + "game.so"; game = dlopen(gamePath.c_str(), RTLD_GLOBAL | RTLD_NOW); if (!game) { Logger::Debug("Error loading {}", dlerror()); return 1; } } void (*InitFunc)(void) = (void (*)())dlsym(game, "game_init"); #elif defined(ARCLIGHT_PLATFORM_WINDOWS) #ifndef ARCLIGHT_SINGLE_EXECUTABLE if (argc >= 2) { SetCurrentDirectoryW(argv[1]); } wchar_t cwd[_MAX_PATH]; DWORD cwdLen; if (cwdLen = GetCurrentDirectoryW(_MAX_PATH, cwd); cwdLen > _MAX_PATH || cwdLen == 0) { Logger::Error("Failed to get current working directory!"); return 1; } Arclight::UnicodeString dllPath = cwd; dllPath += L"\\game.dll"; HINSTANCE game = LoadLibraryW(as_wide_string(dllPath)); if (!game) { Logger::Debug("Error loading {}", dllPath); return 2; } void (*InitFunc)(void) = (void (*)())GetProcAddress(game, "game_init"); if (!InitFunc) { Logger::Debug("Could not resolve symbol GameInit from {}", dllPath); return 2; } #else void (*InitFunc)(void) = game_init; #endif #else #error "Unsupported platform!" #endif assert(InitFunc); { Application app; InitFunc(); } #if defined(ARCLIGHT_PLATFORM_WASM) return 0; #else Platform::Cleanup(); return 0; #endif }
22.701613
91
0.646892
ArclightEngine
d78406929965f85a1c7ea9db28fcea4a0e8163b2
4,364
cpp
C++
src/Cpl/Itc/_0test/simmvc.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
src/Cpl/Itc/_0test/simmvc.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
src/Cpl/Itc/_0test/simmvc.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------- * This file is part of the Colony.Core Project. The Colony.Core Project is an * open source project with a BSD type of licensing agreement. See the license * agreement (license.txt) in the top/ directory or on the Internet at * http://integerfox.com/colony.core/license.txt * * Copyright (c) 2014-2020 John T. Taylor * * Redistributions of the source code must retain the above copyright notice. *----------------------------------------------------------------------------*/ #include "Catch/catch.hpp" #include "Cpl/System/_testsupport/Shutdown_TS.h" #include "Cpl/System/ElapsedTime.h" #include "common.h" #define MY_EVENT_NUMBER 8 #define MY_EVENT_MASK 0x00000100 /// using namespace Cpl::Itc; //////////////////////////////////////////////////////////////////////////////// /* The test app consists of 3 threads: - Two client threads, one contains a viewer, the other contains a writer - One model thread that 'owns' the data being viewed/written */ //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "simmvc", "[simmvc]" ) { CPL_SYSTEM_TRACE_FUNC( SECT_ ); Cpl::System::Shutdown_TS::clearAndUseCounter(); MyMailboxServer modelMbox( MY_EVENT_MASK ); Model myModel( modelMbox ); ViewRequest::SAP modelViewSAP( myModel, modelMbox ); MailboxServer viewerMbox; Viewer myViewer( 0, viewerMbox, modelViewSAP ); Master masterRun( NUM_SEQ_, NUM_WRITES_, myViewer, myModel, myModel, Cpl::System::Thread::getCurrent(), false ); Cpl::System::Thread* t1 = Cpl::System::Thread::create( viewerMbox, "Viewer" ); Cpl::System::Thread* t2 = Cpl::System::Thread::create( modelMbox, "Model" ); Cpl::System::Thread* t3 = Cpl::System::Thread::create( masterRun, "MASTER" ); Cpl::System::Api::sleep( 50 ); // Allow time for threads to actually spin-up // Test the default signal handler viewerMbox.notify( MY_EVENT_NUMBER ); unsigned long startTime = Cpl::System::ElapsedTime::milliseconds(); // Validate result of each sequence int i; for ( i=0; i < NUM_SEQ_; i++ ) { modelMbox.notify( MY_EVENT_NUMBER ); CPL_SYSTEM_TRACE_MSG( SECT_, ("@@ TICK SOURCE: Starting sequence# %d...", i + 1) ); bool signaled = false; for ( int i=0; i < 50; i++ ) { Cpl::System::SimTick::advance( 100 ); Cpl::System::Api::sleepInRealTime( 100 ); if ( Cpl::System::Thread::tryWait() ) { signaled = true; break; } } CPL_SYSTEM_TRACE_MSG( SECT_, (" @@ TICK SOURCE: pause before checking result for seq# %d, signaled=%d. Seq completed at sim tick count of: %lu", i + 1, signaled, Cpl::System::SimTick::current()) ); REQUIRE( signaled ); REQUIRE( myModel.m_value == (NUM_WRITES_ - 1) * ATOMIC_MODIFY_ ); REQUIRE( myViewer.m_attachRspMsg.getPayload().m_value == (NUM_WRITES_ - 1) * ATOMIC_MODIFY_ ); REQUIRE( myViewer.m_ownAttachMsg == true ); REQUIRE( myViewer.m_ownDetachMsg == true ); REQUIRE( myViewer.m_pendingCloseMsgPtr == 0 ); REQUIRE( myViewer.m_opened == false ); REQUIRE( modelMbox.m_sigCount == i + 1 ); t3->signal(); } // Wait for all of the sequences to complete Cpl::System::SimTick::advance( 10 ); Cpl::System::Thread::wait(); // Shutdown threads viewerMbox.pleaseStop(); modelMbox.pleaseStop(); Cpl::System::SimTick::advance( 50 ); Cpl::System::Api::sleep( 50 ); // allow time for threads to stop REQUIRE( t1->isRunning() == false ); REQUIRE( t2->isRunning() == false ); REQUIRE( t3->isRunning() == false ); unsigned elapsedTime = Cpl::System::ElapsedTime::deltaMilliseconds( startTime ); CPL_SYSTEM_TRACE_MSG( SECT_, ("Viewer Timer count=%lu, max possible value=%lu", myViewer.m_timerExpiredCount, elapsedTime / TIMER_DELAY) ); REQUIRE( ((myViewer.m_timerExpiredCount > 1) && (myViewer.m_timerExpiredCount < elapsedTime / TIMER_DELAY)) ); Cpl::System::Thread::destroy( *t1 ); Cpl::System::Thread::destroy( *t2 ); Cpl::System::Thread::destroy( *t3 ); REQUIRE( Cpl::System::Shutdown_TS::getAndClearCounter() == 0u ); }
40.407407
207
0.597617
johnttaylor
d7864a53f29349e15f287da6273a4c442623c336
2,885
cc
C++
src/developer/forensics/testing/fakes/data_provider.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/developer/forensics/testing/fakes/data_provider.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/developer/forensics/testing/fakes/data_provider.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "src/developer/forensics/testing/fakes/data_provider.h" #include <fuchsia/feedback/cpp/fidl.h> #include <fuchsia/mem/cpp/fidl.h> #include <lib/syslog/cpp/macros.h> #include <memory> #include <vector> #include "src/developer/forensics/utils/archive.h" #include "src/lib/fsl/vmo/file.h" #include "src/lib/fsl/vmo/sized_vmo.h" #include "src/lib/fxl/strings/string_printf.h" namespace forensics { namespace fakes { namespace { using namespace fuchsia::feedback; std::string AnnotationsToJSON(const std::vector<Annotation>& annotations) { std::string json = "{\n"; for (const auto& annotation : annotations) { json += fxl::StringPrintf("\t\"%s\": \"%s\"\n", annotation.key.c_str(), annotation.value.c_str()); } json += "}\n"; return json; } std::vector<Annotation> CreateAnnotations() { return { Annotation{.key = "annotation_key_1", .value = "annotation_value_1"}, Annotation{.key = "annotation_key_2", .value = "annotation_value_2"}, Annotation{.key = "annotation_key_3", .value = "annotation_value_3"}, }; } Attachment CreateSnapshot() { std::map<std::string, std::string> attachments; attachments["annotations.json"] = AnnotationsToJSON(CreateAnnotations()); attachments["attachment_key"] = "attachment_value"; fsl::SizedVmo archive; Archive(attachments, &archive); return {.key = "snapshot.zip", .value = std::move(archive).ToTransport()}; } std::unique_ptr<Screenshot> LoadPngScreenshot() { fsl::SizedVmo image; FX_CHECK(fsl::VmoFromFilename("/pkg/data/checkerboard_100.png", &image)) << "Failed to create image vmo"; const size_t image_dim_in_px = 100u; fuchsia::math::Size dimensions; dimensions.width = image_dim_in_px; dimensions.height = image_dim_in_px; std::unique_ptr<Screenshot> screenshot = Screenshot::New(); screenshot->image = std::move(image).ToTransport(); screenshot->dimensions_in_px = dimensions; return screenshot; } } // namespace void DataProvider::GetAnnotations(fuchsia::feedback::GetAnnotationsParameters params, GetAnnotationsCallback callback) { callback(std::move(Annotations().set_annotations(CreateAnnotations()))); } void DataProvider::GetSnapshot(fuchsia::feedback::GetSnapshotParameters parms, GetSnapshotCallback callback) { callback( std::move(Snapshot().set_annotations(CreateAnnotations()).set_archive(CreateSnapshot()))); } void DataProvider::GetScreenshot(ImageEncoding encoding, GetScreenshotCallback callback) { switch (encoding) { case ImageEncoding::PNG: callback(LoadPngScreenshot()); default: callback(nullptr); } } } // namespace fakes } // namespace forensics
30.052083
98
0.709532
csrpi
d78a0060cdcf38ff388b7ff092a736c23791dad8
1,567
cpp
C++
Dynamic Programming/22maximumSumSuchThatNo3ConsecutiveElements.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
1
2021-01-18T14:51:20.000Z
2021-01-18T14:51:20.000Z
Dynamic Programming/22maximumSumSuchThatNo3ConsecutiveElements.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
Dynamic Programming/22maximumSumSuchThatNo3ConsecutiveElements.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; // Max sum with no 3 consecutive is an extension of the below procedure // this is the implementation where no consecutive are in the max sum int maxSumNoConsecutiveElems(vector<int> &a){ // incl contains (prev element excluded sum + current element) // excl contains max(prev excluded sum, prev included sum) // NOTICE: incl adds the current element to the prev max sum, excl, // just stores the max sum found previously without including the // current element in the sum int incl = 0, excl = 0; for(int i=0;i<a.size();i++){ // storing the prev incl to be used in excl int tincl = incl; incl = excl+a[i]; excl = max(tincl,excl); } return max(incl,excl); } int Max(int a, int b, int c){ return max(a,max(b,c)); } int maxSumNo3consecutiveElems(vector<int> &a){ int n = a.size(); // dp array to store the max at each index vector<int> dp(n); for(int i=0;i<n;i++){ if(i==0) dp[i] = a[0]; else if(i==1) dp[i] = dp[0]+a[1]; // we take max of sum of 0&1 or 1&2 or 0&2 else if(i==2) dp[i] = Max(dp[i],a[1]+a[2],a[0]+a[2]); // we got 3 options: // (I) exclude a[i] // (II) exclude a[i-1] // (III) exclude a[i-2] // We have to choose the maximum of the 3 else dp[i] = Max(dp[i-1],dp[i-2]+a[i],dp[i-3]+a[i-1]+a[i]); } return dp[n-1]; } int main(){ vector<int> a = {5,5,10,40,50,35}; cout<<maxSumNoConsecutiveElems(a)<<endl; cout<<maxSumNo3consecutiveElems(a)<<endl; return 0; }
27.491228
71
0.601149
Coderangshu
d78ae7b565651f4759d2dc0b8b93cb4ac626af4a
5,305
cpp
C++
solved/0-b/8-puzzle/puzzle.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/0-b/8-puzzle/puzzle.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/0-b/8-puzzle/puzzle.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <stack> #include <vector> using namespace std; #define INF 1000 #define Zero(v) memset((v), 0, sizeof(v)) // goal[n]: coordinates of number n in the solution configuration const int goal[9][2] = { { 2, 2 }, { 0, 0 }, { 0, 1 }, { 0, 2 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 } }; // moves const int dd[4][2] = { { 1, 0 }, // down { 0, -1 }, // left { -1, 0 }, // up { 0, 1 } // right }; struct Game { int m[3][3]; int tmd; // total sum of manhattan distances int lc; // weight of linear conflicts int r, c; // row and column of blank tile int chl; // index of next children state int last; // last move performed Game() {} void init() { last = -1; tmd = 0; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) { int n = m[i][j]; if (n == 0) { r = i, c = j; continue; } tmd += abs(i - goal[n][0]) + abs(j - goal[n][1]); } lc = 0; for (int i = 0; i < 3; ++i) { if (conflict_in_row(i)) lc += 2; if (conflict_in_col(i)) lc += 2; } } bool conflict_in_row(int r) { int c1, c2; for (c1 = 2; c1 > 0; --c1) if (m[r][c1] > 0 && goal[m[r][c1]][0] == r) break; if (c1 == 0) return false; for (c2 = 0; c2 < c1; ++c2) if (m[r][c2] > 0 && goal[m[r][c2]][0] == r && goal[m[r][c1]][1] < goal[m[r][c2]][1]) return true; return false; } bool conflict_in_col(int c) { int r1, r2; for (r1 = 2; r1 > 0; --r1) if (m[r1][c] > 0 && goal[m[r1][c]][1] == c) break; if (r1 == 0) return false; for (r2 = 0; r2 < r1; ++r2) if (m[r2][c] > 0 && goal[m[r2][c]][1] == c && goal[m[r1][c]][0] < goal[m[r2][c]][0]) return true; return false; } int h() { return tmd + lc; } bool is_solution() { return tmd == 0; } void reset() { chl = 0; } bool next(Game &child, int &dist, int &delta) { int r2, c2; int comp_move = last >= 0 ? (last + 2) % 4 : -1; for (; chl < 4; ++chl) { if (chl == comp_move) continue; r2 = r + dd[chl][0]; c2 = c + dd[chl][1]; if (r2 >= 0 && r2 < 3 && c2 >= 0 && c2 < 3) break; } if (chl >= 4) return false; child = *this; child.last = chl++; int n = child.m[r2][c2]; child.tmd += abs(r - goal[n][0]) + abs(c - goal[n][1]) - abs(r2 - goal[n][0]) - abs(c2 - goal[n][1]); swap(child.m[r][c], child.m[r2][c2]); child.r = r2, child.c = c2; if (r != r2) { if (conflict_in_row(r)) child.lc -= 2; if (conflict_in_row(r2)) child.lc -= 2; if (child.conflict_in_row(r)) child.lc += 2; if (child.conflict_in_row(r2)) child.lc += 2; } if (c != c2) { if (conflict_in_col(c)) child.lc -= 2; if (conflict_in_col(c2)) child.lc -= 2; if (child.conflict_in_col(c)) child.lc += 2; if (child.conflict_in_col(c2)) child.lc += 2; } dist = 1; return true; } bool is_solvable() { int invr = 0; for (int i = 0; i < 9; ++i) { int r = i / 3, c = i % 3; if (m[r][c] != 0) for (int j = 0; j < i; ++j) { int p = j / 3, q = j % 3; if (m[p][q] != 0 && m[p][q] > m[r][c]) ++invr; } } return invr % 2 == 0; } }; template <typename NT, typename DT> bool ida_dls(NT &node, int depth, int g, int &nxt, stack<DT> &st) { if (g == depth) return node.is_solution(); NT child; int dist; DT delta; for (node.reset(); node.next(child, dist, delta);) { int f = g + dist + child.h(); if (f > depth && f < nxt) nxt = f; if (f <= depth && ida_dls(child, depth, g + 1, nxt, st)) { if (st.empty()) st.push(dist); else { int steps = st.top(); st.pop(); st.push(steps + dist); } return true; } } return false; } template <typename NT, typename DT> bool ida_star(NT &root, int limit, stack<DT> &st) { for (int depth = root.h(); depth <= limit;) { int next_depth = INF; if (ida_dls(root, depth, 0, next_depth, st)) return true; if (next_depth == INF) return false; depth = next_depth; } return false; } int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { Game g; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) scanf("%d", &g.m[i][j]); g.init(); printf("Case %d: ", ++ncase); stack<int> st; if (g.is_solvable() && ida_star(g, INF, st)) printf("%d\n", st.empty() ? 0 : st.top()); else puts("impossible"); } return 0; }
26.004902
67
0.416211
abuasifkhan
d78c48b3a0a7604f54c219eb641eab6a3723ce43
3,538
hh
C++
src/core/capability_manager.hh
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/capability_manager.hh
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/capability_manager.hh
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 SK Telecom Co., Ltd. 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. */ #ifndef __NUGU_CAPABILITY_AGENT_H__ #define __NUGU_CAPABILITY_AGENT_H__ #include <map> #include <memory> #include "base/nugu_event.h" #include "clientkit/capability_interface.hh" #include "directive_sequencer.hh" #include "focus_manager.hh" #include "interaction_control_manager.hh" #include "playsync_manager.hh" #include "session_manager.hh" namespace NuguCore { class CapabilityManager : public INetworkManagerListener, public IDirectiveSequencerListener { private: CapabilityManager(); virtual ~CapabilityManager(); public: static CapabilityManager* getInstance(); static void destroyInstance(); void resetInstance(); PlaySyncManager* getPlaySyncManager(); FocusManager* getFocusManager(); SessionManager* getSessionManager(); InteractionControlManager* getInteractionControlManager(); DirectiveSequencer* getDirectiveSequencer(); void addCapability(const std::string& cname, ICapabilityInterface* cap); void removeCapability(const std::string& cname); void requestEventResult(NuguEvent* event); // overriding INetworkManagerListener void onEventSendResult(const char* msg_id, bool success, int code) override; void onEventResponse(const char* msg_id, const char* data, bool success) override; void setWakeupWord(const std::string& word); std::string getWakeupWord(); std::string makeContextInfo(const std::string& cname, Json::Value& ctx); std::string makeAllContextInfo(); bool isSupportDirectiveVersion(const std::string& version, ICapabilityInterface* cap); bool sendCommand(const std::string& from, const std::string& to, const std::string& command, const std::string& param); void sendCommandAll(const std::string& command, const std::string& param); bool getCapabilityProperty(const std::string& cap, const std::string& property, std::string& value); bool getCapabilityProperties(const std::string& cap, const std::string& property, std::list<std::string>& values); void suspendAll(); void restoreAll(); // overriding IDirectiveSequencerListener bool onPreHandleDirective(NuguDirective* ndir) override; bool onHandleDirective(NuguDirective* ndir) override; void onCancelDirective(NuguDirective* ndir) override; private: ICapabilityInterface* findCapability(const std::string& cname); static CapabilityManager* instance; std::map<std::string, ICapabilityInterface*> caps; std::map<std::string, std::string> events; std::map<std::string, std::string> events_cname_map; std::string wword; std::unique_ptr<PlaySyncManager> playsync_manager; std::unique_ptr<FocusManager> focus_manager; std::unique_ptr<SessionManager> session_manager; std::unique_ptr<DirectiveSequencer> directive_sequencer; std::unique_ptr<InteractionControlManager> interaction_control_manager; }; } // NuguCore #endif
36.102041
123
0.749293
nugulinux