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
109
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
48.5k
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
54a35c9edb4161389804c450a775aac3e2d47cc9
7,762
cpp
C++
esp32/libraries/TouchLib-master/src/TLSampleMethodResistive.cpp
zvikapika/HanukiyaIOT
6f54e3d2d945962e9c1ff65d282269ae60898246
[ "MIT" ]
null
null
null
esp32/libraries/TouchLib-master/src/TLSampleMethodResistive.cpp
zvikapika/HanukiyaIOT
6f54e3d2d945962e9c1ff65d282269ae60898246
[ "MIT" ]
null
null
null
esp32/libraries/TouchLib-master/src/TLSampleMethodResistive.cpp
zvikapika/HanukiyaIOT
6f54e3d2d945962e9c1ff65d282269ae60898246
[ "MIT" ]
null
null
null
/* * TLSampleMethodResistive.cpp - Resistive sensing implementation for * TouchLibrary for Arduino Teensy 3.x * * https://github.com/AdmarSchoonen/TLSensor * Copyright (c) 2016 - 2017 Admar Schoonen * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "TouchLib.h" #include "TLSampleMethodResistive.h" #define USE_CORRECT_TRANSFER_FUNCTION 0 #define TL_SAMPLE_METHOD_RESISTIVE_GND_PIN 2 #define TL_SAMPLE_METHOD_RESISTIVE_USE_INTERNAL_PULLUP true /* ATmega2560 has internal pull-ups of 20 - 50 kOhm. Assume it is 35 kOhm */ #define TL_REFERENCE_VALUE_DEFAULT ((int32_t) 35000) /* 32 kOhm */ #define TL_SCALE_FACTOR_DEFAULT ((int32_t) 1) #define TL_VALUE_MAX_DEFAULT ((int32_t) 8000000) /* 8 MOhm */ #define TL_OFFSET_VALUE_DEFAULT ((int32_t) 0) /* Ohm */ #define TL_SET_OFFSET_VALUE_MANUALLY_DEFAULT false #if IS_PARTICLE #define TL_ADC_RESOLUTION_BIT 12 #elif IS_ESP32 #define TL_ADC_RESOLUTION_BIT 12 #elif IS_ATMEGA #define TL_ADC_RESOLUTION_BIT 10 #else #define TL_ADC_RESOLUTION_BIT 10 #endif #define TL_ADC_MAX ((1 << TL_ADC_RESOLUTION_BIT) - 1) #if (USE_CORRECT_TRANSFER_FUNCTION == 1) #define TL_RELEASED_TO_APPROACHED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 4500) #define TL_APPROACHED_TO_RELEASED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 5500) #define TL_APPROACHED_TO_PRESSED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 800) #define TL_PRESSED_TO_APPROACHED_THRESHOLD_DEFAULT \ (TL_VALUE_MAX_DEFAULT - 1000) #else #define TL_RELEASED_TO_APPROACHED_THRESHOLD_DEFAULT 0.5 #define TL_APPROACHED_TO_RELEASED_THRESHOLD_DEFAULT 0.25 #define TL_APPROACHED_TO_PRESSED_THRESHOLD_DEFAULT 5 #define TL_PRESSED_TO_APPROACHED_THRESHOLD_DEFAULT 4 #endif int TLSampleMethodResistivePreSample(struct TLStruct * data, uint8_t nSensors, uint8_t ch) { return 0; } int32_t TLSampleMethodResistiveSample(struct TLStruct * data, uint8_t nSensors, uint8_t ch, bool inv) { struct TLStruct * dCh; int ch_pin, gnd_pin; int32_t sample; bool useInternalPullup; if (inv) { /* Pseudo differential measurements are not supported */ sample = 0; } else { dCh = &(data[ch]); ch_pin = dCh->tlStructSampleMethod.resistive.pin; gnd_pin = dCh->tlStructSampleMethod.resistive.gndPin; useInternalPullup = dCh->tlStructSampleMethod.resistive.useInternalPullup; if (ch_pin < 0) { return 0; /* An error occurred */ } if (useInternalPullup) { /* Enable internal pull-up on analog input */ pinMode(ch_pin, INPUT_PULLUP); } else { /* Disable internal pull-up on analog input */ pinMode(ch_pin, INPUT); } if (gnd_pin >= 0) { /* Configure gnd_pin as digital output, low (gnd) */ pinMode(gnd_pin, OUTPUT); digitalWrite(gnd_pin, LOW); } /* Read */ sample = analogRead(ch_pin); /* Disable internal pull-up on analog input */ pinMode(ch_pin, INPUT); if (gnd_pin >= 0) { /* Leave gnd_pin floating */ pinMode(gnd_pin, INPUT); digitalWrite(gnd_pin, LOW); } } return sample; } int TLSampleMethodResistivePostSample(struct TLStruct * data, uint8_t nSensors, uint8_t ch) { TLStruct * d; int32_t tmp, scale; d = &(data[ch]); switch (d->filterType) { case TLStruct::filterTypeAverage: scale = (((int32_t) d->nMeasurementsPerSensor) << 1) * (TL_ADC_MAX + 1); break; case TLStruct::filterTypeSlewrateLimiter: scale = ((TL_ADC_MAX + 1) << 2); break; case TLStruct::filterTypeMedian: scale = ((TL_ADC_MAX + 1) << 2); break; default: /* Error! */ scale = ((TL_ADC_MAX + 1) << 2); } #if (USE_CORRECT_TRANSFER_FUNCTION == 1) /* * Actual transfer function is * (d->raw / scale) / (1 - (d->raw / scale)), but this is very * sensitive to noise when sensor is not pressed (since tmp will then * be very close to 1). Instead, clip the value to a predefined * maximum. */ if (d->raw > scale) { d->raw = scale; } denum = scale - d->raw; tmp = (d->scaleFactor * d->referenceValue * d->raw + (denum >> 1)) / denum; if (tmp > d->tlStructSampleMethod.resistive.valueMax) { tmp = d->tlStructSampleMethod.resistive.valueMax; } #else tmp = d->scaleFactor * d->referenceValue * d->raw / scale; #endif d->value = tmp; /* Resistance can be negative due to noise! */ return 0; } int32_t TLSampleMethodResistiveMapDelta(struct TLStruct * data, uint8_t nSensors, uint8_t ch, int length) { int32_t n = -1; struct TLStruct * d; int32_t delta; d = &(data[ch]); delta = d->delta - d->releasedToApproachedThreshold / 2; n = map(100 * delta, 0, 100 * d->calibratedMaxDelta, 0, length); n = (n < 0) ? 0 : n; n = (n > length) ? length : n; return n; } int TLSampleMethodResistive(struct TLStruct * data, uint8_t nSensors, uint8_t ch) { struct TLStruct * d; d = &(data[ch]); d->sampleMethodPreSample = TLSampleMethodResistivePreSample; d->sampleMethodSample = TLSampleMethodResistiveSample; d->sampleMethodPostSample = TLSampleMethodResistivePostSample; d->sampleMethodMapDelta = TLSampleMethodResistiveMapDelta; d->tlStructSampleMethod.resistive.pin = A0 + ch; d->tlStructSampleMethod.resistive.gndPin = ch + TL_SAMPLE_METHOD_RESISTIVE_GND_PIN; d->tlStructSampleMethod.resistive.useInternalPullup = TL_SAMPLE_METHOD_RESISTIVE_USE_INTERNAL_PULLUP; d->referenceValue = TL_REFERENCE_VALUE_DEFAULT; d->offsetValue = TL_OFFSET_VALUE_DEFAULT; d->scaleFactor = TL_SCALE_FACTOR_DEFAULT; d->setOffsetValueManually = TL_SET_OFFSET_VALUE_MANUALLY_DEFAULT; d->tlStructSampleMethod.resistive.valueMax = TL_VALUE_MAX_DEFAULT; d->releasedToApproachedThreshold = TL_RELEASED_TO_APPROACHED_THRESHOLD_DEFAULT; d->approachedToReleasedThreshold = TL_APPROACHED_TO_RELEASED_THRESHOLD_DEFAULT; d->approachedToPressedThreshold = TL_APPROACHED_TO_PRESSED_THRESHOLD_DEFAULT; d->pressedToApproachedThreshold = TL_PRESSED_TO_APPROACHED_THRESHOLD_DEFAULT; d->direction = TLStruct::directionNegative; d->sampleType = TLStruct::sampleTypeNormal; d->filterType = TLStruct::filterTypeAverage; d->waterRejectPin = -1; d->waterRejectMode = TLStruct::waterRejectModeFloat; d->pin = &(d->tlStructSampleMethod.resistive.pin); return 0; }
30.439216
98
0.725457
zvikapika
54a443e2c8ec66c132e17f3cf36b936fba077140
2,224
cc
C++
src/LockManagerTest.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/LockManagerTest.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/LockManagerTest.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
/* * LockManagerTest.cc * * Created on: Dec 8, 2016 * Author: theo */ #include <cassert> #include <iostream> #include "AVLTreeLockManager.h" #include "LockManager.h" #include "LockManagerTest.h" #include "TestEvent.h" LockManagerTest::LockManagerTest(LockManager *lock_manager) { _lock_manager = lock_manager; } void LockManagerTest::run() { uint64_t last = 1; // Unit tests for tryBackwardLock. assert(_lock_manager->tryBackwardLock(0, 0, 3, false, new TestEvent(1), &last)); assert(last == 0); assert(!_lock_manager->tryBackwardLock(0, 1, 4, true, new TestEvent(2), &last)); assert(last == 3); // Unit tests for tryLock. assert(_lock_manager->tryLock(1, 0, 5, 15, false)); assert(!_lock_manager->tryLock(1, 1, 1, 5, true)); // Unit tests for freeze. _lock_manager->freeze(0); assert(_lock_manager->tryBackwardLock(0, 1, 3, true, new TestEvent(2), &last)); assert(last == 3); // Unit tests for unlock. _lock_manager->unlock(1); assert(_lock_manager->tryBackwardLock(0, 2, 5, false, new TestEvent(3), &last)); assert(last == 3); _lock_manager->unlock(2); // More sophisticated test. assert(_lock_manager->tryBackwardLock(2, 3, 15, true, new TestEvent(3), &last)); assert(last == 0); assert(_lock_manager->tryBackwardLock(2, 4, 30, true, new TestEvent(4), &last)); assert(last == 0); assert(_lock_manager->tryLock(2, 4, 31, 35, false)); assert(!_lock_manager->tryLock(2, 5, 5, 5, false)); assert(!_lock_manager->tryBackwardLock(2, 6, 40, true, new TestEvent(6), &last)); assert(last == 35); _lock_manager->freeze(3); _lock_manager->freeze(4); assert(_lock_manager->tryBackwardLock(2, 6, 35, true, new TestEvent(6), &last)); assert(last == 35); assert(_lock_manager->tryBackwardLock(2, 7, 50, true, new TestEvent(7), &last)); assert(_lock_manager->tryLock(2, 7, 51, 55, false)); assert(!_lock_manager->tryBackwardLock(2, 8, 70, true, new TestEvent(8), &last)); assert(last == 55); _lock_manager->unlock(6); _lock_manager->unlock(7); assert(_lock_manager->tryBackwardLock(2, 8, 55, true, new TestEvent(8), &last)); assert(last == 35); _lock_manager->freeze(8); std::cout << "Lock Manager Test Successful." << std::endl; }
32.231884
83
0.680306
mkaguilera
54ac1b1efbf79f072467343fcf1c14cad3983c15
1,803
cpp
C++
code/cheonsa/cheonsa_platform_icon.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa_platform_icon.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa_platform_icon.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
#include "cheonsa_platform_icon.h" #include "cheonsa_engine.h" #if defined( cheonsa_platform_windows ) #define WIN32_LEAN_AND_MEAN #include <Windows.h> #undef LoadIcon #endif namespace cheonsa { platform_icon_c::platform_icon_c() : icon_handle( nullptr ) { } platform_icon_c::~platform_icon_c() { unload(); } boolean_c platform_icon_c::load_from_exe( string8_c const & resource_name ) { icon_handle = static_cast< void_c * >( LoadImageA( GetModuleHandleA( NULL ), resource_name.character_list.get_internal_array(), IMAGE_ICON, 0, 0, 0 ) ); return icon_handle != 0; } boolean_c platform_icon_c::load_from_exe( string16_c const & resource_name ) { icon_handle = static_cast< void_c * >( LoadImageW( GetModuleHandleW( NULL ), resource_name.character_list.get_internal_array(), IMAGE_ICON, 0, 0, 0 ) ); return icon_handle != 0; } boolean_c platform_icon_c::load_from_absolute_file_path( string16_c const & file_path_absolute ) { icon_handle = static_cast< void_c * >( LoadImageW( NULL, file_path_absolute.character_list.get_internal_array(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE ) ); return icon_handle != 0; } boolean_c platform_icon_c::load_from_relative_file_path( string16_c const & file_path_relative ) { unload(); #if defined( cheonsa_platform_windows ) string16_c file_path_absolute; if ( engine.get_content_manager()->resolve_absolute_file_path( file_path_relative, file_path_absolute, true, true ) ) { icon_handle = static_cast< void_c * >( LoadImageW( NULL, file_path_absolute.character_list.get_internal_array(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE ) ); } #endif return icon_handle != 0; } void_c platform_icon_c::unload() { if ( icon_handle ) { DestroyIcon( static_cast< HICON >( icon_handle ) ); icon_handle = nullptr; } } }
28.171875
154
0.747643
Olaedaria
2a6150c024f6de94d3415ca38faf869bf06cf2ba
2,776
cpp
C++
source/sprites/AnchorSprite.cpp
xzrunner/sprite2
2d5d8c6b79a63871bdd6cfdcd4805946fde95921
[ "MIT" ]
null
null
null
source/sprites/AnchorSprite.cpp
xzrunner/sprite2
2d5d8c6b79a63871bdd6cfdcd4805946fde95921
[ "MIT" ]
null
null
null
source/sprites/AnchorSprite.cpp
xzrunner/sprite2
2d5d8c6b79a63871bdd6cfdcd4805946fde95921
[ "MIT" ]
null
null
null
#include "sprite2/AnchorSprite.h" #include "sprite2/AnchorActor.h" #include "sprite2/SprVisitorParams.h" #include "sprite2/ActorFactory.h" #include "sprite2/UpdateParams.h" #include "sprite2/SpriteVisitor.h" namespace s2 { void AnchorSprite::OnMessage(const UpdateParams& up, Message msg) { auto actor = up.GetActor(); auto anchor = QueryAnchor(actor); if (!anchor) { return; } UpdateParams up_child(up); up_child.Push(this); auto anchor_spr = anchor->GetSprRaw(); up_child.SetActor(anchor_spr->QueryActor(actor)); const_cast<Sprite*>(anchor_spr)->OnMessage(up_child, msg); } bool AnchorSprite::Update(const UpdateParams& up) { auto actor = up.GetActor(); auto anchor = QueryAnchor(actor); if (!anchor) { return false; } auto spr_real = anchor->GetSprRaw(); // update inherit if (!up.IsForce() && !spr_real->IsInheritUpdate()) { return false; } auto actor_real = spr_real->QueryActor(actor); // visible bool visible = actor_real ? actor_real->IsVisible() : spr_real->IsVisible(); if (!visible) { return false; } UpdateParams up_child(up); up_child.Push(this); up_child.SetActor(actor_real); bool ret = const_cast<Sprite*>(spr_real)->Update(up_child); return ret; } SprPtr AnchorSprite::FetchChildByName(int name, const ActorConstPtr& actor) const { auto anchor = QueryAnchor(actor.get()); if (anchor) { auto anchor_spr = anchor->GetSprRaw(); return anchor_spr->FetchChildByName(name, anchor_spr->QueryActorRef(actor.get())); } else { return nullptr; } } SprPtr AnchorSprite::FetchChildByIdx(int idx, const ActorPtr& actor) const { auto anchor = QueryAnchor(actor.get()); if (anchor) { auto anchor_spr = anchor->GetSprRaw(); return anchor_spr->FetchChildByIdx(idx, anchor_spr->QueryActorRef(actor.get())); } else { return nullptr; } } VisitResult AnchorSprite::TraverseChildren(SpriteVisitor& visitor, const SprVisitorParams& params) const { VisitResult ret = VISIT_OVER; auto& actor = params.actor; auto anchor = actor ? static_cast<const AnchorActor*>(actor)->GetAnchorPtr() : nullptr; if (anchor) { SprVisitorParams cp = params; cp.actor = anchor.get(); SpriteVisitor::VisitChild(visitor, cp, anchor->GetSpr(), ret); } return ret; } VisitResult AnchorSprite::TraverseChildren2(SpriteVisitor2& visitor, const SprVisitorParams2& params) const { auto& actor = params.actor; auto anchor = actor ? S2_VI_PTR_DOWN_CAST<const AnchorActor>(actor)->GetAnchorPtr() : nullptr; if (anchor) { SprVisitorParams2 cp = params; cp.actor = anchor; return anchor->GetSprRaw()->TraverseChildren2(visitor, cp); } else { return VISIT_OVER; } } const Actor* AnchorSprite::QueryAnchor(const Actor* actor) const { return actor ? S2_VI_DOWN_CAST<const AnchorActor*>(actor)->GetAnchor() : nullptr; } }
24.785714
107
0.729107
xzrunner
2a654d6baafef17060e8aabe64bc0de8e7fa9c7e
2,831
hpp
C++
include/trainer/GradientDescent.hpp
YSZhuoyang/CudaNeuralNetwork
1c7d5d6ae8e8bb622e7fcbbac2e3db487a202157
[ "MIT" ]
null
null
null
include/trainer/GradientDescent.hpp
YSZhuoyang/CudaNeuralNetwork
1c7d5d6ae8e8bb622e7fcbbac2e3db487a202157
[ "MIT" ]
null
null
null
include/trainer/GradientDescent.hpp
YSZhuoyang/CudaNeuralNetwork
1c7d5d6ae8e8bb622e7fcbbac2e3db487a202157
[ "MIT" ]
null
null
null
#include "model/MiniNeuralNets.hpp" #ifndef GRADIENT_DESCENT_HPP #define GRADIENT_DESCENT_HPP namespace MiniNeuralNetwork { using namespace MyHelper; class Trainer { public: Trainer( std::shared_ptr<MiniNeuralNets> neuralNets, cublasHandle_t cublasHandle ); ~Trainer(); void train( const float* featureMat, const unsigned short* classIndexMat, const unsigned int numInstances, const unsigned int maxIter, const float learningRate, const float regularParam, const float costThreshold ); void test( const float* featureMat, const unsigned short* classIndexMat, const unsigned int numInstances ); private: inline void forwardProp( Layer* layers, const unsigned int numInstances, cudaStream_t stream1 ); inline void backwardProp( Layer* layers, const unsigned short* dClassIndexMat, const unsigned int numInstances, const float learningParam, const float regularParam, cudaStream_t stream1, cudaStream_t stream2 ); inline void forwardOutput( const Layer& sourceLayer, const Layer& targetLayer, const Connection& connection, const unsigned int numInstances, const std::shared_ptr<ActivationFunction> actFunction, cublasHandle_t cublasHandle, cudaStream_t stream ); inline void backPropError( const Layer& sourceLayer, const Layer& targetLayer, const Connection& connection, const unsigned int numInstances, const std::shared_ptr<ActivationFunction> actFunction, cublasHandle_t cublasHandle, cudaStream_t stream ); inline void updateWeights( const Layer& sourceLayer, const Layer& targetLayer, const Connection& connection, const unsigned int numInstances, const float learningParam, const float regularParam, cublasHandle_t cublasHandle, cudaStream_t stream ); std::shared_ptr<MiniNeuralNets> neuralNets = nullptr; cudaEvent_t* backPropCompletes = nullptr; cudaEvent_t forwardPropComplete; cudaEvent_t trainingComplete; cudaEvent_t testComplete; cublasHandle_t cublasHandle; }; } #endif
34.52439
70
0.553161
YSZhuoyang
2a6942c1f475a9950905d0b87a438fcefc38bc2e
415
hpp
C++
player/include/api/oauth.hpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
36
2018-03-09T08:05:32.000Z
2021-09-09T19:06:39.000Z
player/include/api/oauth.hpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
35
2018-03-15T06:43:49.000Z
2021-04-14T00:07:00.000Z
player/include/api/oauth.hpp
Globidev/twitch-player
062306685e182c422980d57fe7ba9fbdee141c37
[ "MIT" ]
3
2018-05-18T21:17:05.000Z
2021-09-09T19:06:42.000Z
#pragma once #include <QObject> #include <QtPromise> class QTcpServer; class QNetworkRequest; using QtPromise::QPromise; class OAuth: public QObject { Q_OBJECT public: OAuth(QObject * = nullptr); QPromise<QString> query_token(); signals: void token_ready(QString); private: QTcpServer *_local_server; void fetch_token(const QUrl &); void save_token_data(const QByteArray &); };
14.821429
45
0.713253
Globidev
2a6d4c7bbd84e16ea24743ee7c718f2fb44bb50f
26,375
cpp
C++
test/Account_Test.cpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
1
2021-04-24T06:01:57.000Z
2021-04-24T06:01:57.000Z
test/Account_Test.cpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
null
null
null
test/Account_Test.cpp
rigertd/LegacyMUD
cf351cca466158f0682f6c877b88d5c2eb59e240
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************* * Author: Keith Adkins * Date Created: 2/12/2017 * Last Modified: 2/14/2017 * Course: CS467, Winter 2017 * Filename: Account_Test.cpp * * Overview: * Unit test for the Account class. ************************************************************************/ #include <Account.hpp> #include <string> #include <iostream> #include <stdio.h> #include <gtest/gtest.h> namespace { std::string fileName = "legacy_mud_accounts.txt"; // txt file for account data /* Testing with no accounts in the account system. */ TEST(AccountTest, NoAccounts) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Save the account to disk. Clearing any account data stored in the file. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are no accounts."; /* Check if a username is unique. */ EXPECT_TRUE(acc.uniqueUsername("Steve") ) << "Expect true since this username is not the account system."; /* Verify an account. */ EXPECT_FALSE(acc.verifyAccount("Linda", "somepassword") ) << "Expect false since this account is not in the system. "; /* Verify admin status of a user. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false since this user is not in the system."; /* Set the admin of a user. */ EXPECT_FALSE(acc.setAdmin("Linda", false ) ) << "Expect false since this user is not in the system."; /* Changing password. */ EXPECT_FALSE(acc.changePassword("China", "newPassword" ) ) << "Expect false since this user is not in the system."; /* Get UserId. */ EXPECT_EQ(0, acc.getUserId("China" ) ) << "Expect 0 since this user is not in the system."; /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are no accounts."; remove(fileName.c_str()); // delete the account system file } /* Testing with one created account in the account system. */ TEST(AccountTest, OneAccount) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Linda", "validpassword", true, 1 ) ) << "Expect true since this is a valid account creation."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is one account."; /* Save the account to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is one account."; /* Try to create second account with the same username. */ EXPECT_FALSE(acc.createAccount("Linda", "1234", false, 2 ) ) << "Expect false since this username is not unique."; /* Check if a username is unique. Testing with a username this is already in the account system. */ EXPECT_FALSE(acc.uniqueUsername("Linda") ) << "Expect false since this username is in the account system."; /* Check if a username is unique. Testing with a username not in the account system.*/ EXPECT_TRUE(acc.uniqueUsername("George") ) << "Expect true since this username is not in the account system."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "1234") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.verifyAccount("Sally", "password4") ) << "Expect false since this username is invalid."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true this user is an admin."; /* Verify admin status of a user. Testing with invalid username. */ EXPECT_FALSE(acc.verifyAdmin("Mike" ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Linda", false ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false Linda is not an admin."; /* Set the admin of a user. Testing with an invalid username. */ EXPECT_FALSE(acc.setAdmin("George", false ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to true. */ EXPECT_TRUE(acc.setAdmin("Linda", true ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true since this user is now an admin."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(1, acc.getUserId("Linda" ) ) << "Expect 1 since this is the correct user id."; /* Get userId. Testing with invalid username. */ EXPECT_EQ(0, acc.getUserId("Mike" ) ) << "Expect 0 since this username is invalid."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Linda", "newPassword" ) ) << "Expect true since this user a valid account."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "newPassword") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "validpassword") ) << "Expect false since the password is invalid."; /* Changing password. Testing with invalid username. */ EXPECT_FALSE(acc.changePassword("George", "newPassword" ) ) << "Expect false since George is an invalid username."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is only one account."; /* Delete an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.deleteAccount("Betty") ) << "Expect false since the username is valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Linda") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there is are no longer any accounts."; remove(fileName.c_str()); // delete the account system file } /* Testing with two created accounts in the account system. */ TEST(AccountTest, TwoAccounts) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Linda", "validpassword1", true, 1 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Kris", "validpassword2", false, 2 ) ) << "Expect true since this is a valid account creation."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Save the account to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Try to create second account with the same username. */ EXPECT_FALSE(acc.createAccount("Kris", "1234", false, 2 ) ) << "Expect false since this username is not unique."; /* Check if a username is unique. Testing with a username this is already in the account system. */ EXPECT_FALSE(acc.uniqueUsername("Kris") ) << "Expect false since this username is in the account system."; /* Check if a username is unique. Testing with a username not in the account system.*/ EXPECT_TRUE(acc.uniqueUsername("George") ) << "Expect true since this username is not in the account system."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "1234") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Kris", "invalidpassword") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.verifyAccount("Sally", "password4") ) << "Expect false since this username is invalid."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true this user is an admin."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_FALSE(acc.verifyAdmin("Kris" ) ) << "Expect false since this user is not an admin."; /* Verify admin status of a user. Testing with invalid username. */ EXPECT_FALSE(acc.verifyAdmin("Mike" ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Linda", false ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false since this user is not an admin."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Kris", true ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_TRUE(acc.verifyAdmin("Kris" ) ) << "Expect true since this user is now an admin."; /* Set the admin of a user. Testing with an invalid username. */ EXPECT_FALSE(acc.setAdmin("George", false ) ) << "Expect false since this username is invalid."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(1, acc.getUserId("Linda" ) ) << "Expect 1 since this is the correct user id."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(2, acc.getUserId("Kris" ) ) << "Expect 2 since this is the correct user id."; /* Get userId. Testing with invalid username. */ EXPECT_EQ(0, acc.getUserId("Mike" ) ) << "Expect 0 since this username is invalid."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Linda", "newPassword1" ) ) << "Expect true since this user a valid account."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Kris", "newPassword2" ) ) << "Expect true since this user a valid account."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Linda", "newPassword1") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Kris", "newPassword2") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect false since the password is invalid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect false since the password is invalid."; /* Changing password. Testing with invalid username. */ EXPECT_FALSE(acc.changePassword("George", "newPassword" ) ) << "Expect false since George is an invalid username."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Delete an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.deleteAccount("Betty") ) << "Expect false since the username is valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Linda") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(1, acc.getNumberOfAccounts() ) << "Expect 1 since there is now one account."; /* Verify account of deleted user. */ EXPECT_FALSE(acc.verifyAccount("Linda", "newPassword1") ) << "Expect false since this username is deleted from the system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Kris", "newPassword2") ) << "Expect true since the username and password are valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Kris") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there no accounts."; remove(fileName.c_str()); // delete the account system file } /* Testing with Mutliple accounts in the account system. */ TEST(AccountTest, MultipleAccounts) { legacymud::account::Account acc(fileName); /* Get the number of accounts in the account system. */ EXPECT_EQ(0, acc.getNumberOfAccounts() ) << "Expect 0 since there are not any accounts."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Linda", "validpassword1", true, 1 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Kris", "validpassword2", false, 2 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Sue", "validpassword3", false, 3 ) ) << "Expect true since this is a valid account creation."; /* Create a valid account. */ EXPECT_TRUE(acc.createAccount("Mike", "validpassword4", false, 4 ) ) << "Expect true since this is a valid account creation."; /* Get the number of accounts in the account system. */ EXPECT_EQ(4, acc.getNumberOfAccounts() ) << "Expect 4 since there are four accounts."; /* Save the account to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(4, acc.getNumberOfAccounts() ) << "Expect 4 since there are four accounts."; /* Try to create second account with the same username. */ EXPECT_FALSE(acc.createAccount("Mike", "1234", false, 2 ) ) << "Expect false since this username is not unique."; /* Check if a username is unique. Testing with a username this is already in the account system. */ EXPECT_FALSE(acc.uniqueUsername("Kris") ) << "Expect false since this username is in the account system."; /* Check if a username is unique. Testing with a username not in the account system.*/ EXPECT_TRUE(acc.uniqueUsername("George") ) << "Expect true since this username is not in the account system."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Mike", "validpassword4") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Mike", "1234") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with a valid username and password.*/ EXPECT_TRUE(acc.verifyAccount("Sue", "validpassword3") ) << "Expect true since the username and password are valid."; /* Verify an account. Testing with a valid username and invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Sue", "invalidpassword") ) << "Expect false since the password is invalid."; /* Verify an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.verifyAccount("Sally", "password4") ) << "Expect false since this username is invalid."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_TRUE(acc.verifyAdmin("Linda" ) ) << "Expect true this user is an admin."; /* Verify admin status of a user. Testing with a valid username. */ EXPECT_FALSE(acc.verifyAdmin("Mike" ) ) << "Expect false since this user is not an admin."; /* Verify admin status of a user. Testing with invalid username. */ EXPECT_FALSE(acc.verifyAdmin("Larry" ) ) << "Expect false since this username is invalid."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Linda", false ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_FALSE(acc.verifyAdmin("Linda" ) ) << "Expect false since this user is not an admin."; /* Set the admin of a user. Testing with a valid username. Setting admin to false. */ EXPECT_TRUE(acc.setAdmin("Mike", true ) ) << "Expect true since this is a valid username."; /* Verify admin status of a user. Testing with valid username. */ EXPECT_TRUE(acc.verifyAdmin("Mike" ) ) << "Expect true since this user is now an admin."; /* Set the admin of a user. Testing with an invalid username. */ EXPECT_FALSE(acc.setAdmin("Larry", false ) ) << "Expect false since this username is invalid."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(4, acc.getUserId("Mike" ) ) << "Expect 4 since this is the correct user id."; /* Get userId. Testing with a valid username. */ EXPECT_EQ(3, acc.getUserId("Sue" ) ) << "Expect 3 since this is the correct user id."; /* Get userId. Testing with invalid username. */ EXPECT_EQ(0, acc.getUserId("Larry" ) ) << "Expect -1 since this username is invalid."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Mike", "newPassword4" ) ) << "Expect true since this user a valid account."; /* Changing password. Testing with valid username. */ EXPECT_TRUE(acc.changePassword("Sue", "newPassword3" ) ) << "Expect true since this user a valid account."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Mike", "newPassword4") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with a valid password.*/ EXPECT_TRUE(acc.verifyAccount("Sue", "newPassword3") ) << "Expect true since the username and password are valid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Mike", "validpassword4") ) << "Expect false since the password is invalid."; /* Verify account of new password. Testing with old now invalid password.*/ EXPECT_FALSE(acc.verifyAccount("Sue", "validpassword3") ) << "Expect false since the password is invalid."; /* Changing password. Testing with invalid username. */ EXPECT_FALSE(acc.changePassword("George", "newPassword" ) ) << "Expect false since George is an invalid username."; /* Get the number of accounts in the account system. */ EXPECT_EQ(4, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Delete an account. Testing with an invalid username.*/ EXPECT_FALSE(acc.deleteAccount("Betty") ) << "Expect false since the username is valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Mike") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(3, acc.getNumberOfAccounts() ) << "Expect 3 since there are three accounts."; /* Verify account of deleted user. */ EXPECT_FALSE(acc.verifyAccount("Mike", "newPassword4") ) << "Expect false since this username is deleted from the system."; /* Verify account of other user. */ EXPECT_TRUE(acc.verifyAccount("Sue", "newPassword3") ) << "Expect true since the username and password are valid."; /* Delete an account. Testing with a valid username.*/ EXPECT_TRUE(acc.deleteAccount("Sue") ) << "Expect true since the username is valid."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are no accounts."; /* Verify account of deleted user. */ EXPECT_FALSE(acc.verifyAccount("Sue", "newPassword3") ) << "Expect false since this user is no longer in the account system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect true since since this user is still in the account system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect true since since this user is still in the account system."; /* Save the account data to disk. */ EXPECT_TRUE(acc.saveToDisk() ) << "Expect true since nothing should prevent data from being written to disk."; /* Initialize loading all accounts from disk. */ EXPECT_TRUE(acc.initialize() ) << "Expect true since nothing should prevent data from being loaded from disk."; /* Get the number of accounts in the account system. */ EXPECT_EQ(2, acc.getNumberOfAccounts() ) << "Expect 2 since there are two accounts."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Linda", "validpassword1") ) << "Expect true since since this user is still in the account system."; /* Verify account of remaining user. */ EXPECT_TRUE(acc.verifyAccount("Kris", "validpassword2") ) << "Expect true since since this user is still in the account system."; remove(fileName.c_str()); // delete the account system file } }
45.317869
105
0.619905
rigertd
2a6e71a05d077b451507fa23f69677e01d76050b
5,351
cxx
C++
BidirectionalQueue.cxx
jackytck/topcoder
5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3
[ "MIT" ]
null
null
null
BidirectionalQueue.cxx
jackytck/topcoder
5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3
[ "MIT" ]
null
null
null
BidirectionalQueue.cxx
jackytck/topcoder
5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3
[ "MIT" ]
null
null
null
// BEGIN CUT HERE /* // PROBLEM STATEMENT // You are given a bidirectional cyclical queue which contains N elements. You need to extract several elements from this queue. You can do 3 kinds of operations with this queue: Extract first element. After applying this operation, queue a1, ..., aK becomes a2, ..., aK. Shift queue elements left. After applying this operation, queue a1, ..., aK becomes a2, ..., aK, a1. Shift queue elements right. After applying this operation, queue a1, ..., aK becomes aK, a1, ..., aK-1. You are given the initial number of elements in the queue N and a vector <int> indices which contains the initial (1-based) positions of wanted elements in the queue. Return the minimal number of left and right shifts you'll have to perform to extract the wanted elements in the given order. DEFINITION Class:BidirectionalQueue Method:extractElements Parameters:int, vector <int> Returns:int Method signature:int extractElements(int N, vector <int> indices) CONSTRAINTS -N will be between 1 and 50, inclusive. -indices will contain between 1 and N elements, inclusive. -Each element of indices will be between 1 and N, inclusive. -All elements of indices will be distinct. EXAMPLES 0) 10 {1, 2, 3} Returns: 0 The elements are extracted in the same order as they appear in the queue, so no shifts are required. 1) 10 {2, 9, 5} Returns: 8 To extract the first wanted element, 1 left shift is required. After this the next wanted element will be 7th in a queue with 9 elements, so to extract it 3 right shifts are required. Finally, the last wanted element will be 5th in a queue with 8 elements, so either 4 left shifts or 4 right shifts are required. 2) 32 {27, 16, 30, 11, 6, 23} Returns: 59 3) 10 {1, 6, 3, 2, 7, 9, 8, 4, 10, 5} Returns: 14 */ // END CUT HERE #line 68 "BidirectionalQueue.cxx" #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #define sz size() #define PB push_back #define clr(x) memset(x, 0, sizeof(x)) #define forn(i,n) for(__typeof(n) i = 0; i < (n); i++) #define ford(i,n) for(int i = (n) - 1; i >= 0; i--) #define forv(i,v) forn(i, v.sz) #define For(i, st, en) for(__typeof(en) i = (st); i < (en); i++) using namespace std; class BidirectionalQueue { public: int extractElements(int N, vector <int> indices) { int cnt = 0; forv(i, indices) { int left = indices[i]-1, right = N-indices[i]+1; if(left-right<=0) { leftShift(N, indices, left); cnt += left; } else { rightShift(N, indices, right); cnt += right; } extractMin(N, indices); } return cnt; } void extractMin(int& N, vector <int>& indices) { N--; forv(i, indices) indices[i]--; } void leftShift(const int N, vector <int>& indices, int steps) { forv(i, indices) indices[i] -= steps; forv(i, indices) if(indices[i] < 1) indices[i] += N; } void rightShift(const int N, vector <int>& indices, int steps) { forv(i, indices) indices[i] += steps; forv(i, indices) if(indices[i] > N) indices[i] -= N; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 10; int Arr1[] = {1, 2, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(0, Arg2, extractElements(Arg0, Arg1)); } void test_case_1() { int Arg0 = 10; int Arr1[] = {2, 9, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 8; verify_case(1, Arg2, extractElements(Arg0, Arg1)); } void test_case_2() { int Arg0 = 32; int Arr1[] = {27, 16, 30, 11, 6, 23}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 59; verify_case(2, Arg2, extractElements(Arg0, Arg1)); } void test_case_3() { int Arg0 = 10; int Arr1[] = {1, 6, 3, 2, 7, 9, 8, 4, 10, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 14; verify_case(3, Arg2, extractElements(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { BidirectionalQueue ___test; ___test.run_test(-1); } // END CUT HERE
32.041916
312
0.615025
jackytck
2a70b687eb4b63c4533ccc654dccafd36d769adb
800
cpp
C++
example/DetectPortsUDP/detectports.cpp
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
6
2017-08-07T09:22:34.000Z
2019-05-11T09:11:45.000Z
example/DetectPortsUDP/detectports.cpp
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
null
null
null
example/DetectPortsUDP/detectports.cpp
jef42/pcapwrapper
6e5356fabfe2e49f96fdbd8bfbb0f8555e497969
[ "MIT" ]
2
2018-05-15T23:28:43.000Z
2021-11-13T09:53:40.000Z
#include "detectports.h" #include <iostream> #include <pcapwrapper/helpers/common.h> #include <string.h> #include <string> using namespace PCAP; DetectPorts::DetectPorts(PCAP::IpAddress desiredIp) : m_expectedip{desiredIp} { reset(); } void DetectPorts::receive_package(PCAP::ICMPPackage package) { if (package.get_src_ip() == m_expectedip) { const PCAP::uchar *data = package.get_package(); ushort port = (((ushort)data[64]) << 0x08) | ((ushort)data[65]); m_ports[port] = true; } } std::vector<int> DetectPorts::get_ports() { std::vector<int> result; for (int i = 0; i < MAX_PORT; ++i) { if (!m_ports[i]) result.push_back(i); } reset(); return result; } void DetectPorts::reset() { memset(m_ports, '\0', MAX_PORT); }
24.242424
79
0.6325
jef42
2a76a31ba0ab047a5f2ea5ec719e10c36b35931b
4,220
cpp
C++
DSP/extensions/WindowFunctionLib/tests/TTTukeyWindow.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
31
2015-02-28T23:51:10.000Z
2021-12-25T04:16:01.000Z
DSP/extensions/WindowFunctionLib/tests/TTTukeyWindow.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
126
2015-01-01T13:42:05.000Z
2021-07-13T14:11:42.000Z
DSP/extensions/WindowFunctionLib/tests/TTTukeyWindow.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
14
2015-02-10T15:08:32.000Z
2019-09-17T01:21:25.000Z
/** @file * * @ingroup dspWindowFunctionLib * * @brief Unit tests for the Tukey Window Function Unit * * @details * * @authors Nathan Wolek, Tim Place, Trond Lossius * * @copyright Copyright © 2011 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTWindowFunction.h" #include "TTTukeyWindow.h" /* * coefficients calculated using Octave using these variables and commands: * alpha = 0.5 * alphaOverTwo = alpha / 2 * twoOverAlpha = 2 / alpha * x = 0.0:1/127:1.0 * n = 1:length(x) * y = * if x(n) < alphaOverTwo * y(n) = 0.5 * (1 + cos ( pi * ((twoOverAlpha * x(n) ) - 1))); * else * if x(n) > (1 - alphaOverTwo) * y(n) = 0.5 * (1 + cos ( pi * ((twoOverAlpha * x(n) ) - twoOverAlpha + 1))); * else * y(n) = 1; * end * end */ static TTFloat64 sTukeyWindowCoefficients128[128] = { 0, 0.002445670414196688, 0.009758756441687333, 0.0218677164899363, 0.03865409245759671, 0.0599536685724058, 0.08555807786180814, 0.1152168405407152, 0.148639814375505, 0.1855000330531288, 0.2254369047884639, 0.2680597398789554, 0.3129515726976034, 0.3596732407349534, 0.4077676807861221, 0.4567644002546273, 0.5061840798316815, 0.5555432625244022, 0.6043590831616676, 0.6521539921103681, 0.6984604269914436, 0.7428253866937918, 0.7848148629399286, 0.8240180860508026, 0.8600515433748003, 0.8925627310699273, 0.9212336025366787, 0.9457836797666722, 0.9659727971697173, 0.9816034510373285, 0.9925227316586316, 0.9986238191873873, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9986238191873873, 0.9925227316586317, 0.9816034510373286, 0.9659727971697174, 0.9457836797666723, 0.9212336025366786, 0.8925627310699273, 0.8600515433748003, 0.8240180860508026, 0.7848148629399287, 0.7428253866937922, 0.698460426991444, 0.6521539921103678, 0.6043590831616674, 0.5555432625244022, 0.5061840798316815, 0.4567644002546273, 0.4077676807861222, 0.3596732407349537, 0.3129515726976038, 0.2680597398789558, 0.2254369047884637, 0.1855000330531288, 0.148639814375505, 0.1152168405407152, 0.08555807786180825, 0.05995366857240592, 0.03865409245759677, 0.02186771648993618, 0.009758756441687333, 0.002445670414196688, 0 }; TTErr TukeyWindow::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; int badSampleCount = 0; TTAudioObjectBasePtr windowObject = NULL; TTAudioSignalPtr input = NULL; TTAudioSignalPtr output = NULL; int N = 128; TTValue v; TTFloat64 testAlpha = 0.5; // setup windowObject TTObjectBaseInstantiate(TT("WindowFunction"), &windowObject, TTValue(1)); windowObject->setAttributeValue(TT("function"), TT("tukey")); windowObject->setAttributeValue(TT("mode"), TT("apply")); // set the value for alpha windowObject->setAttributeValue(TT("alpha"), testAlpha); TTTestLog("alpha was set to %.10f for test", testAlpha); // create 1 channel audio signal objects TTObjectBaseInstantiate(kTTSym_audiosignal, &input, 1); TTObjectBaseInstantiate(kTTSym_audiosignal, &output, 1); input->allocWithVectorSize(N); output->allocWithVectorSize(N); // create a signal to be transformed and then process it) input->fill(1.0); windowObject->process(input, output); // now test the output for (int n=0; n<N; n++) { TTBoolean result = !TTTestFloatEquivalence(output->mSampleVectors[0][n], sTukeyWindowCoefficients128[n]); badSampleCount += result; if (result) TTTestLog("BAD SAMPLE @ n=%i ( value=%.10f expected=%.10f )", n, output->mSampleVectors[0][n], sTukeyWindowCoefficients128[n]); } TTTestAssertion("Produces correct window coefficients", badSampleCount == 0, testAssertionCount, errorCount); if (badSampleCount) TTTestLog("badSampleCount is %i", badSampleCount); TTObjectBaseRelease(&input); TTObjectBaseRelease(&output); TTObjectBaseRelease(&windowObject); // wrap up test results and pass back to whoever called test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); }
37.017544
161
0.714455
avilleret
2a78d8daff5be631583e25777900db0800f3ef00
5,293
hpp
C++
src/evaluate.hpp
CristianCin/randMathFunction
9394d039b2c42df70f96479ba95bada3b6257b4e
[ "MIT" ]
null
null
null
src/evaluate.hpp
CristianCin/randMathFunction
9394d039b2c42df70f96479ba95bada3b6257b4e
[ "MIT" ]
null
null
null
src/evaluate.hpp
CristianCin/randMathFunction
9394d039b2c42df70f96479ba95bada3b6257b4e
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define PI 3.14159265 bool dbg = false; bool isF(string op){ if(op == "sin") return true; if(op == "cos") return true; if(op == "tan") return true; if(op == "cotan") return true; if(op == "arcsin") return true; if(op == "arccos") return true; if(op == "arctan") return true; if(op == "arccotan") return true; if(op == "sqrt") return true; if(op == "log_2") return true; if(op == "ln") return true; if(op == "log_3") return true; if(op == "log_4") return true; if(op == "log_5") return true; if(op == "log_6") return true; if(op == "log_7") return true; if(op == "log_8") return true; if(op == "log_9") return true; if(op == "log") return true; return false; } int prec(string c) { if(isF(c)) return 4; if(c == "^") return 3; if(c == "*" || c == "/") return 2; if(c == "+" || c == "-") return 1; return -1; } bool isO(string op){ return (prec(op) > 0 || isF(op))? true : false; } vector<string> infixToPostfix(vector<string> s) { stack<string> st; int l = s.size(); vector<string> ns; for(int i = 0; i < l; i++) { if(isO(s[i]) == false && isF(s[i]) == false && s[i] != "(" && s[i] != ")") ns.push_back(s[i]); else if(s[i] == "(") st.push("("); else if(s[i] == ")") { while(!st.empty() && st.top() != "(") { ns.push_back(st.top()); st.pop(); } if(st.top() == "(") st.pop(); } else{ while(!st.empty() && prec(s[i]) < prec(st.top())) { ns.push_back(st.top()); st.pop(); } st.push(s[i]); } } while(!st.empty()) { ns.push_back(st.top()); st.pop(); } return ns; } bool is_number(string number_string) { string::size_type sz; bool is_valid; double parsed_number = 0.0; try { parsed_number = std::stod(number_string, &sz); is_valid = true; } catch(std::exception& ia) { is_valid = false; } return is_valid; } vector<string> tokenization(string token){ string tmp = ""; vector<string> ret; for(int i = 0; i < token.size(); i++){ string x = string(1, token[i]) ; if(x != " "){ if(isO(x) || x == "(" || x == ")" ){ ret.push_back(tmp); ret.push_back(x); tmp = ""; } else tmp += x; }else continue; } if(tmp.size() > 0) ret.push_back(tmp); vector<string> retret; for(auto x : ret) if(x != "") retret.push_back(x); vector<string> newretret; bool flag = false; for(int i = 0; i < retret.size(); i++) if(i > 0 && i + 1 < retret.size() && (isO(retret[i-1]) || retret[i-1] == "(") && retret[i] == "-" && is_number(retret[i+1])) newretret.push_back("-" + retret[i+1]), i++; else newretret.push_back(retret[i]); return newretret; } double apply(double a, double b, string op){ if(op == "+") return a + b; if(op == "-") return a - b; if(op == "*") return a * b; if(op == "/") return a / b; if(op == "^") return pow(a,b); return 0; } double cbl(double base, double arg){ return (double)log10(arg)/(double)log10(base); } double applyF(double a, string op){ if(op == "sin") return sin((a/180)*PI); if(op == "cos") return cos((a/180)*PI); if(op == "tan") return tan((a/180)*PI); if(op == "cotan") return 1/tan((a/180)*PI); if(op == "arcsin") return asin(a) * 180.0 / PI; if(op == "arccos") return acos(a) * 180.0 / PI; if(op == "arctan") return atan(a) * 180.0 / PI; if(op == "arccotan") return PI/2 - atan(a); if(op == "sqrt") return sqrt(a); if(op == "log_2") return log2(a); if(op == "ln") return log(a); if(op == "log_3") return cbl(3,a); if(op == "log_4") return cbl(4,a); if(op == "log_5") return cbl(5,a); if(op == "log_6") return cbl(6,a); if(op == "log_7") return cbl(7,a); if(op == "log_8") return cbl(8,a); if(op == "log_9") return cbl(9,a); if(op == "log") return log10(a); return 0; } double evaluate(string expr){ vector<string> tokens = tokenization(expr); vector<string> post = infixToPostfix(tokens); if(dbg){ for(int i = 0; i < post.size(); i++) cout<<"["<<post[i]<<"]"; cout<<endl; } stack<double> values; for(int i = 0; i < post.size(); i++){ if(isF(post[i]) || isO(post[i])){ if(isF(post[i])){ double value = values.top(); values.pop(); values.push(applyF(value, post[i])); }else{ double value1 = values.top(); values.pop(); double value2 = values.top(); values.pop(); values.push(apply(value2, value1, post[i])); } }else values.push(stold(post[i])); if(dbg){ for(stack<double> tmp = values; !tmp.empty(); tmp.pop()) cout<<tmp.top()<<" "; cout<<endl; } } return values.top(); }
23.317181
132
0.472889
CristianCin
2a7cb726963da0dd2ae1d8cda7ffb780bc1302f7
3,763
cpp
C++
PrismAPI/PrismCore/Enum.cpp
DigitalQR/Prism
e67965040ec9f7375a73a6924051e4962228eecd
[ "MIT" ]
1
2021-06-30T07:13:20.000Z
2021-06-30T07:13:20.000Z
PrismAPI/PrismCore/Enum.cpp
DigitalQR/Prism
e67965040ec9f7375a73a6924051e4962228eecd
[ "MIT" ]
null
null
null
PrismAPI/PrismCore/Enum.cpp
DigitalQR/Prism
e67965040ec9f7375a73a6924051e4962228eecd
[ "MIT" ]
null
null
null
#include "Include\Prism\Enum.h" namespace Prism { Enum::Value::Value() : Name() , NumberValue() { } Enum::Value::Value(const String& name, size_t value) : Name(name) , NumberValue(value) { } Enum::Enum(long uniqueId, const String& space, const String& name, const String& documentation, size_t size, const TemplateInfo* templateInfo, const std::vector<const Attribute*>& attributes, const std::vector<Value>& values) : Type(uniqueId, space, name, documentation, size, templateInfo, attributes, false, true) , m_Values(values) { } Prism::Object Enum::CreateNew(const std::vector<Prism::Object>& params) const { if (params.size() != 0) return nullptr; switch (m_Size) { case 1: { if (params.size() == 0) return new __int8; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int8(params[0].GetAs<__int8>()); else return nullptr; } case 2: { if (params.size() == 0) return new __int16; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int16(params[0].GetAs<__int16>()); else return nullptr; } case 4: { if (params.size() == 0) return new __int32; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int32(params[0].GetAs<__int32>()); else return nullptr; } case 8: { if (params.size() == 0) return new __int64; else if (params.size() == 1 && params[0].GetTypeInfo() == m_AssociatedInfo) return new __int64(params[0].GetAs<__int64>()); else return nullptr; } default: return nullptr; } } Prism::String Enum::ToString(Prism::Object inStorage) const { switch (m_Size) { case 1: { __int8& inValue = *inStorage.GetPtrAs<__int8>(); for (const auto& value : m_Values) { if ((__int8)value.NumberValue == inValue) { return value.Name; } } break; } case 2: { __int16& inValue = *inStorage.GetPtrAs<__int16>(); for (const auto& value : m_Values) { if ((__int16)value.NumberValue == inValue) { return value.Name; } } break; } case 4: { __int32& inValue = *inStorage.GetPtrAs<__int32>(); for (const auto& value : m_Values) { if ((__int32)value.NumberValue == inValue) { return value.Name; } } break; } case 8: { __int64& inValue = *inStorage.GetPtrAs<__int64>(); for (const auto& value : m_Values) { if ((__int64)value.NumberValue == inValue) { return value.Name; } } break; } } return Prism::Type::ToString(inStorage); } bool Enum::ParseFromString(const String& str, Prism::Object outStorage) const { switch (m_Size) { case 1: { __int8& outValue = *outStorage.GetPtrAs<__int8>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int8)value.NumberValue; return true; } } return false; } case 2: { __int16& outValue = *outStorage.GetPtrAs<__int16>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int16)value.NumberValue; return true; } } return false; } case 4: { __int32& outValue = *outStorage.GetPtrAs<__int32>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int32)value.NumberValue; return true; } } return false; } case 8: { __int64& outValue = *outStorage.GetPtrAs<__int64>(); for (const auto& value : m_Values) { if (value.Name == str) { outValue = (__int64)value.NumberValue; return true; } } return false; } default: return false; } } }
17.834123
227
0.599787
DigitalQR
2a7d73c1cbd1eb116a8ae9b4af582b990052501a
15,611
hpp
C++
src/iterators/row.hpp
oraqlle/cortex-iterators
425f71efdc654103458795440752f6804722fc12
[ "MIT" ]
null
null
null
src/iterators/row.hpp
oraqlle/cortex-iterators
425f71efdc654103458795440752f6804722fc12
[ "MIT" ]
null
null
null
src/iterators/row.hpp
oraqlle/cortex-iterators
425f71efdc654103458795440752f6804722fc12
[ "MIT" ]
null
null
null
/// -*- C++ -*- Header compatibility <row.hpp> /// @file row.hpp /// @author Tyler Swann (oraqlle@github.com) /// @brief Row Iterator /// @version 1.0.1 /// @date 2022-05-20 /// /// @ingroup %iterators /// /// @copyright Copyright (c) 2022 /// #ifndef CORTEX_ROW_ITERATOR_HPP # define CORTEX_ROW_ITERATOR_HPP 1 #include <utility> #include <type_traits> #include <iterator> #include <iterators/two_dim.hpp> #if __cpp_lib_three_way_comparison # include <compare> #endif /// __cpp_lib_three_way_comparison #if __cpp_concepts >= 201907L # include <concepts> #endif /// __cpp_concepts >= 201907L # if __cplusplus >= 201402L namespace cortex { /// @brief Row Iterator /// /// @details A row iterator is a iterator that iterates a /// given two dimensional space in row order. Incrementing /// moves the iterator to the next item in that row and /// vice versa for decrementing. Incrementing from the last item /// in a row causes the iterator to jump to the first item in /// the next row. Like wise, decrementing from the first item /// in a row causes the iterator to jump to the last item in /// the previous row. A column iterator is derived from the base /// %cortex::two_dim_iterator. /// /// @tparam _Iterator template<typename _Iterator> class row_iterator : public two_dim_iterator<_Iterator> { protected: using _Base = two_dim_iterator<_Iterator>; using __traits_type = typename _Base::__traits_type; public: using iterator_type = typename _Base::iterator_type; using iterator_category = typename _Base::iterator_category; // #if __cpp_concepts >= 201907L // using iterator_concept = typename _Base::iterator_concept; // #endif /// __cpp_concepts >= 201907L using size_type = typename _Base::size_type; using value_type = typename __traits_type::value_type; using difference_type = typename __traits_type::difference_type; using pointer = typename __traits_type::pointer; using reference = typename __traits_type::reference; public: /// @brief Default Constructor /// /// @details Constructs a row iterator with /// the two_dim_iterators default constrcutor. constexpr row_iterator() noexcept : _Base() { } /// @brief Explicit Value Constrcutor /// /// @details Constructs a column iterator from a reference to /// an iterator of the underlying iterator type, the dimensions /// the column iterator can move through and the current point /// index the iterator points to. Calls the base class constructor. /// /// @param ptr type: iterator_type | qualifier: [const, ref] constexpr row_iterator(const iterator_type& ptr , size_type ridx, size_type cidx , size_type row, size_type col) noexcept : _Base(ptr, ridx, cidx, row, col) {} /// @brief Pre Increment Operator /// /// @details Increments the iterator to the next item in the /// row. If the iterator is at the end of the row, the iterator /// jumps to the first item in the next row. /// /// @return constexpr row_iterator& constexpr row_iterator& operator++ () noexcept { auto old_ridx { this->m_ridx }; auto old_cidx { this->m_cidx }; if (this->m_cidx == this->m_columns - 1) { this->m_cidx = size_type(); this->m_ridx++; } else this->m_cidx++; this->m_current += this->_M_index((this->m_ridx - old_ridx) , (this->m_cidx - old_cidx)); return *this; } /// @brief Post Increment Operator /// /// @details Increments the iterator to the next item in the /// row. If the iterator is at the end of the row, the iterator /// jumps to the first item in the next row. Returns the iterator /// before the increment. /// /// @return constexpr row_iterator constexpr row_iterator operator++ (int) noexcept { auto old { row_iterator(*this) }; if (this->m_cidx == this->m_columns - 1) { this->m_cidx = size_type(); this->m_ridx++; } else this->m_cidx++; this->m_current += this->_M_index((this->m_ridx - old.row_index()) , (this->m_cidx - old.column_index())); return old; } /// @brief Pre Decrement Operator /// /// @details Decrements the iterator to the previous item in the /// row. If the iterator is at the first item in the row, the /// iterator jumps to the last item in the previous row. /// /// @return constexpr row_iterator& constexpr row_iterator& operator-- () noexcept { auto old_ridx { this->m_ridx }; auto old_cidx { this->m_cidx }; if (this->m_cidx == size_type()) { this->m_cidx = this->m_columns; this->m_ridx--; } this->m_cidx--; this->m_current += this->_M_index((this->m_ridx - old_ridx) , (this->m_cidx - old_cidx)); return *this; } /// @brief Post Decrement Operator /// /// @details Decrements the iterator to the previous item in the /// row. If the iterator is at the first item in the row, the /// iterator jumps to the last item in the previous row. Returns /// the iterator before the decrement. /// /// @return constexpr row_iterator constexpr row_iterator operator-- (int) noexcept { auto old { row_iterator(*this) }; if (this->m_cidx == size_type()) { this->m_cidx = this->m_columns; this->m_ridx--; } this->m_cidx--; this->m_current += this->_M_index((this->m_ridx - old.row_index()) , (this->m_cidx - old.column_index())); return old; } /// constexpr reference operator[] (difference_type __n) noexcept /// { /// size_type cols { __n / this->m_columns }; /// auto rows { __n % this->m_columns }; /// return *(this->m_current + this->_M_access(rows, cols)); /// } /// constexpr row_iterator& operator+= (difference_type __step) noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// this->m_current += this->_M_access(rows, cols); /// return *this; /// } /// constexpr row_iterator& operator-= (difference_type __step) noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// this->m_current -= this->_M_access(rows, cols); /// return *this; /// } /// constexpr row_iterator operator+ (difference_type __step) const noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// return row_iterator(this->m_current + this->_M_access(rows, cols), this->m_ridx + rows, this->m_cidx + cols, this->m_rows, this->m_columns); /// } /// constexpr row_iterator operator- (difference_type __step) const noexcept /// { /// size_type cols { __step / this->m_columns }; /// auto rows { __step % this->m_columns }; /// return row_iterator(this->m_current - this->_M_access(rows, cols), this->m_ridx + rows, this->m_cidx + cols, this->m_rows, this->m_columns); /// } }; /// class row_iterator /// @brief Addition Operator Overload. /// /// @details Takes an offset @param __n and a %row_iterator /// @param __i. Constructs a new %row_iterator by adding /// @param __n to @param __i.base(). /// /// @tparam _Iterator /// @tparam _Container /// @param __n /// @param __i /// @return constexpr inline row_iterator<_Iterator, _Container> /// /// [constexpr] /// [noexcept] /// template<typename _Iterator> /// constexpr inline row_iterator<_Iterator> /// operator+ (typename row_iterator<_Iterator>::difference_type __n, /// const row_iterator<_Iterator>& __i) /// noexcept /// { /// std::size_t cols { __n / __i.columns() }; /// auto rows { __n % __i.columns() }; /// auto offset { __i.columns()/// rows + cols }; /// return row_iterator(__i.base() + offset /// , __i.row_index() + rows, __i.column_index() + cols /// , __i.rows(), __i.columns()); /// } /// @brief Less Than Operator /// /// @details Performs less-than comparison of two row /// iterators. A row iterator is considered less than another /// firstly, if it is at a lower row index. If the row indices /// are equal, the row iterator is considered less than another /// if it is at a lower column index. /// /// @tparam _Iterator /// @param __lhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @param __rhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator< (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs.row_index() < __rhs.row_index() ? true : __lhs.row_index() == __rhs.row_index() and __lhs.column_index() < __rhs.column_index() ? true : false; } /// @brief Greater Than Operator /// /// @details Performs greater-than comparison of two row /// iterators. A row iterator is considered greater than /// another firstly, if it is at a higher row index. If the /// row indices are equal, the row iterator is considered /// greater than another if it is at a higher column index. /// /// @tparam _Iterator /// @param __lhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @param __rhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator> (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs.row_index() > __rhs.row_index() ? true : __lhs.row_index() == __rhs.row_index() and __lhs.column_index() > __rhs.column_index() ? true : false; } /// @brief Less Than or Equal Operator /// /// @details Performs less-than-or-equal comparison of two row /// iterators. A row iterator is considered less than or equal /// to another firstly, if they compare equal, secondly if they /// compare less than. /// /// @tparam _Iterator /// @param __lhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @param __rhs type: row_iterator<_Iterator> | qualifier: [const, ref] /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator<= (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs == __rhs ? true : __lhs < __rhs ? true : false; } /// @brief Greater Than or Equal Operator /// /// @details Performs greater-than-or-equal comparison of two row /// iterators. A row iterator is considered greater than or equal /// to another firstly, if they compare equal, secondly if they /// compare greater than. /// /// @tparam _Iterator /// @param __lhs /// @param __rhs /// @return true /// @return false template<typename _Iterator> constexpr inline bool operator>= (const row_iterator<_Iterator>& __lhs, const row_iterator<_Iterator>& __rhs) noexcept { return __lhs == __rhs ? true : __lhs > __rhs ? true : false; } // // /// @brief Makes a new %row_iterator. // /// // /// @details An adaptor for turning STL container iterators // /// into %row_iterators. // /// // /// @code {.cpp} // /// auto it = make_row_iterator<std::container>(c.begin()); // /// @endcode // /// // /// @tparam _Container // /// @param __i // /// @return constexpr auto -> row_iterator<typename _Container::iterator, _Container> // /// // /// [constexpr] // /// [noexcept] // // template<typename _Container> // constexpr auto // make_column(typename _Container::iterator __i) // noexcept // -> row_iterator<typename _Container::iterator> // { return row_iterator<typename _Container::iterator, _Container>(__i); } // // /// @brief Makes a new %row_iterator. // /// // /// @details An adaptor for making C-style array pointers // /// into %row_iterators. // /// // /// @code {.cpp} // /// auto it = make_normal<int*, int[]>(arr); // /// @endcode // /// // /// @tparam _Iterator // /// @tparam _Container // /// @param __i // /// @return constexpr auto -> row_iterator<_Iterator, _Container> // /// // /// [constexpr] // /// [noexcept] // // template<typename _Iterator, typename _Container> // constexpr auto // make_column(_Iterator __i) // noexcept // -> row_iterator<_Iterator, _Container> // { return row_iterator<_Iterator, _Container>(__i); } // # if __cplusplus >= 201703L /// C++17 // // /// @brief Makes a new %row_iterator. // /// // /// @details An adaptor for making STL container iterators // /// into %row_iterators using C++17 type deduction. // /// // /// @code {.cpp} // /// auto it = make_normal(c, c.begin()); // /// @endcode // /// // /// @note @param __c has the attribute [[maybe_unused]] // /// // /// @tparam _Container // /// @tparam _Iterator // /// @param __c // /// @param __i // /// @return constexpr auto -> row_iterator<_Iterator, _Container> // /// // /// [constexpr] // /// [noexcept] // // template<typename _Container, typename _Iterator> // constexpr auto // make_column([[maybe_unused]] const _Container& __c, _Iterator __i) // noexcept // -> row_iterator<_Iterator, _Container> // { return row_iterator<_Iterator, _Container>(__i); } // // # endif /// __cplusplus >= 201703L } /// namespace cortex # endif /// __cplusplus >= 201402L #endif /// CORTEX_ROW_ITERATOR_HPP
32.796218
156
0.556403
oraqlle
2a7efb999e50a381c8c93e69cc93ae13bc444898
1,205
cpp
C++
Sorting Algorithms/Merge_Sorting.cpp
forkkr/Data-Structure-Lab-CSE---2111-
6d1d3e1853083311971d0191630fc9a2afff7b38
[ "MIT" ]
null
null
null
Sorting Algorithms/Merge_Sorting.cpp
forkkr/Data-Structure-Lab-CSE---2111-
6d1d3e1853083311971d0191630fc9a2afff7b38
[ "MIT" ]
null
null
null
Sorting Algorithms/Merge_Sorting.cpp
forkkr/Data-Structure-Lab-CSE---2111-
6d1d3e1853083311971d0191630fc9a2afff7b38
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int Merging(int ar[] , int start , int last , int mid) { int p = mid; int q = last ; int i = start ; int j = mid + 1 ; int tmp[last - start +5]; int k = 0; while(i<=p||j<=q) { if(i>p) tmp[k++] = ar[j++]; else if(j>q) tmp[k++] = ar[i++]; else if(ar[j]>ar[i]) tmp[k++] = ar[j++]; else { tmp[k++] = ar[i++]; } } i = start ; j = 0; while( j < k) { ar[start++]= tmp[j++]; } return 0; } Merge_sort(int ar[], int start , int last) { if(start >= last) return 0; int mid = ( start + last )/2; Merge_sort(ar , start , mid); Merge_sort(ar , mid+1 , last); return Merging(ar , start , last , mid); } int main() { int n; cin>>n; int ar[n+1]; for(int i = 0 ; i < n ; i++) { cin>>ar[i]; } /* for(int i = 0 ; i < n ; i++) { cout<<ar[i]<<" "; } cout<<endl;*/ Merge_sort(ar , 0 , n-1); for(int i = 0 ; i < n ; i++) { cout<<ar[i]<<" "; } }
18.538462
55
0.372614
forkkr
2a8135c21c7c6950f36a3fb3b828ee6664543f03
14,037
cpp
C++
test/storage/log_test.cpp
advanced-database-group/terrier
60c86afd9c9f2a2d030dd9852903e91b0e4db48d
[ "MIT" ]
null
null
null
test/storage/log_test.cpp
advanced-database-group/terrier
60c86afd9c9f2a2d030dd9852903e91b0e4db48d
[ "MIT" ]
null
null
null
test/storage/log_test.cpp
advanced-database-group/terrier
60c86afd9c9f2a2d030dd9852903e91b0e4db48d
[ "MIT" ]
null
null
null
#include <unordered_map> #include <vector> #include "gtest/gtest.h" #include "storage/checkpoint_manager.h" #include "storage/data_table.h" #include "storage/garbage_collector.h" #include "storage/write_ahead_log/log_manager.h" #include "transaction/transaction_manager.h" #include "util/sql_transaction_test_util.h" #include "util/storage_test_util.h" #include "util/test_harness.h" #define LOG_FILE_NAME "test.log" #define CHECKPOINT_FILE_PREFIX "checkpoint_file_" // Note: make sure to clear log files before testing. Because logging's file operation is append. namespace terrier { class WriteAheadLoggingTests : public TerrierTest { public: void StartLogging(uint32_t log_period_milli) { logging_ = true; log_thread_ = std::thread([log_period_milli, this] { LogThreadLoop(log_period_milli); }); } void EndLogging() { logging_ = false; log_thread_.join(); log_manager_.Shutdown(); } void StartGC(transaction::TransactionManager *txn_manager, uint32_t gc_period_milli) { gc_ = new storage::GarbageCollector(txn_manager); run_gc_ = true; gc_thread_ = std::thread([gc_period_milli, this] { GCThreadLoop(gc_period_milli); }); } void EndGC() { run_gc_ = false; gc_thread_.join(); // Make sure all garbage is collected. This take 2 runs for unlink and deallocate gc_->PerformGarbageCollection(); gc_->PerformGarbageCollection(); delete gc_; } std::default_random_engine generator_; storage::RecordBufferSegmentPool pool_{2000, 100}; storage::BlockStore block_store_{100, 100}; storage::LogManager log_manager_{LOG_FILE_NAME, &pool_}; // Members related to running gc / logging. std::thread log_thread_; bool logging_; volatile bool run_gc_ = false; std::thread gc_thread_; storage::GarbageCollector *gc_; storage::CheckpointManager checkpoint_manager_{CHECKPOINT_FILE_PREFIX}; private: void LogThreadLoop(uint32_t log_period_milli) { while (logging_) { std::this_thread::sleep_for(std::chrono::milliseconds(log_period_milli)); log_manager_.Process(); } } void GCThreadLoop(uint32_t gc_period_milli) { while (run_gc_) { std::this_thread::sleep_for(std::chrono::milliseconds(gc_period_milli)); gc_->PerformGarbageCollection(); } } }; // This test uses the LargeTransactionTestObject to simulate some number of transactions with logging turned on, and // then reads the logged out content to make sure they are correct // NOLINTNEXTLINE TEST_F(WriteAheadLoggingTests, LargeLogTest) { // There are 5 columns. The table has 10 rows. Each transaction does 5 operations. The update-select ratio of // operations is 50%-50%. SqlLargeTransactionTestObject tested = SqlLargeTransactionTestObject::Builder() .SetMaxColumns(10) .SetInitialTableSize(50) .SetTxnLength(5) .SetUpdateSelectRatio({0.5, 0.5}) .SetBlockStore(&block_store_) .SetBufferPool(&pool_) .SetGenerator(&generator_) .SetGcOn(true) .SetBookkeeping(true) .SetLogManager(&log_manager_) .build(); StartLogging(10); StartGC(tested.GetTxnManager(), 10); auto result = tested.SimulateOltp(100, 4); EndLogging(); EndGC(); checkpoint_manager_.RegisterTable(tested.GetTable()); std::unordered_map<transaction::timestamp_t, SqlRandomWorkloadTransaction *> txns_map; for (auto *txn : result.first) txns_map[txn->BeginTimestamp()] = txn; // At this point all the log records should have been written out, we can start reading stuff back in. storage::BufferedLogReader in(LOG_FILE_NAME); while (in.HasMore()) { std::vector<byte *> dummy_varlen_contents; storage::LogRecord *log_record = checkpoint_manager_.ReadNextLogRecord(&in, &dummy_varlen_contents); if (log_record->TxnBegin() == transaction::timestamp_t(0)) { // TODO(Tianyu): This is hacky, but it will be a pain to extract the initial transaction. The LargeTransactionTest // harness probably needs some refactor (later after wal is in). // This the initial setup transaction. delete[] reinterpret_cast<byte *>(log_record); continue; } auto it = txns_map.find(log_record->TxnBegin()); if (it == txns_map.end()) { // Okay to write out aborted transaction's redos, just cannot be a commit EXPECT_NE(log_record->RecordType(), storage::LogRecordType::COMMIT); delete[] reinterpret_cast<byte *>(log_record); continue; } if (log_record->RecordType() == storage::LogRecordType::COMMIT) { EXPECT_EQ(log_record->GetUnderlyingRecordBodyAs<storage::CommitRecord>()->CommitTime(), it->second->CommitTimestamp()); EXPECT_TRUE(it->second->Updates()->empty()); // All previous updates have been logged out previously txns_map.erase(it); } else { // This is leveraging the fact that we don't update the same tuple twice in a transaction with // bookkeeping turned on auto *redo = log_record->GetUnderlyingRecordBodyAs<storage::RedoRecord>(); // TODO(Tianyu): The DataTable field cannot be recreated from oid_t yet (we also don't really have oids), // so we are not checking it. auto update_it = it->second->Updates()->find(redo->GetTupleSlot()); EXPECT_NE(it->second->Updates()->end(), update_it); EXPECT_TRUE(StorageTestUtil::ProjectionListEqualShallow(tested.Layout(), update_it->second, redo->Delta())); delete[] reinterpret_cast<byte *>(update_it->second); it->second->Updates()->erase(update_it); } delete[] reinterpret_cast<byte *>(log_record); } // Ensure that the only committed transactions which remain in txns_map are read-only, because any other committing // transaction will generate a commit record and will be erased from txns_map in the checks above, if log records are // properly being written out. If at this point, there is exists any transaction in txns_map which made updates, then // something went wrong with logging. Read-only transactions do not generate commit records, so they will remain in // txns_map. for (const auto &kv_pair : txns_map) { EXPECT_TRUE(kv_pair.second->Updates()->empty()); } unlink(LOG_FILE_NAME); for (auto *txn : result.first) delete txn; for (auto *txn : result.second) delete txn; } // This test uses the LargeTransactionTestObject to simulate some number of transactions with logging turned on, and // then reads the logged out content to make sure they are correct. Varlens allowed. // NOLINTNEXTLINE TEST_F(WriteAheadLoggingTests, LargeLogTestWithVarlen) { // There are 5 columns. The table has 10 rows. Each transaction does 5 operations. The update-select ratio of // operations is 50%-50%. SqlLargeTransactionTestObject tested = SqlLargeTransactionTestObject::Builder() .SetMaxColumns(10) .SetInitialTableSize(50) .SetTxnLength(5) .SetUpdateSelectRatio({0.5, 0.5}) .SetBlockStore(&block_store_) .SetBufferPool(&pool_) .SetGenerator(&generator_) .SetGcOn(true) .SetBookkeeping(true) .SetLogManager(&log_manager_) .SetVarlenAllowed(true) .build(); StartLogging(10); auto result = tested.SimulateOltp(100, 4); EndLogging(); checkpoint_manager_.RegisterTable(tested.GetTable()); std::unordered_map<transaction::timestamp_t, SqlRandomWorkloadTransaction *> txns_map; for (auto *txn : result.first) txns_map[txn->BeginTimestamp()] = txn; // At this point all the log records should have been written out, we can start reading stuff back in. storage::BufferedLogReader in(LOG_FILE_NAME); while (in.HasMore()) { std::vector<byte *> varlen_contents; storage::LogRecord *log_record = checkpoint_manager_.ReadNextLogRecord(&in, &varlen_contents); if (log_record->TxnBegin() == transaction::timestamp_t(0)) { // TODO(Tianyu): This is hacky, but it will be a pain to extract the initial transaction. The LargeTransactionTest // harness probably needs some refactor (later after wal is in). // This the initial setup transaction. for (auto varlen_content : varlen_contents) { delete[] varlen_content; } delete[] reinterpret_cast<byte *>(log_record); continue; } auto it = txns_map.find(log_record->TxnBegin()); if (it == txns_map.end()) { // Okay to write out aborted transaction's redos, just cannot be a commit EXPECT_NE(log_record->RecordType(), storage::LogRecordType::COMMIT); for (auto varlen_content : varlen_contents) { delete[] varlen_content; } delete[] reinterpret_cast<byte *>(log_record); continue; } if (log_record->RecordType() == storage::LogRecordType::COMMIT) { EXPECT_EQ(log_record->GetUnderlyingRecordBodyAs<storage::CommitRecord>()->CommitTime(), it->second->CommitTimestamp()); EXPECT_TRUE(it->second->Updates()->empty()); // All previous updates have been logged out previously txns_map.erase(it); } else { // This is leveraging the fact that we don't update the same tuple twice in a transaction with // bookkeeping turned on auto *redo = log_record->GetUnderlyingRecordBodyAs<storage::RedoRecord>(); // TODO(Tianyu): The DataTable field cannot be recreated from oid_t yet (we also don't really have oids), // so we are not checking it. auto update_it = it->second->Updates()->find(redo->GetTupleSlot()); EXPECT_NE(it->second->Updates()->end(), update_it); EXPECT_TRUE(StorageTestUtil::ProjectionListEqualDeep(tested.Layout(), update_it->second, redo->Delta())); delete[] reinterpret_cast<byte *>(update_it->second); it->second->Updates()->erase(update_it); } for (auto varlen_content : varlen_contents) { delete[] varlen_content; } delete[] reinterpret_cast<byte *>(log_record); } // Ensure that the only committed transactions which remain in txns_map are read-only, because any other committing // transaction will generate a commit record and will be erased from txns_map in the checks above, if log records are // properly being written out. If at this point, there is exists any transaction in txns_map which made updates, then // something went wrong with logging. Read-only transactions do not generate commit records, so they will remain in // txns_map. for (const auto &kv_pair : txns_map) { EXPECT_TRUE(kv_pair.second->Updates()->empty()); } // Cannot open GC earlier, because it would free transaction workload's varlen contents. Bookkeeping does not // copy an entire varlen out. StartGC(tested.GetTxnManager(), 10); EndGC(); unlink(LOG_FILE_NAME); for (auto *txn : result.first) delete txn; for (auto *txn : result.second) delete txn; } // This test simulates a series of read-only transactions, and then reads the generated log file back in to ensure that // read-only transactions do not generate any log records, as they are not necessary for recovery. // NOLINTNEXTLINE TEST_F(WriteAheadLoggingTests, ReadOnlyTransactionsGenerateNoLogTest) { // Each transaction is read-only (update-select ratio of 0-100). Also, no need for bookkeeping. SqlLargeTransactionTestObject tested = SqlLargeTransactionTestObject::Builder() .SetMaxColumns(5) .SetInitialTableSize(10) .SetTxnLength(5) .SetUpdateSelectRatio({0.0, 1.0}) .SetBlockStore(&block_store_) .SetBufferPool(&pool_) .SetGenerator(&generator_) .SetGcOn(true) .SetBookkeeping(false) .SetLogManager(&log_manager_) .build(); StartLogging(10); StartGC(tested.GetTxnManager(), 10); auto result = tested.SimulateOltp(100, 4); EndLogging(); EndGC(); // Read-only workload has completed. Read the log file back in to check that no records were produced for these // transactions. checkpoint_manager_.RegisterTable(tested.GetTable()); int log_records_count = 0; storage::BufferedLogReader in(LOG_FILE_NAME); while (in.HasMore()) { std::vector<byte *> dummy_varlen_contents; storage::LogRecord *log_record = checkpoint_manager_.ReadNextLogRecord(&in, &dummy_varlen_contents); if (log_record->TxnBegin() == transaction::timestamp_t(0)) { // (TODO) Currently following pattern from LargeLogTest of skipping the initial transaction. When the transaction // testing framework changes, fix this. delete[] reinterpret_cast<byte *>(log_record); continue; } log_records_count += 1; delete[] reinterpret_cast<byte *>(log_record); } EXPECT_EQ(log_records_count, 0); unlink(LOG_FILE_NAME); for (auto *txn : result.first) delete txn; for (auto *txn : result.second) delete txn; } } // namespace terrier
46.946488
120
0.647218
advanced-database-group
2a8527bd81e57dbb2bad07046fdb6138dc58b2ce
2,340
cpp
C++
Immortal/Framework/Vector.cpp
QSXW/Immortal
32adcc8609b318752dd97f1c14dc7368b47d47d1
[ "Apache-2.0" ]
6
2021-09-15T08:56:28.000Z
2022-03-29T15:55:02.000Z
Immortal/Framework/Vector.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
null
null
null
Immortal/Framework/Vector.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
4
2021-12-05T17:28:57.000Z
2022-03-29T15:55:05.000Z
#include "impch.h" #include "Vector.h" namespace Immortal { namespace Vector { bool DecomposeTransform(const mat4& transform, Vector3& position, Vector3& rotation, Vector3& scale) { using T = float; mat4 localMatrix(transform); // Normalize the matrix. if (EpsilonEqual(localMatrix[3][3], static_cast<float>(0), Epsilon<T>())) return false; // First, isolate perspective. This is the messiest. if ( EpsilonNotEqual(localMatrix[0][3], static_cast<T>(0), Epsilon<T>()) || EpsilonNotEqual(localMatrix[1][3], static_cast<T>(0), Epsilon<T>()) || EpsilonNotEqual(localMatrix[2][3], static_cast<T>(0), Epsilon<T>())) { // Clear the perspective partition localMatrix[0][3] = localMatrix[1][3] = localMatrix[2][3] = static_cast<T>(0); localMatrix[3][3] = static_cast<T>(1); } // Next take care of translation (easy). position = Vector3(localMatrix[3]); localMatrix[3] = Vector4(0, 0, 0, localMatrix[3].w); Vector3 Row[3] = { Vector3(0.0f), Vector3(0.0f), Vector3(0.0f) }; // Now get scale and shear. for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Row[i][j] = localMatrix[i][j]; } } // Compute X scale factor and normalize first row. scale.x = Length(Row[0]); Row[0] = Detail::scale(Row[0], static_cast<T>(1)); scale.y = Length(Row[1]); Row[1] = Detail::scale(Row[1], static_cast<T>(1)); scale.z = Length(Row[2]); Row[2] = Detail::scale(Row[2], static_cast<T>(1)); // At this point, the matrix (in rows[]) is orthonormal. // Check for a coordinate system flip. If the determinant // is -1, then negate the matrix and the scaling factors. #if 0 Vector3 Pdum3; Pdum3 = cross(Row[1], Row[2]); // v3Cross(row[1], row[2], Pdum3); if (dot(Row[0], Pdum3) < 0) { for (length_t i = 0; i < 3; i++) { scale[i] *= static_cast<T>(-1); Row[i] *= static_cast<T>(-1); } } #endif rotation.y = asin(-Row[0][2]); if (cos(rotation.y) != 0) { rotation.x = atan2(Row[1][2], Row[2][2]); rotation.z = atan2(Row[0][1], Row[0][0]); } else { rotation.x = atan2(-Row[2][0], Row[1][1]); rotation.z = 0; } return true; } } }
27.529412
100
0.55812
QSXW
2a8bc871386aa8324ed470aad365372e19b28bca
2,575
cpp
C++
src/use_mmap/mmapUT.cpp
unihykes/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
2
2018-03-27T02:46:03.000Z
2018-05-24T02:49:17.000Z
src/use_mmap/mmapUT.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
src/use_mmap/mmapUT.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** LICENSE: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author:liu.hao(33852613@163.com) Time:2017-6 info: 共享内存文件 shm_open:创建内存文件,路径要求类似/filename,以/起头,然后文件名,中间不能带/ 可以使用cat查看该内存文件的内容 cat /dev/shm/xxxxx ***************************************************************************************************/ #include <mkheaders.h> #include <gtest/gtest.h> //#include<stdio.h> //#include<stdlib.h> //#include<string.h> //#include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<sys/stat.h> #include<sys/mman.h> //////////////////////////////////////////////////////////////////////////////// // mmapUT // class mmapUT : public testing::Test { protected: static void SetUpTestCase(){} static void TearDownTestCase(){} virtual void SetUp(){} virtual void TearDown(){} protected: }; /*封装打印出错函数*/ void sys_err(const char *str,int num){ perror(str); exit(num); } TEST_F(mmapUT, Write) { int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777); //O_EXCL|O_CREAT,若文件已经存在,则报错 if(fd < 0){ /*直接打开文件读写*/ fd = shm_open("/hello.txt",O_RDWR,0777); } else { //若为自己创建的文件,则为文件分配内存空间大小 //ftruncate会将参数fd指定的文件大小改为参数length指定的大小。 ftruncate(fd,4096); } //mmap将一个文件或者其它对象映射进内存。 //void* mmap ( void * addr , size_t len , int prot , int flags , int fd , off_t offset ) void *ptr = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); //写文件 printf("start writeing data....\n"); strcpy((char*)ptr,"mmap:do something!"); printf("write over\n"); //阻塞进程 getchar(); //删除内存映射文件 shm_unlink("/hello.txt"); close(fd); } TEST_F(mmapUT, Read) { int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777); if(fd < 0){ fd = shm_open("/hello.txt",O_RDWR,0777); } else { ftruncate(fd,4096); } void *ptr = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); //读文件 printf("start reading data....\n"); printf("%s\n", (char*)ptr); printf("read over\n"); //删除内存映射文件 shm_unlink("/hello.txt"); close(fd); }
22.991071
101
0.611262
unihykes
2a8bd543dd5a49d4f19b179e519805f196d02405
1,021
cc
C++
src/motif/main.cc
chenxuhao/GraphMiner
493a16990238648ed4f8af263b2bf06aabb0758a
[ "MIT" ]
25
2021-07-31T15:29:30.000Z
2022-03-30T02:50:33.000Z
src/motif/main.cc
chenxuhao/GraphMiner
493a16990238648ed4f8af263b2bf06aabb0758a
[ "MIT" ]
1
2022-03-27T20:43:23.000Z
2022-03-27T20:43:23.000Z
src/motif/main.cc
chenxuhao/GraphMiner
493a16990238648ed4f8af263b2bf06aabb0758a
[ "MIT" ]
2
2021-12-06T17:59:48.000Z
2022-01-26T22:58:16.000Z
// Copyright 2020 Massachusetts Institute of Technology // Contact: Xuhao Chen <cxh@mit.edu> #include "motif.h" int main(int argc, char *argv[]) { if (argc < 3) { std::cout << "Usage: " << argv[0] << "<graph> <k> [ngpu(0)] [chunk_size(1024)]\n"; std::cout << "Example: " << argv[0] << " /graph_inputs/mico/graph 4\n"; exit(1); } Graph g(argv[1]); int k = atoi(argv[2]); int n_devices = 1; int chunk_size = 1024; if (argc > 3) n_devices = atoi(argv[3]); if (argc > 4) chunk_size = atoi(argv[4]); std::cout << k << "-motif counting (only for undirected graphs)\n"; auto m = g.size(); auto nnz = g.sizeEdges(); std::cout << "|V| " << m << " |E| " << nnz << "\n"; int num_patterns = num_possible_patterns[k]; std::cout << "num_patterns: " << num_patterns << "\n"; std::vector<uint64_t> total(num_patterns, 0); MotifSolver(g, k, total, n_devices, chunk_size); for (int i = 0; i < num_patterns; i++) std::cout << "pattern " << i << ": " << total[i] << "\n"; return 0; }
31.90625
86
0.574927
chenxuhao
2a8d54132f8e4e2e9b1b61d5b03a3d9d061f9142
790
cpp
C++
Module 1/Lecture 3/3d_distance.cpp
bhattigurjot/cpp-exercises
9ae770fec1b2bcdc9811b2901e62f883d3e6ed2c
[ "MIT" ]
null
null
null
Module 1/Lecture 3/3d_distance.cpp
bhattigurjot/cpp-exercises
9ae770fec1b2bcdc9811b2901e62f883d3e6ed2c
[ "MIT" ]
null
null
null
Module 1/Lecture 3/3d_distance.cpp
bhattigurjot/cpp-exercises
9ae770fec1b2bcdc9811b2901e62f883d3e6ed2c
[ "MIT" ]
null
null
null
#include<iostream> #include<cmath> using namespace std; void print(float ux, float uy, float uz, float vx, float vy, float vz); float dist3(float ux, float uy, float uz, float vx, float vy, float vz); int main() { print(1,2,3,0,0,0); print(1,2,3,1,2,3); print(1,2,3,7,-4,5); } float dist3(float ux, float uy, float uz, float vx, float vy, float vz) { /* 3D Distance Calculation Function */ float dist = 0.0f; float res = pow(vx-ux, 2) + pow(vy-uy, 2) + pow(vz-uz, 2); dist = sqrt(res); return dist; } void print(float ux, float uy, float uz, float vx, float vy, float vz) { /* Print Function */ cout << "Distance between (" << ux << "," << uy << "," << uz << ") and (" << vx << "," << vy << "," << vz << ") = " << dist3(ux,uy,uz,vx,vy,vz) << endl; }
19.75
78
0.572152
bhattigurjot
2a8dfafc28d1d865f90be0619e75dbedba4e4be4
11,631
cpp
C++
core/common/str.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
28
2017-04-30T13:56:13.000Z
2022-03-20T06:54:37.000Z
core/common/str.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
72
2017-04-25T03:42:58.000Z
2021-12-04T06:35:28.000Z
core/common/str.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
12
2017-04-16T06:25:24.000Z
2021-07-07T13:28:27.000Z
#include "str.h" #include <string> #include <algorithm> #include <cstring> #include <vector> #include <cctype> #include <stdexcept> namespace str { using namespace std; std::string hexdump(const std::string& in) { std::string res; for (size_t i = 0; i < in.size(); i++) { if (i != 0) res += ' '; char buf[3]; snprintf(buf, 3, "%02hhX", in[i]); res += buf; } return res; } static std::string inspect(char c, bool utf8) { int d = static_cast<unsigned char>(c); if (utf8 && d >= 0x80) return string() + (char) d; if (isprint(d)) { switch (d) { case '\'': return "\\\'"; case '\"': return "\\\""; case '\?': return "\\?"; case '\\': return "\\\\"; default: return string() + (char) d; } } switch (d) { case '\a': return "\\a"; case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; default: return string("\\x") + "0123456789abcdef"[d>>4] + "0123456789abcdef"[d&0xf]; } } std::string inspect(const std::string str) { bool utf8 = validate_utf8(str); std::string res = "\""; for (auto c : str) { res += inspect(c, utf8); } res += "\""; return res; } std::string repeat(const std::string& in, int n) { std::string res; for (int i = 0; i < n; i++) { res += in; } return res; } std::string group_digits(const std::string& in, const std::string& separator) { std::string tail; auto end = in.find('.'); // end of integral part if (end != string::npos) tail = in.substr(end); else end = in.size(); std::string res; std::string integer = in.substr(0, end); std::reverse(integer.begin(), integer.end()); std::string delim = separator; std::reverse(delim.begin(), delim.end()); for (size_t i = 0; i < end; i++) { if (i != 0 && i%3 == 0) res += delim; res += integer[i]; } std::reverse(res.begin(), res.end()); return res + tail; } std::vector<std::string> split(const std::string& in, const std::string& separator) { std::vector<std::string> res; const char *p = in.c_str(); const char *sep = separator.c_str(); const char *q; while (true) { q = strstr(p, sep); if (q) { res.push_back(std::string(p, q)); p = q + std::strlen(sep); } else { res.push_back(std::string(p)); return res; } } } std::vector<std::string> split(const std::string& in, const std::string& separator, int limit) { if (limit <= 0) throw std::domain_error("limit <= 0"); std::vector<std::string> res; const char *p = in.c_str(); const char *sep = separator.c_str(); const char *q; while (true) { q = strstr(p, sep); if ((int)res.size() < limit-1 && q != nullptr) { res.push_back(std::string(p, q)); p = q + std::strlen(sep); } else { res.push_back(std::string(p)); return res; } } } std::string codepoint_to_utf8(uint32_t codepoint) { std::string res; if (/* codepoint >= 0 && */ codepoint <= 0x7f) { res += (char) codepoint; } else if (codepoint >= 0x80 && codepoint <= 0x7ff) { res += (char) (0xb0 | (codepoint >> 6)); res += (char) (0x80 | (codepoint & 0x3f)); } else if (codepoint >= 0x800 && codepoint <= 0xffff) { res += (char) (0xe0 | (codepoint >> 12)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } else if (codepoint >= 0x10000 && codepoint <= 0x1fffff) { res += (char) (0xf0 | (codepoint >> 18)); res += (char) (0x80 | ((codepoint >> 12) & 0x3f)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } else if (codepoint >= 0x200000 && codepoint <= 0x3ffffff) { res += (char) (0xf8 | (codepoint >> 24)); res += (char) (0x80 | ((codepoint >> 18) & 0x3f)); res += (char) (0x80 | ((codepoint >> 12) & 0x3f)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } else { // [0x4000000, 0x7fffffff] res += (char) (0xfb | (codepoint >> 30)); res += (char) (0x80 | ((codepoint >> 24) & 0x3f)); res += (char) (0x80 | ((codepoint >> 18) & 0x3f)); res += (char) (0x80 | ((codepoint >> 12) & 0x3f)); res += (char) (0x80 | ((codepoint >> 6) & 0x3f)); res += (char) (0x80 | (codepoint & 0x3f)); } return res; } #include <stdarg.h> std::string format(const char* fmt, ...) { // 必要なバイト数の計算のために vsnprintf を呼び出し、実際に文字列 // を作るためにもう一度 vsnprintf を呼び出す。 // 1度目の vsnprintf の呼び出しのあと ap の値は未定義になるので、 // 2度目の呼び出しのために aq にコピーしておく。 va_list ap, aq; std::string res; va_start(ap, fmt); va_copy(aq, ap); int size = vsnprintf(NULL, 0, fmt, ap); char *data = new char[size + 1]; vsnprintf(data, size + 1, fmt, aq); va_end(aq); va_end(ap); res = data; delete[] data; return res; } bool contains(const std::string& haystack, const std::string& needle) { return haystack.find(needle) != std::string::npos; } std::string replace_prefix(const std::string& s, const std::string& prefix, const std::string& replacement) { if (s.size() < prefix.size()) return s; if (s.substr(0, prefix.size()) == prefix) return replacement + s.substr(prefix.size()); else return s; } std::string replace_suffix(const std::string& s, const std::string& suffix, const std::string& replacement) { if (s.size() < suffix.size()) return s; if (s.substr(s.size() - suffix.size(), suffix.size()) == suffix) return s.substr(0, s.size() - suffix.size()) + replacement; else return s; } std::string upcase(const std::string& input) { std::string res; for (auto c : input) { if (isalpha(c)) res += toupper(c); else res += c; } return res; } std::string downcase(const std::string& input) { std::string res; for (auto c : input) { if (isalpha(c)) res += tolower(c); else res += c; } return res; } std::string capitalize(const std::string& input) { std::string res; bool prevWasAlpha = false; for (auto c : input) { if (isalpha(c)) { if (prevWasAlpha) res += tolower(c); else { res += toupper(c); prevWasAlpha = true; } }else { res += c; prevWasAlpha = false; } } return res; } bool is_prefix_of(const std::string& prefix, const std::string& string) { if (string.size() < prefix.size()) return false; return string.substr(0, prefix.size()) == prefix; } bool has_prefix(const std::string& subject, const std::string& prefix) { return is_prefix_of(prefix, subject); } bool has_suffix(const std::string& subject, const std::string& suffix) { if (subject.size() < suffix.size()) return false; return subject.substr(subject.size() - suffix.size(), suffix.size()) == suffix; } std::string join(const std::string& delimiter, const std::vector<std::string>& vec) { std::string res; for (auto it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) res += delimiter; res += *it; } return res; } std::string ascii_dump(const std::string& in, const std::string& replacement) { std::string res; for (auto c : in) { if (std::isprint(c)) res += c; else res += replacement; } return res; } std::string extension_without_dot(const std::string& filename) { auto i = filename.rfind('.'); if (i == std::string::npos) return ""; else return filename.substr(i + 1); } int count(const std::string& haystack, const std::string& needle) { if (needle.empty()) throw std::domain_error("cannot count empty strings"); size_t start = 0; int n = 0; while ((start = haystack.find(needle, start)) != std::string::npos) { n++; start++; } return n; } std::string rstrip(const std::string& str) { std::string res = str; while (!res.empty()) { auto c = res.back(); if (c == ' ' || (c >= 0x09 && c <= 0x0d) || c == '\0') res.pop_back(); else break; } return res; } std::string strip(const std::string& str) { auto it = str.begin(); while (it != str.end()) { auto c = *it; if (c == ' ' || (c >= 0x09 && c <= 0x0d) || c == '\0') it++; else break; } std::string res(it, str.end()); while (!res.empty()) { auto c = res.back(); if (c == ' ' || (c >= 0x09 && c <= 0x0d) || c == '\0') res.pop_back(); else break; } return res; } std::string escapeshellarg_unix(const std::string& str) { std::string buf = "\'"; for (char c : str) { if (c == '\'') buf += "\'\"\'\"\'"; else buf += c; } buf += "\'"; return buf; } std::string STR() { return ""; } std::vector<std::string> to_lines(const std::string& text) { std::vector<std::string> res; std::string line; for (auto it = text.begin(); it != text.end(); ++it) { if (*it == '\n') { line += *it; res.push_back(line); line.clear(); }else { line.push_back(*it); } } res.push_back(line); if (res.back() == "") res.pop_back(); return res; } std::string indent_tab(const std::string& text, int n) { if (n < 0) throw std::domain_error("domain error"); auto lines = to_lines(text); auto space = repeat("\t", n); for (size_t i = 0; i < lines.size(); ++i) lines[i] = space + lines[i]; return join("", lines); } bool validate_utf8(const std::string& str) { auto it = str.begin(); while (it != str.end()) { if ((*it & 0x80) == 0) // 0xxx xxxx { it++; continue; }else if ((*it & 0xE0) == 0xC0) // 110x xxxx { it++; if (it == str.end()) return false; if ((*it & 0xC0) == 0x80) it++; else return false; }else if ((*it & 0xF0) == 0xE0) // 1110 xxxx { it++; for (int i = 0; i < 2; ++i) { if (it == str.end()) return false; if ((*it & 0xC0) == 0x80) it++; else return false; } }else if ((*it & 0xF8) == 0xF0) // 1111 0xxx { it++; for (int i = 0; i < 3; ++i) { if (it == str.end()) return false; if ((*it & 0xC0) == 0x80) it++; else return false; } }else return false; } return true; } } // namespace str
22.716797
107
0.481472
plonk
2a96b2476316dd4bcbd57d3969ec3742e17882be
2,738
cpp
C++
samples/03_advances/05_convert_to_wscene/src/main.cpp
SiminBadri/Wolf.Engine
3da04471ec26e162e1cbb7cc88c7ce37ee32c954
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
1
2020-07-15T13:14:26.000Z
2020-07-15T13:14:26.000Z
samples/03_advances/05_convert_to_wscene/src/main.cpp
foroughmajidi/Wolf.Engine
f08a8cbd519ca2c70b1c8325250dc9af7ac4c498
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
null
null
null
samples/03_advances/05_convert_to_wscene/src/main.cpp
foroughmajidi/Wolf.Engine
f08a8cbd519ca2c70b1c8325250dc9af7ac4c498
[ "BSL-1.0", "Apache-2.0", "libpng-2.0" ]
null
null
null
/* Project : Wolf Engine. Copyright(c) Pooya Eimandar (http://PooyaEimandar.com) . All rights reserved. Source : Please direct any bug to https://github.com/PooyaEimandar/Wolf.Engine/issues Website : http://WolfSource.io Name : main.cpp Description : This sample shows how to convert collada file to Wolf Scene Pack Comment : Read more information about this sample on http://wolfsource.io/gpunotes/ */ #include <pch.h> #include <w_io.h> #include <w_content_manager.h> #include <stdio.h> using namespace std; using namespace wolf; using namespace wolf::system; using namespace wolf::content_pipeline; int main() { //set content path directory auto _current_path_dir = wolf::system::io::get_current_directoryW(); #ifdef WIN32 auto _content_path_dir = _current_path_dir + L"/../../../../content/"; #elif defined(__APPLE__) auto _content_path_dir = _current_path_dir + L"/../../../../../content/"; #endif // WIN32 wolf::system::w_logger_config _log_config; _log_config.app_name = L"05_convert_to_wscene.Win32"; _log_config.log_path = _current_path_dir; _log_config.log_to_std_out = true; logger.initialize(_log_config); //log to output file logger.write(L"wolf initialized"); //++++++++++++++++++++++++++++++++++++++++++++++++++++ //The following codes have been added for this project //++++++++++++++++++++++++++++++++++++++++++++++++++++ //load all models from following folder "content/models/sponza/" auto _parent_dir = _content_path_dir + L"models/sponza/"; std::vector<std::wstring> _file_names; wolf::system::io::get_files_folders_in_directoryW(_parent_dir, _file_names); for (auto& _file_name : _file_names) { auto _ext = wolf::system::io::get_file_extentionW(_file_name); auto _base_name = wolf::system::io::get_base_file_nameW(_file_name); if (_ext.empty() || _ext == L"." || _ext == L".wscene") continue; auto _scene = w_content_manager::load<w_cpipeline_scene>(_parent_dir + _file_name); if (_scene) { logger.write(L"start converting: {}", _file_name); std::vector<w_cpipeline_scene> _scene_packs = { *_scene }; auto _out_path = _parent_dir + _base_name + L".wscene"; if (w_content_manager::save_wolf_scenes_to_file(_scene_packs, _out_path) == W_PASSED) { logger.write(L"scene {} converted", _file_name); } else { logger.write(L"error on converting {}", _file_name); } _scene->release(); } else { logger.write(L"file {} not exists or not supported", _file_name); } } w_content_manager::release(); //++++++++++++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++++++++++++ release_heap_data(); return EXIT_SUCCESS; }
32.595238
104
0.647918
SiminBadri
2a9743b2207d0b7a8f2eed317a8d3ff32b895839
3,479
cpp
C++
windz/log/LogStream.cpp
Crystalwindz/windz
f13ea10187eb1706d1c7b31b34ce1bf458d721bd
[ "MIT" ]
null
null
null
windz/log/LogStream.cpp
Crystalwindz/windz
f13ea10187eb1706d1c7b31b34ce1bf458d721bd
[ "MIT" ]
null
null
null
windz/log/LogStream.cpp
Crystalwindz/windz
f13ea10187eb1706d1c7b31b34ce1bf458d721bd
[ "MIT" ]
null
null
null
#include "windz/log/LogStream.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <strings.h> #include <algorithm> #include <limits> namespace windz { namespace { const char digits[] = "9876543210123456789"; const char *zero = digits + 9; const char digitsHex[] = "0123456789abcdef"; // From muduo // Efficient Integer to String Conversions, by Matthew Wilson. template <typename T> size_t Convert(char buf[], T value) { T i = value; char *p = buf; do { int lsd = static_cast<int>(i % 10); i /= 10; *p++ = zero[lsd]; } while (i != 0); if (value < 0) { *p++ = '-'; } *p = '\0'; std::reverse(buf, p); return p - buf; } size_t ConvertHex(char buf[], uintptr_t value) { uintptr_t i = value; char *p = buf; do { int lsd = static_cast<int>(i % 16); i /= 16; *p++ = digitsHex[lsd]; } while (i != 0); *p = '\0'; std::reverse(buf, p); return p - buf; } } // namespace template <typename T> void LogStream::FormatInteger(T v) { if (buffer_.Avail() >= kMaxNumericSize) { size_t len = Convert(buffer_.cur(), v); buffer_.Add(len); } } LogStream &LogStream::operator<<(bool v) { buffer_.Append(v ? "1" : "0", 1); return *this; } LogStream &LogStream::operator<<(short v) { *this << static_cast<int>(v); return *this; } LogStream &LogStream::operator<<(unsigned short v) { *this << static_cast<unsigned int>(v); return *this; } LogStream &LogStream::operator<<(int v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(unsigned int v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(unsigned long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(long long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(unsigned long long v) { FormatInteger(v); return *this; } LogStream &LogStream::operator<<(float v) { *this << static_cast<double>(v); return *this; } LogStream &LogStream::operator<<(double v) { if (buffer_.Avail() >= kMaxNumericSize) { int len = snprintf(buffer_.cur(), kMaxNumericSize, "%.12g", v); buffer_.Add(len); } return *this; } LogStream &LogStream::operator<<(long double v) { if (buffer_.Avail() >= kMaxNumericSize) { int len = snprintf(buffer_.cur(), kMaxNumericSize, "%.12Lg", v); buffer_.Add(len); } return *this; } LogStream &LogStream::operator<<(char v) { buffer_.Append(&v, 1); return *this; } LogStream &LogStream::operator<<(const char *v) { if (v) { buffer_.Append(v, strlen(v)); } else { buffer_.Append("(null)", 6); } return *this; } LogStream &LogStream::operator<<(const unsigned char *v) { *this << reinterpret_cast<const char *>(v); return *this; } LogStream &LogStream::operator<<(const std::string &v) { buffer_.Append(v.c_str(), v.length()); return *this; } LogStream &LogStream::operator<<(const void *p) { uintptr_t v = reinterpret_cast<uintptr_t>(p); if (buffer_.Avail() >= kMaxNumericSize) { char *buf = buffer_.cur(); buf[0] = '0'; buf[1] = 'x'; size_t len = ConvertHex(buf + 2, v); buffer_.Add(len + 2); } return *this; } } // namespace windz
20.345029
72
0.590112
Crystalwindz
2a9c0caa50e3d3f36694ac5b2c1ea0bd37257366
7,680
cpp
C++
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/textinput_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2020-10-04T18:50:01.000Z
2020-10-04T18:50:01.000Z
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/textinput_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
null
null
null
DESIRE-Modules/UI-HorusUI/Externals/horus_ui/src/textinput_widget.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2018-09-18T08:03:33.000Z
2018-09-18T08:03:33.000Z
#include "horus.h" #include "types.h" #include "ui_theme.h" #include "renderer.h" #include "unicode_text_cache.h" #include "ui_font.h" #include "ui_context.h" #include "util.h" #include <math.h> #include <string.h> #include <algorithm> namespace hui { bool textInput( char* text, u32 maxLength, TextInputValueMode valueMode, const char* defaultText, Image icon, bool password, const char* passwordChar) { auto bodyElem = &ctx->theme->getElement(WidgetElementId::TextInputBody); auto bodyTextCaretElemState = ctx->theme->getElement(WidgetElementId::TextInputCaret).normalState(); auto bodyTextSelectionElemState = ctx->theme->getElement(WidgetElementId::TextInputSelection).normalState(); auto bodyTextDefaultElemState = ctx->theme->getElement(WidgetElementId::TextInputDefaultText).normalState(); addWidgetItem(fmaxf(bodyElem->normalState().height * ctx->globalScale, bodyElem->normalState().font->getMetrics().height)); if (!ctx->focusChanged) buttonBehavior(); if (ctx->focusChanged && ctx->currentWidgetId != ctx->widget.focusedWidgetId) { ctx->widget.changeEnded = true; } auto bodyElemState = &bodyElem->normalState(); bool isEditingThis = ctx->currentWidgetId == ctx->textInput.widgetId && ctx->widget.focused && ctx->isActiveLayer(); ctx->textInput.themeElement = bodyElem; if (ctx->widget.focused) { bodyElemState = &bodyElem->getState(WidgetStateType::Focused); } auto clipRect = Rect( ctx->widget.rect.x + bodyElemState->border, ctx->widget.rect.y + bodyElemState->border, ctx->widget.rect.width - bodyElemState->border * 2, ctx->widget.rect.height - bodyElemState->border * 2); const u32 maxHiddenCharLen = 1024; static char hiddenPwdText[maxHiddenCharLen] = ""; bool isEmptyText = false; char* textToDraw = (char*)text; UnicodeString pwdStr; utf8ToUtf32(passwordChar, pwdStr); ctx->textInput.editNow = false; ctx->textInput.password = password; ctx->textInput.passwordCharUnicode = pwdStr; if (ctx->event.type == InputEvent::Type::Key && ctx->event.key.code == KeyCode::Enter && ctx->event.key.down && ctx->widget.focused) { if (!ctx->textInput.widgetId) { ctx->textInput.widgetId = ctx->currentWidgetId; isEditingThis = true; ctx->textInput.editNow = true; ctx->textInput.selectAllOnFocus = true; } else { ctx->textInput.widgetId = 0; ctx->textInput.editNow = false; isEditingThis = false; ctx->widget.focusedWidgetId = 0; ctx->widget.changeEnded = true; } } if (ctx->focusChanged && ctx->currentWidgetId == ctx->widget.focusedWidgetId) { ctx->textInput.editNow = true; isEditingThis = 0 != ctx->textInput.widgetId; ctx->textInput.selectAllOnFocus = true; if (isEditingThis) { ctx->textInput.widgetId = ctx->currentWidgetId; } } if (ctx->widget.pressed && ctx->currentWidgetId != ctx->textInput.widgetId) { ctx->textInput.widgetId = ctx->currentWidgetId; ctx->textInput.editNow = true; isEditingThis = true; ctx->textInput.selectAllOnFocus = true; ctx->textInput.firstMouseDown = true; ctx->widget.pressed = false; ctx->widget.focusedWidgetPressed = false; } if (ctx->textInput.editNow) { ctx->textInput.rect = ctx->widget.rect; ctx->textInput.clipRect = clipRect; ctx->textInput.maxTextLength = maxLength; ctx->textInput.selectionActive = false; ctx->textInput.valueType = valueMode; ctx->textInput.scrollOffset = 0; utf8ToUtf32(text, ctx->textInput.text); utf8ToUtf32(defaultText, ctx->textInput.defaultText); if (ctx->textInput.selectAllOnFocus) { ctx->textInput.selectAll(); } // this must be called to handle the event in the text input ways // otherwise it needs a second click to do stuff for the edit box ctx->textInput.processEvent(ctx->event); Rect rc; rc.x = ctx->widget.rect.x; rc.y = ctx->widget.rect.y; rc.width = ctx->widget.rect.width; rc.height = ctx->widget.rect.height; ctx->inputProvider->startTextInput(0, rc); bodyElemState = &bodyElem->getState(WidgetStateType::Focused); forceRepaint(); } ctx->renderer->cmdSetColor(bodyElemState->color); ctx->renderer->cmdDrawImageBordered(bodyElemState->image, bodyElemState->border, ctx->widget.rect, ctx->globalScale); ctx->renderer->cmdSetColor(bodyElemState->textColor); ctx->renderer->cmdSetFont(bodyElemState->font); ctx->renderer->pushClipRect(clipRect); if (isEditingThis) { int offs = ctx->textInput.caretPosition; if (ctx->textInput.caretPosition > ctx->textInput.text.size()) offs = ctx->textInput.text.size() - 1; FontTextSize textToCursorSize; UnicodeString textToCursor; textToCursor = UnicodeString( ctx->textInput.text.begin(), ctx->textInput.text.begin() + offs); if (!password) { textToCursorSize = bodyElemState->font->computeTextSize(textToCursor); } else { textToCursorSize = bodyElemState->font->computeTextSize(pwdStr); textToCursorSize.width *= textToCursor.size(); } const f32 cursorWidth = bodyTextCaretElemState.width; const f32 cursorBorder = bodyTextCaretElemState.border; Rect cursorRect( clipRect.x + textToCursorSize.width - ctx->textInput.scrollOffset, clipRect.y + cursorBorder, cursorWidth, clipRect.height - cursorBorder * 2); if (ctx->textInput.selectionActive) { int startSel = ctx->textInput.selectionBegin, endSel = ctx->textInput.selectionEnd, tmpSel; if (startSel > endSel) { tmpSel = startSel; startSel = endSel; endSel = tmpSel; } FontTextSize selectedTextSize; FontTextSize textToSelectionStartSize; UnicodeString selectedText = UnicodeString(ctx->textInput.text.begin() + startSel, ctx->textInput.text.begin() + endSel); UnicodeString textToSelectionStart = UnicodeString(ctx->textInput.text.begin(), ctx->textInput.text.begin() + startSel); if (!password) { selectedTextSize = bodyElemState->font->computeTextSize(selectedText); textToSelectionStartSize = bodyElemState->font->computeTextSize(textToSelectionStart); } else { selectedTextSize = bodyElemState->font->computeTextSize(pwdStr); textToSelectionStartSize = selectedTextSize; selectedTextSize.width *= selectedText.size(); textToSelectionStartSize.width *= textToSelectionStart.size(); } Rect selRect( clipRect.x + textToSelectionStartSize.width - ctx->textInput.scrollOffset, clipRect.y, selectedTextSize.width, clipRect.height); // draw selection rect ctx->renderer->cmdSetColor(bodyTextSelectionElemState.color); ctx->renderer->cmdDrawSolidRectangle(selRect); } // draw cursor ctx->renderer->cmdSetColor(bodyTextCaretElemState.color); ctx->renderer->cmdDrawSolidRectangle(cursorRect); } if (isEditingThis) { memset((char*)text, 0, maxLength); utf32ToUtf8NoAlloc(ctx->textInput.text, text, maxLength); } if (password && defaultText != textToDraw) { u32 len = std::min(utf8Len(textToDraw), maxHiddenCharLen); hiddenPwdText[0] = 0; for (int i = 0; i < len; i++) { strcat(hiddenPwdText, passwordChar); } textToDraw = hiddenPwdText; } isEmptyText = !strcmp(textToDraw, ""); if (isEmptyText && defaultText) { textToDraw = (char*)defaultText; ctx->renderer->cmdSetColor(bodyTextDefaultElemState.color); } else { ctx->renderer->cmdSetColor(bodyElemState->color); } auto textRect = Rect( clipRect.x - (isEditingThis ? ctx->textInput.scrollOffset : 0), clipRect.y, clipRect.width, clipRect.height); // draw the actual text ctx->renderer->cmdDrawTextInBox( textToDraw, textRect, HAlignType::Left, VAlignType::Bottom); ctx->renderer->popClipRect(); setAsFocusable(); ctx->currentWidgetId++; return ctx->textInput.textChanged; } }
26.947368
124
0.721875
nyaki-HUN
2aa0326817c91a36bb82f5bcc874487e3f3939ea
1,036
cpp
C++
src/old/class/http.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
src/old/class/http.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
src/old/class/http.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
#include <curl/curl.h> #include "http.class.h" size_t Http::WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } // Cosa fa : Esegue una richiesta di tipo get ad una pagina web ed estrapola il risultato // sUrl : stringa, url al quale effettuare la richiesta // Ritorna : sRet -> stringa, valore di ritorno estratto dalla pagina string Http::get(string sUrl){ // Converto il tipo dell'url perchè "curl_easy_setopt(curl, CURLOPT_URL,sUrl" si aspetta che sUrl sia di tipo const char* const char *sUrlRequest = sUrl.c_str(); CURL *curl; CURLcode res; string sRet; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, sUrlRequest); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, this->WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &sRet); res = curl_easy_perform(curl); curl_easy_cleanup(curl); } return sRet; }
29.6
122
0.724903
lucabertoni
2aa83d470fab739e88fab56e773028da8bfa15ba
2,743
cpp
C++
bacs/problem/src/single/test/matcher.cpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
null
null
null
bacs/problem/src/single/test/matcher.cpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
10
2018-02-06T14:46:36.000Z
2018-03-20T13:37:20.000Z
bacs/problem/src/single/test/matcher.cpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
1
2021-11-26T10:59:09.000Z
2021-11-26T10:59:09.000Z
#include <bacs/problem/single/test/matcher.hpp> #include <bunsan/fnmatch.hpp> #include <boost/regex.hpp> namespace bacs::problem::single::test { class matcher::impl { public: virtual ~impl() {} virtual bool match(const std::string &test_id) const = 0; }; class matcher::id : public matcher::impl { public: explicit id(const std::string &test_id) : m_test_id(test_id) {} bool match(const std::string &test_id) const override { return test_id == m_test_id; } private: const std::string m_test_id; }; class matcher::wildcard : public matcher::impl { public: explicit wildcard(const TestQuery::Wildcard &query) : m_wildcard(query.value(), flags(query)) {} bool match(const std::string &test_id) const override { return m_wildcard(test_id); } private: bunsan::fnmatcher::flag flags(const TestQuery::Wildcard &query) { bunsan::fnmatcher::flag flags_ = bunsan::fnmatcher::defaults; for (const int flag : query.flag()) { switch (static_cast<TestQuery::Wildcard::Flag>(flag)) { case problem::single::TestQuery::Wildcard::IGNORE_CASE: flags_ |= bunsan::fnmatcher::icase; break; } } return flags_; } private: const bunsan::fnmatcher m_wildcard; }; class matcher::regex : public matcher::impl { public: explicit regex(const TestQuery::Regex &query) : m_regex(query.value(), flags(query)) {} bool match(const std::string &test_id) const override { return boost::regex_match(test_id, m_regex); } private: boost::regex_constants::syntax_option_type flags( const problem::single::TestQuery::Regex &query) { boost::regex_constants::syntax_option_type flags_ = boost::regex_constants::normal; for (const int flag : query.flag()) { switch (static_cast<TestQuery::Regex::Flag>(flag)) { case TestQuery::Regex::IGNORE_CASE: flags_ |= boost::regex_constants::icase; break; } } return flags_; } private: const boost::regex m_regex; }; matcher::matcher(const TestQuery &query) : m_impl(make_query(query)) {} matcher::~matcher() {} bool matcher::operator()(const std::string &test_id) const { BOOST_ASSERT(m_impl); return m_impl->match(test_id); } std::shared_ptr<const matcher::impl> matcher::make_query( const TestQuery &query) { switch (query.query_case()) { case TestQuery::kId: return std::make_shared<id>(query.id()); case TestQuery::kWildcard: return std::make_shared<wildcard>(query.wildcard()); case TestQuery::kRegex: return std::make_shared<regex>(query.regex()); default: BOOST_THROW_EXCEPTION(matcher_not_set_error()); return nullptr; } } } // namespace bacs::problem::single::test
25.877358
71
0.674079
bacsorg
2aa9d383dc18661fc0511cb6e579547e3671f107
2,072
cpp
C++
test/Matuna.OCLLayerKernelTest/OCLLayerKernelTest.cpp
mihed/ATML
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
test/Matuna.OCLLayerKernelTest/OCLLayerKernelTest.cpp
mihed/ATML
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
[ "BSL-1.0", "BSD-3-Clause" ]
3
2015-06-08T19:51:53.000Z
2015-07-01T10:15:06.000Z
test/Matuna.OCLLayerKernelTest/OCLLayerKernelTest.cpp
mihed/ATML
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch/catch.hpp" #include "Matuna.OCLHelper/OCLHelper.h" #include "Matuna.OCLHelper/OCLProgram.h" #include "Matuna.OCLConvNet/LayerKernel.h" #include <memory> using namespace Matuna::Helper; using namespace Matuna::MachineLearning; SCENARIO("Testing and executing a layer kernel") { auto platformInfos = OCLHelper::GetPlatformInfos(); for (auto& platformInfo : platformInfos) { auto context = OCLHelper::GetContext(platformInfo); auto program = new OCLProgram(); program->SetName("Testprogram"); LayerKernel<cl_float>* kernel = new LayerKernel<cl_float>(); int memoryCount = 100; cl_float scalar = 10; auto memory = context->CreateMemory(CL_MEM_READ_WRITE, memoryCount * sizeof(cl_float)); kernel->SetKernelName("DivideByScalarKernel"); string path = OCLProgram::DefaultSourceLocation + "LayerTestKernel.cl"; kernel->AddSourcePath(path); kernel->AddIncludePath(OCLProgram::DefaultSourceLocation); kernel->AddGlobalSize(memoryCount); kernel->AddDefineSubsitute(path, "OFFSET_SCALAR", 10); program->AttachKernel(unique_ptr<OCLKernel>(kernel)); context->AttachProgram(unique_ptr<OCLProgram>(program), context->GetDevices()); kernel->SetMemoryArg(memory.get(), 0); kernel->SetRealArg(scalar, 1); for(auto device: context->GetDevices()) device->ExecuteKernel(kernel); auto program2 = new OCLProgram(); program->SetName("Testprogram2"); LayerKernel<cl_float>* kernel2 = new LayerKernel<cl_float>(); kernel2->SetKernelName("DivideByScalarKernel"); kernel2->AddSourcePath(path); kernel2->AddIncludePath(OCLProgram::DefaultSourceLocation); kernel2->AddGlobalSize(memoryCount); kernel2->AddDefineSubsitute(path, "OFFSET_SCALAR", 10); kernel2->AddDefine(path, "USE_OFFSET"); program2->AttachKernel(unique_ptr<OCLKernel>(kernel2)); context->AttachProgram(unique_ptr<OCLProgram>(program2), context->GetDevices()); kernel2->SetMemoryArg(memory.get(), 0); kernel2->SetRealArg(scalar, 1); for(auto device: context->GetDevices()) device->ExecuteKernel(kernel2); } }
33.419355
89
0.757722
mihed
2aaaee190366f7e846efc88b533958e8dbb41b87
419
cpp
C++
source/aufgabe-1-12.cpp
GottaGoGitHub/programmiersprachen-abgabe-1
f1707ef3fecd84105f754c206497a4fb350b1c86
[ "MIT" ]
null
null
null
source/aufgabe-1-12.cpp
GottaGoGitHub/programmiersprachen-abgabe-1
f1707ef3fecd84105f754c206497a4fb350b1c86
[ "MIT" ]
null
null
null
source/aufgabe-1-12.cpp
GottaGoGitHub/programmiersprachen-abgabe-1
f1707ef3fecd84105f754c206497a4fb350b1c86
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> float volumen(float radius, float hoehe){ float vol = M_PI * radius * radius * hoehe; return vol; } float oberflaeche(float radius, float hoehe){ float of = 2 * M_PI * radius * (radius + hoehe); return of; } int main(){ int r = 4; int h = 5; std::cout << "Fuer Radius = 4 und Hoehe = 5: " << volumen(4, 5) << " und " << oberflaeche(4, 5) << "\n"; }
19.952381
108
0.577566
GottaGoGitHub
2aac0fe3b3cd7a84b3fdeaa5168daa3e924ae1f7
12,898
cc
C++
src/base/WCSimDataCleaner.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
src/base/WCSimDataCleaner.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
src/base/WCSimDataCleaner.cc
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
#include "WCSimDataCleaner.hh" #include "WCSimRecoDigit.hh" #include "WCSimRecoCluster.hh" #include "WCSimRecoClusterDigit.hh" #include <cmath> #include <iostream> #include <cassert> ClassImp(WCSimDataCleaner) static WCSimDataCleaner *fgDataCleaner = 0; WCSimDataCleaner *WCSimDataCleaner::Instance() { if (!fgDataCleaner) { fgDataCleaner = new WCSimDataCleaner(); } if (!fgDataCleaner) { assert(fgDataCleaner); } if (fgDataCleaner) { } return fgDataCleaner; } void WCSimDataCleaner::Config(Int_t config) { WCSimDataCleaner::Instance()->SetConfig(config); } void WCSimDataCleaner::MinPulseHeight(Double_t min) { WCSimDataCleaner::Instance()->SetMinPulseHeight(min); } void WCSimDataCleaner::NeighbourRadius(Double_t radius) { WCSimDataCleaner::Instance()->SetNeighbourRadius(radius); } void WCSimDataCleaner::NeighbourDigits(Int_t digits) { WCSimDataCleaner::Instance()->SetNeighbourDigits(digits); } void WCSimDataCleaner::ClusterRadius(Double_t radius) { WCSimDataCleaner::Instance()->SetClusterRadius(radius); } void WCSimDataCleaner::ClusterDigits(Int_t digits) { WCSimDataCleaner::Instance()->SetClusterDigits(digits); } void WCSimDataCleaner::TimeWindow(Double_t window) { WCSimDataCleaner::Instance()->SetTimeWindow(window); } void WCSimDataCleaner::PrintParameters() { WCSimDataCleaner::Instance()->RunPrintParameters(); } WCSimDataCleaner::WCSimDataCleaner() { // cleaning mode fConfig = WCSimDataCleaner::kPulseHeightAndClusters; // default cleaning parameters fMinPulseHeight = 0.0; // minimum pulse height (PEs) fNeighbourRadius = 200.0; // clustering window (cm) fMinNeighbourDigits = 2; // minimum neighbouring digits fClusterRadius = 200.0; // clustering window (cm) fMinClusterDigits = 50; // minimum clustered digits fTimeWindow = 25.0; // timing window (ns) // vector of filtered digits fFilterAll = new std::vector<WCSimRecoDigit *>; fFilterByPulseHeight = new std::vector<WCSimRecoDigit *>; fFilterByNeighbours = new std::vector<WCSimRecoDigit *>; fFilterByClusters = new std::vector<WCSimRecoDigit *>; // vector of clusters fClusterList = new std::vector<WCSimRecoCluster *>; } WCSimDataCleaner::~WCSimDataCleaner() { delete fFilterAll; delete fFilterByPulseHeight; delete fFilterByNeighbours; delete fFilterByClusters; delete fClusterList; } void WCSimDataCleaner::RunPrintParameters() { std::cout << " *** WCSimDataCleaner::PrintParameters() *** " << std::endl; std::cout << " Data Cleaner Parameters: " << std::endl << " Config = " << fConfig << std::endl << " MinPulseHeight = " << fMinPulseHeight << std::endl << " NeighbourRadius = " << fNeighbourRadius << std::endl << " MinNeighbourDigits = " << fMinNeighbourDigits << std::endl << " ClusterRadius = " << fClusterRadius << std::endl << " MinClusterDigits = " << fMinClusterDigits << std::endl << " TimeWindow = " << fTimeWindow << std::endl; return; } void WCSimDataCleaner::Reset() { return; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::Run(std::vector<WCSimRecoDigit *> *myDigitList) { std::cout << " *** WCSimDataCleaner::Run(...) *** " << std::endl; // input digit list // ================ std::vector<WCSimRecoDigit *> *myInputList = myDigitList; std::vector<WCSimRecoDigit *> *myOutputList = myDigitList; // filter all digits // ================= myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterAll(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kNone) return myOutputList; // filter by pulse height // ====================== myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterByPulseHeight(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kPulseHeight) return myOutputList; // filter using neighbouring digits // ================================ myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterByNeighbours(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kPulseHeightAndNeighbours) return myOutputList; // filter using clustered digits // ============================= myInputList = ResetDigits(myOutputList); myOutputList = (std::vector<WCSimRecoDigit *> *)(this->FilterByClusters(myInputList)); myOutputList = FilterDigits(myOutputList); if (fConfig == WCSimDataCleaner::kPulseHeightAndClusters) return myOutputList; // return vector of filtered digits // ================================ return myOutputList; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::ResetDigits(std::vector<WCSimRecoDigit *> *myDigitList) { for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); recoDigit->ResetFilter(); } return myDigitList; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterDigits(std::vector<WCSimRecoDigit *> *myDigitList) { for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); recoDigit->PassFilter(); } return myDigitList; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterAll(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // ============================== fFilterAll->clear(); // filter all digits // ================= for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); fFilterAll->push_back(recoDigit); } // return vector of filtered digits // ================================ std::cout << " filter all: " << fFilterAll->size() << std::endl; return fFilterAll; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterByPulseHeight(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // =============================== fFilterByPulseHeight->clear(); // filter by pulse height // ====================== for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); if (recoDigit->GetQPEs() > fMinPulseHeight) { fFilterByPulseHeight->push_back(recoDigit); } } // return vector of filtered digits // ================================ std::cout << " filter by pulse height: " << fFilterByPulseHeight->size() << std::endl; return fFilterByPulseHeight; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterByNeighbours(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // =============================== fFilterByNeighbours->clear(); // create array of neighbours // ========================== Int_t Ndigits = myDigitList->size(); if (Ndigits <= 0) { return fFilterByNeighbours; } Int_t *numNeighbours = new Int_t[Ndigits]; for (Int_t idigit = 0; idigit < Ndigits; idigit++) { numNeighbours[idigit] = 0; } // count number of neighbours // ========================== for (UInt_t idigit1 = 0; idigit1 < myDigitList->size(); idigit1++) { for (UInt_t idigit2 = idigit1 + 1; idigit2 < myDigitList->size(); idigit2++) { WCSimRecoDigit *fdigit1 = (WCSimRecoDigit *)(myDigitList->at(idigit1)); WCSimRecoDigit *fdigit2 = (WCSimRecoDigit *)(myDigitList->at(idigit2)); Double_t dx = fdigit1->GetX() - fdigit2->GetX(); Double_t dy = fdigit1->GetY() - fdigit2->GetY(); Double_t dz = fdigit1->GetZ() - fdigit2->GetZ(); Double_t dt = fdigit1->GetTime() - fdigit2->GetTime(); Double_t drsq = dx * dx + dy * dy + dz * dz; if (drsq > 0.0 && drsq < fNeighbourRadius * fNeighbourRadius && fabs(dt) < fTimeWindow) { numNeighbours[idigit1]++; numNeighbours[idigit2]++; } } } // filter by number of neighbours // ============================== for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *fdigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); if (numNeighbours[idigit] >= fMinNeighbourDigits) { fFilterByNeighbours->push_back(fdigit); } } // delete array of neighbours // ========================== delete[] numNeighbours; // return vector of filtered digits // ================================ std::cout << " filter by neighbours: " << fFilterByNeighbours->size() << std::endl; return fFilterByNeighbours; } std::vector<WCSimRecoDigit *> *WCSimDataCleaner::FilterByClusters(std::vector<WCSimRecoDigit *> *myDigitList) { // clear vector of filtered digits // =============================== fFilterByClusters->clear(); // run clustering algorithm // ======================== std::vector<WCSimRecoCluster *> *myClusterList = (std::vector<WCSimRecoCluster *> *)(this->RecoClusters(myDigitList)); for (UInt_t icluster = 0; icluster < myClusterList->size(); icluster++) { WCSimRecoCluster *myCluster = (WCSimRecoCluster *)(myClusterList->at(icluster)); for (Int_t idigit = 0; idigit < myCluster->GetNDigits(); idigit++) { WCSimRecoDigit *myDigit = (WCSimRecoDigit *)(myCluster->GetDigit(idigit)); fFilterByClusters->push_back(myDigit); } } // return vector of filtered digits // ================================ std::cout << " filter by clusters: " << fFilterByClusters->size() << std::endl; return fFilterByClusters; } std::vector<WCSimRecoCluster *> *WCSimDataCleaner::RecoClusters(std::vector<WCSimRecoDigit *> *myDigitList) { // delete cluster digits // ===================== for (UInt_t i = 0; i < vClusterDigitList.size(); i++) { delete (WCSimRecoClusterDigit *)(vClusterDigitList.at(i)); } vClusterDigitList.clear(); // delete clusters // =============== for (UInt_t i = 0; i < vClusterList.size(); i++) { delete (WCSimRecoCluster *)(vClusterList.at(i)); } vClusterList.clear(); // clear vector clusters // ===================== fClusterList->clear(); // make cluster digits // =================== for (UInt_t idigit = 0; idigit < myDigitList->size(); idigit++) { WCSimRecoDigit *recoDigit = (WCSimRecoDigit *)(myDigitList->at(idigit)); WCSimRecoClusterDigit *clusterDigit = new WCSimRecoClusterDigit(recoDigit); vClusterDigitList.push_back(clusterDigit); } // run clustering algorithm // ======================== for (UInt_t idigit1 = 0; idigit1 < vClusterDigitList.size(); idigit1++) { for (UInt_t idigit2 = idigit1 + 1; idigit2 < vClusterDigitList.size(); idigit2++) { WCSimRecoClusterDigit *fdigit1 = (WCSimRecoClusterDigit *)(vClusterDigitList.at(idigit1)); WCSimRecoClusterDigit *fdigit2 = (WCSimRecoClusterDigit *)(vClusterDigitList.at(idigit2)); Double_t dx = fdigit1->GetX() - fdigit2->GetX(); Double_t dy = fdigit1->GetY() - fdigit2->GetY(); Double_t dz = fdigit1->GetZ() - fdigit2->GetZ(); Double_t dt = fdigit1->GetTime() - fdigit2->GetTime(); Double_t drsq = dx * dx + dy * dy + dz * dz; if (drsq > 0.0 && drsq < fClusterRadius * fClusterRadius && fabs(dt) < fTimeWindow) { fdigit1->AddClusterDigit(fdigit2); fdigit2->AddClusterDigit(fdigit1); } } } // collect up clusters // =================== Bool_t carryon = 0; for (UInt_t idigit = 0; idigit < vClusterDigitList.size(); idigit++) { WCSimRecoClusterDigit *fdigit = (WCSimRecoClusterDigit *)(vClusterDigitList.at(idigit)); if (fdigit->IsClustered() == 0 && fdigit->GetNClusterDigits() > 0) { vClusterDigitCollection.clear(); vClusterDigitCollection.push_back(fdigit); fdigit->SetClustered(); carryon = 1; while (carryon) { carryon = 0; for (UInt_t jdigit = 0; jdigit < vClusterDigitCollection.size(); jdigit++) { WCSimRecoClusterDigit *cdigit = (WCSimRecoClusterDigit *)(vClusterDigitCollection.at(jdigit)); if (cdigit->IsAllClustered() == 0) { for (Int_t kdigit = 0; kdigit < cdigit->GetNClusterDigits(); kdigit++) { WCSimRecoClusterDigit *cdigitnew = (WCSimRecoClusterDigit *)(cdigit->GetClusterDigit(kdigit)); if (cdigitnew->IsClustered() == 0) { vClusterDigitCollection.push_back(cdigitnew); cdigitnew->SetClustered(); carryon = 1; } } } } } if ((Int_t)vClusterDigitCollection.size() >= fMinClusterDigits) { WCSimRecoCluster *cluster = new WCSimRecoCluster(); fClusterList->push_back(cluster); vClusterList.push_back(cluster); for (UInt_t jdigit = 0; jdigit < vClusterDigitCollection.size(); jdigit++) { WCSimRecoClusterDigit *cdigit = (WCSimRecoClusterDigit *)(vClusterDigitCollection.at(jdigit)); WCSimRecoDigit *recodigit = (WCSimRecoDigit *)(cdigit->GetRecoDigit()); cluster->AddDigit(recodigit); } } } } // return vector of clusters // ========================= return fClusterList; }
28.347253
119
0.65956
chipsneutrino
2ab139ec223782022e5b03681888693d49ab0918
39,723
cc
C++
supersonic/cursor/core/hybrid_aggregate_test.cc
IssamElbaytam/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
201
2015-03-18T21:55:00.000Z
2022-03-03T01:48:26.000Z
supersonic/cursor/core/hybrid_aggregate_test.cc
edisona/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
6
2015-03-19T16:47:19.000Z
2020-10-05T09:38:26.000Z
supersonic/cursor/core/hybrid_aggregate_test.cc
edisona/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
54
2015-03-19T16:31:57.000Z
2021-12-31T10:14:57.000Z
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <memory> #include "supersonic/base/infrastructure/projector.h" #include "supersonic/cursor/base/cursor.h" #include "supersonic/cursor/base/cursor_transformer.h" #include "supersonic/cursor/core/aggregate.h" #include "supersonic/cursor/core/hybrid_group_utils.h" #include "supersonic/cursor/core/sort.h" #include "supersonic/cursor/core/spy.h" #include "supersonic/cursor/infrastructure/ordering.h" #include "supersonic/testing/block_builder.h" #include "supersonic/testing/comparators.h" #include "supersonic/testing/operation_testing.h" #include "supersonic/testing/repeating_block.h" #include "gtest/gtest.h" #include "gtest/gtest.h" #include "supersonic/utils/container_literal.h" namespace supersonic { namespace { class HybridAggregateTest : public testing::Test { protected: CompoundSingleSourceProjector empty_projector_; }; class HybridAggregateSpyTest : public testing::TestWithParam<bool> {}; // A lot of tests just copied from aggregate_groups_test.cc. Maybe it would be // better to share this code somehow and avoid "copy & paste". FailureOrOwned<Cursor> CreateGroupAggregate( const SingleSourceProjector& group_by, const AggregationSpecification& aggregation, Cursor* input) { std::unique_ptr<Cursor> input_owner(input); return BoundHybridGroupAggregate( group_by.Clone(), aggregation, "", HeapBufferAllocator::Get(), 16, NULL, input_owner.release()); } // Sorts cursor according to all columns in an ascending order. This function is // needed because group provides no guarantees over the order of returned rows, // so output needs to be sorted before it is compared against expected output. static Cursor* Sort(Cursor* input) { SortOrder sort_order; sort_order.add(ProjectAllAttributes(), ASCENDING); std::unique_ptr<const BoundSortOrder> bound_sort_order( SucceedOrDie(sort_order.Bind(input->schema()))); std::unique_ptr<const SingleSourceProjector> result_projector( ProjectAllAttributes()); std::unique_ptr<const BoundSingleSourceProjector> bound_result_projector( SucceedOrDie(result_projector->Bind(input->schema()))); return SucceedOrDie(BoundSort( bound_sort_order.release(), bound_result_projector.release(), std::numeric_limits<size_t>::max(), "", HeapBufferAllocator::Get(), input)); } TEST_F(HybridAggregateTest, SimpleAggregation) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(4).BuildCursor()); EXPECT_EQ("sum", aggregate->schema().attribute(0).name()); EXPECT_TRUE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountWithInputColumn) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().AddRow(2).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountWithDefinedOutputType) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregationWithDefinedOutputType(COUNT, "col0", "count", INT32); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(2).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountWithNullableInputColumn) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().AddRow(1).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, CountAll) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().AddRow(2).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Three kinds of COUNT. TEST_F(HybridAggregateTest, CountAllColumnDistinct) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(1) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "", "count_all"); aggregation.AddAggregation(COUNT, "col0", "count_column"); aggregation.AddDistinctAggregation(COUNT, "col0", "count_distinct"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64, UINT64, UINT64>().AddRow(3, 2, 1).BuildCursor()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_FALSE(aggregate->schema().attribute(1).is_nullable()); EXPECT_FALSE(aggregate->schema().attribute(2).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationWithOnlyNullInputs) { Cursor* input = TestDataBuilder<INT32>() .AddRow(__) .AddRow(__) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(__).BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationWithOutputTypeDifferentFromInputType) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregationWithDefinedOutputType(SUM, "col0", "sum", INT64); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT64>().AddRow(4).BuildCursor()); EXPECT_EQ("sum", aggregate->schema().attribute(0).name()); EXPECT_TRUE(aggregate->schema().attribute(0).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, MultipleAggregations) { Cursor* input = TestDataBuilder<INT32>() .AddRow(1) .AddRow(2) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); aggregation.AddAggregation(MAX, "col0", "max"); aggregation.AddAggregation(MIN, "col0", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32>().AddRow(6, 3, 1).BuildCursor()); EXPECT_EQ("sum", aggregate->schema().attribute(0).name()); EXPECT_EQ("max", aggregate->schema().attribute(1).name()); EXPECT_EQ("min", aggregate->schema().attribute(2).name()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, DistinctAggregation) { Cursor* input = TestDataBuilder<INT32>() .AddRow(3) .AddRow(4) .AddRow(4) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddDistinctAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); // Only distinct values are summed (3 + 4). std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(7).BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, DistinctCountAggregation) { Cursor* input = TestDataBuilder<INT32>() .AddRow(3) .AddRow(4) .AddRow(4) .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddDistinctAggregationWithDefinedOutputType( COUNT, "col0", "count", INT32); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(0).name()); // There are two distinct values (3, 4). std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32>().AddRow(2).BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, DistinctCountAggregationNeedsInputColumn) { Cursor* input = TestDataBuilder<INT32>() .AddRow(3) .BuildCursor(); AggregationSpecification aggregation; // This should not work, there is no way to find distinct values if input // column is not specified. aggregation.AddDistinctAggregationWithDefinedOutputType( COUNT, "", "count", INT32); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); EXPECT_TRUE(result.is_failure()); } TEST_F(HybridAggregateTest, AggregationWithGroupBy) { Cursor* input = TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(3, -3) .AddRow(1, 4) .AddRow(3, -5) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col1", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32>().AddRow(1, 7).AddRow(3, -8).BuildCursor()); EXPECT_EQ("col0", aggregate->schema().attribute(0).name()); EXPECT_EQ("sum", aggregate->schema().attribute(1).name()); EXPECT_FALSE(aggregate->schema().attribute(0).is_nullable()); EXPECT_TRUE(aggregate->schema().attribute(1).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationWithGroupByNullableColumn) { Cursor* input = TestDataBuilder<INT32, INT32>() .AddRow(3, -3) .AddRow(__, 4) .AddRow(3, -5) .AddRow(__, 1) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col1", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); std::unique_ptr<Cursor> expected_output(TestDataBuilder<INT32, INT32>() .AddRow(3, -8) .AddRow(__, 5) .BuildCursor()); EXPECT_EQ("col0", aggregate->schema().attribute(0).name()); EXPECT_EQ("sum", aggregate->schema().attribute(1).name()); EXPECT_TRUE(aggregate->schema().attribute(0).is_nullable()); EXPECT_TRUE(aggregate->schema().attribute(1).is_nullable()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } INSTANTIATE_TEST_CASE_P(SpyUse, HybridAggregateSpyTest, testing::Bool()); TEST_P(HybridAggregateSpyTest, GroupBySecondColumn) { Cursor* input = TestDataBuilder<INT32, STRING>() .AddRow(-3, "foo") .AddRow(2, "bar") .AddRow(3, "bar") .AddRow(-2, "foo") .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col1")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); if (GetParam()) { std::unique_ptr<CursorTransformerWithSimpleHistory> spy_transformer( PrintingSpyTransformer()); aggregate->ApplyToChildren(spy_transformer.get()); aggregate.reset(spy_transformer->Transform(aggregate.release())); } std::unique_ptr<Cursor> expected_output(TestDataBuilder<STRING, INT32>() .AddRow("foo", -5) .AddRow("bar", 5) .BuildCursor()); EXPECT_EQ("col1", aggregate->schema().attribute(0).name()); EXPECT_EQ("sum", aggregate->schema().attribute(1).name()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, GroupByTwoColumns) { Cursor* input = TestDataBuilder<STRING, INT32, INT32>() .AddRow("foo", 1, 3) .AddRow("bar", 2, -3) .AddRow("foo", 1, 4) .AddRow("bar", 3, -5) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttributes(util::gtl::Container("col0", "col1"))); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col2", "sum"); std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_columns, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, INT32, INT32>() .AddRow("foo", 1, 7) .AddRow("bar", 2, -3) .AddRow("bar", 3, -5) .BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, GroupByTwoColumnsWithMultipleAggregations) { Cursor* input = TestDataBuilder<STRING, INT32, INT32>() .AddRow("foo", 1, 3) .AddRow("bar", 2, -3) .AddRow("foo", 1, 4) .AddRow("bar", 3, -5) .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttributes(util::gtl::Container("col0", "col1"))); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col2", "sum"); aggregation.AddAggregation(MIN, "col2", "min"); aggregation.AddAggregation(COUNT, "", "count"); std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_columns, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(4).name()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, INT32, INT32, INT32, UINT64>() // Group by col, group by col, SUM col, MIN col, COUNT col .AddRow("foo", 1, 7, 3, 2) .AddRow("bar", 2, -3, -3, 1) .AddRow("bar", 3, -5, -5, 1) .BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, GroupByWithoutAggregateFunctions) { Cursor* input = TestDataBuilder<STRING>() .AddRow("foo") .AddRow("bar") .AddRow("foo") .AddRow("bar") .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification empty_aggregator; std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_column, empty_aggregator, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING>().AddRow("foo").AddRow("bar").BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } // Aggregation on empty input with empty key should return empty result. TEST_F(HybridAggregateTest, AggregationOnEmptyInput) { Cursor* input = TestDataBuilder<DATETIME>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(MIN, "col0", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<DATETIME>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Aggregation on empty input with group by columns should return empty result. TEST_F(HybridAggregateTest, AggregationOnEmptyInputWithGroupByColumn) { Cursor* input = TestDataBuilder<STRING, DATETIME>().BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(MIN, "col1", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, DATETIME>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Count on empty input with empty key should return empty result. TEST_F(HybridAggregateTest, CountOnEmptyInput) { Cursor* input = TestDataBuilder<DATETIME>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(0).name()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<UINT64>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } // Count on empty input with group by columns should return empty result. TEST_F(HybridAggregateTest, CountOnEmptyInputWithGroupByColumn) { Cursor* input = TestDataBuilder<STRING, DATETIME>() .BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_column( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col1", "count"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(*group_by_column, aggregation, input))); EXPECT_EQ("count", aggregate->schema().attribute(1).name()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<STRING, UINT64>().BuildCursor()); EXPECT_CURSORS_EQUAL(expected_output.release(), aggregate.release()); } TEST_F(HybridAggregateTest, AggregationInputColumnMissingError) { Cursor* input = TestDataBuilder<INT32>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "NotExistingCol", "sum"); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_ATTRIBUTE_MISSING, result.exception().return_code()); } TEST_F(HybridAggregateTest, AggregationResultColumnExistsError) { Cursor* input = TestDataBuilder<INT32, INT32>().BuildCursor(); AggregationSpecification aggregation; // Two results can not be stored in the same column. aggregation.AddAggregation(SUM, "col0", "result_col"); aggregation.AddAggregation(MIN, "col1", "result_col"); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_ATTRIBUTE_EXISTS, result.exception().return_code()); } TEST_F(HybridAggregateTest, NotSupportedAggregationError) { Cursor* input = TestDataBuilder<BINARY>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); FailureOrOwned<Cursor> result( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_INVALID_ARGUMENT_TYPE, result.exception().return_code()); } TEST_F(HybridAggregateTest, ExceptionFromInputPropagated) { Cursor* input = TestDataBuilder<INT32>() .ReturnException(ERROR_GENERAL_IO_ERROR) .BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(COUNT, "col0", "count"); FailureOrOwned<Cursor> cursor( CreateGroupAggregate(empty_projector_, aggregation, input)); ASSERT_TRUE(cursor.is_success()); ResultView result = cursor.get()->Next(100); ASSERT_TRUE(result.is_failure()); EXPECT_EQ(ERROR_GENERAL_IO_ERROR, result.exception().return_code()); } TEST_F(HybridAggregateTest, LargeInput) { TestDataBuilder<INT64, STRING> cursor_builder; for (int i = 0; i < 3 * Cursor::kDefaultRowCount + 1; ++i) { cursor_builder.AddRow(13, "foo") .AddRow(17, "bar") .AddRow(13, "foo"); } Cursor* input = cursor_builder.BuildCursor(); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttributes(util::gtl::Container("col0", "col1"))); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col0", "sum"); std::unique_ptr<Cursor> aggregate(SucceedOrDie( CreateGroupAggregate(*group_by_columns, aggregation, input))); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT64, STRING, INT64>() .AddRow(13, "foo", 2 * 13 * (3 * Cursor::kDefaultRowCount + 1)) .AddRow(17, "bar", 17 * (3 * Cursor::kDefaultRowCount + 1)) .BuildCursor()); EXPECT_CURSORS_EQUAL(Sort(expected_output.release()), Sort(aggregate.release())); } TEST_F(HybridAggregateTest, TransformTest) { Cursor* input = TestDataBuilder<DATETIME>().BuildCursor(); AggregationSpecification aggregation; aggregation.AddAggregation(MIN, "col0", "min"); std::unique_ptr<Cursor> aggregate( SucceedOrDie(CreateGroupAggregate(empty_projector_, aggregation, input))); std::unique_ptr<CursorTransformerWithSimpleHistory> spy_transformer( PrintingSpyTransformer()); aggregate->ApplyToChildren(spy_transformer.get()); // Spy transformer should add one child, it will be a transformed version of // the input cursor. ASSERT_EQ(1, spy_transformer->GetHistoryLength()); } // Some new tests. To be removed if the duplicated the tests above. TEST_F(HybridAggregateTest, NoGroupByColumns) { OperationTest test; test.SetInput(TestDataBuilder<INT32>() .AddRow(1) .AddRow(1) .AddRow(3) .AddRow(3) .AddRow(2) .AddRow(3) .AddRow(1) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, UINT64, UINT64>() .AddRow(14, 7, 3) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( empty_projector_.Clone(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, Simple1) { OperationTest test; test.SetIgnoreRowOrder(true); test.SetInput( TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(1, 4) .AddRow(3, -3) .AddRow(2, 4) .AddRow(3, -5) .Build()); test.SetExpectedResult( TestDataBuilder<INT32, INT32, INT32, UINT64, UINT64>() .AddRow(1, 7, 2, 2, 1) .AddRow(2, 4, 2, 1, 1) .AddRow(3, -8, 6, 2, 1) .Build()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col1", "sum"); aggregation->AddAggregation(SUM, "col0", "sum2"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( group_by_columns.release(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, DistinctAggregations) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(1, 4) .AddRow(3, -1) .AddRow(3, -2) .AddRow(2, 4) .AddRow(3, -3) .AddRow(1, 3) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(1, 7, 2, 1) .AddRow(2, 4, 1, 1) .AddRow(3, -6, 3, 1) .Build()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddDistinctAggregation(SUM, "col1", "sum"); aggregation->AddDistinctAggregation(COUNT, "col1", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "cnt2"); test.Execute(HybridGroupAggregate( group_by_columns.release(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, NonDistinctAndDistinctAggregations) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 3) .AddRow(1, 4) .AddRow(3, -1) .AddRow(3, -2) .AddRow(2, 4) .AddRow(3, -3) .AddRow(1, 3) .AddRow(1, __) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, INT32, UINT64, UINT64>() .AddRow(1, 7, 2, 10, 3, 4) .AddRow(2, 4, 1, 4, 1, 1) .AddRow(3, -6, 3, -6, 3, 3) .Build()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddDistinctAggregation(SUM, "col1", "sum"); aggregation->AddDistinctAggregation(COUNT, "col1", "cnt"); aggregation->AddAggregation(SUM, "col1", "sum2"); aggregation->AddAggregation(COUNT, "col1", "cnt2"); aggregation->AddAggregation(COUNT, "", "cnt3"); test.Execute(HybridGroupAggregate( group_by_columns.release(), aggregation.release(), 16, "", test.input())); } // Test hybrid group transform for two distinct aggregations some non-distinct // aggregations including COUNT(*). Each distinct aggregation should get its // copy of data. All non-distinct aggregation share one copy of the data. // COUNT(*) gets a new column in the non-distinct data. TEST_F(HybridAggregateTest, HybridGroupTransformTest) { std::unique_ptr<Cursor> input(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, 1) .AddRow(1, 4, 2) .AddRow(3, -3, 3) .AddRow(2, 4, 4) .AddRow(3, -5, 5) .BuildCursor()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32, INT32, INT32, INT32>() .AddRow(1, 3, __, __, __, __) .AddRow(1, 4, __, __, __, __) .AddRow(3, -3, __, __, __, __) .AddRow(2, 4, __, __, __, __) .AddRow(3, -5, __, __, __, __) .AddRow(1, __, 1, __, __, __) .AddRow(1, __, 2, __, __, __) .AddRow(3, __, 3, __, __, __) .AddRow(2, __, 4, __, __, __) .AddRow(3, __, 5, __, __, __) .AddRow(1, __, __, 3, 1, 0) .AddRow(1, __, __, 4, 1, 0) .AddRow(3, __, __, -3, 3, 0) .AddRow(2, __, __, 4, 2, 0) .AddRow(3, __, __, -5, 3, 0) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col1", "sum"); aggregation.AddAggregation(SUM, "col0", "sum2"); aggregation.AddAggregation(COUNT, "col0", "cnt"); aggregation.AddAggregation(COUNT, "", "cnt_star"); aggregation.AddAggregation(COUNT, "", "cnt_star2"); aggregation.AddDistinctAggregation(COUNT, "col1", "dcnt1"); aggregation.AddDistinctAggregation(SUM, "col2", "dsum2"); aggregation.AddDistinctAggregation(COUNT, "col2", "dcnt2"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_FALSE(transformed->schema().attribute(0).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(1).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(2).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(3).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(4).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(5).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } TEST_F(HybridAggregateTest, HybridGroupTransformOnlyDistinct) { std::unique_ptr<Cursor> input(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, 10) .AddRow(1, 4, 11) .AddRow(3, -3, 10) .AddRow(2, 4, 11) .AddRow(3, -5, 10) .BuildCursor()); std::unique_ptr<Cursor> expected_output(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, __) .AddRow(1, 4, __) .AddRow(3, -3, __) .AddRow(2, 4, __) .AddRow(3, -5, __) .AddRow(1, __, 10) .AddRow(1, __, 11) .AddRow(3, __, 10) .AddRow(2, __, 11) .AddRow(3, __, 10) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1"); aggregation.AddDistinctAggregation(COUNT, "col2", "distinct2"); aggregation.AddDistinctAggregation(SUM, "col1", "distinct1b"); aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1c"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } TEST_F(HybridAggregateTest, HybridGroupTransformDistinctAndCountAll) { std::unique_ptr<Cursor> input(TestDataBuilder<INT32, INT32, INT32>() .AddRow(1, 3, 10) .AddRow(1, 4, 11) .AddRow(3, -3, 10) .AddRow(2, 4, 11) .AddRow(3, -5, 10) .BuildCursor()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32, INT32>() .AddRow(1, 3, __, __) .AddRow(1, 4, __, __) .AddRow(3, -3, __, __) .AddRow(2, 4, __, __) .AddRow(3, -5, __, __) .AddRow(1, __, 10, __) .AddRow(1, __, 11, __) .AddRow(3, __, 10, __) .AddRow(2, __, 11, __) .AddRow(3, __, 10, __) .AddRow(1, __, __, 0) .AddRow(1, __, __, 0) .AddRow(3, __, __, 0) .AddRow(2, __, __, 0) .AddRow(3, __, __, 0) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1"); aggregation.AddDistinctAggregation(COUNT, "col2", "distinct2"); aggregation.AddDistinctAggregation(SUM, "col1", "distinct1b"); aggregation.AddDistinctAggregation(COUNT, "col1", "distinct1c"); aggregation.AddAggregation(COUNT, "", "count_all"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } // The example from implementation comment. TEST_F(HybridAggregateTest, HybridGroupTransformExampleTest) { std::unique_ptr<Cursor> input( TestDataBuilder<INT32, INT32, INT32, INT32, INT32>() .AddRow(1, 2, 3, 4, 5) .AddRow(6, 7, 8, 9, 0) .BuildCursor()); std::unique_ptr<Cursor> expected_output( TestDataBuilder<INT32, INT32, INT32, INT32, INT32>() .AddRow(1, 2, __, __, __) .AddRow(6, 7, __, __, __) .AddRow(1, __, 3, __, __) .AddRow(6, __, 8, __, __) .AddRow(1, __, __, 4, 2) .AddRow(6, __, __, 9, 7) .BuildCursor()); std::unique_ptr<const SingleSourceProjector> group_by_columns( ProjectNamedAttribute("col0")); AggregationSpecification aggregation; aggregation.AddAggregation(SUM, "col3", "sum2"); aggregation.AddAggregation(SUM, "col1", "sum"); aggregation.AddDistinctAggregation(COUNT, "col1", "dcnt1"); aggregation.AddDistinctAggregation(COUNT, "col2", "dcnt2"); std::unique_ptr<Cursor> transformed(SucceedOrDie(BoundHybridGroupAggregate( group_by_columns.release(), aggregation, "", HeapBufferAllocator::Get(), 0, (new HybridGroupDebugOptions)->set_return_transformed_input(true), input.release()))); EXPECT_FALSE(transformed->schema().attribute(0).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(1).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(2).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(3).is_nullable()); EXPECT_TRUE(transformed->schema().attribute(4).is_nullable()); EXPECT_CURSORS_EQUAL(expected_output.release(), transformed.release()); } // Several tests that check that hybrid group's group by columns can be // specified by various kinds of projectors (by position, all columns, renaming // projectors). // TODO(user): It would be useful to be able to assert which branch of the // hybrid group algorithm was chosen (three branches that differ in the number // of projections applied), so we could make sure we are testing them all... TEST_F(HybridAggregateTest, GroupByColumnPosition1) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 0) .AddRow(1, 0) .AddRow(3, 0) .AddRow(3, 0) .AddRow(2, 0) .AddRow(3, 0) .AddRow(1, 0) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(0, 14, 7, 3) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( ProjectAttributeAt(1), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, GroupByAllColumns) { OperationTest test; test.SetInput(TestDataBuilder<INT32>() .AddRow(1) .AddRow(1) .AddRow(3) .AddRow(3) .AddRow(2) .AddRow(3) .AddRow(1) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(1, 3, 3, 1) .AddRow(2, 2, 1, 1) .AddRow(3, 9, 3, 1) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( ProjectAllAttributes(), aggregation.release(), 16, "", test.input())); } TEST_F(HybridAggregateTest, GroupByColumnRenamed) { OperationTest test; test.SetInput(TestDataBuilder<INT32, INT32>() .AddRow(1, 0) .AddRow(1, 0) .AddRow(3, 0) .AddRow(3, 0) .AddRow(2, 0) .AddRow(3, 0) .AddRow(1, 0) .Build()); test.SetExpectedResult(TestDataBuilder<INT32, INT32, UINT64, UINT64>() .AddRow(0, 14, 7, 3) .Build()); std::unique_ptr<AggregationSpecification> aggregation( new AggregationSpecification); aggregation->AddAggregation(SUM, "col0", "sum"); aggregation->AddAggregation(COUNT, "col0", "cnt"); aggregation->AddDistinctAggregation(COUNT, "col0", "dcnt"); test.Execute(HybridGroupAggregate( ProjectNamedAttributeAs("col1", "key"), aggregation.release(), 16, "", test.input())); } } // namespace } // namespace supersonic
40.533673
80
0.65914
IssamElbaytam
2ab509d027a430f7d149af45caa410bed541eb1d
3,644
cpp
C++
src/Shared.cpp
IWantedToBeATranslator/2D-Strip-Packing
4ee9a220f2e9debf775b020d961f0ba547f32636
[ "MIT" ]
1
2017-12-12T19:23:44.000Z
2017-12-12T19:23:44.000Z
src/Shared.cpp
IWantedToBeATranslator/2D-Strip-Packing
4ee9a220f2e9debf775b020d961f0ba547f32636
[ "MIT" ]
1
2016-04-20T18:47:05.000Z
2016-05-04T08:05:45.000Z
src/Shared.cpp
IWantedToBeATranslator/2D-Strip-Packing
4ee9a220f2e9debf775b020d961f0ba547f32636
[ "MIT" ]
1
2019-07-14T15:39:27.000Z
2019-07-14T15:39:27.000Z
#include "Shared.h" Resources algosResources; int eCount = 120; spColorRectSprite* _bloxArray = new spColorRectSprite[eCount]; spClipRectActor _blockClip; spTextField _mainInfo; int* bloxHeights = new int[eCount]; int* bloxWidths = new int[eCount]; int algosHeights = 0; int algosSpaces = 0; int spaceUsed = 0; int screenWidth = 700; int screenHeight = 1000; float clipHeight; float clipWidth; spColorRectSprite spawnRandomBlock(float stageWidth, float stageHeight, float buttonWidth, float buttonHeight, int Xmod, int Ymod) { Color randColor((int)(rand() % 215 + 20), (int)(rand() % 215 + 20), (int)(rand() % 215 + 20), (int)(rand() % 215 + 20)); int bloxWidth = (int)rand() % (int)(stageWidth) / Xmod + 20; int bloxHeight = (int)rand() % (int)(stageWidth) / Ymod + 20; int posX = (int)rand() % (int)(stageWidth - buttonWidth - bloxWidth); int posY = (int)rand() % (int)(stageHeight - buttonHeight - bloxHeight); spColorRectSprite blox = initActor( new ColorRectSprite, arg_color = randColor, arg_x = posX, arg_y = posY, arg_w = bloxWidth, arg_h = bloxHeight, arg_blend = blend_disabled ); _blockClip->addChild(blox); spColorRectSprite left = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = 0, arg_y = 0, arg_w = 1, arg_h = bloxHeight, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(left); spColorRectSprite right = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = bloxWidth, arg_y = 0, arg_w = 1, arg_h = bloxHeight + 1, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(right); spColorRectSprite top = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = 0, arg_y = 0, arg_w = bloxWidth, arg_h = 1, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(top); spColorRectSprite bottom = initActor( new ColorRectSprite, arg_color = Color::Black, arg_x = 0, arg_y = bloxHeight, arg_w = bloxWidth + 1, arg_h = 1, arg_attachTo = blox, arg_blend = blend_disabled ); blox->addChild(bottom); spTextField bloxWidthText = initActor( new TextField, arg_color = Color(0, 0, 0), arg_y = bloxHeight - 15, arg_anchor = Vector2(1, 1), arg_text = (std::string)std::to_string(bloxWidth), arg_attachTo = blox, arg_input = false ); Rect tempRect = bloxWidthText->getTextRect(); bloxWidthText->setX(bloxWidth / 2 - tempRect.getWidth() / 2); blox->addChild(bloxWidthText); spTextField bloxHeightText = initActor( new TextField, arg_color = Color(0, 0, 0), arg_x = bloxWidth - 15, arg_rotation = -MATH_PI / 2, arg_anchor = Vector2(1, 1), arg_text = (std::string)std::to_string(bloxHeight), arg_attachTo = blox, arg_input = false ); tempRect = bloxHeightText->getTextRect(); bloxHeightText->setY(bloxHeight / 2 + tempRect.getHeight() / 2); blox->addChild(bloxHeightText); return blox; } void sortNonDecr(spColorRectSprite * blocks, int * blockHeights, int * blockWidths) { spColorRectSprite bloxBuffer; int tempbuf; FOR(m, 0, eCount) { FOR(n, 0, eCount - 1) { if (blockHeights[n] < blockHeights[n + 1]) { tempbuf = blockWidths[n]; blockWidths[n] = blockWidths[n + 1]; blockWidths[n + 1] = tempbuf; tempbuf = blockHeights[n]; blockHeights[n] = blockHeights[n + 1]; blockHeights[n + 1] = tempbuf; bloxBuffer = blocks[n]; blocks[n] = blocks[n + 1]; blocks[n + 1] = bloxBuffer; } } } }
26.028571
131
0.649012
IWantedToBeATranslator
2ab8fbf2535cfcac80e64bd88f1c8ffc46090fac
3,005
cc
C++
src/QGenderSelector.cc
png85/QGenderSelector
e4df122b582c9c9861416c4dad11d2a24daf44c0
[ "BSD-3-Clause" ]
null
null
null
src/QGenderSelector.cc
png85/QGenderSelector
e4df122b582c9c9861416c4dad11d2a24daf44c0
[ "BSD-3-Clause" ]
null
null
null
src/QGenderSelector.cc
png85/QGenderSelector
e4df122b582c9c9861416c4dad11d2a24daf44c0
[ "BSD-3-Clause" ]
null
null
null
#include <QDebug> #ifndef HAS_CXX11_NULLPTR #define nullptr 0 #endif #include "QGenderSelector.h" QGenderSelector::QGenderSelector(QWidget* parent) : QFrame(parent) , m_layout(nullptr) , m_radioMale(nullptr) , m_radioFemale(nullptr) , m_radioOther(nullptr) , m_selectedGender(Other) { qRegisterMetaType<Gender>("QGenderSelector::Gender"); setupUi(); setSelectedGender(m_selectedGender); } void QGenderSelector::setupUi() { try { m_layout = new QHBoxLayout(this); } catch (std::bad_alloc& ex) { QString msg = tr("Failed to allocate memory for new QBoxLayout in %1: %2").arg(Q_FUNC_INFO, ex.what()); qCritical() << msg; throw; } try { m_buttonGroup = new QButtonGroup(m_layout); } catch (std::bad_alloc& ex) { QString msg = tr("Failed to allocate memory for new QButtonGroup in %1: %2").arg(Q_FUNC_INFO, ex.what()); qCritical() << msg; throw; } QList<QRadioButton*> radioButtons; try { m_radioMale = new QRadioButton(tr("Male"), this); m_radioMale->setIcon(QIcon(":/icons/genders/male.png")); m_layout->addWidget(m_radioMale); m_buttonGroup->addButton(m_radioMale, static_cast<int>(Male)); m_radioFemale = new QRadioButton(tr("Female"), this); m_radioFemale->setIcon(QIcon(":/icons/genders/female.png")); m_layout->addWidget(m_radioFemale); m_buttonGroup->addButton(m_radioFemale, static_cast<int>(Female)); m_radioOther = new QRadioButton(tr("Other"), this); m_radioOther->setIcon(QIcon(":/icons/genders/other.png")); m_layout->addWidget(m_radioOther); m_buttonGroup->addButton(m_radioOther, static_cast<int>(Other)); } catch (std::bad_alloc& ex) { QString msg = tr("Failed to allocate memory for new QRadioButton in %1: %2").arg(Q_FUNC_INFO, ex.what()); qCritical() << msg; throw; } connect(m_buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(buttonGroup_buttonClicked(int))); QFrame::setLayout(m_layout); } void QGenderSelector::buttonGroup_buttonClicked(int id) { m_selectedGender = static_cast<Gender>(id); emit selectedGenderChanged(m_selectedGender); emit selectedGenderChanged(genderToDicomVR(m_selectedGender)); } void QGenderSelector::setSelectedGender(QGenderSelector::Gender g) { m_selectedGender = g; switch (g) { case Male: m_radioMale->setChecked(true); m_radioFemale->setChecked(false); m_radioOther->setChecked(false); break; case Female: m_radioMale->setChecked(false); m_radioFemale->setChecked(true); m_radioOther->setChecked(false); break; case Other: default: m_radioMale->setChecked(false); m_radioFemale->setChecked(false); m_radioOther->setChecked(true); break; } } void QGenderSelector_initResources() { Q_INIT_RESOURCE(QGenderSelector); }
27.318182
113
0.658236
png85
2abcb0a402576a40db36efcd62d48c7ae939fbac
2,198
cpp
C++
src/Game/Tile.cpp
warzes/RPGInBox
3d8ccbb38711cf6a1b2542113fa4d9a9e53c9e31
[ "MIT" ]
3
2021-07-12T14:54:01.000Z
2021-09-06T07:45:40.000Z
src/Game/Tile.cpp
warzes/RPGInBox
3d8ccbb38711cf6a1b2542113fa4d9a9e53c9e31
[ "MIT" ]
null
null
null
src/Game/Tile.cpp
warzes/RPGInBox
3d8ccbb38711cf6a1b2542113fa4d9a9e53c9e31
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Tile.h" #include "IGameCamera.h" #include "ResourceManager.h" #include "DebugNew.h" //----------------------------------------------------------------------------- const std::map<TileType, std::string> textureFloorName = { {TileType::Grass, "../data/temp/textures/map/outdoor/plains-ground2.png"}, {TileType::Road, "../data/temp/textures/map/outdoor/road.png"}, }; //----------------------------------------------------------------------------- const std::map<TileDecorType, std::string> textureDecorName = { {TileDecorType::None, ""}, {TileDecorType::Tree, "../data/temp/textures/map/outdoor/plains-tree2.png"}, {TileDecorType::Tree2, "../data/temp/textures/map/outdoor/plains-tree3.png"}, }; //----------------------------------------------------------------------------- Tile Tile::Create(ResourceManager& resource, TileType type, TileDecorType decor) { Tile tile; tile.type = type; tile.decor = decor; tile.textureTile = resource.GetTexture(textureFloorName.at(type)); if (decor != TileDecorType::None) tile.textureDecor = resource.GetTexture(textureDecorName.at(decor)); //if (textureFloorName != "") // tile.textureTile = resource.GetTexture(textureFloorName); //if (decor != TileDecorType::None && textureDecorName != "") // tile.textureDecor = resource.GetTexture(textureDecorName); return tile; } //----------------------------------------------------------------------------- void Tile::Draw(IGameCamera* camera, const Vector2& pos) { if (!textureTile) return; // Floor render DrawCubeTexture(*textureTile, { pos.x, -0.5f, pos.y }, 1, 1, 1, WHITE); //DrawModel(model, Vector3{ (float)x, 0.0f, (float)y }, 0.5f, WHITE); // object render if (!textureDecor || decor == TileDecorType::None) return; DrawBillboard(camera->GetCamera(), *textureDecor, { pos.x, 1.0f, pos.y }, 2.0f, WHITE); //DrawCubeTexture(m_resourceMgr.textureTree, Vector3{ (float)x, 0.5f, (float)y }, 1, 1, 1, WHITE); //DrawCubeTexture(tx, Vector3{ (float)x, 1.5f, (float)y }, 1, 1, 1, GREEN); //DrawCubeTexture(tx, Vector3{ (float)x, 0.5f, (float)y }, 0.25f, 1, 0.25f, BROWN); } //-----------------------------------------------------------------------------
42.269231
99
0.572338
warzes
2abe9aca53375ac18c7ffd4c74d19f614c434b00
440
cpp
C++
contest/AtCoder/abc054/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/AtCoder/abc054/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/AtCoder/abc054/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "string.hpp" #include "vector.hpp" int main() { int n(in), m(in); Vector<String> a(n, in), b(m, in); for (int i = 0; i <= n - m; ++i) { for (int j = 0; j <= n - m; ++j) { bool f = true; for (int y = 0; y < m; ++y) { if (a[i + y].substr(j, m) != b[y]) { f = false; } } if (f) { cout << true << endl; return 0; } } } cout << false << endl; }
19.130435
44
0.381818
not522
2ac161fe17f70736e67259973c29806aaf9d8dbb
5,200
cpp
C++
Lighting/readFiles.cpp
arturnista/glfwstudy
fa24539c88149d388aebada68e6e10b862e19829
[ "MIT" ]
null
null
null
Lighting/readFiles.cpp
arturnista/glfwstudy
fa24539c88149d388aebada68e6e10b862e19829
[ "MIT" ]
null
null
null
Lighting/readFiles.cpp
arturnista/glfwstudy
fa24539c88149d388aebada68e6e10b862e19829
[ "MIT" ]
null
null
null
#define _SCL_SECURE_NO_WARNINGS #pragma warning(disable:4996) #include "readFiles.h" const char* readFile(string filename) { string fullFileData; ifstream openedFile(filename.c_str()); if (openedFile.is_open()) { string line; while (getline(openedFile, line)) { fullFileData += line + '\n'; } openedFile.close(); } // Copy the string char * writable = new char[fullFileData.size() + 1]; std::copy(fullFileData.begin(), fullFileData.end(), writable); writable[fullFileData.size()] = '\0'; return writable; } void fetchFileData(string filename, vector<GLfloat>& pointsVector, vector<GLuint>& indexVector, vector<GLfloat>& normalVector) { ifstream openedFile(filename.c_str()); if (openedFile.is_open()) { string line; string strNumber; while(!openedFile.eof()) { openedFile >> line; if(line.compare("v") == 0) { openedFile >> strNumber; pointsVector.push_back( stof(strNumber) ); openedFile >> strNumber; pointsVector.push_back( stof(strNumber) ); openedFile >> strNumber; pointsVector.push_back( stof(strNumber) ); } else if(line.compare("vn") == 0) { openedFile >> strNumber; normalVector.push_back( stof(strNumber) ); openedFile >> strNumber; normalVector.push_back( stof(strNumber) ); openedFile >> strNumber; normalVector.push_back( stof(strNumber) ); } else if(line.compare("f") == 0) { int count = 3; for (size_t i = 0; i < count; i++) { openedFile >> strNumber; int doubleIdx = strNumber.find("//"); if(doubleIdx > 0) { string fstNumber = strNumber.substr(0, doubleIdx); string secNumber = strNumber.substr(doubleIdx + 2); indexVector.push_back( stof(fstNumber) ); // normalVector.push_back( stof(secNumber) ); } else { int singleIdx = strNumber.find("/"); if(singleIdx > 0) { string fstNumber = strNumber.substr(0, singleIdx); string nextString = strNumber.substr(singleIdx + 1); int nextIndex = nextString.find("/"); string secNumber = nextString.substr(0, nextIndex); string trdNumber = nextString.substr(nextIndex + 1); indexVector.push_back( stof(fstNumber) ); // normalVector.push_back( stof(trdNumber) ); } else { indexVector.push_back( stof(strNumber) ); } } } } } openedFile.close(); } } gameObject readObjectFile(string filename, float size, vec3 color) { std::vector<GLfloat> pointsVector = {}; std::vector<GLuint> indexVector = {}; std::vector<GLfloat> normalVector = {}; fetchFileData(filename, pointsVector, indexVector, normalVector); int pointsCounter = pointsVector.size() * 3; int vertexCounter = indexVector.size(); cout << filename << "\t"; cout << "vertex count" << " = " << pointsVector.size() << '\t'; cout << "face count" << " = " << vertexCounter << '\n'; GLfloat *points = new GLfloat[pointsCounter]; float lineSize = 9; int counter = 0; for (size_t i = 0; i < pointsCounter; i += lineSize) { // Position points[i + 0] = pointsVector.at(counter); points[i + 1] = pointsVector.at(counter + 1); points[i + 2] = pointsVector.at(counter + 2); // Color points[i + 3] = color.x; points[i + 4] = color.y; points[i + 5] = color.z; if(normalVector.size() > 0) { points[i + 6] = normalVector.at(counter); points[i + 7] = normalVector.at(counter + 1); points[i + 8] = normalVector.at(counter + 2); } else { points[i + 6] = 1.0f; points[i + 7] = 0.0f; points[i + 8] = 0.0f; } counter += 3; } // copy(pointsVector.begin(), pointsVector.end(), points); // if(size != 1) for (size_t i = 0; i < pointsCounter; i++) points[i] = points[i] * size; GLuint VBO = 0; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, pointsCounter * sizeof(GLfloat), points, GL_STATIC_DRAW); GLuint VAO = 0; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); // Positions glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, lineSize * sizeof(GLfloat), (void*)0); glEnableVertexAttribArray(0); // Colors glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, lineSize * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); // Normal glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, lineSize * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); if(vertexCounter > 0) { GLuint *indexArray = new GLuint[vertexCounter]; copy(indexVector.begin(), indexVector.end(), indexArray); for (size_t i = 0; i < vertexCounter; i++) indexArray[i] = indexArray[i] - 1; GLuint EBO = 0; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * vertexCounter, indexArray, GL_STATIC_DRAW); } return { VAO, vertexCounter, size, }; } gameObject readObjectFile(string filename, float size) { glm::vec3 color = glm::vec3( static_cast <float> (rand()) / static_cast <float> (RAND_MAX), static_cast <float> (rand()) / static_cast <float> (RAND_MAX), static_cast <float> (rand()) / static_cast <float> (RAND_MAX) ); return readObjectFile(filename, size, color); }
29.050279
107
0.660577
arturnista
2ac6b4e01d4de1730cfa471c02c28130113840c8
8,498
hpp
C++
foedus_code/foedus-core/include/foedus/storage/hash/hash_reserve_impl.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/storage/hash/hash_reserve_impl.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/storage/hash/hash_reserve_impl.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #ifndef FOEDUS_STORAGE_HASH_HASH_RESERVE_IMPL_HPP_ #define FOEDUS_STORAGE_HASH_HASH_RESERVE_IMPL_HPP_ #include "foedus/error_code.hpp" #include "foedus/storage/hash/fwd.hpp" #include "foedus/storage/hash/hash_combo.hpp" #include "foedus/storage/hash/hash_id.hpp" #include "foedus/thread/fwd.hpp" #include "foedus/xct/sysxct_functor.hpp" namespace foedus { namespace storage { namespace hash { /** * @brief A system transaction to reserve a physical record(s) in a hash data page. * @ingroup HASH * @see SYSXCT * @details * A record insertion happens in two steps: * \li During Execution: Physically inserts a deleted record for the key in the data page. * \li During Commit: Logically flips the delete-bit and installs the payload. * * This system transaction does the former. * * This does nothing and returns kErrorCodeOk in the following cases: * \li The page turns out to already contain a satisfying physical record for the key. * * In all other cases, this sysxct creates or finds the record. * In other words, this sysxct guarantees a success as far as it returns kErrorCodeOk. * * Locks taken in this sysxct (in order of taking): * \li Page-lock of the target or the tail page if target_ is not the tail * (in the order of the chain, so no deadlock). * \li Record-lock of an existing, matching record. Only when we have to expand the record. * This also happens after the page-lock of the enclosing page, before the page-lock of * following pages, so every lock is in order. * * Note, however, that it might not be in address order (address order might be tail -> head). * We thus might have a false deadlock-abort. However, as far as the first lock on the * target_ page is unconditional, all locks after that should be non-racy, so all try-lock * should succeed. We might want to specify a bit larger max_retries (5?) for this reason. * * @par Differences from Masstree's reserve * This sysxct is simpler than masstree::ReserveRecords for a few reasons. * \li No need to split the page * \li No need to adopt a split page * * We thus contain all required logics (reserve/expansion/migrate) in this sysxct. * In all circumstances, this sysxct finds or reserves the required record. * Simpler for the caller. * * So far this sysxct installs only one physical record at a time. * TASK(Hideaki): Probably it helps by batching several records. */ struct ReserveRecords final : public xct::SysxctFunctor { /** Thread context */ thread::Thread* const context_; /** * @brief The data page to install a new physical record. * @details * This might NOT be the head page of the hash bin. * The contract here is that the caller must be sure that * any pages before this page in the chain must not contain a record * of the given key that is not marked as moved. * In other words, the caller must have checked that there is no such record * before hint_check_from_ of target_. * * \li Example 1: the caller found an existing record in target_ that is not moved. * hint_check_from_ < target_->get_key_count(), and target_ might not be the tail of the bin. * \li Example 2: the caller found no existing non-moved record. * hint_check_from_ == target_->get_key_count(), and target_ is the tail of the bin. * * Of course, by the time this sysxct takes a lock, other threads might insert * more records, some of which might have the key. This sysxct thus needs to * resume search from target_ and hint_check_from_ (but, not anywhere before!). */ HashDataPage* const target_; /** The key of the new record */ const void* const key_; /** * Hash info of the key. * It's &, so lifetime of the caller's HashCombo object must be longer than this sysxct. */ const HashCombo& combo_; /** Byte length of the key */ const KeyLength key_length_; /** Minimal required length of the payload */ const PayloadLength payload_count_; /** * When we expand the record or allocate a new record, we might * allocate a larger-than-necessary space guided by this hint. * It's useful to avoid future record expansion. * @pre aggressive_payload_count_hint_ >= payload_count_ */ const PayloadLength aggressive_payload_count_hint_; /** * The in-page location from which this sysxct will look for matching records. * The caller is \e sure that no record before this position can match the slice. * Thanks to append-only writes in data pages, the caller can guarantee that the records * it observed are final. * * In most cases, this is same as key_count after locking, thus completely avoiding the re-check. * In some cases, the caller already found a matching key in this index, but even in that case * this sysxct must re-search after locking because the record might be now moved. */ const DataPageSlotIndex hint_check_from_; /** * [Out] The slot of the record that is found or created. * As far as this sysxct returns kErrorCodeOk, this guarantees the following. * @post out_slot_ != kSlotNotFound * @post out_page_'s out_slot_ is at least at some point a valid non-moved record * of the given key with satisfying max-payload length. */ DataPageSlotIndex out_slot_; /** * [Out] The page that contains the found/created record. * As far as this sysxct returns kErrorCodeOk, out_page_ is either the target_ itself * or some page after target_. * @post out_page_ != nullptr */ HashDataPage* out_page_; ReserveRecords( thread::Thread* context, HashDataPage* target, const void* key, KeyLength key_length, const HashCombo& combo, PayloadLength payload_count, PayloadLength aggressive_payload_count_hint, DataPageSlotIndex hint_check_from) : xct::SysxctFunctor(), context_(context), target_(target), key_(key), combo_(combo), key_length_(key_length), payload_count_(payload_count), aggressive_payload_count_hint_(aggressive_payload_count_hint), hint_check_from_(hint_check_from), out_slot_(kSlotNotFound), out_page_(nullptr) { } virtual ErrorCode run(xct::SysxctWorkspace* sysxct_workspace) override; /** * The main loop (well, recursion actually). */ ErrorCode find_or_create_or_expand( xct::SysxctWorkspace* sysxct_workspace, HashDataPage* page, DataPageSlotIndex examined_records); ErrorCode expand_record( xct::SysxctWorkspace* sysxct_workspace, HashDataPage* page, DataPageSlotIndex index); ErrorCode find_and_lock_spacious_tail( xct::SysxctWorkspace* sysxct_workspace, HashDataPage* from_page, HashDataPage** tail); /** * Installs it as a fresh-new physical record, assuming the given page is the tail * and already locked. */ ErrorCode create_new_record_in_tail_page(HashDataPage* tail); ErrorCode create_new_tail_page( HashDataPage* cur_tail, HashDataPage** new_tail); DataPageSlotIndex search_within_page( const HashDataPage* page, DataPageSlotIndex key_count, DataPageSlotIndex examined_records) const; /** * Appends a new physical record to the page. * The caller must make sure there is no race in the page. * In other words, the page must be either locked or a not-yet-published page. */ DataPageSlotIndex append_record_to_page(HashDataPage* page, xct::XctId initial_xid) const; }; } // namespace hash } // namespace storage } // namespace foedus #endif // FOEDUS_STORAGE_HASH_HASH_RESERVE_IMPL_HPP_
40.660287
99
0.730525
sam1016yu
2acd9c96f14697bc28ea6bbcba21a2d4fb13b485
288
cc
C++
test/foo_test.cc
jingleman/cmake-gtest-gbench-starter
19bb4e3c17a2dea4c372d9cdbfab1eb557d1a5f0
[ "MIT" ]
27
2017-01-14T19:48:26.000Z
2022-01-30T01:09:16.000Z
test/foo_test.cc
jingleman/cmake-gtest-gbench-starter
19bb4e3c17a2dea4c372d9cdbfab1eb557d1a5f0
[ "MIT" ]
1
2018-11-12T19:53:37.000Z
2018-11-30T18:23:10.000Z
test/foo_test.cc
jingleman/cmake-gtest-gbench-starter
19bb4e3c17a2dea4c372d9cdbfab1eb557d1a5f0
[ "MIT" ]
13
2017-02-12T00:53:53.000Z
2021-10-02T01:59:00.000Z
#include <iostream> #include "gtest/gtest.h" #include "nemo/foo.hh" TEST(NemoFoo, Positives) { EXPECT_EQ(38, nemo::foo(-4)); EXPECT_EQ(42, nemo::foo(0)); } TEST(NemoFoo, Negatives) { EXPECT_NE(-1, nemo::foo(99)); EXPECT_NE(0, nemo::foo(-41)); EXPECT_NE(42, nemo::foo(42)); }
18
31
0.642361
jingleman
2acfa040b8768fabb1f707f57acffb09db8ad8e8
10,266
cpp
C++
src/player.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
11
2015-03-02T07:43:00.000Z
2021-12-04T04:53:02.000Z
src/player.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
1
2015-03-28T17:17:13.000Z
2016-10-10T05:49:07.000Z
src/player.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
3
2016-11-04T01:14:31.000Z
2020-05-07T23:42:27.000Z
/**************************** Copyright © 2006-2015 Luke Salisbury This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ****************************/ #include "engine.h" #include "elix/elix_string.hpp" #include "core.h" #include "game_config.h" #include "game_system.h" #include "display/display_functions.h" #include "platform_media.h" extern ObjectEffect default_fx; /* - Controller Layout axis 0: X/Y/Z -255 to 255. axis 1: A/B/C -255 to 255. pointer: 2d location. button 00: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 01: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 02: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 03: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 04: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 05: 0 - unpressed, 1 - Just pressed, 2 - holding (action) button 06: 0 - unpressed, 1 - Just pressed, 2 - holding (menu) button 07: 0 - unpressed, 1 - Just pressed, 2 - holding (right) button 08: 0 - unpressed, 1 - Just pressed, 2 - holding (left) button 09: 0 - unpressed, 1 - Just pressed, 2 - holding (down) button 10: 0 - unpressed, 1 - Just pressed, 2 - holding (up) button 11: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 12: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 13: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 14: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) button 15: 0 - unpressed, 1 - Just pressed, 2 - holding (undefined) internal button 16: (confirm) 0 - unpressed, 1 - Just pressed, 2 - holding internal button 17: (cancel) 0 - unpressed, 1 - Just pressed, 2 - holding internal button 18: (pointer press) 0 - unpressed, 1 - Just pressed, 2 - holding internal button 19: (shutdown) 0 - unpressed, 1 - Just pressed, 2 - holding */ inline int KeyboardAxis(int key1, int key2) { if ( key1 && !key2 ) return -255; else if ( !key1 && key2 ) return 255; return 0; } Player::Player(uint32_t id, uint8_t control) { this->_id = id; this->SetControls((uint8_t)id); this->_control = control; this->timer = 0; this->_entity = NULL; this->_pointer[0] = this->_pointer[1] = this->_pointer[2] = 10; this->PlayerColour = default_fx; this->PlayerColour.primary_colour.r = this->PlayerColour.primary_colour.b = this->PlayerColour.primary_colour.g = this->PlayerColour.primary_colour.a = 200; } Player::~Player() { this->ClearController(); if ( this->_entity ) { this->_entity->Delete(); this->_entity = NULL; } } std::string Player::GetControllerName() { return this->control_name; } void Player::SetControls( std::string controller_name ) { this->control_name = controller_name; this->SetupController( controller_name ); } void Player::SetControls(uint8_t preset) { std::string control_value = "default"; if ( lux::config ) { std::string control_name = "player.controller"; control_name.append( 1, (char)(preset + '0') ); control_value = lux::config->GetString(control_name); } this->SetControls( control_value ); } /* Cache Input */ void Player::CachePointerValues() { switch (this->_pointerConfig.device) { case CONTROLAXIS: { //TODO this->_pointer[0] += lux::core->GetInput(CONTROLAXIS, this->_pointerConfig.device_number,this->_pointerConfig.sym[0]) / 128; this->_pointer[1] += lux::core->GetInput(CONTROLAXIS, this->_pointerConfig.device_number,this->_pointerConfig.sym[2]) / 128; this->_pointer[2] = 1; break; } case MOUSEAXIS: { this->_pointer[0] = lux::core->GetInput(MOUSEAXIS, 0,0); this->_pointer[1] = lux::core->GetInput(MOUSEAXIS, 0,1); this->_pointer[2] = 1; break; } default: { this->_pointer[0] = this->_pointer[1] = this->_pointer[2] = 0; break; } } } void Player::CacheAxisValues( uint8_t n ) { switch (this->_controllerConfig[n].device) { case KEYBOARD: { int key1, key2; /* X axis */ key1 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[0]); key2 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[1]); this->_controller[(n*3)+0] = KeyboardAxis(key1, key2); /* y axis */ key1 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[2]); key2 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[3]); this->_controller[(n*3)+1] = KeyboardAxis(key1, key2); /* z axis */ key1 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[4]); key2 = lux::core->GetInput(KEYBOARD, 0,this->_controllerConfig[n].sym[5]); this->_controller[(n*3)+2] = KeyboardAxis(key1, key2); break; } case CONTROLAXIS: { this->_controller[(n*3)+0] = lux::core->GetInput(CONTROLAXIS, this->_controllerConfig[n].device_number, this->_controllerConfig[n].sym[0]); this->_controller[(n*3)+1] = lux::core->GetInput(CONTROLAXIS, this->_controllerConfig[n].device_number,this->_controllerConfig[n].sym[2]); this->_controller[(n*3)+2] = lux::core->GetInput(CONTROLAXIS, this->_controllerConfig[n].device_number,this->_controllerConfig[n].sym[4]); break; } default: break; } // if ( this->_buttonConfig[n].device == CONTROLBUTTON || this->_buttonConfig[n].device == CONTROLAXIS ) // lux::core->SystemMessage(SYSTEM_MESSAGE_DEBUG) << "axis[" << +n << "] x:" << this->_controller[(n*3)+0] << " y:" << this->_controller[(n*3)+1] << " z:" << this->_controller[(n*3)+2] << std::endl; } void Player::CacheButtonValues(uint8_t n) { if ( lux::core == NULL ) return; int key = lux::core->GetInput( this->_buttonConfig[n].device, this->_buttonConfig[n].device_number, this->_buttonConfig[n].sym ); if ( key ) this->_button[n] = (this->_button[n] ? 2 : 1); else this->_button[n] = 0; // if ( this->_buttonConfig[n].device == CONTROLBUTTON || this->_buttonConfig[n].device == CONTROLAXIS ) // lux::core->SystemMessage(SYSTEM_MESSAGE_DEBUG) << "button[" << +n << "] " << this->_button[n] << std::endl; } void Player::Loop() { if (_control == LOCAL) { /* Pointer */ this->CachePointerValues(); /* Button/Axis */ for (uint8_t n = 0; n < 19; n++) { if (n < 2) { this->CacheAxisValues(n); } this->CacheButtonValues(n); } #ifdef NETWORKENABLED if ( lux::core->GetTime() > (this->timer + 333) ) { this->timer = lux::core->GetTime(); if ( this->_entity ) { this->_entity->displaymap = lux::gameworld->active_map->Ident(); if ( lux::core->CreateMessage((uint8_t)4, true) ) { lux::core->MessageAppend(this->_entity->x); lux::core->MessageAppend(this->_entity->y); lux::core->MessageAppend(this->_entity->displaymap); lux::core->MessageSend(); } } } #endif } else if ( this->_control == REMOTE ) { } } LuxSprite * Player::GetInputSprite( int8_t axis, int8_t key, int8_t pointer ) { LuxSprite * sprite = NULL; if ( axis >= 0 && axis < 12 ) { uint8_t a = axis/6; // Axis (Either 1 or 2) uint8_t s = axis%6; // Axis Direction int32_t m = 0; if ( this->_controllerConfig[a].device == CONTROLAXIS ) { m = ( s % 2 ? 0 : 0x80000000 ); //If remainder, we want positive value } sprite = lux::engine->media.GetInputImage( this->_controllerConfig[a].device, this->_controllerConfig[a].device_number, this->_controllerConfig[a].sym[s] | m ); } else if ( key >= 0 && key < 19 ) { sprite = lux::engine->media.GetInputImage(this->_buttonConfig[key].device, this->_buttonConfig[key].device_number, this->_buttonConfig[key].sym); } else if ( pointer >= 0 ) { sprite = lux::engine->media.GetInputImage(this->_pointerConfig.device, this->_pointerConfig.device_number, this->_pointerConfig.sym[0]); } return sprite; } int16_t Player::GetControllerAxis(uint8_t axis) { if (axis < 6) { return (int16_t)this->_controller[axis]; } return -1; } int16_t Player::GetButton(uint8_t key) { if (key < 19) { return (int16_t)this->_button[key]; } return -1; } int16_t Player::GetPointer(uint8_t axis) { if (axis < 2) { return (int16_t)this->_pointer[axis]; } return -1; } void Player::SetControllerAxis(uint8_t axis, int16_t value) { if (axis < 4) { this->_controller[axis] = value; } } void Player::SetButton(uint8_t key, int16_t value) { if (key < 16) { this->_button[key] = value; } } void Player::SetPointer(uint8_t axis, int16_t value) { if ( axis < 2 ) { this->_pointer[axis] = value; } } MapObject *Player::GetPointerObject() { return NULL; } /* Entity */ Entity * Player::GetEntity() { return this->_entity; } void Player::SetEntity(Entity * entity) { this->_entity = entity; } void Player::SetEntityPostion( fixed x, fixed y, uint8_t z_layer, uint32_t mapid ) { if ( this->_entity ) { #ifdef NETWORKENABLED lux::core->NetworkLock(); #endif this->_entity->x = x; this->_entity->y = y; this->_entity->z_layer = z_layer; this->_entity->displaymap = mapid; #ifdef NETWORKENABLED lux::core->NetworkUnlock(); #endif } } void Player::Message( int32_t * data, uint32_t size ) { if ( this->_entity ) { #ifdef NETWORKENABLED lux::core->NetworkLock(); #endif this->_entity->callbacks->Push( this->_entity->_data, size ); this->_entity->callbacks->PushArray( this->_entity->_data, data, size, NULL ); this->_entity->callbacks->Push( this->_entity->_data, 0 ); this->_entity->Call("NetMessage", (char*)""); #ifdef NETWORKENABLED lux::core->NetworkUnlock(); #endif } } void Player::SetName(std::string name) { this->_name = name; } std::string Player::GetName( ) { return this->_name; }
27.449198
243
0.667933
mokoi
2ade04cfa5f59cb6558411487dafbfd39a12c9b5
2,515
cpp
C++
pop/src/commands/PopCommand.cpp
webOS-ports/mojomail
49358ac2878e010f5c6e3bd962f047c476c11fc3
[ "Apache-2.0" ]
6
2015-01-09T02:20:27.000Z
2021-01-02T08:14:23.000Z
mojomail/pop/src/commands/PopCommand.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
3
2019-05-11T19:17:56.000Z
2021-11-24T16:04:36.000Z
mojomail/pop/src/commands/PopCommand.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
6
2015-01-09T02:21:13.000Z
2021-01-02T02:37:10.000Z
// @@@LICENSE // // Copyright (c) 2009-2013 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // LICENSE@@@ #include "commands/PopCommand.h" #include "client/PopSession.h" #include "commands/PopCommandResult.h" #include <sstream> #include "client/SyncSession.h" using namespace std; MojLogger PopCommand::s_log("com.palm.pop.client"); PopCommand::PopCommand(Listener& listener, Command::Priority priority) : Command(listener, priority), m_log(s_log), m_lastFunction(NULL), m_isCancelled(false) { } PopCommand::~PopCommand() { } bool PopCommand::PrepareToRun() { if (m_isCancelled) { return false; } else { return true; } } void PopCommand::RunIfReady() { if(PrepareToRun()) { RunImpl(); } } void PopCommand::Run() { MojLogInfo(m_log, "running command %s", Describe().c_str()); try { RunIfReady(); } catch(const exception& e) { Failure(e); } catch(...) { Failure(boost::unknown_exception()); } } const MojRefCountedPtr<PopCommandResult>& PopCommand::GetResult() { if(m_result.get()) { return m_result; } else { m_result.reset(new PopCommandResult()); return m_result; } } void PopCommand::Run(MojSignal<>::SlotRef slot) { if(m_result.get()) { m_result->ConnectDoneSlot(slot); } else { m_result.reset(new PopCommandResult(slot)); } Run(); } void PopCommand::SetResult(const MojRefCountedPtr<PopCommandResult>& result) { m_result = result; } void PopCommand::Cleanup() { } void PopCommand::Cancel() { m_isCancelled = true; // No need to remove command from command manager. The command should be // taken out of comamnd queue before it is cancelled. Cleanup(); } void PopCommand::Status(MojObject& status) const { MojErr err; err = status.putString("class", Describe().c_str()); ErrorToException(err); if(m_lastFunction != NULL) { err = status.putString("lastFunction", m_lastFunction); ErrorToException(err); } if(m_isCancelled) { err = status.put("cancelled", true); ErrorToException(err); } }
19.496124
76
0.706958
webOS-ports
2adfa4f053b54d03783143ef2975b341585ef9de
429
cpp
C++
1-Iniciante/10/2754.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
1-Iniciante/10/2754.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
1-Iniciante/10/2754.cpp
pedrospaulo/01-C-
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
[ "MIT" ]
null
null
null
#include <stdio.h> int main(){ double a, b; a = 234.345; b = 45.698; printf("%.6lf - %.6lf\n", a, b); printf("%.0lf - %.0lf\n", a, b); printf("%.1lf - %.1lf\n", a, b); printf("%.2lf - %.2lf\n", a, b); printf("%.3lf - %.3lf\n", a, b); printf("%.6e - %.6e\n", a, b); printf("%.6E - %.6E\n", a, b); printf("%.3lf - %.3lf\n", a, b); printf("%.3lf - %.3lf\n", a, b); return 0; }
21.45
36
0.417249
pedrospaulo
2ae191ffc744a8211ebbf6e56ec0bc93226e076a
1,447
cpp
C++
Source/UnrealCPP/OnComponentHit/OnComponentHit.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
6
2018-04-22T15:27:39.000Z
2021-11-02T17:33:58.000Z
Source/UnrealCPP/OnComponentHit/OnComponentHit.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
null
null
null
Source/UnrealCPP/OnComponentHit/OnComponentHit.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
4
2018-07-26T15:39:46.000Z
2020-12-28T08:10:35.000Z
// Harrison McGuire // UE4 Version 4.18.2 // https://github.com/Harrison1/unrealcpp // https://severallevels.io // https://harrisonmcguire.com #include "OnComponentHit.h" #include "Components/BoxComponent.h" #include "Components/StaticMeshComponent.h" // Sets default values AOnComponentHit::AOnComponentHit() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Use a sphere as a simple collision representation MyComp = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComp")); MyComp->SetSimulatePhysics(true); MyComp->SetNotifyRigidBodyCollision(true); MyComp->BodyInstance.SetCollisionProfileName("BlockAllDynamic"); MyComp->OnComponentHit.AddDynamic(this, &AOnComponentHit::OnCompHit); // Set as root component RootComponent = MyComp; } // Called when the game starts or when spawned void AOnComponentHit::BeginPlay() { Super::BeginPlay(); } // Called every frame void AOnComponentHit::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AOnComponentHit::OnCompHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL)) { if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, FString::Printf(TEXT("I Hit: %s"), *OtherActor->GetName())); } }
27.826923
159
0.750518
Harrison1
2ae78bbf1a3a33bd97dabb65c87239644c78f816
4,449
cpp
C++
Drivers/src/MPU6050.cpp
John-Carr/SolarGatorsBSP_STM
df68ccd2add244c90a573a5d4e1de5400361a2b5
[ "MIT" ]
null
null
null
Drivers/src/MPU6050.cpp
John-Carr/SolarGatorsBSP_STM
df68ccd2add244c90a573a5d4e1de5400361a2b5
[ "MIT" ]
null
null
null
Drivers/src/MPU6050.cpp
John-Carr/SolarGatorsBSP_STM
df68ccd2add244c90a573a5d4e1de5400361a2b5
[ "MIT" ]
null
null
null
/* * MPU6050.cpp * * Created on: Jan 24, 2022 * Author: John Carr */ #include "MPU6050.hpp" namespace SolarGators { namespace Drivers { MPU6050::MPU6050(I2C_HandleTypeDef *hi2c, uint8_t addr):hi2c_(hi2c),addr_(addr) { } MPU6050::~MPU6050() { } uint8_t MPU6050::Init() { uint8_t check; uint8_t Data; // check device ID WHO_AM_I HAL_I2C_Mem_Read(hi2c_, addr_, WHO_AM_I_REG, 1, &check, 1, i2c_timeout); if (check == 104) // 0x68 will be returned by the sensor if everything goes well { // power management register 0X6B we should write all 0's to wake the sensor up Data = 0; HAL_I2C_Mem_Write(hi2c_, addr_, PWR_MGMT_1_REG, 1, &Data, 1, i2c_timeout); // Set DATA RATE of 1KHz by writing SMPLRT_DIV register Data = 0x07; HAL_I2C_Mem_Write(hi2c_, addr_, SMPLRT_DIV_REG, 1, &Data, 1, i2c_timeout); // Set accelerometer configuration in ACCEL_CONFIG Register // XA_ST=0,YA_ST=0,ZA_ST=0, FS_SEL=0 -> 2g Data = 0x00; HAL_I2C_Mem_Write(hi2c_, addr_, ACCEL_CONFIG_REG, 1, &Data, 1, i2c_timeout); // Set Gyroscopic configuration in GYRO_CONFIG Register // XG_ST=0,YG_ST=0,ZG_ST=0, FS_SEL=0 -> 250 deg/s Data = 0x00; HAL_I2C_Mem_Write(hi2c_, addr_, GYRO_CONFIG_REG, 1, &Data, 1, i2c_timeout); return 0; } return 1; } void MPU6050::ReadAccel() { uint8_t Rec_Data[6]; // Read 6 BYTES of data starting from ACCEL_XOUT_H register HAL_I2C_Mem_Read(hi2c_, addr_, ACCEL_XOUT_H_REG, 1, Rec_Data, 6, i2c_timeout); accel_.x = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); accel_.y = (int16_t) (Rec_Data[2] << 8 | Rec_Data[3]); accel_.z = (int16_t) (Rec_Data[4] << 8 | Rec_Data[5]); } void MPU6050::ReadGyro() { uint8_t Rec_Data[6]; // Read 6 BYTES of data starting from GYRO_XOUT_H register HAL_I2C_Mem_Read(hi2c_, addr_, GYRO_XOUT_H_REG, 1, Rec_Data, 6, i2c_timeout); gyro_.x = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); gyro_.y = (int16_t) (Rec_Data[2] << 8 | Rec_Data[3]); gyro_.z = (int16_t) (Rec_Data[4] << 8 | Rec_Data[5]); } void MPU6050::ReadTemp() { uint8_t Rec_Data[2]; int16_t temp; // Read 2 BYTES of data starting from TEMP_OUT_H_REG register HAL_I2C_Mem_Read(hi2c_, addr_, TEMP_OUT_H_REG, 1, Rec_Data, 2, i2c_timeout); temp = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); temperature_ = (float) ((int16_t) temp / (float) 340.0 + (float) 36.53); } void MPU6050::ReadAll() { uint8_t Rec_Data[14]; // Read 14 BYTES of data starting from ACCEL_XOUT_H register HAL_I2C_Mem_Read(hi2c_, addr_, ACCEL_XOUT_H_REG, 1, Rec_Data, 14, i2c_timeout); accel_.x = (int16_t) (Rec_Data[0] << 8 | Rec_Data[1]); accel_.y = (int16_t) (Rec_Data[2] << 8 | Rec_Data[3]); accel_.z = (int16_t) (Rec_Data[4] << 8 | Rec_Data[5]); temperature_ = (int16_t) (Rec_Data[6] << 8 | Rec_Data[7]); gyro_.x = (int16_t) (Rec_Data[8] << 8 | Rec_Data[9]); gyro_.y = (int16_t) (Rec_Data[10] << 8 | Rec_Data[11]); gyro_.z = (int16_t) (Rec_Data[12] << 8 | Rec_Data[13]); } point_3d_t MPU6050::GetRawAccel() { ReadAccel(); return GetLastAccel(); } fpoint_3d_t MPU6050::GetAdjAccel() { ReadAccel(); return GetLastAdjAccel(); } point_3d_t MPU6050::GetLastAccel() { return accel_; } fpoint_3d_t MPU6050::GetLastAdjAccel() { fpoint_3d_t ret; /*** convert the RAW values into acceleration in 'g' we have to divide according to the Full scale value set in FS_SEL I have configured FS_SEL = 0. So I am dividing by 16384.0 for more details check ACCEL_CONFIG Register ****/ ret.x = static_cast<float>(accel_.x) / 16384.0; ret.y = static_cast<float>(accel_.y) / 16384.0; ret.z = static_cast<float>(accel_.z) / 14418.0; return ret; } point_3d_t MPU6050::GetRawGyro() { ReadGyro(); return gyro_; } fpoint_3d_t MPU6050::GetAdjGyro() { ReadGyro(); return GetLastAdjGyro(); } point_3d_t MPU6050::GetLastGyro() { return gyro_; } fpoint_3d_t MPU6050::GetLastAdjGyro() { fpoint_3d_t ret; /*** convert the RAW values into dps (�/s) we have to divide according to the Full scale value set in FS_SEL I have configured FS_SEL = 0. So I am dividing by 131.0 for more details check GYRO_CONFIG Register ****/ ret.x = static_cast<float>(gyro_.x) / 131.0; ret.y = static_cast<float>(gyro_.y) / 131.0; ret.z = static_cast<float>(gyro_.z) / 131.0; return ret; } } /* namespace Drivers */ } /* namespace SolarGators */
27.128049
85
0.665093
John-Carr
2af075aae50298928cf55c5df1dbf088ddc2a313
57,048
cc
C++
local/CrystalSystem.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
local/CrystalSystem.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
local/CrystalSystem.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
#undef LCM_SUPPRESS_VIEWS #include <cstdlib> #include "CrystalSystem.h" #include "lcm_MetaPropagation.h" #include "cmatrix.h" #include "rmatrix.h" #include "space_T.h" #include "ScratchList.h" #include "matlabio.h" #include "ListList.h" #include "NMR.h" namespace libcmatrix { using ::std::sqrt; const size_t invalid_value=-1; /****************************************************************/ CrystalSymmetriseBase::CrystalSymmetriseBase(size_t N, size_t M, size_t neigs,int flags) : neigs_(neigs), ncells_(N), total_(M*N), useeigsym_(flags & MetaFlags::UseEigSymmetry), scalefacs(neigs*neigs+1,DEADBEEF) { const size_t max(neigs*neigs); if (neigs % N) throw InvalidParameter("CrystalSymmetriseBase"); for (size_t j=1;j<=max;j++) { if ( (max % j)==0) scalefacs(j)=N/sqrt(double(j)); } maxstates_=long(1)<<total_; } //Basic 1D symmetriser class SimpleSymmetrise : public CrystalSymmetriseBase { public: SimpleSymmetrise(int N, int M, int flags_); complex symmetrise(Matrix<double>& store, magicsize_t,magicsize_t,int k) const { return symmetrise_(store,k); } complex symmetrise(Matrix<complex>& store, magicsize_t,magicsize_t,int k) const { return symmetrise_(store,k); } CrystalSymmetriseBase* clone() const { return new SimpleSymmetrise(*this); } void addtoevals(BaseList<complex>& evals, size_t blki, size_t blkj, size_t r, size_t c) const; bool haspermutation() const { return false; } private: List<complex> eigfacs; template<typename T> complex symmetrise_(Matrix<T>&, int k) const; }; struct simple_creator { explicit simple_creator(size_t N_,size_t M_) : M(M_), shift(M_*N_-M_), mask((1<<M)-1) {} const size_t M; const size_t shift; const state_t mask; magicsize_t push_states(List<state_t>& state_list, BaseList<bool> used, state_t current) const { size_t count=0; const state_t start=current; do { used(current)=true; //flag state used count++; state_list.push_back(current); current=(current>>M) | ((current & mask)<<shift); //apply translation } while (current!=start); //stop when we return to beginning return count; } }; void CrystalSymmetriseBase::makeindices() { if (linkedstates_.empty()) throw Failed("CrystalSymmetriseBase::makeindices called before linked states created"); const long totdim=maxstates(); //total number of states //indexes take a state number and return the set(block) number and position (index) within set state_to_block_.create(totdim,invalid_value); state_to_index_.create(totdim,invalid_value); for (size_t blk=permutation_blocks();blk--;) { const BaseList<state_t> clist(linkedstates_(blk)); size_t j=clist.size(); for (;j--;) { state_to_block_(clist(j))=blk; state_to_index_(clist(j))=j; } } } void CrystalSymmetriseBase::make_eigfacs(BaseList<complex> eigfacs) { const size_t N=eigfacs.size(); for (size_t j=N;j--;) eigfacs(j)=expi(2*M_PI*double(j)/N); //store e^2pi i n/N } SimpleSymmetrise::SimpleSymmetrise(int N, int M_, int flags_) : CrystalSymmetriseBase(N,M_,N,flags_), eigfacs(N) { useeigs = useeigsym_ ? 1+N/2 : N; //number of active eigenvalues isreal_.create(useeigs,false); isreal_.front()=true; if (!useeigsym_ || ((N & 1)==0)) isreal_(N/2)=true; size_t j,k; make_eigfacs(eigfacs); haseig.create(N+1,useeigs,false); //haseig(j,k) is true if a set of size j contains eigenvalue k, where j is a factor of N for (j=1;j<=N;j++) { if ( (N % j)==0) { const size_t step=N/j; for (k=0;k<useeigs;k+=step) haseig(j,k)=true; } } simple_creator creator(N,M_); getsymmetry(creator); //get sets of symmetry-linked states } /***************************************************/ CrystalOpGenerator::CrystalOpGenerator(const spinhalf_system& sys_, const CrystalStructure& cstructv, int flagsv, int verbosev) : SpinOpGeneratorBase(cstructv,sys_.nspins(),flagsv,verbosev), sysp_(N_==1 ? &sys_ : sys_.clone(N_),N_==1 ? mxflag::nondynamic : mxflag::normal) { create(); } CrystalOpGenerator::CrystalOpGenerator(const spinhalf_system& sys_, const CrystalStructure& cstructv, const char *nuclabel, int flagsv, int verbosev) : SpinOpGeneratorBase(cstructv,sys_.nspins(),flagsv,verbosev), sysp_(N_==1 ? &sys_ : sys_.clone(N_),N_==1 ? mxflag::nondynamic : mxflag::normal) { create(ExplicitList<1,nuclei_spec>(nuclabel)); } CrystalOpGenerator::CrystalOpGenerator(const spinhalf_system& sys_, const CrystalStructure& cstructv, const BaseList<nuclei_spec>& blocknucsv, int flagsv, int verbosev) : SpinOpGeneratorBase(cstructv,sys_.nspins(),flagsv,verbosev), sysp_(N_==1 ? &sys_ : sys_.clone(N_),N_==1 ? mxflag::nondynamic : mxflag::normal) { create(blocknucsv); } CrystalOpGenerator::CrystalOpGenerator(const HamiltonianStructure& structurev, const CrystalStructure& cstructv, int verbosev) : SpinOpGeneratorBase(cstructv,structurev,verbosev), sysp_(new spinhalf_system(structurev.spinsystem(),N_),mxflag::normal) { if (quadrupole_order()!=1) throw Failed("CrystalOpGenerator doesn't support 2nd order quadrupoles"); create(structurev.blockingnuclei()); } template<typename T> void CrystalOpGenerator::create(BlockedMatrix<T>& dest, const block_pattern& blkspec) const { block_pattern::iterator iter(blkspec); // const size_t limit=actual_mzblocks(); const size_t eigblks(eigstr_.eigblocks()); const size_t mzblks=blkspec.blocks; const size_t totblks(eigblks*mzblks); // size_t mzlevels=blkspec.mzlevels; // if (blkspec.hasmiddle) // mzlevels=(mzlevels+1)/2; //actual cutoff ScratchList<size_t> rstr(totblks); ScratchList<size_t> cstr(totblks); size_t r,c,mz; bool ismiddle; while (iter.next(r,c,mz,ismiddle)) { // if (r>=mzlevels) { // r=c; // assert(blkspec.hasmiddle); // } // else { // if (c>=mzlevels) { // c=r; // assert(blkspec.hasmiddle); // } // } // if (ismiddle) { // if (c>r) // c=r; // else // r=c; // } for (size_t k=eigblks;k--;) { const size_t ind(eigstr_.index(mz,k)); rstr(ind)=eigsizes(r,k); cstr(ind)=eigsizes(c,k); } } if (verbose()>1) std::cout << "Creating empty BlockedMatrix: rows: " << rstr << " cols: " << cstr << '\n'; dest.create(rstr,cstr); } //iterates over a set of blocks class CrystalSystem_iterator { public: CrystalSystem_iterator(const CrystalOpGenerator&); //zero coherence blocks CrystalSystem_iterator(const CrystalOpGenerator&, const block_pattern&, size_t nuc, int coher, bool isupper =false); bool next(size_t&, size_t&); //are we blocked by coherence? // bool isblocked() const { return sym.isblocked(); } template<typename T> void addsym(MatrixTensor<complex>&, size_t blki, size_t blkj, int l, int m, int k, bool, Type2Type<T>); template<typename T> void addsym(BlockedMatrixTensor<complex>&, size_t blki, size_t blkj, int l, int m, bool, Type2Type<T>); template<class T> void addsym(BlockedMatrix<complex>&, size_t, size_t, Type2Type<T>, bool); template<class T> void addsym(cmatrix&, size_t, size_t, int k, const T&, bool); template<class T> void addsym(complex&, size_t, size_t, int k, const T&, bool); void add(BlockedMatrix<complex>&, const BaseList<complex>&, size_t, size_t) const; void add_hermitian(BlockedMatrix<complex>&, const BaseList<complex>&, size_t, size_t) const; void add(cmatrix&, complex, size_t, size_t, int) const; void add_hermitian(cmatrix&, complex, size_t, size_t, int) const; void mla(BlockedMatrix<complex>&, double,const operator_spec&); bool Ipevalues(DynamicList<complex>&, size_t blki,size_t blkj,int); bool Fpevalues(DynamicList<complex>&, size_t blki,size_t blkj,size_t nuc =NULL_NUCLEUS); void docreate(); bool isdiagonal() const { return (rmzind==cmzind); } void ensure_null(BlockedMatrixTensor<complex>&, int l) const; void ensure_null(BlockedMatrix<complex>&) const; size_t rows(size_t k) const { return rblkstr(k); } size_t cols(size_t k) const { return cblkstr(k); } template<class T> bool Hcoupling_matrix(const Matrix<T>& couplings,int,int,size_t blki,size_t blkj); bool A2_matrix(const Matrix<space_T>& tensors,size_t blki,size_t blkj,int m); bool A2_matrix(const rmatrix& couplings,size_t blki,size_t blkj) { return Hcoupling_matrix(couplings,2,-1,blki,blkj); } bool A2_matrix(const Matrix<space_T>& couplings,size_t blki,size_t blkj) { return Hcoupling_matrix(couplings,2,-1,blki,blkj); } bool A0_matrix(const rmatrix& couplings,size_t blki,size_t blkj) { return Hcoupling_matrix(couplings,1,1,blki,blkj); } size_t get_block(int eval) const { return sym.eigstr_.index(mzcount,eval); } rmatrix& get_store(size_t rs, size_t cs, const Type2Type<double>&) { rmatrix& res(rstores(rs,cs)); if (!res) res.create(rs,cs); return res; } cmatrix& get_store(size_t rs, size_t cs, const Type2Type<complex>&) { cmatrix& res(cstores(rs,cs)); if (!res) res.create(rs,cs); return res; } double symmetrise0(const Type2Type<double>&) const { return ncells*H00; } complex symmetrise0(const Type2Type<complex>&) const { return float_t(ncells)*H00c; } double symmetrise0(size_t rs,size_t cs, const Type2Type<double>&) const { return scalefacs(rs*cs)*sum(rstores(rs,cs)); } complex symmetrise0(size_t rs,size_t cs, const Type2Type<complex>&) const { return scalefacs(rs*cs)*sum(cstores(rs,cs)); } private: const CrystalOpGenerator& sym; const CrystalSymmetriseBase& symmetriser; size_t useeigs; const List<double>& scalefacs; const List<size_t>& state_to_block; const List<size_t>& state_to_index; int coher_; //coherence being considered BaseList<size_t> nucmzinds; size_t ncells; size_t neigs; bool finished; //true if there are no blocks left bool isupper; //true if problem is symmetric and we are only iterating over upper diagonal size_t rmzind,cmzind; //current row/col block size_t mzcount; bool bumpmz; BaseList<size_t> cwhich; //current set (row,column) of states BaseList<size_t> rwhich; size_t brablks,ketblks; //number of bra/ket states size_t rows_,cols_; //size of mz2 block size_t crow,ccol; //current bra/ket index Matrix<rmatrix> rstores; Matrix<cmatrix> cstores; double H00; complex H00c; DynamicList<complex> evalues; BaseList<size_t> rblkstr; BaseList<size_t> cblkstr; int verbose; // bool ismiddle; block_pattern::iterator mziter; void resetmz2(); bool nextmz2() { mzcount++; size_t mzeigSD; //!< ignored - could be merged with mzcount, but don't want to touch! if (mziter.next(rmzind,cmzind,mzeigSD)) { resetmz2(); return true; } return false; } void init(size_t selnuc); }; class CrystalSystem_diagiterator { public: CrystalSystem_diagiterator(const CrystalOpGenerator&); bool next(size_t&); size_t get_block(int eval) const { return sym.eigstr_.index(mzind,eval); } private: const CrystalOpGenerator& sym; BaseList<size_t> rwhich; //current set of states int blki; //current index size_t mzind; bool bumpmz; void resetmz2(); }; CrystalSystem_diagiterator::CrystalSystem_diagiterator(const CrystalOpGenerator& Sym) : sym(Sym) { mzind=Sym.actual_mzblocks()-1; resetmz2(); } void CrystalSystem_diagiterator::resetmz2() { rwhich.create(sym.blockindices(mzind)); blki=rwhich.length()-1; bumpmz=false; } bool CrystalSystem_diagiterator::next(size_t& blk) { if (bumpmz) { mzind--; resetmz2(); } if (blki<0) return false; //finished blk = rwhich(blki--); if ((blki<0) && mzind) bumpmz=true; return true; } CrystalSystem_iterator::CrystalSystem_iterator(const CrystalOpGenerator& Sym) : sym(Sym), symmetriser(*(Sym.symmetriserp_)), scalefacs(symmetriser.scale_factors()), state_to_block(symmetriser.state_to_block()), state_to_index(symmetriser.state_to_index()), coher_(0), isupper(false), mziter(Sym.diag_blkspec_) { init(Sym.defaultnucleus_); } CrystalSystem_iterator::CrystalSystem_iterator(const CrystalOpGenerator& Sym, const block_pattern& blkspec, size_t selnuc, int coherv, bool isupper_) : sym(Sym), symmetriser(*(Sym.symmetriserp_)), scalefacs(symmetriser.scale_factors()), state_to_block(symmetriser.state_to_block()), state_to_index(symmetriser.state_to_index()), coher_(coherv), isupper(isupper_), mziter(blkspec) { if (isupper && (coherv!=0)) throw InternalError("CrystalSystem_iterator: isupper incompatible with non-zero coherences"); init(selnuc); } void CrystalSystem_iterator::init(size_t selnuc) { useeigs=symmetriser.actual_eigenvalues(); ncells=symmetriser.ncells(); neigs=symmetriser.eigenvalues(); finished=false; rstores.create(neigs+1,neigs+1); cstores.create(neigs+1,neigs+1); // evalues.create(symmetriser.actual_eigenvalues(),mxflag::normal); evalues.create(symmetriser.actual_eigenvalues()); //!< removed normal flag (May 10) Why there? verbose=sym.verbose(); if (selnuc) nucmzinds.create(sym.allmzinds_.row(sym.nuctoindex(selnuc))); bumpmz=false; nextmz2(); mzcount=0; } //reset after changing rmzind/cmzind void CrystalSystem_iterator::resetmz2() { size_t usermz=rmzind; size_t usecmz=cmzind; const size_t maxind=sym.mzsizes.size(); if (rmzind>=maxind) usermz=cmzind; else { if (cmzind>=maxind) usecmz=rmzind; } // if (rmzind>cmzind) // usermz=cmzind; // else // usecmz=rmzind; // } rblkstr.create(sym.eigsizes.row(usermz)); //get block structure for given mz pair cblkstr.create(sym.eigsizes.row(usecmz)); rows_=sym.mzsizes(usermz); //size of block cols_=sym.mzsizes(usecmz); //if single state set, store set number for quick reference //store junk value otherwise to catch attempts to use firstrblk in other cases // if (rows_==1) // firstrblk=int(sym.mzblocking_(usermz).front()); // else // firstrblk=-1; //must use actual indices here! rwhich.create(sym.blockindices(rmzind)); //update rwhich etc. to point to current set of bra states cwhich.create(sym.blockindices(cmzind)); brablks=rwhich.length(); ketblks=cwhich.length(); crow=ccol=0; } bool CrystalSystem_iterator::next(size_t& rblk, size_t& cblk) { int blkcoher; do { if (bumpmz) { if (!nextmz2()) finished=true; else { resetmz2(); bumpmz=false; } } if (finished) return false; //iterator is exhausted? rblk=rwhich(crow); //read current position cblk=cwhich(ccol); ccol++; //increment col index if (ccol==ketblks) { crow++; //increment row index ccol= isupper ? crow : 0; //upper diagonal only? if (crow==brablks) //finished state block? bumpmz=true; } if (nucmzinds.empty()) return true; blkcoher=(int)nucmzinds(cblk)-(int)nucmzinds(rblk); } while (blkcoher!=coher_); return true; } //construct dipolar matrix for given set of bra/ket states //ignore couplings to spins of type nuc (unless NULL_NUCLEUS) template<class T> bool CrystalSystem_iterator::Hcoupling_matrix(const Matrix<T>& couplings, int scalez, int scalexy, size_t blki, size_t blkj) { if (sym.nspins()!=couplings.cols()) throw Mismatch("Hcoupling_matrix: coupling matrix doesn't match CrystalOpGenerator"); const ListList<state_t>& linkedstates(symmetriser.linkedstates()); const BaseList<state_t> cstates(linkedstates(blkj)); const size_t blkisize=linkedstates.size(blki); const size_t blkjsize=linkedstates.size(blkj); rmatrix& H(rstores(blkisize,blkjsize)); //where we'll store the temporary matrix bool issingle=(blkisize==1) && (blkjsize==1); //single element? reducer_<double,T> reduce; //clear temporary matrix if (issingle) H00=0.0; else { if (!H) //if temp. matrix doesn't exist, make it H.create(blkisize,blkjsize); H=0; } const basespin_system& sys=*(sym.sysp_); const double scalez2=scalez*0.5; const size_t total(sym.nspins()); const size_t M(sym.nspins_cell()); for (size_t j=0;j<M;j++) { const state_t maskj=maskelement(total,j); for (size_t k=0;k<M;k++) { //loop over spin pairs const bool ishomo=(sys(j)==sys(k)); //homonuclear coupling for (size_t cell=0;cell<ncells;cell++) { //loop over cells if ((j>k) || cell) { //don't count both (0,j)-(0,k) and (0,k)-(0,j) const size_t sk=sym.cell_to_spin(cell,k); //index of spin (cell,k) const state_t masksk=maskelement(total,sk); const T& curcoup((j<sk) ? couplings(j,sk) : couplings(sk,j)); if (!curcoup) continue; const double coup=(cell ? 0.25 : 0.5)*reduce(curcoup); if (coup==0.0) continue; const state_t mask=maskj | masksk; //has bits corresponding to spins j & sk set for (size_t jj=blkjsize;jj--;) { const state_t cstate=cstates(jj); //current ket state const bool isflip=!(cstate & maskj) ^ !(cstate & masksk); if (blki==blkj) { //zz components const double del= isflip ? -coup : coup; if (issingle) ::libcmatrix::mla(H00,scalez2,del); else ::libcmatrix::mla(H(jj,jj),scalez2,del); } if (ishomo && isflip) { const state_t nstate=cstate ^ mask; //flip spin states if (state_to_block(nstate)==blki ) { //is new spin state within bra states? if (issingle) H00+=scalexy*coup; else H(state_to_index(nstate),jj)+=scalexy*coup; } } } } } } } if (verbose>1) { std::cout << "H" << blki << "," << blkj; if (issingle) std::cout << ": " << H00 << "\n"; else std::cout << ":\n" << H << "\n"; } return issingle; } //return true if result is single element //corresponding function for spinning Hamiltonian (Fourier component m) bool CrystalSystem_iterator::A2_matrix(const Matrix<space_T>& tensors,size_t blki, size_t blkj, int m) { if (sym.nspins_cell()!=tensors.rows()) throw Mismatch("Hcoupling_matrix"); const ListList<state_t>& linkedstates(symmetriser.linkedstates()); const BaseList<state_t> cstates(linkedstates(blkj)); const size_t blkisize=linkedstates.size(blki); const size_t blkjsize=linkedstates.size(blkj); cmatrix& H=cstores(blkisize,blkjsize); const bool issingle=(blkisize==1) && (blkjsize==1); if (issingle) H00c=0.0; else { if (!H) H.create(blkisize,blkjsize); H=0; } const basespin_system& sys=*(sym.sysp_); const size_t total(sym.nspins()); const size_t M(sym.nspins_cell()); for (size_t j=0;j<M;j++) { const state_t maskj=maskelement(total,j); for (size_t k=0;k<M;k++) { const bool ishomo=(sys(j)==sys(k)); for (size_t cell=0;cell<ncells;cell++) { if ((j>k) || cell) { const size_t sk=sym.cell_to_spin(cell,k); const state_t masksk=maskelement(total,sk); const space_T& curtens((j<sk) ? tensors(j,sk) : tensors(sk,j)); if (!curtens) continue; const state_t mask=maskj | masksk; const complex coup=(cell ? 0.25 : 0.5)*curtens(2,m); for (size_t jj=blkjsize;jj--;) { const state_t cstate=cstates(jj); const bool isflip = !(cstate & maskj) ^ !(cstate & masksk); if (blki==blkj) { const complex del= isflip ? -coup : coup; if (issingle) H00c+=del; else H(jj,jj)+=del; } if (ishomo && isflip) { const state_t nstate=cstate ^ mask; if (state_to_block(nstate)==blki ) { if (issingle) H00c-=coup; else H(state_to_index(nstate),jj)-=coup; } } } } } } } if (verbose>1) { std::cout << "H(" << m << ")" << blki << "," << blkj; if (issingle) std::cout << ": " << H00c << "\n"; else std::cout << ":\n" << H << "\n"; } return issingle; } //return value corresponding to eigenvalue m of H transformed into symmetrised basis template<class T> complex SimpleSymmetrise::symmetrise_(Matrix<T>& H, int m) const { if (m==0) throw Failed("symmetrise: don't use for k=0!"); const size_t blkisize=H.rows(); const size_t blkjsize=H.cols(); if (!haseig(blkisize,m) || !haseig(blkjsize,m)) //don't have that eigenvalue for this no. of bra/ket states throw Failed("symmetrise: eigenvalue doesn't exist in given block"); complex s(0.0); for (size_t ii=blkisize;ii--;) { const BaseList<T> Hii=H.row(ii); size_t wh=(m*(ncells_-ii)) % ncells_; for (size_t jj=0;jj<blkjsize;jj++) { // const size_t wh=(m*(jj-ii+N)) % N; mla(s,Hii(jj),eigfacs(wh)); wh+=m; if (wh>=ncells_) wh-=ncells_; } } return s*scalefacs(blkisize*blkjsize); } //return 2 mz for given nucleus type and state int CrystalOpGenerator::mz2val(size_t nuc,state_t state) const { int retval=0; const size_t total(nspins()); for (size_t j=0;j<nspins_cell();j++) { //loop over spins in unit cell if ((*sysp_)(j).nucleus()!=nuc) continue; for (size_t i=0;i<N_;i++) { //loop over cells if (state & maskelement(total,cell_to_spin_(i,j))) //count -1/2 for bit set, +1/2 for not set retval--; else retval++; } } return retval; } //return 2 Fz for given state (val) and total number of spins // = (bits unset)-(bits set) = total bits - 2 (bits set) int CrystalOpGenerator::mz2val(state_t val) const { int retval(nspins()); while (val) { //while still some bits set if (val & 1) retval-=2; val>>=1; } return retval; } //compute symmetrised Iz for given spin ListList<double> diag_Iz(const CrystalOpGenerator& sys, size_t spinn) { return sys.diag_Iz(spinn); } void CrystalOpGenerator::mla_Fz(ListList<double>& dest, double scale, nuclei_spec whichn) const { const size_t nuc=whichn(); if (nuc!=NULL_NUCLEUS) ::libcmatrix::mla(dest,scale,diag_Fz(nuc)); else { if (tzops_.empty()) throw Failed("Can't compute unspecific Fz here"); for (size_t j=nspins_cell();j--;) ::libcmatrix::mla(dest,scale,tzops_(j)); } } void CrystalOpGenerator::rawdiag_Fz(ListList<double>& dest, size_t nuc) const { const basespin_system& sys(spinsystem()); List<size_t> whichspins(nspins_cell()); whichspins.create(0); for (size_t i=nspins_cell();i--;) { if (sys(i).nucleus()==nuc) whichspins.push_back(i); } make_tzop(dest,whichspins); } // construct symmetrised z operator void CrystalOpGenerator::mla_Iz(ListList<double>& tzop, double scale, size_t spinn) const { if (tzops_.empty()) throw Failed("Can't compute Iz when permutation active"); ::libcmatrix::mla(tzop,scale,tzops_(spinn)); } void CrystalOpGenerator::make_tzop(ListList<double>& tzop, const BaseList<size_t>& spins) const { create(tzop); #ifndef NDEBUG tzop=DEADBEEF; //easier to spot problems #endif const size_t n(spins.size()); ScratchList<state_t> masks(n); const size_t total(nspins()); size_t j,k,ablk; for (j=n;j--;) masks(j)=maskelement(total,spins(j)); CrystalSystem_diagiterator iter(*this); const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); const size_t useeigs=symmetriserp_->actual_eigenvalues(); while (iter.next(ablk)) { //loop over state sets const BaseList<state_t> states(linkedstates(ablk)); const size_t blksize=states.length(); const BaseList<int> ptrs(eigptrs.row(ablk)); //stash value of eigptrs for set double sum=0.0; for (j=n;j--;) { const state_t& mask(masks(j)); for (k=blksize;k--;) //loop over states sum+=Izelement_raw(states(k) & mask); } sum*=N_/blksize; for (k=useeigs;k--;) {//store result (sum) in correct position (ptrs(k)) of each eigenvalue block (k) const size_t ind(iter.get_block(k)); const int ptr(ptrs(k)); if (ptr>=0) //easy way to check that eigenvalue is present (tzop(ind))(size_t(ptr))=sum; } } if (verbose()>1) std::cout << "Computed Fz for spins " << spins << ": " << tzop << '\n'; } /* given system spanning reduced Hilbert space construct "reverse index" taking state to index within sub-space */ void makerindex(List<size_t>& rind,const spinhalf_system& sys) { const BaseList<state_t> states=sys.ketstates(); rind.create(sys.size()); rind=-1; //fill with dummy for (size_t i=states.length();i--;) //loop over sub-space rind(states(i))=i; } //return sum over columns in source in dest template<class T> void colsum(List<T>& dest,const Matrix<T>& source) { if (!source) throw Undefined("colsum"); size_t r=source.rows(); dest=source.row(--r); for (;r--;) dest+=source.row(r); } void CrystalOpGenerator::makemzinds(Matrix<size_t>& allmzinds, List<size_t>& maxmzinds, const BaseList<size_t>& nucs) { const size_t ntypes=nucs.size(); const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); const size_t permblocks=linkedstates.size(); allmzinds.create(ntypes,permblocks); maxmzinds.create(ntypes); size_t nuci,j; for (nuci=0;nuci<ntypes;nuci++) { //calculate 2mz for all blocks and all nuclei const size_t tmpnuc=indextonuc(nuci); BaseList<size_t> curmz2(allmzinds.row(nuci)); const size_t maxI2(sysp_->nspins(tmpnuc)); for (j=permblocks;j--;) curmz2(j)=(maxI2-mz2val(tmpnuc,linkedstates(j,0)))/2; maxmzinds(nuci)=size_t(maxI2+1.5); } } //Common part of CrystalOpGenerator constructor (private) void CrystalOpGenerator::create(const BaseList<nuclei_spec>& nucs) { if (M_<1 || N_<1) throw InvalidParameter("CrystalOpGenerator"); if (cstruct.dimensions()<2 && !cstruct.haspermutation()) symmetriserp_.reset(new SimpleSymmetrise(N_,M_,flags())); else { #ifdef LCM_ENABLE_GENERICPERIODIC symmetriserp_.reset(new GeneralSymmetrise(cstruct,M_,flags(),verbose())); #else throw Failed("library compiled without support for periodicity in >1 dimension"); #endif } const size_t useeigs=symmetriserp_->actual_eigenvalues(); const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); const size_t permblocks=linkedstates.size(); if (verbose()) { std::cout << "Found " << permblocks << " sets of symmetry-linked states\n"; if (verbose()>1) std::cout << linkedstates << '\n'; } init_blockstr(useeigs,nucs); defaultnucleus_= (indextonuc.size()==1) ? indextonuc.front() : NULL_NUCLEUS; //find sizes of eigenvalue blocks const size_t nblocks(actual_mzblocks()); eigsizes.create(nblocks,useeigs,size_t(0)); eigptrs.create(permblocks,useeigs,-1); size_t j,k; List<int> eigcount(useeigs); const CrystalSymmetriseBase& symmetriser(*symmetriserp_); List< List<size_t> > subsizes(useeigs*mzblocking_.size()); for (size_t indexi=mzblocking_.size();indexi--;) { //loop over mz blocks const bool included(indexi<nblocks); const ListList<size_t> curmzblocking(mzblocking_(indexi)); eigcount=0; for (size_t minorj=curmzblocking.size();minorj--;) { const BaseList<size_t> cwhich(curmzblocking(minorj)); for (j=cwhich.length();j--;) { //loop over each set size_t blk=cwhich(j); const magicsize_t shape=symmetriser.blockshape(blk); const BaseList<bool> whichvalues(symmetriser.which_eigenvalues(shape)); //eigptrs(blk,k) gives the index within the symmetrised block for eigenvalue k generated from set blk for (k=useeigs;k--;) { if (whichvalues(k)) { eigptrs(blk,k)=eigcount(k)++; if (included) { List<size_t>& cursubsize(subsizes(index(indexi,k))); if (cursubsize.empty()) cursubsize.create(curmzblocking.size(),size_t(0U)); cursubsize(minorj)++; } } } } } if (included) { BaseList<size_t> csizes(eigsizes.row(indexi)); csizes+=eigcount; } } if (verbose()) { std::cout << "Eigenvalue distribution:\n" << eigsizes; double flopc=0; const BaseList<size_t> asrow(eigsizes.row()); for (j=asrow.size();j--;) { const size_t csize(asrow(j)); flopc+=csize*csize*csize; } std::cout << "Flop count: " << flopc << '\n'; if (verbose()>1) std::cout << "Eigenvalue pointers:\n" << eigptrs; } mzsizes.create(nblocks); for (j=nblocks;j--;) { const BaseList<size_t> blks(blockindices(j)); size_t mzsize=0; for (k=blks.length();k--;) { const size_t blk(blks(k)); mzsize+=linkedstates.size(blk); } mzsizes(j)=mzsize; } if (verbose()) std::cout << "Sizes of mz blocks: " << mzsizes << '\n'; diagstr_.create(nblocks*useeigs); //diagonal structure for (size_t mz=nblocks;mz--;) { for (k=useeigs;k--;) { const size_t ind(eigstr_.index(mz,k)); diagstr_(ind)=eigsizes(mz,k); } } if (verbose()>1) std::cout << "Overall diagonal structure: " << diagstr_ << '\n'; if (flags() & MetaFlags::UsePartitioning) { partitioned_diagstr_=subsizes; init_partitioning(); } //don't built z operators if permutation symmetry active if (!symmetriserp_->haspermutation()) { tzops_.create(M_); for (size_t m=0;m<M_;m++) { make_tzop(tzops_(m),m); if (verbose()) std::cout << "Iz_" << m << ": " << tzops_(m) << '\n'; } } diag_blkspec_=block_pattern(*this); } void CrystalSymmetriseBase::print(std::ostream& ostr) const { ostr << "Linked states: " << linkedstates_ << "\n"; ostr << "Eigenvalue pattern:\n" << haseig; } std::ostream& operator<< (std::ostream& ostr, const CrystalOpGenerator& a) { if (a.N_==0) return ostr << "<undefined>\n"; ostr << "Total spin system: " << *(a.sysp_) << "\n"; ostr << "Number of cells: " << a.N_ << "\n"; const SpinOpGeneratorBase& asbase(a); asbase.print(ostr); if (a.verbose()) { a.symmetriserp_->print(ostr); ostr << "Eigenvalue distribution:\n" << a.eigsizes << "\n"; if (a.verbose()>1) ostr << "Ptrs:\n" << a.eigptrs << "\n"; } return ostr; } void CrystalSystem_iterator::ensure_null(BlockedMatrix<complex>& Hmats) const { if (!Hmats) { sym.create(Hmats); Hmats=complex(0.0); } } void CrystalSystem_iterator::ensure_null(BlockedMatrixTensor<complex>& Htens, int l) const { if (!Htens) { sym.create(Htens); Htens=complex(0.0); } if (!(Htens.front().have_rank(l))) Htens.ensure_rank(l,complex(0.0)); } //add symmetrised block (blki,blkj) to spinning Hamiltonian component m template<typename T> void CrystalSystem_iterator::addsym(MatrixTensor<complex>& Htens, size_t blki,size_t blkj,int l, int m, int eval,bool issingle, Type2Type<T> realcomplex) { if (issingle && (eval!=0)) return; BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); //k=0 is special case if (eval==0) { const size_t blkisize(symmetriser.blocksize(blki)); const size_t blkjsize(symmetriser.blocksize(blkj)); const complex val= complex(issingle ? symmetrise0(realcomplex) : symmetrise0(blkisize,blkjsize,realcomplex)); if (Htens.ismatrix()) { cmatrix& Hsym=Htens.matrix(l,m); Hsym(reigptrs.front(),ceigptrs.front())+=val; } else Htens.element(l,m)+=val; } else { const magicsize_t blkishape(symmetriser.blockshape(blki)); const magicsize_t blkjshape(symmetriser.blockshape(blkj)); const int dr=reigptrs(eval); const int dc=ceigptrs(eval); if ((dr>=0) && (dc>=0)) { //if eigenvalue exists const size_t lrows(symmetriser.blocksize(blki)); const size_t lcols(symmetriser.blocksize(blkj)); const complex val=symmetriser.symmetrise(get_store(lrows,lcols,realcomplex),blkishape,blkjshape,eval); if (Htens.ismatrix()) { cmatrix& Hsym=Htens.matrix(l,m); Hsym(dr,dc)+=val; } else { assert((dr==0) && (dc==0)); Htens.element(l,m)+=val; } } } } template<typename T> void CrystalSystem_iterator::addsym(BlockedMatrixTensor<complex>& Htens, size_t blki,size_t blkj,int l,int m, bool issingle, Type2Type<T> realcomplex) { if (issingle) { const size_t ind(get_block(0)); addsym(Htens(ind),blki,blkj,l,m,0,true,realcomplex); return; } for (size_t eval=useeigs;eval--;) { const size_t ind(get_block(eval)); addsym(Htens(ind),blki,blkj,l,m,eval,false,realcomplex); } } template<class T> void CrystalSystem_iterator::addsym(complex& Hk,size_t blki,size_t blkj,int eval,const T& type_, bool issingle) { assert((sym.eigptrs(blki,eval)==0) && (sym.eigptrs(blkj,eval)==0)); if (issingle) { if (eval==0) Hk+=symmetrise0(type_); return; } const size_t lrows(symmetriser.blocksize(blki)); const size_t lcols(symmetriser.blocksize(blkj)); if (eval==0) Hk+=symmetrise0(lrows,lcols,type_); else { const magicsize_t rs=symmetriser.blockshape(blki); const magicsize_t cs=symmetriser.blockshape(blkj); Matrix<T>& store(get_store(lrows,lcols,type_)); Hk+=symmetriser.symmetrise(store,rs,cs,eval); } } template<class T> void CrystalSystem_iterator::addsym(cmatrix& Hk,size_t blki,size_t blkj,int eval,const T& type_, bool issingle) { const int dr=sym.eigptrs(blki,eval); const int dc=sym.eigptrs(blkj,eval); if (issingle) { if (eval==0) Hk(dr,dc)+=symmetrise0(type_); return; } const size_t lrows=symmetriser.blocksize(blki); const size_t lcols=symmetriser.blocksize(blkj); if (eval==0) Hk(dr,dc)+=symmetrise0(lrows,lcols,type_); else { if ((dc>=0) && (dr>=0)) { const magicsize_t rs=symmetriser.blockshape(blki); const magicsize_t cs=symmetriser.blockshape(blkj); Hk(dr,dc)+=symmetriser.symmetrise(get_store(lrows,lcols,type_),rs,cs,eval); } } } template<class T> void CrystalSystem_iterator::addsym(BlockedMatrix<complex>& Hmats,size_t blki,size_t blkj, Type2Type<T> type_, bool issingle) { if (issingle) { const size_t ind(get_block(0)); addsym(Hmats(ind),blki,blkj,0,type_,true); return; } BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); cmatrix& Hsym0(Hmats(get_block(0))); Hsym0(reigptrs.front(),ceigptrs.front())+=symmetrise0(symmetriser.blocksize(blki),symmetriser.blocksize(blkj),type_); const size_t lrows=symmetriser.blocksize(blki); const size_t lcols=symmetriser.blocksize(blkj); const magicsize_t rs=symmetriser.blockshape(blki); const magicsize_t cs=symmetriser.blockshape(blkj); Matrix<T>& store(get_store(lrows,lcols,type_)); for (size_t eval=1;eval<useeigs;eval++) { const int dr=reigptrs(eval); const int dc=ceigptrs(eval); if ((dc>=0) && (dr>=0)) { const size_t ind(get_block(eval)); cmatrix& Hsym(Hmats(ind)); Hsym(size_t(dr),size_t(dc))+=symmetriser.symmetrise(store,rs,cs,eval); } } } void CrystalOpGenerator::add_A2(BlockedMatrixTensor<complex>& Htens, const Matrix<space_T>& tensors) const { size_t blki,blkj; CrystalSystem_iterator iter(*this); iter.ensure_null(Htens,2); while (iter.next(blki,blkj)) { for (int m=-2;m<=2;m++) { const bool issingle=iter.A2_matrix(tensors,blki,blkj,m); iter.addsym(Htens,blki,blkj,2,m,issingle,Type2Type<complex>()); } } } void CrystalOpGenerator::add_A0(BlockedMatrixTensor<complex>& Htens, const Matrix<double>& A0s) const { size_t blki,blkj; CrystalSystem_iterator iter(*this); iter.ensure_null(Htens,0); while (iter.next(blki,blkj)) { const bool issingle=iter.A0_matrix(A0s,blki,blkj); iter.addsym(Htens,blki,blkj,0,0,issingle,Type2Type<double>()); } } template<class T> void CrystalOpGenerator::add_A2(BlockedMatrix<complex>& Hmats, const Matrix<T>& couplings) const { CrystalSystem_iterator iter(*this); iter.ensure_null(Hmats); size_t blki,blkj; while (iter.next(blki,blkj)) { const bool issingle=iter.A2_matrix(couplings,blki,blkj); iter.addsym(Hmats,blki,blkj,Type2Type<double>(),issingle); } } void CrystalOpGenerator::add_A0(BlockedMatrix<complex>& Hmats, const rmatrix& couplings) const { CrystalSystem_iterator iter(*this); iter.ensure_null(Hmats); size_t blki,blkj; while (iter.next(blki,blkj)) { const bool issingle=iter.A0_matrix(couplings,blki,blkj); iter.addsym(Hmats,blki,blkj,Type2Type<double>(),issingle); } } //create symmetrised shift Hamiltonian, given shifts and complete set of symmetrised z operators ListList<double> diag_Hcs(const CrystalOpGenerator& sys, const BaseList<double>& shifts) { ListList<double> Hcs(mxflag::temporary); const size_t M=sys.nspins_cell(); if (M!=shifts.size()) throw Mismatch("diag_Hcs: size of shift vector"); for (size_t m=0;m<M;m++) mla(Hcs,shifts(m),sys.diag_Iz(m)); return Hcs; } static void multiply_full(cmatrix& dest, const complex& v, const BaseList<double>& H) { size_t n=H.size(); dest.create(n,n); dest=complex(0.0); for (;n--;) mla(dest(n,n),H(n),v); } static void mla(Tensor<cmatrix>& d, const Tensor<complex>& A, const BaseList<double>& H) { for (int l=A.rank();l>=0;l--) { if (A.have_rank(l)) { //rank present? if (!d.have_rank(l)) { d.ensure_rank(l); for (int m=-l;m<=l;m++) multiply_full(d(l,m),A(l,m),H); } else { for (int m=-l;m<=l;m++) mla(d(l,m),A(l,m),H); } } } } void CrystalOpGenerator::add_Hcs(BlockedMatrixTensor<complex>& Htens, const space_T& CSA, size_t m) const { if (Htens.size()!=diagstr_.size()) throw Mismatch("add_Hcs"); for (size_t k=Htens.size();k--;) //loop over eigenvalues switch (diagstr_(k)) { case 0: break; case 1: { space_T& curHisol=Htens(k).element(); ::libcmatrix::mla(curHisol,diag_Iz(m)(k).front(),CSA); } break; default: { Tensor<cmatrix>& curHtens=Htens(k).matrix(); ::libcmatrix::mla(curHtens,CSA,diag_Iz(m)(k)); } } } //special case for single state block (k=0 only) // void add_Hcs(space_T& Hisol, const CrystalOpGenerator& sys, const BaseList<space_T>& CSAs) // { // (void)sys.state(); //ensure single state // const size_t M=sys.nspins(); // if (M!=CSAs.length()) // throw Mismatch("add_Hcs"); // for (size_t m=M;m--;) // mla(Hisol,sys.diag_Iz(m)(0U,0U),CSAs(m)); // } void CrystalOpGenerator::add_Hcs(cmatrix& dest, double shift, size_t m, int k) const { ::libcmatrix::mla(dest,shift,diag_Iz(m)(k)); } template<class T1,class T2,class T3> void multiply(BlockedMatrix<T1>& d, const T2& v, const ListList<T3>& a) { LCM_STATIC_CHECK( LCM_DIM(T2)==0, BlockedMatrix_multiply); const size_t n=a.size(); ScratchList<size_t> sizes(n); size_t i; for (i=n;i--;) sizes(i)=a.size(i); d.create(sizes); for (i=n;i--;) multiply(d(i),v,a(i)); } void CrystalOpGenerator::add_Hcs(BlockedMatrix<complex>& dest, double shift, size_t m) const { ::libcmatrix::mla(dest,shift,diag_Iz(m)); } void CrystalOpGenerator::add_Hcs(ListList<double>& dest, double shift, size_t m) const { ::libcmatrix::mla(dest,shift,diag_Iz(m)); } void SimpleSymmetrise::addtoevals(BaseList<complex>& evals, size_t blki, size_t blkj, size_t r, size_t c) const { const size_t blkisize(linkedstates_.size(blki)); const size_t blkjsize(linkedstates_.size(blkj)); const double scale=scalefacs(blkisize*blkjsize); //normalisation factor evals(0)+=scale; //eigenvalue 0 const int mstep=ncells_+c-r; for (size_t m=1;m<useeigs;m++) { if (haseig(blkisize,m) && haseig(blkjsize,m)) { //if eigenvalue present const size_t wh=(m*mstep) % ncells_; mla(evals(m),scale,eigfacs(wh)); } } } //Symmetrised Ip bool CrystalSystem_iterator::Ipevalues(DynamicList<complex>& evals, size_t blki, size_t blkj, int spini) { const BaseList<state_t> cstates(symmetriser.linkedstates()(blkj)); const size_t total(sym.nspins()); if (verbose>2) { const BaseList<state_t> rstates(symmetriser.linkedstates()(blki)); std::cout << "Col states: "; printbin(std::cout,cstates,total); std::cout << '\n'; std::cout << "Row states: "; printbin(std::cout,rstates,total); std::cout << '\n'; } const state_t flipmask=~maskelement(total,spini); evals=0.0; //clear result bool haveany=false; for (size_t c=cstates.size();c--;) { const state_t nstate=cstates(c) & flipmask; // if bit is already clear, nstate cannot be in blki if (state_to_block(nstate)==blki) { symmetriser.addtoevals(evals,blki,blkj,state_to_index(nstate),c); haveany=true; } } return haveany; } bool CrystalSystem_iterator::Fpevalues(DynamicList<complex>& evals,size_t blki,size_t blkj,size_t nuc) { const BaseList<state_t> cstates(symmetriser.linkedstates()(blkj)); const size_t total(sym.nspins()); if (verbose>2) { const BaseList<state_t> rstates(symmetriser.linkedstates()(blki)); std::cout << "Col states: "; printbin(std::cout,cstates,total); std::cout << '\n'; std::cout << "Row states: "; printbin(std::cout,rstates,total); std::cout << '\n'; } bool haveany=false; evals=0.0; const size_t M(sym.nspins_cell()); for (size_t c=cstates.size();c--;) { //loop over ket states const state_t ostate=cstates(c); for (size_t spini=0;spini<M;spini++) { //loop over unit cell if (nuc==NULL_NUCLEUS || sym(spini).nucleus()==nuc) { //considering this spin? const state_t flipmask=~maskelement(total,spini); const state_t nstate=ostate & flipmask; // if bit is clear, nstate cannot be in blki if (state_to_block(nstate)==blki) { symmetriser.addtoevals(evals,blki,blkj,state_to_index(nstate),c); haveany=true; } } } } return haveany; } //accumulate symmetrised elements into final matrix set void CrystalSystem_iterator::add(BlockedMatrix<complex>& dest, const BaseList<complex>& evals, size_t blki, size_t blkj) const { BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); for (size_t eval=useeigs;eval--;) { int dr=reigptrs(eval); int dc=ceigptrs(eval); if ((dr>=0) && (dc>=0)) {//eigenvalue exists? const size_t ind(get_block(eval)); dest(ind)(size_t(dr),size_t(dc))+=evals(eval); } } } //ditto but for Hermitian operator where iterated over upper diagonal only void CrystalSystem_iterator::add_hermitian(BlockedMatrix<complex>& dest, const BaseList<complex>& evals, size_t blki, size_t blkj) const { BaseList<int> reigptrs(sym.eigptrs.row(blki)); BaseList<int> ceigptrs(sym.eigptrs.row(blkj)); for (size_t eval=useeigs;eval--;) { int dr=reigptrs(eval); int dc=ceigptrs(eval); if ((dr>=0) && (dc>=0)) { assert(dr!=dc); const size_t ind(get_block(eval)); const complex& v=evals(eval); dest(ind)(size_t(dr),size_t(dc))+=v; dest(ind)(size_t(dc),size_t(dr))+=conj(v); } } } //as above, but for single eigenvalue void CrystalSystem_iterator::add(cmatrix& dest, complex v, size_t blki, size_t blkj, int eval) const { const int dr=sym.eigptrs(blki,eval); const int dc=sym.eigptrs(blkj,eval); if ((dr>=0) && (dc>=0)) dest(size_t(dr),size_t(dc))+=v; } void CrystalSystem_iterator::add_hermitian(cmatrix& dest, complex v, size_t blki, size_t blkj, int eval) const { const int dr=sym.eigptrs(blki,eval); const int dc=sym.eigptrs(blkj,eval); if ((dr>=0) && (dc>=0)) { dest(size_t(dr),size_t(dc))+=v; dest(size_t(dc),size_t(dr))+=conj(v); } } void CrystalOpGenerator::mla_Iz(ListList<double>& dest, double scale, const operator_spec& spec) const { if (spec.op!='z') throw InvalidParameter("mla_Iz: only valid for z operators"); if (spec.nuc==NULL_NUCLEUS) mla_Iz(dest,scale,spec.number); else mla_Fz(dest,scale,spec.nuc); } //ditto, all eigenvalues void CrystalOpGenerator::mla(BlockedMatrix<complex>& dest, block_pattern& blkspec, double scale, const operator_spec& opspec) const { if (opspec.op=='z') { //ignore 'c' as not valid ListList<double> destz; mla_Iz(destz,scale,opspec); dest+=destz; blkspec=block_pattern(*this); return; } blkspec=block_pattern(*this,opspec); if (!dest) { create(dest,blkspec); dest=complex(0.0); } else { if (dest.length()!=totalblocks()) throw Mismatch("rawmla"); } size_t nuc(opspec.nuc); if (nuc==NULL_NUCLEUS) nuc=(*sysp_)(opspec.number).nucleus(); CrystalSystem_iterator iter(*this,blkspec,nuc,1); iter.mla(dest,scale,opspec); } namespace { const char PUREERR[]="productoperator_spec: scale factor must be pure real or pure imaginary"; } void CrystalOpGenerator::add(BlockedMatrix<complex>& dest, block_pattern& blkspec, const productoperator_spec& spec) const { static const complex iconst(0.0,1.0); for (size_t i=spec.size();i--;) { const BaseList<operator_spec> opspec(spec.specs(i)); if (opspec.size()!=1) throw Failed("Can't use multi-spin productoperators with CrystalSystem"); const complex& cscale(spec.scales(i)); if (imag(cscale)) { if (real(cscale)) throw Failed(PUREERR); BlockedMatrix<complex> tmp; mla(tmp,blkspec,imag(cscale),opspec.front()); ::libcmatrix::mla(dest,iconst,tmp); } else mla(dest,blkspec,real(cscale),opspec.front()); } } void CrystalSystem_iterator::mla(BlockedMatrix<complex>& dest, double scale, const operator_spec& opspec) { size_t blki,blkj; const size_t nuc=opspec.nucleus(sym.spinsystem()); const bool notherm(sym.isblocked(nuc)); //if blocked by coherence, don't construct both sides of hermitian operators const bool isI=(opspec.nuc==NULL_NUCLEUS); while (next(blki,blkj)) { const bool haveany = isI ? Ipevalues(evalues,blki,blkj,opspec.number) : Fpevalues(evalues,blki,blkj,opspec.nuc); if (verbose>1) { std::cout << "I/Fp" << blki << "," << blkj << ": "; if (haveany) std::cout << evalues << '\n'; else std::cout << "<all zero>\n"; } if (!haveany) continue; switch (opspec.op) { case 'x': evalues*=0.5*scale; if (notherm) add(dest,evalues,blki,blkj); else add_hermitian(dest,evalues,blki,blkj); break; case 'y': evalues*=complex(0,-0.5*scale); if (notherm) add(dest,evalues,blki,blkj); else add_hermitian(dest,evalues,blki,blkj); break; case '+': if (scale!=1.0) evalues*=scale; add(dest,evalues,blki,blkj); break; case '-': if (scale!=1.0) evalues*=scale; conj_ip(evalues); add(dest,evalues,blkj,blki); break; default: throw InvalidParameter("Operator must be x, y, + , or -"); } } } void sum_permuted(rmatrix& dest,const rmatrix& source,const BaseList<size_t>& next, int N) { dest=source; rmatrix tmp; for (size_t i=1;i<N;i++) { tmp=dest(next,next); dest=tmp; dest+=source; } } void sum_permuted(List<double>& dest,const BaseList<double>& source,const BaseList<size_t>& next, int N) { dest=source; List<double> tmp; for (int i=1;i<N;i++) { tmp=dest(next); dest=tmp; tmp+=source; } } //Specialise default add_Hamiltonian template<class OutType, class StoreType> void add_coupling_Hamiltonians(OutType& dest, const CrystalOpGenerator& opgen, const HamiltonianStore<StoreType>& Hstore) { Matrix<double> A0s; Matrix<StoreType> A2s; Hstore.split_couplings(A0s,A2s); if (!!A0s) { if (opgen.verbose()>1) std::cout << "A0 couplings\n" << A0s; opgen.add_A0(dest,A0s); if (opgen.verbose()>1) std::cout << "After A0 add\n" << dest; } if (opgen.verbose()>1) std::cout << "A2 couplings\n" << A2s; opgen.add_A2(dest,A2s); } template<> void BlockedSpinningHamiltonianImpl<complex,CrystalOpGenerator>::interactions(const HamiltonianStore<space_T>& store) { const size_t verbose(opgen_.verbose()); BlockedMatrixTensor<complex> tmp; add_Hamiltonian(tmp,opgen_,store); size_t n(tmp.size()); List<SpinningHamiltonian>& H(*this); if (H.size()!=n) { if (H.empty()) H.create(n,SpinningHamiltonian(rotor_speed_,rotor_phase_,rinfo_)); else throw Mismatch("BlockedSpinningHamiltonian::interactions"); } for (;n--;) { MatrixTensor<complex>& source(tmp(n)); if (verbose>1) std::cout << "MatrixTensor(" << n << ")\n" << source << '\n'; SpinningHamiltonian& Hspin(H(n)); switch (source.rows()) { case 0: break; case 1: Hspin.tensor(source.element()); if (!!Hbase_) Hspin+=Hbase_(n); break; default: Hspin.tensor(source.matrix()); source.clear(); if (!!Hbase_) Hspin+=Hbase_(n); break; } } } template<> struct Ham_traits< BlockedMatrixTensor<complex> > { typedef space_T coupling_type; }; LCM_INSTANTIATE_TYPED_HAMILTONIANS(CrystalOpGenerator,complex) LCM_INSTANTIATE_SPINOPGEN_CREATE(CrystalOpGenerator) template void add_Hamiltonian<BlockedMatrix<complex>, CrystalOpGenerator, Tensor<complex> >(BlockedMatrix<complex>&, CrystalOpGenerator const&, HamiltonianStore< Tensor<libcmatrix::complex> > const&); //template<> BlockedFilter::BlockedFilter(const CrystalOpGenerator&, const BaseList<int>&); } //namespace libcmatrix // static void translate_raw(rmatrix &dest,const rmatrix &source,const BaseList<size_t> &TT) // { // const int n=TT.length(); // if (!issquare(source) || n!=source.rows()) throw Mismatch("translate_raw"); // dest.create(n,n); // for (int i=n;i--;) // for (int j=n;j--;) // dest(TT(i),TT(j))=source(i,j); // } // void Tmatrix(cmatrix& TV, const ListList<state_t>& TT, int total, const BaseList<size_t>& which) // { // int j; // const bool havesel=(which.length()!=0); // const size_t blks=havesel ? which.length() : TT.blocks(); // const long fulldim=long(1)<<total; // long totdim=0; //size of output matrix // if (havesel) { // for (j=blks;j--;) //sum over selected blocks // totdim+=TT.size(which(j)); // } // else // totdim=fulldim; // TV.create(totdim,totdim,0.0); //construct matrix to be filled // int point=0; // for (j=blks;j--;) { //loop over blocks // const BaseList<state_t> clist=TT(havesel ? which(j) : j); //get state list // const size_t size=clist.length(); // const double scale=1.0/sqrt((double)size); //normalisation factor // for (size_t n=size;n--;) { // for (size_t m=size;m--;) // TV(clist(m),point)=expi( (2*M_PI*m*n)/size)*scale; // point++; // } // } // } //create tensor of correct size (spinning) for eigenvalue, k, default value, val // void // CrystalOpGenerator::clear(Tensor<cmatrix>& ctens, int k, double val) const // { // if (ismatrix(k)) { // const size_t rows=rblkstr(k); // const size_t cols=cblkstr(k); // ctens.create(2,mxflag::maximum); // for (int m=-2;m<=2;m++) // create (2,0) matrix, even if unused // ctens(2,m).create(rows,cols,val); // } // else //if eigenvalue doesn't exist, kill off // ctens.clear(); // } // //space_T used to store "single element" H's in spinning case // void // CrystalOpGenerator::clear(space_T& Hisol, int k, double val) const // { // if (!ismatrix(k)) { // Hisol.create(2,mxflag::maximum); // Hisol=complex(val); // } // else // Hisol.clear(); // } // //create tensors of correct size (spinning) // void // CrystalOpGenerator::clear(List< Tensor<cmatrix> >& Htens, BaseList<space_T> Hisol, double val, double valisol) const // { // const bool use_isol=(Hisol.length()!=0); // Htens.create(useeigs); // for (size_t j=useeigs;j--;) { // if (ismatrix(j)) // clear(Htens(j),j,val); // else { // if (use_isol) // clear(Hisol(j),j,valisol); // } // } // } // void // CrystalOpGenerator::clear(BaseList<cmatrix> Hmats, BaseList<double> Hisol, double val, double valisol) const // { // if (Hmats.size()!=useeigs) // throw Mismatch("CrystalOpGenerator::clear"); // const size_t n=Hisol.size(); // if (n) { // if (n!=useeigs) // throw Mismatch("CrystalOpGenerator::clear"); // Hisol=valisol; // } // for (size_t j=useeigs;j--;) { // if (ismatrix(j)) // clear(Hmats(j),j,val); // else // Hmats(j).clear(); // } // } //void // CrystalOpGenerator::clear(BaseList<cmatrix> Hmats, double val) const // { // if (Hmats.size()!=useeigs) // throw Mismatch("CrystalOpGenerator::clear"); // for (size_t j=useeigs;j--;) // clear(Hmats(j),j,val); // } // void // CrystalOpGenerator::clear(List<cmatrix>& Hmats, List<double>& Hisol, double val, double valisol) const // { // Hmats.create(useeigs); // Hisol.create(useeigs); // clear(static_cast<BaseList<cmatrix>& >(Hmats),Hisol,val,valisol); // } // void // CrystalOpGenerator::clear(List<cmatrix>& Hmats, BaseList<double> Hisol, double val, double valisol) const // { // Hmats.create(useeigs); // clear(static_cast<BaseList<cmatrix>& >(Hmats),Hisol,val,valisol); // } // void // CrystalOpGenerator::clear(BlockedMatrix<complex>& Hmats, double val) const // { // if (isdiagonal()) // Hmats.create(rblkstr,val); // else // Hmats.create(rblkstr,cblkstr,val); // } // void // CrystalOpGenerator::clear(cmatrix& d, int k, double val) const // { // if (exists(k)) // d.create(rows(k),cols(k),val); // else // d.clear(); // } //add symmetrised block (blki,blkj) eigenvalue eval to (static) Hamiltonian // void // CrystalOpGenerator::place(cmatrix& Hk, complex& Hisol, size_t blki, size_t blkj, int eval) const // { // const int dr=sym.eigptrs(blki,eval); // const int dc=sym.eigptrs(blkj,eval); // const size_t rs=sym.T.size(blki); // const size_t cs=sym.T.size(blkj); // if (eval==0) { // if (ismatrix(0U)) // Hk(dr,dc)=csymmetrise0(rs,cs); // else // Hisol=csymmetrise0(rs,cs); // } // else { // if ((dr>=0) && (dc>=0)) { // if (ismatrix(eval)) // Hk(dr,dc)=csymmetrise(rs,cs,eval); // else { // Hisol=csymmetrise(rs,cs,eval); // } // } // } // } //calculate matrix that symmetrises w.r.t translation (not useful for large systems!) // void // CrystalOpGenerator::get_diag(cmatrix& D) const // { // List<size_t> rind; // makerindex(rind,*sysp_); //create state->index reverse index // D.create(sysp_->size(),sysp_->size(),0.0); //empty matrix // CrystalSystem_diagiterator iter(*this); // const ListList<state_t>& linkedstates(symmetriserp_->linkedstates()); // size_t blk; // size_t point=0; // while (iter.next(blk)) { //loop over state sets // const BaseList<state_t> states(linkedstates(blk)); //state list // const size_t blksize=states.size(); // const double scalef=1.0/sqrt(double(blksize)); //normalisation factor // for (size_t j=0;j<blksize;j++) { // for (size_t k=0;k<blksize;k++) // D(rind(states(k)),point)=eigfacs((j*k) % N_)*scalef; // point++; // } // } // if (point!=D.cols()) //sanity check - have we filled D? // throw Failed("get_diag"); // } //As above but restricted to single eigenvalue (usek) // void // CrystalOpGenerator::get_diag(cmatrix& D,int usek) const // { // List<size_t> rind; // makerindex(rind,sys); // D.create(rows(),diag_str_(usek),0.0); // CrystalSystem_diagiterator iter(*this); // size_t blk; // size_t point=0; // while (iter.next(blk)) { // const BaseList<state_t> states(linkedstates_(blk)); // const size_t blksize=states.size(); // if (sym.haseig(blksize,usek)) { // const double scalef=1.0/sqrt(double(blksize)); // for (size_t k=0;k<blksize;k++) // D(rind(states(k)),point)=sym.eigfacs( (usek*k) % N)*scalef; // point++; // } // } // if (point!=D.cols()) // throw Failed(); // } // void // CrystalOpGenerator::create(cmatrix& a, int k) const // { // const size_t rs=rblkstr(k); // if (isdiagonal()) // a.create(rs,rs); // else // a.create(rs,cblkstr(k)); // } // void // CrystalOpGenerator::create(MatrixTensor<complex>& a, int k) const // { // if (!isdiagonal()) // throw Failed("Can only create MatrixTensor objects for diagonal CrystalOpGenerator"); // a.create(rblkstr(k),2,mxflag::maximum); // } // void // CrystalOpGenerator::create(BlockedMatrix<complex>& Hmats) const // { // if (isdiagonal()) // Hmats.create(rblkstr); // else // Hmats.create(rblkstr,cblkstr); // } // void // CrystalOpGenerator::create(BlockedMatrixTensor<complex>& Htens) const // { // if (!isdiagonal()) // throw Failed("Can only create MatrixTensor objects for diagonal CrystalOpGenerator"); // Htens.create(rblkstr,2,mxflag::maximum); // } // void // CrystalOpGenerator::add_Hcoupling(complex& H, P_GENSPINNINGMATRIX func, const Matrix<space_T>& tensors, int m) const // { // if (firstrblk<0 || !(this->*func)(tensors,firstrblk,firstrblk,m)) // throw Failed("sym_Hdipolar_element: not single state block!"); // H+=symmetrise0(Type2Type<complex>()); // } //as above but for single eigenvalue // template<class Type> inline void CrystalOpGenerator::addtoeval(Type& s, size_t blkisize, size_t blkjsize, size_t r, size_t c, int m) // { // if (haseig(blkisize,m) && haseig(blkjsize,m)) { // const int wh=(m*(N+c-r)) % N; // mla(s,scalefacs(blkisize,blkjsize),eigfacs(wh)); // } // }
28.958376
200
0.661005
dch0ph
2af49f6548a23e9d8075e31edfcdcec88ff0e80b
2,167
cpp
C++
nd-coursework/books/cpp/BeginningC++17/Chapter07/Exercises/Exercise7_02/Exercise7_02.cpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/BeginningC++17/Chapter07/Exercises/Exercise7_02/Exercise7_02.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/BeginningC++17/Chapter07/Exercises/Exercise7_02/Exercise7_02.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2021 Cody R. Drisko. All rights reserved. // Licensed under the MIT License. See the LICENSE file in the project root for more information. // // Name: Exercise7_02.cpp // Author: cdrisko // Date: 08/02/2020-13:27:53 // Description: Determining all unique words from a user's input over an arbitrary number of lines #include <iomanip> #include <iostream> #include <string> #include <vector> int main() { std::string text; std::cout << "Enter some text terminated by *:\n"; std::getline(std::cin, text, '*'); std::vector<std::string> words; std::vector<unsigned int> counts; std::size_t maxLength {}; const std::string separators { " ,;:.\"!?'\n" }; std::size_t start { text.find_first_not_of(separators) }; while (start != std::string::npos) { std::size_t end = text.find_first_of(separators, start + 1); if (end == std::string::npos) end = text.length(); bool wordMatch {false}; std::string currentWord {text.substr(start, end - start)}; // Determine if the word has already been added to the vector for (std::size_t i {}; i < words.size(); ++i) { if (currentWord == words[i]) { wordMatch = true; ++counts[i]; break; } } if (!wordMatch) { words.push_back(currentWord); counts.push_back(1); } start = text.find_first_not_of(separators, end + 1); } // Determine max length for formatting purposes for (const auto& word : words) if (word.length() > maxLength) maxLength = word.length(); // Output the data 3 to a line, left aligned for the word, right aligned for the count for (std::size_t i {}, count {}; i < words.size(); ++i) { std::cout << std::setw(maxLength) << std::left << std::setw(maxLength) << words[i] << std::setw(4) << std::right << counts[i] << " "; if (++count == 3) { std::cout << std::endl; count = 0; } } std::cout << std::endl; }
28.142857
98
0.551915
crdrisko
2af4b636d42086a487f00c81ef1659e958235d8d
801
hpp
C++
rt/rtweekend.hpp
rrobio/zr_ren
4ffc61320100e1917c42a8155b45ad2d50f7040a
[ "MIT" ]
null
null
null
rt/rtweekend.hpp
rrobio/zr_ren
4ffc61320100e1917c42a8155b45ad2d50f7040a
[ "MIT" ]
null
null
null
rt/rtweekend.hpp
rrobio/zr_ren
4ffc61320100e1917c42a8155b45ad2d50f7040a
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <cstdlib> #include <limits> #include <memory> #include <random> using std::shared_ptr; using std::make_shared; using std::sqrt; double const infinity = std::numeric_limits<double>::infinity(); double const pi = 3.1415926535897932385; inline double degrees_to_radians(double degrees) { return degrees * pi / 180.0; } inline double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } inline double random_double(double min, double max) { return min + (max-min)*random_double(); } inline double clamp(double x, double min, double max) { if (x < min) return min; if (x > max) return max; return x; } #include "ray.hpp" #include "vec3.hpp"
18.627907
73
0.722846
rrobio
2afa200b89ca95727a85619a6b17c74eda94a1c6
240
cpp
C++
libboost-container-hash/tests/basics/driver.cpp
build2-packaging/boost
203d505dd3ba04ea50785bc8b247a295db5fc718
[ "BSL-1.0" ]
4
2021-02-23T11:24:33.000Z
2021-09-11T20:10:46.000Z
libboost-container-hash/tests/basics/driver.cpp
build2-packaging/boost
203d505dd3ba04ea50785bc8b247a295db5fc718
[ "BSL-1.0" ]
null
null
null
libboost-container-hash/tests/basics/driver.cpp
build2-packaging/boost
203d505dd3ba04ea50785bc8b247a295db5fc718
[ "BSL-1.0" ]
null
null
null
#include <boost/container_hash/extensions.hpp> #include <boost/container_hash/hash_fwd.hpp> #include <boost/container_hash/hash.hpp> #include <boost/functional/hash_fwd.hpp> #include <boost/functional/hash.hpp> int main () { return 0; }
20
46
0.770833
build2-packaging
2afacb9a31068fdb0add18d2d1c43d8190accb51
149
cpp
C++
explicit/toposort.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
explicit/toposort.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
explicit/toposort.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
1
2020-04-24T02:28:32.000Z
2020-04-24T02:28:32.000Z
// // toposort.cpp // explicit // // Created by Li Li on 25/8/13. // Copyright (c) 2013 Lilissun. All rights reserved. // #include "toposort.h"
14.9
53
0.630872
lilissun
63085f41f985a57944532103b7134c8b94bc6fe1
4,456
cc
C++
number-of-islands.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
number-of-islands.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
number-of-islands.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <random> #include <set> #include <map> #include <unordered_map> #include <unordered_set> #include <queue> #include <iomanip> #include <algorithm> using namespace std; template<class T, class S> ostream& operator<<(ostream& os, const unordered_map<T, S>& v) { bool f = true; os << "{"; for (auto& t: v) { if (f) os << "(" << t.first << "," << t.second << ")"; else os << "," << "(" << t.first << "," << t.second << ")"; } return os << "}"; } template <class T> ostream& operator<<(ostream& os, const vector<T>& vs) { os << "["; for (auto& s: vs) { os << std::setw(3) << s << " "; } return os <<"]\n"; } class Solution { public: int numIslands(vector<vector<char>>& grid) { int c = 0; int n = grid.size(); if (n == 0) return 0; int m = grid[0].size(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '1') { c++; dfs(grid, i, j); } } } return c; } void dfs(vector<vector<char>>& grid, int i, int j) { int n = grid.size(); int m = grid[0].size(); if (i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == '0') { return; } grid[i][j] = '0'; if (i > 0 && grid[i-1][j] == '1') { dfs(grid, i-1, j); } if (i < n-1 && grid[i+1][j] == '1') { dfs(grid, i+1, j); } if (j > 0 && grid[i][j-1] == '1') { dfs(grid, i, j-1); } if (j < m-1 && grid[i][j+1] == '1') { dfs(grid, i, j+1); } } }; //flood fill class Solution2 { public: int numIslands(vector<vector<char>>& grid) { int c = 0; int n = grid.size(); if (n == 0) return 0; int m = grid[0].size(); vector<vector<bool>> b(n, vector<bool>(m, false)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!b[i][j] && grid[i][j] == '1') { c++; b[i][j] = true; helper(grid, b, i, j, c); } } } return c; } void helper(vector<vector<char>>& grid, vector<vector<bool>>& b, int i, int j, int &c) { int n = grid.size(); int m = grid[0].size(); if (i > 0 && !b[i-1][j] && grid[i-1][j] == '1') { b[i-1][j] = true; helper(grid, b, i-1, j, c); } if (i < n-1 && !b[i+1][j] && grid[i+1][j] == '1') { b[i+1][j] = true; helper(grid, b, i+1, j, c); } if (j > 0 && !b[i][j-1] && grid[i][j-1] == '1') { b[i][j-1] = true; helper(grid, b, i, j-1, c); } if (j < m-1 && !b[i][j+1] && grid[i][j+1] == '1') { b[i][j+1] = true; helper(grid, b, i, j+1, c); } } }; int main(int argc, char *argv[]) { { vector<vector<char>> grid = { {'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}, }; cout << Solution().numIslands(grid) << std::endl; // 1 cout << Solution2().numIslands(grid) << std::endl; // 1 } { vector<vector<char>> grid = { {'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}, }; cout << Solution().numIslands(grid) << std::endl; // 3 cout << Solution2().numIslands(grid) << std::endl; // 3 } { vector<vector<char>> grid = { {'0', '0', '0', '0', '0'}, {'0', '1', '1', '1', '0'}, {'1', '0', '0', '1', '0'}, {'1', '1', '0', '0', '1'}, {'0', '0', '0', '0', '1'}, }; cout << Solution().numIslands(grid) << std::endl; // 3 cout << Solution2().numIslands(grid) << std::endl; // 3 } { vector<vector<char>> grid = { {'1', '1', '1'}, {'0', '1', '0'}, {'1', '1', '1'}, }; cout << Solution().numIslands(grid) << std::endl; // 1 cout << Solution2().numIslands(grid) << std::endl; // 1 } return 0; }
23.956989
92
0.360862
sonald
debabfa9624630c30a6bad131bbd73fc8a1d91e2
1,196
cpp
C++
data-structure/A1028/main.cpp
pipo-chen/play-ptat
d97d0bafcb6ef0a32f4969e0adffd400c673bf77
[ "MIT" ]
1
2021-05-26T23:14:01.000Z
2021-05-26T23:14:01.000Z
data-structure/A1028/main.cpp
pipo-chen/play-pat
4968f7f1db3fdb48925f5c29574cdc72339c7233
[ "MIT" ]
null
null
null
data-structure/A1028/main.cpp
pipo-chen/play-pat
4968f7f1db3fdb48925f5c29574cdc72339c7233
[ "MIT" ]
null
null
null
// // main.cpp // A1028 // // Created by mark on 2021/5/27. // Copyright © 2021 xihe. All rights reserved. // #include <iostream> #include <cstring> #include <algorithm> using namespace :: std; struct Student { char name[10]; long id; int grade; }stu[100010]; bool cmp_id(Student a, Student b) { //准考证从小到大排 return a.id < b.id; } bool cmp_name(Student a, Student b) { //按名字字典序从小到大排 if (strcmp(a.name, b.name) != 0) return strcmp(a.name, b.name) < 0; return a.id < b.id; } bool cmp_grade(Student a, Student b) { //按分数从小到大排,分数相同,按准考证从小到大排 if (a.grade != b.grade) return a.grade < b.grade; return a.id < b.id; } int main(int argc, const char * argv[]) { int n, c; scanf("%d %d", &n, &c); for (int i = 0; i < n; i++) { //输出id 的时候 前面不足 就补零 scanf("%ld %s %d",&stu[i].id, stu[i].name, &stu[i].grade); } if (c == 1) { sort(stu, stu + n, cmp_id); } else if (c == 2) { sort(stu, stu + n, cmp_name); } else { sort(stu, stu + n, cmp_grade); } for (int i = 0; i < n; i++) { printf("%06ld %s %d\n",stu[i].id, stu[i].name, stu[i].grade); } return 0; }
21.357143
69
0.529264
pipo-chen
debee1f4abf1a11091e5d92b0ed344428474a607
1,765
cpp
C++
Solutions/bitmap.cpp
sjnonweb/spoj
72cf2afcf4466f1356a8646b5e4f925144cb9172
[ "MIT" ]
1
2016-10-05T20:07:03.000Z
2016-10-05T20:07:03.000Z
Solutions/bitmap.cpp
sjnonweb/spoj
72cf2afcf4466f1356a8646b5e4f925144cb9172
[ "MIT" ]
null
null
null
Solutions/bitmap.cpp
sjnonweb/spoj
72cf2afcf4466f1356a8646b5e4f925144cb9172
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <queue> using namespace std; int mat[200][200]; void bfs(int,int); int main() { int test; cin>>test; while(test--) { vector < pair <int,int> > vc; int m,n; cin>>m>>n; int i,j; char ch; for(i=0;i<m;i++) { for(j=0;j<n;j++) { cin>>ch; if(ch=='1') { mat[i][j]=-1; vc.push_back(make_pair(i,j)); } else mat[i][j]=1000; } } for(i=0;i<vc.size();i++) { bfs(vc[i].first,vc[i].second); } for(i=0;i<m;i++) { for(j=0;j<n;j++) { cout<<mat[i][j]<<" "; } cout<<endl; } } return 0; } void bfs(int i, int j) { int distance; mat[i][j]=0; queue<int> q; q.push(i); q.push(j); while(!q.empty()) { int x=q.front(); q.pop(); int y=q.front(); q.pop(); distance=mat[x][y]+1; if(y-1>=0 && distance<mat[x][y-1]) { mat[x][y-1]=distance; q.push(x); q.push(y-1); } if(y+1>=0 && distance<mat[x][y+1]) { mat[x][y+1]=distance; q.push(x); q.push(y+1); } if(x-1>=0 && distance<mat[x-1][y]) { mat[x-1][y]=distance; q.push(x-1); q.push(y); } if(x+1>=0 && distance<mat[x+1][y]) { mat[x+1][y]=distance; q.push(x+1); q.push(y); } } }
19.184783
49
0.338244
sjnonweb
dec3f5e72bbf5cc0e80336eeda77f3e074ca65e7
16,314
cc
C++
examples/chat/node_modules/php-embed/src/node_php_embed.cc
jehovahsays/MMOSOCKETHTML5JSCHAT
3ae5956184ee1a1b63b1a8083fd3a43edd30dffd
[ "MIT" ]
34
2015-10-28T06:08:50.000Z
2021-12-22T06:34:28.000Z
examples/chat/node_modules/php-embed/src/node_php_embed.cc
jehovahsays/MMOSOCKETHTML5JSCHAT
3ae5956184ee1a1b63b1a8083fd3a43edd30dffd
[ "MIT" ]
3
2016-02-15T22:09:42.000Z
2019-10-06T23:19:01.000Z
examples/chat/node_modules/php-embed/src/node_php_embed.cc
jehovahsays/MMOSOCKETHTML5JSCHAT
3ae5956184ee1a1b63b1a8083fd3a43edd30dffd
[ "MIT" ]
6
2015-11-19T14:27:34.000Z
2019-10-09T23:36:51.000Z
// Main entry point: this is the node module declaration, contains // the PhpRequestWorker which shuttles messages between node and PHP, // and contains the SAPI hooks to configure PHP to talk to node. // Copyright (c) 2015 C. Scott Ananian <cscott@cscott.net> #include "src/node_php_embed.h" #include <dlfcn.h> // for dlopen() #include <string> #include <unordered_map> #include "nan.h" extern "C" { #include "sapi/embed/php_embed.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "ext/standard/head.h" #include "ext/standard/info.h" } #include "src/macros.h" #include "src/node_php_jsbuffer_class.h" #include "src/node_php_jsobject_class.h" #include "src/node_php_jsserver_class.h" #include "src/node_php_jswait_class.h" #include "src/phprequestworker.h" #include "src/values.h" using node_php_embed::MapperChannel; using node_php_embed::OwnershipType; using node_php_embed::PhpRequestWorker; using node_php_embed::Value; using node_php_embed::ZVal; using node_php_embed::node_php_jsbuffer; using node_php_embed::node_php_jsobject_call_method; static void node_php_embed_ensure_init(void); static char *node_php_embed_startup_file; static char *node_php_embed_extension_dir; ZEND_DECLARE_MODULE_GLOBALS(node_php_embed); /* PHP extension metadata */ extern zend_module_entry node_php_embed_module_entry; static int node_php_embed_startup(sapi_module_struct *sapi_module) { TRACE(">"); // Remove the "hardcoded INI" entries if (php_embed_module.ini_entries) { free(php_embed_module.ini_entries); } php_embed_module.ini_entries = NULL; #ifndef EXTERNAL_LIBPHP5 // Add an appropriate "extension_dir" directive. // (Unless we're linking against an external libphp5.so, in which case // we'll assume it knows best where its own extensions are.) if (node_php_embed_extension_dir) { std::string ini("extension_dir="); ini += node_php_embed_extension_dir; ini += "\n"; php_embed_module.ini_entries = strdup(ini.c_str()); } #endif // Proceed with startup. if (php_module_startup(sapi_module, &node_php_embed_module_entry, 1) == FAILURE) { return FAILURE; } TRACE("<"); return SUCCESS; } static int node_php_embed_ub_write(const char *str, unsigned int str_length TSRMLS_DC) { TRACE(">"); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return str_length; /* in module shutdown */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "write", 5, 0); // Special buffer type to pass `str` as a node buffer and avoid copying. zval buffer, *args[] = { &buffer }; INIT_ZVAL(buffer); node_php_embed::node_php_jsbuffer_create(&buffer, str, str_length, OwnershipType::NOT_OWNED TSRMLS_CC); call_user_function(EG(function_table), stream.PtrPtr(), &method, retval.Ptr(), 1, args TSRMLS_CC); if (EG(exception)) { NPE_ERROR("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); } zval_dtor(&buffer); TRACE("<"); return str_length; } static void node_php_embed_flush(void *server_context) { // Invoke stream.write with a PHP "JsWait" callback, which causes PHP // to block until the callback is handled. TRACE(">"); TSRMLS_FETCH(); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return; /* we're in module shutdown, no request any more */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "write", 5, 0); // Special buffer type to pass `str` as a node buffer and avoid copying. zval buffer; INIT_ZVAL(buffer); node_php_embed::node_php_jsbuffer_create(&buffer, "", 0, OwnershipType::NOT_OWNED TSRMLS_CC); // Create the special JsWait object. zval wait; INIT_ZVAL(wait); node_php_embed::node_php_jswait_create(&wait TSRMLS_CC); zval *args[] = { &buffer, &wait }; call_user_function(EG(function_table), stream.PtrPtr(), &method, retval.Ptr(), 2, args TSRMLS_CC); if (EG(exception)) { // This exception is often the "ASYNC inside SYNC" TypeError, which // is harmless in this context, so don't be noisy about it. TRACE("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); } zval_dtor(&buffer); zval_dtor(&wait); TRACE("<"); } static void node_php_embed_send_header(sapi_header_struct *sapi_header, void *server_context TSRMLS_DC) { TRACE(">"); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return; /* we're in module shutdown, no headers any more */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. // The "sendHeader" method is a special JS-side method to translate // headers into node.js format. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "sendHeader", 10, 0); // Special buffer type to pass `str` as a node buffer and avoid copying. zval buffer, *args[] = { &buffer }; INIT_ZVAL(buffer); if (sapi_header) { // NULL is passed to indicate "last call" node_php_embed::node_php_jsbuffer_create( &buffer, sapi_header->header, sapi_header->header_len, OwnershipType::NOT_OWNED TSRMLS_CC); } call_user_function(EG(function_table), stream.PtrPtr(), &method, retval.Ptr(), 1, args TSRMLS_CC); if (EG(exception)) { NPE_ERROR("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); } zval_dtor(&buffer); TRACE("<"); } static int node_php_embed_read_post(char *buffer, uint count_bytes TSRMLS_DC) { // Invoke stream.read with a PHP "JsWait" callback, which causes PHP // to block until the callback is handled. TRACE(">"); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return 0; /* we're in module shutdown, no request any more */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "read", 4, 0); zval size; INIT_ZVAL(size); ZVAL_LONG(&size, count_bytes); // Create the special JsWait object. zval wait; INIT_ZVAL(wait); node_php_embed::node_php_jswait_create(&wait TSRMLS_CC); zval *args[] = { &size, &wait }; // We can't use call_user_function yet because the PHP function caches // are not properly set up. Use the backdoor. node_php_jsobject_call_method(stream.Ptr(), &method, 2, args, retval.Ptr(), retval.PtrPtr() TSRMLS_CC); if (EG(exception)) { NPE_ERROR("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); return 0; } zval_dtor(&wait); // Transfer the data from the retval to the buffer if (!(retval.IsObject() && Z_OBJCE_P(retval.Ptr()) == php_ce_jsbuffer)) { NPE_ERROR("Return value was not buffer :("); return 0; } node_php_jsbuffer *b = reinterpret_cast<node_php_jsbuffer *> (zend_object_store_get_object(retval.Ptr() TSRMLS_CC)); assert(b->length <= count_bytes); memcpy(buffer, b->data, b->length); TRACEX("< (read %lu)", b->length); return static_cast<int>(b->length); } static char * node_php_embed_read_cookies(TSRMLS_D) { // This is a hack to prevent the SAPI from overwriting the // cookie data we set up in the PhpRequestWorker constructor. return SG(request_info).cookie_data; } static void node_php_embed_register_server_variables( zval *track_vars_array TSRMLS_DC) { TRACE(">"); PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); // Invoke the init_func in order to set up the $_SERVER variables. ZVal init_func{ZEND_FILE_LINE_C}; ZVal server{ZEND_FILE_LINE_C}; ZVal wait{ZEND_FILE_LINE_C}; worker->GetInitFunc().ToPhp(channel, init_func TSRMLS_CC); assert(init_func.Type() == IS_OBJECT); // Create a wrapper that will allow the JS function to set $_SERVER. node_php_embed::node_php_jsserver_create(server.Ptr(), track_vars_array TSRMLS_CC); // Allow the JS function to be asynchronous. node_php_embed::node_php_jswait_create(wait.Ptr() TSRMLS_CC); // Now invoke the JS function, passing in the wrapper zval *r = nullptr; zend_call_method_with_2_params(init_func.PtrPtr(), Z_OBJCE_P(init_func.Ptr()), nullptr, "__invoke", &r, server.Ptr(), wait.Ptr()); if (EG(exception)) { NPE_ERROR("Exception in server init function"); zend_clear_exception(TSRMLS_C); } if (r) { zval_ptr_dtor(&r); } TRACE("<"); } NAN_METHOD(setIniPath) { TRACE(">"); REQUIRE_ARGUMENT_STRING(0, ini_path); if (php_embed_module.php_ini_path_override) { free(php_embed_module.php_ini_path_override); } php_embed_module.php_ini_path_override = (*ini_path) ? strdup(*ini_path) : nullptr; TRACE("<"); } NAN_METHOD(setStartupFile) { TRACE(">"); REQUIRE_ARGUMENT_STRING(0, file_name); if (node_php_embed_startup_file) { free(node_php_embed_startup_file); } node_php_embed_startup_file = (*file_name) ? strdup(*file_name) : nullptr; TRACE("<"); } NAN_METHOD(setExtensionDir) { TRACE(">"); REQUIRE_ARGUMENT_STRING(0, ext_dir); if (node_php_embed_extension_dir) { free(node_php_embed_extension_dir); } node_php_embed_extension_dir = (*ext_dir) ? strdup(*ext_dir) : nullptr; TRACE("<"); } NAN_METHOD(request) { TRACE(">"); REQUIRE_ARGUMENTS(4); REQUIRE_ARGUMENT_STRING_NOCONV(0); if (!info[1]->IsObject()) { return Nan::ThrowTypeError("stream expected"); } if (!info[2]->IsArray()) { return Nan::ThrowTypeError("argument array expected"); } if (!info[3]->IsObject()) { return Nan::ThrowTypeError("server vars object expected"); } if (!info[4]->IsFunction()) { return Nan::ThrowTypeError("init function expected"); } if (!info[5]->IsFunction()) { return Nan::ThrowTypeError("callback expected"); } v8::Local<v8::String> source = info[0].As<v8::String>(); v8::Local<v8::Object> stream = info[1].As<v8::Object>(); v8::Local<v8::Array> args = info[2].As<v8::Array>(); v8::Local<v8::Object> server_vars = info[3].As<v8::Object>(); v8::Local<v8::Value> init_func = info[4]; Nan::Callback *callback = new Nan::Callback(info[5].As<v8::Function>()); node_php_embed_ensure_init(); Nan::AsyncQueueWorker(new PhpRequestWorker(callback, source, stream, args, server_vars, init_func, node_php_embed_startup_file)); TRACE("<"); } /** PHP module housekeeping */ PHP_MINFO_FUNCTION(node_php_embed) { php_info_print_table_start(); php_info_print_table_row(2, "Version", NODE_PHP_EMBED_VERSION); php_info_print_table_row(2, "Node version", NODE_VERSION_STRING); php_info_print_table_row(2, "PHP version", PHP_VERSION); php_info_print_table_end(); } static void node_php_embed_globals_ctor( zend_node_php_embed_globals *node_php_embed_globals TSRMLS_DC) { node_php_embed_globals->worker = nullptr; node_php_embed_globals->channel = nullptr; } static void node_php_embed_globals_dtor( zend_node_php_embed_globals *node_php_embed_globals TSRMLS_DC) { // No clean up required. } PHP_MINIT_FUNCTION(node_php_embed) { TRACE("> PHP_MINIT_FUNCTION"); PHP_MINIT(node_php_jsbuffer_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(node_php_jsobject_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(node_php_jsserver_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(node_php_jswait_class)(INIT_FUNC_ARGS_PASSTHRU); TRACE("< PHP_MINIT_FUNCTION"); return SUCCESS; } zend_module_entry node_php_embed_module_entry = { STANDARD_MODULE_HEADER, "node-php-embed", /* extension name */ nullptr, /* function entries */ PHP_MINIT(node_php_embed), /* MINIT */ nullptr, /* MSHUTDOWN */ nullptr, /* RINIT */ nullptr, /* RSHUTDOWN */ PHP_MINFO(node_php_embed), /* MINFO */ NODE_PHP_EMBED_VERSION, ZEND_MODULE_GLOBALS(node_php_embed), (void(*)(void* TSRMLS_DC))node_php_embed_globals_ctor, (void(*)(void* TSRMLS_DC))node_php_embed_globals_dtor, nullptr, /* post deactivate func */ STANDARD_MODULE_PROPERTIES_EX }; /** Node module housekeeping. */ static void ModuleShutdown(void *arg); #ifdef ZTS static void ***tsrm_ls; #endif static bool node_php_embed_inited = false; static void node_php_embed_ensure_init(void) { if (node_php_embed_inited) { return; } TRACE(">"); node_php_embed_inited = true; // Module must be opened with RTLD_GLOBAL so that PHP can later // load extensions. So re-invoke dlopen to twiddle the flags. if (node_php_embed_extension_dir) { std::string path(node_php_embed_extension_dir); path += "/node_php_embed.node"; dlopen(path.c_str(), RTLD_LAZY|RTLD_GLOBAL|RTLD_NOLOAD); } // We also have to lie about the sapi name (!) in order to get opcache // to start up. (Well, we could also patch PHP to fix this.) char *old_name = php_embed_module.name; // opcache is unhappy if we deallocate this, so keep it around forever-ish. static char new_name[] = { "cli" }; php_embed_module.name = new_name; php_embed_init(0, nullptr PTSRMLS_CC); // Shutdown the initially-created request; we'll create our own request // objects inside PhpRequestWorker. php_request_shutdown(nullptr); PhpRequestWorker::CheckRequestInfo(TSRMLS_C); node::AtExit(ModuleShutdown, nullptr); // Reset the SAPI module name now that all extensions (opcache in // particular) are loaded. php_embed_module.name = old_name; TRACE("<"); } NAN_MODULE_INIT(ModuleInit) { TRACE(">"); node_php_embed_startup_file = NULL; node_php_embed_extension_dir = NULL; php_embed_module.php_ini_path_override = nullptr; php_embed_module.php_ini_ignore = true; php_embed_module.php_ini_ignore_cwd = true; php_embed_module.ini_defaults = nullptr; // The following initialization statements are kept in the same // order as the fields in `struct _sapi_module_struct` (SAPI.h) php_embed_module.startup = node_php_embed_startup; php_embed_module.ub_write = node_php_embed_ub_write; php_embed_module.flush = node_php_embed_flush; php_embed_module.send_header = node_php_embed_send_header; php_embed_module.read_post = node_php_embed_read_post; php_embed_module.read_cookies = node_php_embed_read_cookies; php_embed_module.register_server_variables = node_php_embed_register_server_variables; // Most of init will be done lazily in node_php_embed_ensure_init() // Initialize object type allowing access to PHP objects from JS node_php_embed::PhpObject::Init(target); // Export functions NAN_EXPORT(target, setIniPath); NAN_EXPORT(target, setStartupFile); NAN_EXPORT(target, setExtensionDir); NAN_EXPORT(target, request); TRACE("<"); } void ModuleShutdown(void *arg) { TRACE(">"); TSRMLS_FETCH(); // The php_embed_shutdown expects there to be an open request, so // create one just for it to shutdown for us. php_request_startup(TSRMLS_C); php_embed_shutdown(TSRMLS_C); if (php_embed_module.php_ini_path_override) { free(php_embed_module.php_ini_path_override); php_embed_module.php_ini_path_override = NULL; } if (node_php_embed_startup_file) { free(node_php_embed_startup_file); node_php_embed_startup_file = NULL; } TRACE("<"); } NODE_MODULE(node_php_embed, ModuleInit)
36.660674
80
0.716072
jehovahsays
dec5f3eff0c32ae0ad9d69d3ca362fc866dd4dfe
10,479
hpp
C++
include/codegen/arithmetic_ops.hpp
tetzank/codegen
790aeccd6f2651dff053118593606fe8e560071c
[ "MIT" ]
389
2019-05-19T16:51:28.000Z
2022-02-27T12:29:38.000Z
include/codegen/arithmetic_ops.hpp
tetzank/codegen
790aeccd6f2651dff053118593606fe8e560071c
[ "MIT" ]
3
2019-05-20T05:42:57.000Z
2019-07-17T18:50:17.000Z
include/codegen/arithmetic_ops.hpp
tetzank/codegen
790aeccd6f2651dff053118593606fe8e560071c
[ "MIT" ]
20
2019-05-19T17:00:02.000Z
2021-12-29T01:47:50.000Z
/* * Copyright © 2019 Paweł Dziepak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include "codegen/module_builder.hpp" namespace codegen { namespace detail { enum class arithmetic_operation_type { add, sub, mul, div, mod, and_, or_, xor_, }; template<arithmetic_operation_type Op, typename LHS, typename RHS> class arithmetic_operation { LHS lhs_; RHS rhs_; static_assert(std::is_same_v<typename LHS::value_type, typename RHS::value_type>); public: using value_type = typename LHS::value_type; arithmetic_operation(LHS lhs, RHS rhs) : lhs_(std::move(lhs)), rhs_(std::move(rhs)) {} llvm::Value* eval() const { if constexpr (std::is_integral_v<value_type>) { switch (Op) { case arithmetic_operation_type::add: return current_builder->ir_builder_.CreateAdd(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::sub: return current_builder->ir_builder_.CreateSub(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::mul: return current_builder->ir_builder_.CreateMul(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::div: if constexpr (std::is_signed_v<value_type>) { return current_builder->ir_builder_.CreateSDiv(lhs_.eval(), rhs_.eval()); } else { return current_builder->ir_builder_.CreateUDiv(lhs_.eval(), rhs_.eval()); } case arithmetic_operation_type::mod: if constexpr (std::is_signed_v<value_type>) { return current_builder->ir_builder_.CreateSRem(lhs_.eval(), rhs_.eval()); } else { return current_builder->ir_builder_.CreateURem(lhs_.eval(), rhs_.eval()); } case arithmetic_operation_type::and_: return current_builder->ir_builder_.CreateAnd(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::or_: return current_builder->ir_builder_.CreateOr(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::xor_: return current_builder->ir_builder_.CreateXor(lhs_.eval(), rhs_.eval()); } } else { switch (Op) { case arithmetic_operation_type::add: return current_builder->ir_builder_.CreateFAdd(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::sub: return current_builder->ir_builder_.CreateFSub(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::mul: return current_builder->ir_builder_.CreateFMul(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::div: return current_builder->ir_builder_.CreateFDiv(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::mod: return current_builder->ir_builder_.CreateFRem(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::and_: [[fallthrough]]; case arithmetic_operation_type::or_: [[fallthrough]]; case arithmetic_operation_type::xor_: abort(); } } } friend std::ostream& operator<<(std::ostream& os, arithmetic_operation const& ao) { auto symbol = [] { switch (Op) { case arithmetic_operation_type::add: return '+'; case arithmetic_operation_type::sub: return '-'; case arithmetic_operation_type::mul: return '*'; case arithmetic_operation_type::div: return '/'; case arithmetic_operation_type::mod: return '%'; case arithmetic_operation_type::and_: return '&'; case arithmetic_operation_type::or_: return '|'; case arithmetic_operation_type::xor_: return '^'; } }(); return os << '(' << ao.lhs_ << ' ' << symbol << ' ' << ao.rhs_ << ')'; } }; enum class pointer_arithmetic_operation_type { add, sub, }; template<pointer_arithmetic_operation_type Op, typename LHS, typename RHS> class pointer_arithmetic_operation { LHS lhs_; RHS rhs_; static_assert(std::is_pointer_v<typename LHS::value_type>); static_assert(std::is_integral_v<typename RHS::value_type>); using rhs_value_type = typename RHS::value_type; public: using value_type = typename LHS::value_type; pointer_arithmetic_operation(LHS lhs, RHS rhs) : lhs_(std::move(lhs)), rhs_(std::move(rhs)) {} llvm::Value* eval() const { auto& mb = *current_builder; auto rhs = rhs_.eval(); if constexpr (sizeof(rhs_value_type) < sizeof(uint64_t)) { if constexpr (std::is_unsigned_v<rhs_value_type>) { rhs = mb.ir_builder_.CreateZExt(rhs, type<uint64_t>::llvm()); } else { rhs = mb.ir_builder_.CreateSExt(rhs, type<int64_t>::llvm()); } } switch (Op) { case pointer_arithmetic_operation_type::add: return mb.ir_builder_.CreateInBoundsGEP(lhs_.eval(), rhs); case pointer_arithmetic_operation_type::sub: return mb.ir_builder_.CreateInBoundsGEP(lhs_.eval(), mb.ir_builder_.CreateSub(constant<int64_t>(0), rhs)); } abort(); } friend std::ostream& operator<<(std::ostream& os, pointer_arithmetic_operation const& ao) { auto symbol = [] { switch (Op) { case pointer_arithmetic_operation_type::add: return '+'; case pointer_arithmetic_operation_type::sub: return '-'; } }(); return os << '(' << ao.lhs_ << ' ' << symbol << ' ' << ao.rhs_ << ')'; } }; } // namespace detail template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator+(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::add, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator-(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::sub, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator*(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::mul, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator/(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::div, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator%(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::mod, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator&(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::and_, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator|(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::or_, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator^(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::xor_, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_pointer_v<typename LHS::value_type>>, typename = void> auto operator+(LHS lhs, RHS rhs) { return detail::pointer_arithmetic_operation<detail::pointer_arithmetic_operation_type::add, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_pointer_v<typename LHS::value_type>>, typename = void> auto operator-(LHS lhs, RHS rhs) { return detail::pointer_arithmetic_operation<detail::pointer_arithmetic_operation_type::sub, LHS, RHS>(std::move(lhs), std::move(rhs)); } } // namespace codegen
44.974249
120
0.662945
tetzank
decb5f3e24416b5c57dff14134c7bd4af36dfda0
1,593
cpp
C++
OOD/Mediator.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
1
2020-04-14T05:44:50.000Z
2020-04-14T05:44:50.000Z
OOD/Mediator.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
null
null
null
OOD/Mediator.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
2
2020-09-02T08:56:31.000Z
2021-06-22T11:20:58.000Z
#include <iostream> #include <string> using namespace std; class BaseComponent; class Mediator { public: virtual void Notify(BaseComponent* sender, string event) const = 0; }; class BaseComponent { public: BaseComponent(Mediator* mediator_ = NULL) : mediator(mediator_) {} void set_mediator(Mediator* mediator_) { this->mediator = mediator_; } protected: Mediator* mediator; }; class Component1 : public BaseComponent { public: void doA() { if (mediator) { cout << "Component1 do A" << endl; mediator->Notify(this, "A"); } } void doB() { if (mediator) { cout << "Component1 do B" << endl; mediator->Notify(this, "B"); } } }; class Component2 : public BaseComponent { public: void doC() { if (mediator) { cout << "Component2 do C" << endl; mediator->Notify(this, "C"); } } void doD() { if (mediator) { cout << "Component2 do D" << endl; mediator->Notify(this, "D"); } } }; class ConcreteMediator : public Mediator { public: ConcreteMediator(Component1* comp1_, Component2* comp2_) : comp_1(comp1_), comp_2(comp2_) { comp_1->set_mediator(this); comp_2->set_mediator(this); } void Notify(BaseComponent* sender, string event) const override { if (event == "A") { this->comp_1->doB(); } if (event == "C") { this->comp_2->doD(); } } private: Component1* comp_1; Component2* comp_2; }; void client() { Component1* comp1 = new Component1(); Component2* comp2 = new Component2(); ConcreteMediator* mediator = new ConcreteMediator(comp1, comp2); comp1->doA(); comp2->doC(); } int main() { client(); return 0; }
18.964286
92
0.654739
FrancsXiang
ded17ec2fa9669d5627c4a5f44d09827ea652fed
502
hpp
C++
include/RunStatisticsPrinter.hpp
pixie-net/pixie-net-api
743e473845fc6c6d674d454b3a419d55372d99d4
[ "Unlicense" ]
null
null
null
include/RunStatisticsPrinter.hpp
pixie-net/pixie-net-api
743e473845fc6c6d674d454b3a419d55372d99d4
[ "Unlicense" ]
3
2019-04-07T17:18:47.000Z
2019-11-10T22:08:18.000Z
include/RunStatisticsPrinter.hpp
spaulaus/pixie-net
743e473845fc6c6d674d454b3a419d55372d99d4
[ "Unlicense" ]
null
null
null
/// @file RunStatisticsPrinter.hpp /// @brief /// @author S. V. Paulauskas /// @date March 07, 2020 #ifndef PIXIE_NET_RUNSTATISTICSPRINTER_HPP #define PIXIE_NET_RUNSTATISTICSPRINTER_HPP #include <string> #include "RunStatistics.hpp" class RunStatisticsPrinter { public: std::string format_stats_as_json(const RunStatistics &stats); private: std::string format_channel_for_json(const unsigned int &channel, const RunStatistics &stats) const; }; #endif //PIXIE_NET_RUNSTATISTICSPRINTER_HPP
23.904762
103
0.782869
pixie-net
deddaa5f897b59953aab13c08c8174c32390374e
1,096
cpp
C++
05.Purity-avoding-mutable-state/5.6-calculating-the-coordinates-of-the-neighboring-cell.cpp
Haceau-Zoac/Functional-Programming-in-C-
f3130d9faaaed2e3d5358f74341e4349f337d592
[ "MIT" ]
null
null
null
05.Purity-avoding-mutable-state/5.6-calculating-the-coordinates-of-the-neighboring-cell.cpp
Haceau-Zoac/Functional-Programming-in-C-
f3130d9faaaed2e3d5358f74341e4349f337d592
[ "MIT" ]
null
null
null
05.Purity-avoding-mutable-state/5.6-calculating-the-coordinates-of-the-neighboring-cell.cpp
Haceau-Zoac/Functional-Programming-in-C-
f3130d9faaaed2e3d5358f74341e4349f337d592
[ "MIT" ]
null
null
null
enum direction_t { Left, Right, Up, Down }; class position_t { public: position_t(position_t const& original, direction_t direction); int x; int y; }; class maze_t { public: auto is_wall(position_t) const -> bool; }; auto next_position(direction_t direction, position_t const& previous_position, maze_t const& maze) -> position_t { position_t const desired_position{ previous_position, direction }; return maze.is_wall(desired_position) ? previous_position : desired_position; } position_t::position_t(position_t const& original, direction_t direction) // Uses the ternary operator to match against the possible direction values // and initialize the correct values of x and y. You could also use a switch // statement in the body of the constructor. : x{ direction == Left ? original.x - 1 : direction == Right ? original.x + 1 : original.x } , y{ direction == Up ? original.y + 1 : direction == Down ? original.y - 1 : original.y } {}
28.102564
98
0.642336
Haceau-Zoac
dedf7c03d1c65efbcaa565d8e992e67eb126a424
3,491
cpp
C++
src/bindings/bnd_arccurve.cpp
lukegehron/rhino3dm
0e124084f7397f72aa82e499124a9232497573f0
[ "MIT" ]
343
2018-10-17T07:36:55.000Z
2022-03-31T08:18:36.000Z
src/bindings/bnd_arccurve.cpp
iintrigued/rhino3dm
aa3cffaf66a22883de64b4bc096d554341c1ce39
[ "MIT" ]
187
2018-10-18T23:07:44.000Z
2022-03-24T02:05:00.000Z
src/bindings/bnd_arccurve.cpp
iintrigued/rhino3dm
aa3cffaf66a22883de64b4bc096d554341c1ce39
[ "MIT" ]
115
2018-10-18T01:17:20.000Z
2022-03-31T16:43:58.000Z
#include "bindings.h" BND_ArcCurve::BND_ArcCurve() { SetTrackedPointer(new ON_ArcCurve(), nullptr); } BND_ArcCurve::BND_ArcCurve(ON_ArcCurve* arccurve, const ON_ModelComponentReference* compref) { SetTrackedPointer(arccurve, compref); } BND_ArcCurve::BND_ArcCurve(const BND_ArcCurve& other) { ON_ArcCurve* ac = new ON_ArcCurve(*other.m_arccurve); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Arc& arc) { ON_ArcCurve* ac = new ON_ArcCurve(arc.m_arc); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Arc& arc, double t0, double t1) { ON_ArcCurve* ac = new ON_ArcCurve(arc.m_arc, t0, t1); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Circle& circle) { ON_ArcCurve* ac = new ON_ArcCurve(circle.m_circle); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Circle& circle, double t0, double t1) { ON_ArcCurve* ac = new ON_ArcCurve(circle.m_circle, t0, t1); SetTrackedPointer(ac, nullptr); } BND_Arc* BND_ArcCurve::GetArc() const { return new BND_Arc(m_arccurve->m_arc); } void BND_ArcCurve::SetTrackedPointer(ON_ArcCurve* arccurve, const ON_ModelComponentReference* compref) { m_arccurve = arccurve; BND_Curve::SetTrackedPointer(arccurve, compref); } #if defined(ON_PYTHON_COMPILE) namespace py = pybind11; void initArcCurveBindings(pybind11::module& m) { py::class_<BND_ArcCurve, BND_Curve>(m, "ArcCurve") .def(py::init<>()) .def(py::init<const BND_ArcCurve&>(), py::arg("other")) .def(py::init<const BND_Arc&>(), py::arg("arc")) .def(py::init<const BND_Arc, double, double>(), py::arg("arc"), py::arg("t0"), py::arg("t1")) .def(py::init<const BND_Circle&>(), py::arg("circle")) .def(py::init<const BND_Circle&, double, double>(), py::arg("circle"), py::arg("t0"), py::arg("t1")) .def_property_readonly("Arc", &BND_ArcCurve::GetArc) .def_property_readonly("IsCompleteCircle", &BND_ArcCurve::IsCompleteCircle) .def_property_readonly("Radius", &BND_ArcCurve::GetRadius) .def_property_readonly("AngleRadians", &BND_ArcCurve::AngleRadians) .def_property_readonly("AngleDegrees", &BND_ArcCurve::AngleDegrees) ; } #endif #if defined(ON_WASM_COMPILE) using namespace emscripten; static BND_ArcCurve* JsConstructFromArc(const BND_Arc& arc) { return new BND_ArcCurve(arc); } static BND_ArcCurve* JsConstructFromArc2(const BND_Arc& arc, double t0, double t1) { return new BND_ArcCurve(arc, t0, t1); } static BND_ArcCurve* JsConstructFromCircle(const BND_Circle& c) { return new BND_ArcCurve(c); } static BND_ArcCurve* JsConstructFromCircle2(const BND_Circle& c, double t0, double t1) { return new BND_ArcCurve(c, t0, t1); } void initArcCurveBindings(void*) { class_<BND_ArcCurve, base<BND_Curve>>("ArcCurve") .constructor<>() .constructor<const BND_Arc&>() .class_function("createFromArc", &JsConstructFromArc, allow_raw_pointers()) .class_function("createFromArc", &JsConstructFromArc2, allow_raw_pointers()) .class_function("createFromCircle", &JsConstructFromCircle, allow_raw_pointers()) .class_function("createFromCircle", &JsConstructFromCircle2, allow_raw_pointers()) //.property("arc", &BND_ArcCurve::GetArc, allow_raw_pointers()) .property("isCompleteCircle", &BND_ArcCurve::IsCompleteCircle) .property("radius", &BND_ArcCurve::GetRadius) .property("angleRadians", &BND_ArcCurve::AngleRadians) .property("angleDegrees", &BND_ArcCurve::AngleDegrees) ; } #endif
35.989691
126
0.741335
lukegehron
dee2cd3b6100c754c56c40c94f9d272e4beb7bf7
2,305
hpp
C++
MuleUtilities/asset/include/mule/asset/FileReader.hpp
Godlike/Mule
3601d3e063aa2a0a1bbf7289e97bdeb5e5899589
[ "MIT" ]
null
null
null
MuleUtilities/asset/include/mule/asset/FileReader.hpp
Godlike/Mule
3601d3e063aa2a0a1bbf7289e97bdeb5e5899589
[ "MIT" ]
9
2018-02-01T03:59:06.000Z
2018-12-17T04:07:16.000Z
MuleUtilities/asset/include/mule/asset/FileReader.hpp
Godlike/Mule
3601d3e063aa2a0a1bbf7289e97bdeb5e5899589
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 by Godlike * This code is licensed under the MIT license (MIT) * (http://opensource.org/licenses/MIT) */ #ifndef MULE_ASSET_FILE_READER_HPP #define MULE_ASSET_FILE_READER_HPP #include <cstdint> #include <string> #include <vector> namespace mule { namespace asset { /** @brief Provides lazy access to file content * * File contents are loaded only when needed */ class FileReader { public: /** @brief Bit flags describing the state of FileReader */ struct Flags { //! File was not accessed static const uint8_t uninitialized = 0b00000000; //! File was accessed static const uint8_t accessed = 0b00000001; //! File was read to the end static const uint8_t eof = 0b00000010; //! Bit mask describing a good state static const uint8_t ok = accessed | eof; //! Error encountered while reading file static const uint8_t error = 0b00000100; }; /** @brief Constructs an object * * @param path path to be used for file access */ FileReader(char const* path); ~FileReader() = default; /** @brief Checks if file was successfully read * * Reads the file if it was not yet read * * @return @c true if @ref m_flags is Flags::ok */ bool IsGood(); /** @brief Returns the path used by FileReader */ std::string const& GetPath() const { return m_path; } /** @brief Returns file contents * * Reads the file if it was not yet read * * @return const reference to a buffer with file contents */ std::vector<uint8_t> const& GetContent(); /** @brief Returns moved file contents * * Sets @ref m_flags value to Flags::uninitialized * * @return moved buffer with file contents */ std::vector<uint8_t> MoveContent(); private: /** @brief Represents lazy access file reading routine * * Checks if @ref m_flags is Flags::uninitialized and loads * file contents if it is. */ void LazyAccess(); //! Describes FileReader state uint8_t m_flags; //! Path to the file std::string m_path; //! Buffer with file contents std::vector<uint8_t> m_buffer; }; } } #endif // MULE_ASSET_FILE_READER_HPP
22.821782
64
0.631236
Godlike
dee63d1b372e3665741e501e2311d8809a5ddbef
1,318
hpp
C++
src/PhysicsSystem.hpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
2
2018-05-13T05:27:29.000Z
2018-05-29T06:35:57.000Z
src/PhysicsSystem.hpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
null
null
null
src/PhysicsSystem.hpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
null
null
null
#ifndef PHYSICSSYSTEM__HPP #define PHYSICSSYSTEM__HPP //DESCRIPTION /* System used to deal with physics components and handle the per frame changes of entities. Interactions between entities is handled by the collision system. */ //INCLUDES #include <vector> #include <algorithm> #include <SDL2/SDL.h> #include "KF_math.hpp" #include "AbstractSystem.hpp" #include "EntityManager.hpp" #include "Messenger.hpp" #include "Message.hpp" #include "physics/KF_physics.hpp" //CLASSES class PhysicsSystem; //DEFINITIONS //MACROS //TYPEDEFS //FUNCTIONS //BEGIN class PhysicsSystem : public AbstractSystem { private: timeType previousTime = SDL_GetTicks(); timeType currentTime = 0; std::vector<AbstractForceGenerator*> generatorContainer; public: PhysicsSystem(); virtual ~PhysicsSystem(); //Generator methods void addForceGenerator(AbstractForceGenerator* generator); void removeForceGenerator(AbstractForceGenerator* gen); void removeForceGenerator(stringType generatorName); AbstractForceGenerator* getForceGenerator(stringType generatorName); boolType hasForceGenerator(stringType generatorName); const std::vector<AbstractForceGenerator*>& getForceGeneratorContainer(); void createMessages(); void process(); }; #endif //END PHYSICSSYSTEM__HPP
22.724138
77
0.764795
benzap
deec7f28da5171ff13a977de2bc27671736bbeaa
571
cpp
C++
aoc2015/aoc151001.cpp
jiayuehua/adventOfCode
fd47ddefd286fe94db204a9850110f8d1d74d15b
[ "Unlicense" ]
null
null
null
aoc2015/aoc151001.cpp
jiayuehua/adventOfCode
fd47ddefd286fe94db204a9850110f8d1d74d15b
[ "Unlicense" ]
null
null
null
aoc2015/aoc151001.cpp
jiayuehua/adventOfCode
fd47ddefd286fe94db204a9850110f8d1d74d15b
[ "Unlicense" ]
null
null
null
#include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <fmt/format.h> #include <string> #include <iomanip> int main(int argc, char **argv) { std::string sa("1113222113"); std::string sr; std::string sb; for (int i = 0; i < 50; ++i) { for (auto it = sa.begin(), end = sa.begin(); it != sa.end(); it = end) { char c = *it; end = std::find_if(it, sa.end(), [c](char e) { return e != c; }); sb += std::to_string(end - it); sb += c; } sa = std::exchange(sb, ""); } fmt::print("{}", sa.size()); }
22.84
76
0.539405
jiayuehua
def38bf45be159dec1481769db71fda69e44eff8
3,056
cpp
C++
RLSimion/CNTKWrapper/cntk-wrapper.cpp
utercero/SimionZoo
1fa570ae88f5d7e88e13a67ec27cda2de820ffee
[ "Zlib" ]
30
2019-02-20T19:33:15.000Z
2020-03-26T13:46:51.000Z
RLSimion/CNTKWrapper/cntk-wrapper.cpp
utercero/SimionZoo
1fa570ae88f5d7e88e13a67ec27cda2de820ffee
[ "Zlib" ]
52
2018-02-28T17:16:37.000Z
2019-02-15T18:26:21.000Z
RLSimion/CNTKWrapper/cntk-wrapper.cpp
borjafdezgauna/SimionZoo
42dd3106d60077bea7e6b64b9f25c3268adc3be8
[ "Zlib" ]
25
2019-02-20T19:30:52.000Z
2022-01-01T03:15:21.000Z
/* SimionZoo: A framework for online model-free Reinforcement Learning on continuous control problems Copyright (c) 2016 SimionSoft. https://github.com/simionsoft 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 "cntk-network.h" #include "cntk-wrapper.h" #define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__) void CNTKWrapper::setDevice(bool useGPU) { #pragma EXPORT if (useGPU) CNTK::DeviceDescriptor::TrySetDefaultDevice(CNTK::DeviceDescriptor::GPUDevice(0)); else CNTK::DeviceDescriptor::TrySetDefaultDevice(CNTK::DeviceDescriptor::CPUDevice()); } IDiscreteQFunctionNetwork* CNTKWrapper::getDiscreteQFunctionNetwork(vector<string> inputStateVariables, size_t numActionSteps , string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkDiscreteQFunctionNetwork(inputStateVariables, numActionSteps, networkLayersDefinition, learnerDefinition, useNormalization); } IContinuousQFunctionNetwork* CNTKWrapper::getContinuousQFunctionNetwork(vector<string> inputStateVariables, vector<string> inputActionVariables , string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkContinuousQFunctionNetwork(inputStateVariables, inputActionVariables, networkLayersDefinition, learnerDefinition, useNormalization); } IVFunctionNetwork* CNTKWrapper::getVFunctionNetwork(vector<string> inputStateVariables, string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkVFunctionNetwork(inputStateVariables, networkLayersDefinition, learnerDefinition, useNormalization); } IDeterministicPolicyNetwork* CNTKWrapper::getDeterministicPolicyNetwork(vector<string> inputStateVariables, vector<string> outputActionVariables, string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkDeterministicPolicyNetwork(inputStateVariables, outputActionVariables, networkLayersDefinition, learnerDefinition, useNormalization); }
47.75
226
0.829843
utercero
def7f729a001893eeecfe957d3b8dd36f6f156a3
94
hpp
C++
aa/aa_tools.hpp
salleaffaire/lmolly
62012a7219035bee90b9ad3f2b49625e09b0c206
[ "MIT" ]
null
null
null
aa/aa_tools.hpp
salleaffaire/lmolly
62012a7219035bee90b9ad3f2b49625e09b0c206
[ "MIT" ]
null
null
null
aa/aa_tools.hpp
salleaffaire/lmolly
62012a7219035bee90b9ad3f2b49625e09b0c206
[ "MIT" ]
null
null
null
#ifndef AA_TOOLS_HPP___ #define AA_TOOLS_HPP___ #include <iostream> #include <mutex> #endif
11.75
23
0.787234
salleaffaire
7206b81f6cf3a4c5f69f020f3bf4b01747102377
1,173
cpp
C++
Array/easy/414_Third_Maximum_Number/ThirdMaxNumber.cpp
quq99/Leetcode_notes
eb3bee5ed161a0feb4ce1d48b682c000c95b4be3
[ "MIT" ]
1
2019-05-16T23:18:17.000Z
2019-05-16T23:18:17.000Z
Array/easy/414_Third_Maximum_Number/ThirdMaxNumber.cpp
quq99/Leetcode_notes
eb3bee5ed161a0feb4ce1d48b682c000c95b4be3
[ "MIT" ]
null
null
null
Array/easy/414_Third_Maximum_Number/ThirdMaxNumber.cpp
quq99/Leetcode_notes
eb3bee5ed161a0feb4ce1d48b682c000c95b4be3
[ "MIT" ]
null
null
null
// ThirdMaxNumber.cpp #include<vector> using std::vector; class ThirdMaxNumber { public: int thirdMax(vector<int>& nums) { int first = INT_MIN; int second = first; int third = second; int count = 0; bool once = true; for (int i = 0; i < nums.size(); ++i) { // [1, 2, INT_MIN, INT_MIN] if (nums[i] == INT_MIN && once) { count++; once = false; } if (nums[i]==first || nums[i]==second) continue; if (nums[i] > first) { third = second; second = first; first = nums[i]; count++; } else if (nums[i] > second) { third = second; second = nums[i]; count++; } else if (nums[i] > third) { third = nums[i]; count++; } } if (count < 3) return first; else return third; } };
27.27907
64
0.351236
quq99
720bc63f6db2bc66bc41ab14f5f82b0035a24eca
1,711
cpp
C++
Assignment 3/Assignment 3/StudentEmployee.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 3/Assignment 3/StudentEmployee.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 3/Assignment 3/StudentEmployee.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
/* Assignment: 3 Description: Paycheck Calculator Author: Justin Harper WSU ID: 10696738 Completion Time: 8hrs In completing this program, I received help from the following people: myself version 1.0 I am happy with this version! */ #include "StudentEmployee.h" #include "Employee.h" #include <iostream> using namespace std; //constructor for the StudentEmployee class StudentEmployee::StudentEmployee(string name, int id, bool isWorking, int hrsWorked, bool workStudy, double wage) { setName(name); setEID(id); setStatus(isWorking); _hrsWorked = hrsWorked; _workStudy = workStudy; _wage = wage; } //StudentEmployee function to get the wage double StudentEmployee::getWage() const { return _wage; } //StudentEmployee function to set the wage void StudentEmployee::setWage(double wage) { _wage = wage; return; } //StudentEmployee function to get the hours worked int StudentEmployee::getHrsWorked() const { return _hrsWorked; } //StudentEmployee function to set the hours worked void StudentEmployee::setHrsWorked(int hrs) { _hrsWorked = hrs; return; } //StudentEmployee function to get the weekly pay double StudentEmployee::getWeeklyPay() const { return (_hrsWorked * _wage); } //StudentEmployee function to get the work study status bool StudentEmployee::isWorkStudy() const { return _workStudy; } //StudentEmployee function to set the work study status void StudentEmployee::setWorkStudy(bool ws) { _workStudy = ws; return; } //returns the string representaiton of a StudentEmployee object string StudentEmployee::toString() { string x = Employee::toString() + "\t" + to_string(_hrsWorked) + "\t" + boolstring(_workStudy) + "\t" + to_string(_wage); return x; }
18.397849
122
0.755114
justin-harper
720f18e0d69129ebaa192dbb61719c210937df35
9,610
hpp
C++
core/utils/bitpack.hpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
core/utils/bitpack.hpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
core/utils/bitpack.hpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2021 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #ifndef IRESEARCH_BITPACK_H #define IRESEARCH_BITPACK_H #include "shared.hpp" #include "store/data_output.hpp" #include "store/data_input.hpp" #include "utils/simd_utils.hpp" namespace iresearch { // ---------------------------------------------------------------------------- // --SECTION-- bit packing encode/decode helpers // ---------------------------------------------------------------------------- // // Normal packed block has the following structure: // <BlockHeader> // </NumberOfBits> // </BlockHeader> // </PackedData> // // In case if all elements in a block are equal: // <BlockHeader> // <ALL_EQUAL> // </BlockHeader> // </PackedData> // // ---------------------------------------------------------------------------- namespace bitpack { constexpr uint32_t ALL_EQUAL = 0U; // returns true if one can use run length encoding for the specified numberof bits constexpr bool rl(const uint32_t bits) noexcept { return ALL_EQUAL == bits; } // skip block of the specified size that was previously // written with the corresponding 'write_block' function inline void skip_block32(index_input& in, uint32_t size) { assert(size); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { in.read_vint(); } else { in.seek(in.file_pointer() + packed::bytes_required_32(size, bits)); } } // skip block of the specified size that was previously // written with the corresponding 'write_block' function inline void skip_block64(index_input& in, uint64_t size) { assert(size); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { in.read_vlong(); } else { in.seek(in.file_pointer() + packed::bytes_required_64(size, bits)); } } // writes block of 'size' 32 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<typename PackFunc> uint32_t write_block32( PackFunc&& pack, data_output& out, const uint32_t* RESTRICT decoded, uint32_t size, uint32_t* RESTRICT encoded) { assert(size); assert(encoded); assert(decoded); if (simd::all_equal<false>(decoded, size)) { out.write_byte(ALL_EQUAL); out.write_vint(*decoded); return ALL_EQUAL; } // prior AVX2 scalar version works faster for 32-bit values #ifdef HWY_CAP_GE256 const uint32_t bits = simd::maxbits<false>(decoded, size); #else const uint32_t bits = packed::maxbits32(decoded, decoded + size); #endif assert(bits); const size_t buf_size = packed::bytes_required_32(size, bits); std::memset(encoded, 0, buf_size); pack(decoded, encoded, size, bits); out.write_byte(static_cast<byte_type>(bits & 0xFF)); out.write_bytes(reinterpret_cast<byte_type*>(encoded), buf_size); return bits; } // writes block of 'Size' 32 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<size_t Size, typename PackFunc> uint32_t write_block32( PackFunc&& pack, data_output& out, const uint32_t* RESTRICT decoded, uint32_t* RESTRICT encoded) { static_assert(Size); assert(encoded); assert(decoded); if (simd::all_equal<false>(decoded, Size)) { out.write_byte(ALL_EQUAL); out.write_vint(*decoded); return ALL_EQUAL; } // prior AVX2 scalar version works faster for 32-bit values #ifdef HWY_CAP_GE256 const uint32_t bits = simd::maxbits<Size, false>(decoded); #else const uint32_t bits = packed::maxbits32(decoded, decoded + Size); #endif assert(bits); const size_t buf_size = packed::bytes_required_32(Size, bits); std::memset(encoded, 0, buf_size); pack(decoded, encoded, bits); out.write_byte(static_cast<byte_type>(bits & 0xFF)); out.write_bytes(reinterpret_cast<byte_type*>(encoded), buf_size); return bits; } // writes block of 'size' 64 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<typename PackFunc> uint32_t write_block64( PackFunc&& pack, data_output& out, const uint64_t* RESTRICT decoded, uint64_t size, uint64_t* RESTRICT encoded) { assert(size); assert(encoded); assert(decoded); if (simd::all_equal<false>(decoded, size)) { out.write_byte(ALL_EQUAL); out.write_vint(*decoded); return ALL_EQUAL; } // scalar version is always faster for 64-bit values const uint32_t bits = packed::maxbits64(decoded, decoded + size); const size_t buf_size = packed::bytes_required_64(size, bits); std::memset(encoded, 0, buf_size); pack(decoded, encoded, size, bits); out.write_byte(static_cast<byte_type>(bits & 0xFF)); out.write_bytes(reinterpret_cast<const byte_type*>(encoded), buf_size); return bits; } // writes block of 'Size' 64 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<size_t Size, typename PackFunc> uint32_t write_block64( PackFunc&& pack, data_output& out, const uint64_t* RESTRICT decoded, uint64_t* RESTRICT encoded) { static_assert(Size); return write_block64(std::forward<PackFunc>(pack), out, decoded, Size, encoded); } // reads block of 'Size' 32 bit integers from the stream // that was previously encoded with the corresponding // 'write_block32' function template<size_t Size, typename UnpackFunc> void read_block32( UnpackFunc&& unpack, data_input& in, uint32_t* RESTRICT encoded, uint32_t* RESTRICT decoded) { static_assert(Size); assert(encoded); assert(decoded); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { std::fill_n(decoded, Size, in.read_vint()); } else { const size_t required = packed::bytes_required_32(Size, bits); const auto* buf = in.read_buffer(required, BufferHint::NORMAL); if (buf) { unpack(decoded, reinterpret_cast<const uint32_t*>(buf), bits); return; } #ifdef IRESEARCH_DEBUG const auto read = in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); assert(read == required); UNUSED(read); #else in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); #endif // IRESEARCH_DEBUG unpack(decoded, encoded, bits); } } // reads block of 'size' 32 bit integers from the stream // that was previously encoded with the corresponding // 'write_block32' function template<typename UnpackFunc> void read_block32( UnpackFunc&& unpack, data_input& in, uint32_t* RESTRICT encoded, uint32_t size, uint32_t* RESTRICT decoded) { assert(size); assert(encoded); assert(decoded); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { std::fill_n(decoded, size, in.read_vint()); } else { const size_t required = packed::bytes_required_32(size, bits); const auto* buf = in.read_buffer(required, BufferHint::NORMAL); if (buf) { unpack(decoded, reinterpret_cast<const uint32_t*>(buf), size, bits); return; } #ifdef IRESEARCH_DEBUG const auto read = in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); assert(read == required); UNUSED(read); #else in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); #endif // IRESEARCH_DEBUG unpack(decoded, encoded, size, bits); } } // reads block of 'Size' 64 bit integers from the stream // that was previously encoded with the corresponding // 'write_block64' function template<size_t Size, typename UnpackFunc> void read_block64( UnpackFunc&& unpack, data_input& in, uint64_t* RESTRICT encoded, uint64_t* RESTRICT decoded) { static_assert(Size); assert(encoded); assert(decoded); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { std::fill_n(decoded, Size, in.read_vlong()); } else { const size_t required = packed::bytes_required_64(Size, bits); const auto* buf = in.read_buffer(required, BufferHint::NORMAL); if (buf) { unpack(decoded, reinterpret_cast<const uint64_t*>(buf), bits); return; } #ifdef IRESEARCH_DEBUG const auto read = in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); assert(read == required); UNUSED(read); #else in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); #endif // IRESEARCH_DEBUG unpack(decoded, encoded, bits); } } } // bitpack } // iresearch #endif // IRESEARCH_BITPACK_H
27.936047
82
0.661394
geenen124
721255ad57354655e55fb97d74dae1a9ec15c863
8,168
hpp
C++
include/codegen/include/Polyglot/Localization.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Polyglot/Localization.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Polyglot/Localization.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:10 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: UnityEngine.ScriptableObject #include "UnityEngine/ScriptableObject.hpp" // Including type: Polyglot.Language #include "Polyglot/Language.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Polyglot namespace Polyglot { // Forward declaring type: LocalizationDocument class LocalizationDocument; // Forward declaring type: LocalizationAsset class LocalizationAsset; // Forward declaring type: LanguageDirection struct LanguageDirection; // Forward declaring type: ILocalize class ILocalize; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine::Events namespace UnityEngine::Events { // Forward declaring type: UnityEvent class UnityEvent; } // Forward declaring namespace: System namespace System { // Forward declaring type: String class String; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: SystemLanguage struct SystemLanguage; } // Completed forward declares // Type namespace: Polyglot namespace Polyglot { // Autogenerated type: Polyglot.Localization class Localization : public UnityEngine::ScriptableObject { public: // static field const value: static private System.String KeyNotFound static constexpr const char* KeyNotFound = "[{0}]"; // Get static field: static private System.String KeyNotFound static ::Il2CppString* _get_KeyNotFound(); // Set static field: static private System.String KeyNotFound static void _set_KeyNotFound(::Il2CppString* value); // private Polyglot.LocalizationDocument customDocument // Offset: 0x18 Polyglot::LocalizationDocument* customDocument; // private System.Collections.Generic.List`1<Polyglot.LocalizationAsset> inputFiles // Offset: 0x20 System::Collections::Generic::List_1<Polyglot::LocalizationAsset*>* inputFiles; // Get static field: static private Polyglot.Localization instance static Polyglot::Localization* _get_instance(); // Set static field: static private Polyglot.Localization instance static void _set_instance(Polyglot::Localization* value); // private System.Collections.Generic.List`1<Polyglot.Language> supportedLanguages // Offset: 0x28 System::Collections::Generic::List_1<Polyglot::Language>* supportedLanguages; // private Polyglot.Language selectedLanguage // Offset: 0x30 Polyglot::Language selectedLanguage; // private Polyglot.Language fallbackLanguage // Offset: 0x34 Polyglot::Language fallbackLanguage; // public UnityEngine.Events.UnityEvent Localize // Offset: 0x38 UnityEngine::Events::UnityEvent* Localize; // public Polyglot.LocalizationDocument get_CustomDocument() // Offset: 0x18FE2B0 Polyglot::LocalizationDocument* get_CustomDocument(); // public System.Collections.Generic.List`1<Polyglot.LocalizationAsset> get_InputFiles() // Offset: 0x18FE2B8 System::Collections::Generic::List_1<Polyglot::LocalizationAsset*>* get_InputFiles(); // static public Polyglot.Localization get_Instance() // Offset: 0x18FDE24 static Polyglot::Localization* get_Instance(); // static public System.Void set_Instance(Polyglot.Localization value) // Offset: 0x18FE374 static void set_Instance(Polyglot::Localization* value); // static private System.Boolean get_HasInstance() // Offset: 0x18FE2C0 static bool get_HasInstance(); // public System.Collections.Generic.List`1<Polyglot.Language> get_SupportedLanguages() // Offset: 0x18FE3CC System::Collections::Generic::List_1<Polyglot::Language>* get_SupportedLanguages(); // public Polyglot.LanguageDirection get_SelectedLanguageDirection() // Offset: 0x18FE3D4 Polyglot::LanguageDirection get_SelectedLanguageDirection(); // private Polyglot.LanguageDirection GetLanguageDirection(Polyglot.Language language) // Offset: 0x18FE3E8 Polyglot::LanguageDirection GetLanguageDirection(Polyglot::Language language); // public System.Int32 get_SelectedLanguageIndex() // Offset: 0x18FE104 int get_SelectedLanguageIndex(); // public Polyglot.Language get_SelectedLanguage() // Offset: 0x18FE404 Polyglot::Language get_SelectedLanguage(); // public System.Void set_SelectedLanguage(Polyglot.Language value) // Offset: 0x18FE40C void set_SelectedLanguage(Polyglot::Language value); // private System.Boolean IsLanguageSupported(Polyglot.Language language) // Offset: 0x18FE4F4 bool IsLanguageSupported(Polyglot::Language language); // public System.Void InvokeOnLocalize() // Offset: 0x18FE574 void InvokeOnLocalize(); // public System.Collections.Generic.List`1<System.String> get_EnglishLanguageNames() // Offset: 0x18FE090 System::Collections::Generic::List_1<::Il2CppString*>* get_EnglishLanguageNames(); // public System.Collections.Generic.List`1<System.String> get_LocalizedLanguageNames() // Offset: 0x18FE824 System::Collections::Generic::List_1<::Il2CppString*>* get_LocalizedLanguageNames(); // public System.String get_EnglishLanguageName() // Offset: 0x18FE898 ::Il2CppString* get_EnglishLanguageName(); // public System.String get_LocalizedLanguageName() // Offset: 0x18FE910 ::Il2CppString* get_LocalizedLanguageName(); // public System.Void SelectLanguage(System.Int32 selected) // Offset: 0x18FE958 void SelectLanguage(int selected); // public System.Void SelectLanguage(Polyglot.Language selected) // Offset: 0x18FE9E0 void SelectLanguage(Polyglot::Language selected); // public Polyglot.Language ConvertSystemLanguage(UnityEngine.SystemLanguage selected) // Offset: 0x18FE9E4 Polyglot::Language ConvertSystemLanguage(UnityEngine::SystemLanguage selected); // public System.Void AddOnLocalizeEvent(Polyglot.ILocalize localize) // Offset: 0x18FDEB0 void AddOnLocalizeEvent(Polyglot::ILocalize* localize); // public System.Void RemoveOnLocalizeEvent(Polyglot.ILocalize localize) // Offset: 0x18FEA20 void RemoveOnLocalizeEvent(Polyglot::ILocalize* localize); // static public System.String Get(System.String key) // Offset: 0x18FE8E0 static ::Il2CppString* Get(::Il2CppString* key); // static public System.String Get(System.String key, Polyglot.Language language) // Offset: 0x18FEB0C static ::Il2CppString* Get(::Il2CppString* key, Polyglot::Language language); // static public System.Boolean KeyExist(System.String key) // Offset: 0x18FEF90 static bool KeyExist(::Il2CppString* key); // static public System.Collections.Generic.List`1<System.String> GetKeys() // Offset: 0x18FF044 static System::Collections::Generic::List_1<::Il2CppString*>* GetKeys(); // static public System.String GetFormat(System.String key, System.Object[] arguments) // Offset: 0x18FF12C static ::Il2CppString* GetFormat(::Il2CppString* key, ::Array<::Il2CppObject*>* arguments); // public System.Boolean InputFilesContains(Polyglot.LocalizationDocument doc) // Offset: 0x18FF184 bool InputFilesContains(Polyglot::LocalizationDocument* doc); // public System.Void .ctor() // Offset: 0x18FF2E8 // Implemented from: UnityEngine.ScriptableObject // Base method: System.Void ScriptableObject::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static Localization* New_ctor(); }; // Polyglot.Localization } DEFINE_IL2CPP_ARG_TYPE(Polyglot::Localization*, "Polyglot", "Localization"); #pragma pack(pop)
44.879121
95
0.74192
Futuremappermydud
7218cd9b1bb2200cc5bc6da3bd7e94a6b954870a
17,880
cpp
C++
src/engines/Examples/Basic/05b-ObsGroupAppend.cpp
Gibies/ioda
5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75
[ "Apache-2.0" ]
1
2021-06-09T16:11:50.000Z
2021-06-09T16:11:50.000Z
src/engines/Examples/Basic/05b-ObsGroupAppend.cpp
Gibies/ioda
5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75
[ "Apache-2.0" ]
null
null
null
src/engines/Examples/Basic/05b-ObsGroupAppend.cpp
Gibies/ioda
5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75
[ "Apache-2.0" ]
3
2021-06-09T16:12:02.000Z
2021-11-14T09:19:25.000Z
/* * (C) Copyright 2020-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \addtogroup ioda_cxx_ex * * @{ * * \defgroup ioda_cxx_ex_5b Ex 5b: Appending to ObsGroups * \brief Appending to ObsGroups * \see 05b-ObsGroupAppend.cpp for comments and the walkthrough. * * @{ * * \file 05b-ObsGroupAppend.cpp * \brief ObsGroup * * The ObsGroup class is derived from the Group class and provides some help in * organizing your groups, variables, attributes and dimension scales into a cohesive * structure intended to house observation data. In this case "structure" refers to the * hierarchical layout of the groups and the proper management of dimension scales * associated with the variables. * * The ObsGroup and underlying layout policies (internal to ioda-engines) present a stable * logical group hierarchical layout to the client while keeping the actual layout implemented * in the backend open to change. The logical "frontend" layout appears to the client to be * as shown below: * * layout notes * * / top-level group * nlocs dimension scales (variables, coordinate values) * nchans * ... * ObsValue/ group: observational measurement values * brightness_temperature variable: Tb, 2D, nlocs X nchans * air_temperature variable: T, 1D, nlocs * ... * ObsError/ group: observational error estimates * brightness_temperature * air_temperature * ... * PreQC/ group: observational QC marks from data provider * brightness_temperature * air_temperature * ... * MetaData/ group: meta data associated with locations * latitude * longitude * datetime * ... * ... * * It is intended to keep this layout stable so that the client interface remains stable. * The actual layout used in the various backends can optionally be organized differently * according to their needs. * * The ObsGroup class also assists with the management of dimension scales. For example, if * a dimension is resized, the ObsGroup::resize function will resize the dimension scale * along with all variables that use that dimension scale. * * The basic ideas is to dimension observation data with nlocs as the first dimension, and * allow nlocs to be resizable so that it's possible to incrementally append data along * the nlocs (1st) dimension. For data that have rank > 1, the second through nth dimensions * are of fixed size. For example, brightness_temperature can be store as 2D data with * dimensions (nlocs, nchans). * * \author Stephen Herbener (stephenh@ucar.edu), Ryan Honeyager (honeyage@ucar.edu) **/ #include <array> // Arrays are fixed-length vectors. #include <iomanip> // std::setw #include <iostream> // We want I/O. #include <numeric> // std::iota #include <string> // We want strings #include <valarray> // Like a vector, but can also do basic element-wise math. #include <vector> // We want vectors #include "Eigen/Dense" // Eigen Arrays and Matrices #include "ioda/Engines/Factory.h" // Used to kickstart the Group engine. #include "ioda/Exception.h" // Exceptions and debugging #include "ioda/Group.h" // Groups have attributes. #include "ioda/ObsGroup.h" #include "unsupported/Eigen/CXX11/Tensor" // Eigen Tensors int main(int argc, char** argv) { using namespace ioda; // All of the ioda functions are here. using std::cerr; using std::endl; using std::string; using std::vector; try { // It's possible to transfer data in smaller pieces so you can, for example, avoid // reading the whole input file into memory. Transferring by pieces can also be useful // when you don't know a priori how many locations are going to be read in. To accomplish // this, you set the maximum size of the nlocs dimension to Unlimited and use the // ObsSpace::generate function to allocate more space at the end of each variable for // the incoming section. // // For this example, we'll use the same data as in example 05a, but transfer it to // the backend in four pieces, 10 locations at a time. // Create the backend. For this code we are using a factory function, // constructFromCmdLine, made for testing purposes, which allows one to specify // a backend from the command line using the "--ioda-engine-options" option. // // There exists another factory function, constructBackend, which allows you // to create a backend without requiring the command line option. The signature // for this function is: // // constructBackend(BackendNames, BackendCreationParameters &); // // // BackendNames is an enum type with values: // Hdf5File - file backend using HDF5 file // ObsStore - in-memory backend // // BackendCreationParameters is a C++ structure with members: // fileName - string, used for file backend // // actions - enum BackendFileActions type: // Create - create a new file // Open - open an existing file // // createMode - enum BackendCreateModes type: // Truncate_If_Exists - overwrite existing file // Fail_If_Exists - throw exception if file exists // // openMode - enum BackendOpenModes types: // Read_Only - open in read only mode // Read_Write - open in modify mode // // Here are some code examples: // // Create backend using an hdf5 file for writing: // // Engines::BackendNames backendName; // backendName = Engines::BackendNames::Hdf5File; // // Engines::BackendCreationParameters backendParams; // backendParams.fileName = fileName; // backendParams.action = Engines::BackendFileActions::Create; // backendParams.createMode = Engines::BackendCreateModes::Truncate_If_Exists; // // Group g = constructBackend(backendName, backendParams); // // Create backend using an hdf5 file for reading: // // Engines::BackendNames backendName; // backendName = Engines::BackendNames::Hdf5File; // // Engines::BackendCreationParameters backendParams; // backendParams.fileName = fileName; // backendParams.action = Engines::BackendFileActions::Open; // backendParams.openMode = Engines::BackendOpenModes::Read_Only; // // Group g = constructBackend(backendName, backendParams); // // Create an in-memory backend: // // Engines::BackendNames backendName; // backendName = Engines::BackendNames::ObsStore; // // Engines::BackendCreationParameters backendParams; // // Group g = constructBackend(backendName, backendParams); // // Create the backend using the command line construct function Group g = Engines::constructFromCmdLine(argc, argv, "Example-05b.hdf5"); // Create an ObsGroup object using the ObsGroup::generate function. This function // takes a Group arguemnt (the backend we just created above) and a vector of dimension // creation specs. const int numLocs = 40; const int numChans = 30; const int sectionSize = 10; // experiment with different sectionSize values // The NewDimensionsScales_t is a vector, that holds specs for one dimension scale // per element. An individual dimension scale spec is held in a NewDimensionsScale // object, whose constructor arguments are: // 1st - dimension scale name // 2nd - size of dimension. May be zero. // 3rd - maximum size of dimension // resizeable dimensions are said to have "unlimited" size, so there // is a built-in variable ("Unlimited") that can be used to denote // unlimited size. If Unspecified (the default), we assume that the // maximum size is the same as the initial size (the previous parameter). // 4th - suggested chunk size for dimension (and associated variables). // This defaults to the initial size. This parameter must be nonzero. If // the initial size is zero, it must be explicitly specified. // // For transferring data in pieces, make sure that nlocs maximum dimension size is // set to Unlimited. We'll set the initial size of nlocs to the sectionSize (10). ioda::NewDimensionScales_t newDims{ NewDimensionScale<int>("nlocs", sectionSize, Unlimited), NewDimensionScale<int>("nchans", numChans) }; // Construct an ObsGroup object, with 2 dimensions nlocs, nchans, and attach // the backend we constructed above. Under the hood, the ObsGroup::generate function // initializes the dimension coordinate values to index numbering 1..n. This can be // overwritten with other coordinate values if desired. ObsGroup og = ObsGroup::generate(g, newDims); // We now have the top-level group containing the two dimension scales. We need // Variable objects for these dimension scales later on for creating variables so // build those now. ioda::Variable nlocsVar = og.vars["nlocs"]; ioda::Variable nchansVar = og.vars["nchans"]; // Next let's create the variables. The variable names should be specified using the // hierarchy as described above. For example, the variable brightness_temperature // in the group ObsValue is specified in a string as "ObsValue/brightness_temperature". string tbName = "ObsValue/brightness_temperature"; string latName = "MetaData/latitude"; string lonName = "MetaData/longitude"; // Set up the creation parameters for the variables. All three variables in this case // are float types, so they can share the same creation parameters object. ioda::VariableCreationParameters float_params; float_params.chunk = true; // allow chunking float_params.compressWithGZIP(); // compress using gzip float_params.setFillValue<float>(-999); // set the fill value to -999 // Create the variables. Note the use of the createWithScales function. This should // always be used when working with an ObsGroup object. Variable tbVar = og.vars.createWithScales<float>(tbName, {nlocsVar, nchansVar}, float_params); Variable latVar = og.vars.createWithScales<float>(latName, {nlocsVar}, float_params); Variable lonVar = og.vars.createWithScales<float>(lonName, {nlocsVar}, float_params); // Add attributes to variables. In this example, we are adding enough attribute // information to allow Panoply to be able to plot the ObsValue/brightness_temperature // variable. Note the "coordinates" attribute on tbVar. It is sufficient to just // give the variable names (without the group structure) to Panoply (which apparently // searches the entire group structure for these names). If you want to follow this // example in your code, just give the variable names without the group prefixes // to insulate your code from any subsequent group structure changes that might occur. tbVar.atts.add<std::string>("coordinates", {"longitude latitude nchans"}, {1}) .add<std::string>("long_name", {"ficticious brightness temperature"}, {1}) .add<std::string>("units", {"K"}, {1}) .add<float>("valid_range", {100.0, 400.0}, {2}); latVar.atts.add<std::string>("long_name", {"latitude"}, {1}) .add<std::string>("units", {"degrees_north"}, {1}) .add<float>("valid_range", {-90.0, 90.0}, {2}); lonVar.atts.add<std::string>("long_name", {"longitude"}, {1}) .add<std::string>("units", {"degrees_east"}, {1}) .add<float>("valid_range", {-360.0, 360.0}, {2}); // Let's create some data for this example. Eigen::ArrayXXf tbData(numLocs, numChans); std::vector<float> lonData(numLocs); std::vector<float> latData(numLocs); float midLoc = static_cast<float>(numLocs) / 2.0f; float midChan = static_cast<float>(numChans) / 2.0f; for (std::size_t i = 0; i < numLocs; ++i) { lonData[i] = static_cast<float>(i % 8) * 3.0f; // We use static code analysis tools to check for potential bugs // in our source code. On the next line, the clang-tidy tool warns about // our use of integer division before casting to a float. Since there is // no actual bug, we indicate this with NOLINT. latData[i] = static_cast<float>(i / 8) * 3.0f; // NOLINT(bugprone-integer-division) for (std::size_t j = 0; j < numChans; ++j) { float del_i = static_cast<float>(i) - midLoc; float del_j = static_cast<float>(j) - midChan; tbData(i, j) = 250.0f + sqrt(del_i * del_i + del_j * del_j); } } // Transfer the data piece by piece. In this case we are moving consecutive, // contiguous pieces from the source to the backend. // // Things to consider: // If numLocs/sectionSize has a remainder, then the final section needs to be // smaller to match up. // // The new size for resizing the variables needs to be the current size // plus the count for this section. std::size_t numLocsTransferred = 0; std::size_t isection = 1; int fwidth = 10; std::cout << "Transferring data in sections to backend:" << std::endl << std::endl; std::cout << std::setw(fwidth) << "Section" << std::setw(fwidth) << "Start" << std::setw(fwidth) << "Count" << std::setw(fwidth) << "Resize" << std::endl; while (numLocsTransferred < numLocs) { // Figure out the starting point and size (count) for the current piece. std::size_t sectionStart = numLocsTransferred; std::size_t sectionCount = sectionSize; if ((sectionStart + sectionCount) > numLocs) { sectionCount = numLocs - sectionStart; } // Figure out the new size for the nlocs dimension Dimensions nlocsDims = nlocsVar.getDimensions(); Dimensions_t nlocsNewSize = (isection == 1) ? sectionCount : nlocsDims.dimsCur[0] + sectionCount; // Print out stats so you can see what's going on std::cout << std::setw(fwidth) << isection << std::setw(fwidth) << sectionStart << std::setw(fwidth) << sectionCount << std::setw(fwidth) << nlocsNewSize << std::endl; // Resize the nlocs dimension og.resize({std::pair<Variable, Dimensions_t>(nlocsVar, nlocsNewSize)}); // Create selection objects for transferring the data // We'll use the HDF5 hyperslab style of selection which denotes a start index // and count for each dimension. The start and count values need to be vectors // where the ith entry corresponds to the ith dimension of the variable. Latitue // and longitude are 1D and Tb is 2D. Start with 1D starts and counts denoting // the sections to transfer for lat and lon, then add the start and count values // for channels and transfer Tb. // starts and counts for lat and lon std::vector<Dimensions_t> starts(1, sectionStart); std::vector<Dimensions_t> counts(1, sectionCount); Selection feSelect; feSelect.extent({nlocsNewSize}).select({SelectionOperator::SET, starts, counts}); Selection beSelect; beSelect.select({SelectionOperator::SET, starts, counts}); latVar.write<float>(latData, feSelect, beSelect); lonVar.write<float>(lonData, feSelect, beSelect); // Add the start and count values for the channels dimension. We will select // all channels, so start is zero, and count is numChans starts.push_back(0); counts.push_back(numChans); Selection feSelect2D; feSelect2D.extent({nlocsNewSize, numChans}).select({SelectionOperator::SET, starts, counts}); Selection beSelect2D; beSelect2D.select({SelectionOperator::SET, starts, counts}); tbVar.writeWithEigenRegular(tbData, feSelect2D, beSelect2D); numLocsTransferred += sectionCount; isection++; } // The ObsGroup::generate program has, under the hood, automatically assigned // the coordinate values for nlocs and nchans dimension scale variables. The // auto-assignment uses the values 1..n upon creation. Since we resized nlocs, // the coordinates at this point will be set to 1..sectionSize followed by all // zeros to the end of the variable. This can be addressed two ways: // // 1. In the above loop, add a write to the nlocs variable with the corresponding // coordinate values for each section. // 2. In the case where you simply want 1..n as the coordinate values, wait // until transferring all the sections of variable data, check the size // of the nlocs variable, and write the entire 1..n values to the variable. // // We'll do option 2 here int nlocsSize = gsl::narrow<int>(nlocsVar.getDimensions().dimsCur[0]); std::vector<int> nlocsVals(nlocsSize); std::iota(nlocsVals.begin(), nlocsVals.end(), 1); nlocsVar.write(nlocsVals); // Done! } catch (const std::exception& e) { ioda::unwind_exception_stack(e); return 1; } return 0; }
48.455285
100
0.654698
Gibies
721ba8ca705716f1448757db5bf34109112c4d89
981
cpp
C++
Online Assignment 01/Version C/Version C - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
19
2021-04-28T13:32:15.000Z
2022-03-08T11:52:59.000Z
Online Assignment 01/Version C/Version C - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
5
2021-03-03T08:06:15.000Z
2021-12-26T18:14:45.000Z
Online Assignment 01/Version C/Version C - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
27
2021-01-18T22:35:01.000Z
2022-02-22T19:52:19.000Z
// Paper Version : C #include<iostream> using namespace std; // Class declarration class Lab { private: int labID; int capacity; public: void setLabDetails(int lID, int c); int getCapacity(); }; int main() { // Create an Objects Lab l1, l2, l3; // Set values to Objects l1.setLabDetails(401, 60); l2.setLabDetails(402, 40); l3.setLabDetails(403, 30); int capacity; cout << "Insert Capacity : "; cin >> capacity; if(capacity <= l3.getCapacity()){ cout << "Lab 403" << endl; } else if(capacity <= l2.getCapacity()){ cout << "Lab 402" << endl; } else if(capacity <= l1.getCapacity()){ cout << "Lab 401" << endl; } else{ cout << "Invalid input" << endl; } return 0; } // Class methods definition void Lab::setLabDetails(int lID, int c) { labID = lID; capacity = c; } int Lab::getCapacity() { return capacity; }
16.913793
43
0.552497
GIHAA
721def850ee1995eaafab2a11d042e460b26374e
761
cpp
C++
Source/Dynamics/RigidBody/SphericalJoint.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
Source/Dynamics/RigidBody/SphericalJoint.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
Source/Dynamics/RigidBody/SphericalJoint.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
#include "SphericalJoint.h" //#include "Dynamics/RigidBody/RigidUtil.h" namespace PhysIKA { SphericalJoint::SphericalJoint(std::string name) : Joint(name) { } SphericalJoint::SphericalJoint(Node* predecessor, Node* successor) : Joint(predecessor, successor) { } void SphericalJoint::setJointInfo(const Vector3f& r) { for (int i = 0; i < 3; ++i) { Vector3f unit_axis; unit_axis[i] = 1; Vector3f v = unit_axis.cross(r); this->m_S(0, i) = unit_axis[0]; this->m_S(1, i) = unit_axis[1]; this->m_S(2, i) = unit_axis[2]; this->m_S(3, i) = -v[0]; this->m_S(4, i) = -v[1]; this->m_S(5, i) = -v[2]; this->m_S.getBases()[i].normalize(); } } } // namespace PhysIKA
21.138889
66
0.579501
weikm
721fc0dd32783489fb6b161f3d1cde85534f2d79
4,049
cc
C++
squid/squid3-3.3.8.spaceify/src/acl/DestinationIp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/acl/DestinationIp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/acl/DestinationIp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * DEBUG: section 28 Access Control * AUTHOR: Duane Wessels * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org> */ #include "squid.h" #include "acl/DestinationIp.h" #include "acl/FilledChecklist.h" #include "client_side.h" #include "comm/Connection.h" #include "HttpRequest.h" #include "SquidConfig.h" char const * ACLDestinationIP::typeString() const { return "dst"; } int ACLDestinationIP::match(ACLChecklist *cl) { ACLFilledChecklist *checklist = Filled(cl); // Bug 3243: CVE 2009-0801 // Bypass of browser same-origin access control in intercepted communication // To resolve this we will force DIRECT and only to the original client destination. // In which case, we also need this ACL to accurately match the destination if (Config.onoff.client_dst_passthru && (checklist->request->flags.intercepted || checklist->request->flags.spoofClientIp)) { assert(checklist->conn() && checklist->conn()->clientConnection != NULL); return ACLIP::match(checklist->conn()->clientConnection->local); } const ipcache_addrs *ia = ipcache_gethostbyname(checklist->request->GetHost(), IP_LOOKUP_IF_MISS); if (ia) { /* Entry in cache found */ for (int k = 0; k < (int) ia->count; ++k) { if (ACLIP::match(ia->in_addrs[k])) return 1; } return 0; } else if (!checklist->request->flags.destinationIpLookedUp) { /* No entry in cache, lookup not attempted */ debugs(28, 3, "aclMatchAcl: Can't yet compare '" << name << "' ACL for '" << checklist->request->GetHost() << "'"); checklist->changeState (DestinationIPLookup::Instance()); return 0; } else { return 0; } } DestinationIPLookup DestinationIPLookup::instance_; DestinationIPLookup * DestinationIPLookup::Instance() { return &instance_; } void DestinationIPLookup::checkForAsync(ACLChecklist *cl)const { ACLFilledChecklist *checklist = Filled(cl); checklist->asyncInProgress(true); ipcache_nbgethostbyname(checklist->request->GetHost(), LookupDone, checklist); } void DestinationIPLookup::LookupDone(const ipcache_addrs *, const DnsLookupDetails &details, void *data) { ACLFilledChecklist *checklist = Filled((ACLChecklist*)data); assert (checklist->asyncState() == DestinationIPLookup::Instance()); checklist->request->flags.destinationIpLookedUp=true; checklist->request->recordLookup(details); checklist->asyncInProgress(false); checklist->changeState (ACLChecklist::NullState::Instance()); checklist->matchNonBlocking(); } ACL * ACLDestinationIP::clone() const { return new ACLDestinationIP(*this); }
34.905172
129
0.694492
spaceify
7220b26be69e6aee31ac9da80d0d52fbbfac3d00
672
hpp
C++
src/ProjectForecast/Views/HumanView.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2019-04-09T13:03:11.000Z
2021-01-27T04:58:29.000Z
src/ProjectForecast/Views/HumanView.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
2
2017-02-06T03:48:45.000Z
2020-08-31T01:30:10.000Z
src/ProjectForecast/Views/HumanView.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2020-06-28T08:19:53.000Z
2020-06-28T16:30:19.000Z
#pragma once #include "../InputControllers/InputControllers.hpp" #include "KEngine/Interfaces/IEvent.hpp" #include "KEngine/Views/HumanView.hpp" namespace sf { class Event; } namespace pf { class HumanView : public ke::HumanView { public: HumanView(); virtual ~HumanView(); virtual void attachEntity(ke::EntityId entityId) override; virtual void update(ke::Time elapsedTime) override; private: void handleWindowEvent(ke::EventSptr event); std::string testTextBuffer; ke::MouseInputControllerUptr mouseController; ke::KeyboardInputControllerUptr keyboardController; }; }
19.2
66
0.678571
yxbh
7224c60576efa277fb91c372b8811437eb8fbbbc
2,450
cpp
C++
11_CPP/08_CPP08/ex01/span.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/08_CPP08/ex01/span.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/08_CPP08/ex01/span.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* span.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tderwedu <tderwedu@student.s19.be> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/25 18:41:16 by tderwedu #+# #+# */ /* Updated: 2021/10/27 10:31:27 by tderwedu ### ########.fr */ /* */ /* ************************************************************************** */ #include "span.hpp" /* ======================= CONSTRUCTORS / DESTRUCTORS ======================= */ Span::Span(int n) : _N(n) {} Span::Span(Span const& src): _N(src._N), _vec(src._vec) {} Span::~Span() {} /* ============================ MEMBER FUNCTIONS ============================ */ void Span::addNumber(int nbr) { if (_vec.size() == _N) throw OutOfRangeException(); _vec.push_back(nbr); } int Span::shortestSpan(void) const { std::vector<int> diff(_vec); std::vector<int> sorted(_vec); if (_N < 2) throw NotEnoughItemsException(); std::sort(sorted.begin(), sorted.end()); std::transform(++sorted.begin(), sorted.end(), sorted.begin(), diff.begin(), std::minus<int>()); return (*std::min_element(diff.begin(), --diff.end())); } int Span::longestSpan(void) const { int min; int max; if (_N < 2) throw NotEnoughItemsException(); min = *std::min_element(_vec.begin(), _vec.end()); max = *std::max_element(_vec.begin(), _vec.end()); return (max - min); } /* =========================== OPERATOR OVERLOADS =========================== */ Span& Span::operator=(Span const& src) { if (this != &src) { _N = src._N; _vec = src._vec; } return (*this); } int& Span::operator[](t_ui i) { if (i > _N) throw OutOfRangeException(); return _vec[i]; } /* =============================== EXCEPTIONS =============================== */ char const* Span::OutOfRangeException::what() const throw() { return "Out Of Range"; } char const* Span::NotEnoughItemsException::what() const throw() { return "Not Enough Items"; }
28.488372
97
0.388571
tderwedu
7227476512d2e151478de9c3458c12f99b947667
4,319
cpp
C++
src/main.cpp
tbukic/CubicSpline
f851ffeca38c89ef124bd4cadecf189a6373596c
[ "MIT" ]
2
2020-04-13T20:15:48.000Z
2021-03-18T08:44:50.000Z
src/main.cpp
tbukic/CubicSpline
f851ffeca38c89ef124bd4cadecf189a6373596c
[ "MIT" ]
null
null
null
src/main.cpp
tbukic/CubicSpline
f851ffeca38c89ef124bd4cadecf189a6373596c
[ "MIT" ]
null
null
null
/* * main.cpp * * Created on: Nov, 2015 * Author: Tomislav */ #include <cstdlib> #include <iostream> #include <fstream> #include <memory> #include <utility> #include <string> #include <stdexcept> #include <sstream> #include "CubicSpline/CubicSpline.h" using node = CubicSpline::node; using function = CubicSpline::function; using function_ptr = CubicSpline::function_ptr; using second_derivatives = std::pair<double, double>; using function_data = std::pair< function_ptr, std::unique_ptr<second_derivatives> >; using spline_ptr = std::unique_ptr<CubicSpline>; std::istream & operator>>(std::istream & input, function_data & data) { data.first->clear(); std::string readed; while (std::getline(input, readed)) { if (readed.empty()) { // reads until empty line break; } std::istringstream s_stream(readed); double point, value; if (!(s_stream >> point) || !(s_stream >> value) || !s_stream.eof()) { throw std::runtime_error("Bad input!"); } data.first->push_back(node(point, value)); } std::getline(input, readed); std::istringstream s_stream(readed); if ( !(s_stream >> data.second->first) || !(s_stream >> data.second->second) || !s_stream.eof() ) { throw std::runtime_error("Bad input!"); } return input; } void run_interpolation(spline_ptr spline) { const std::string EXIT_INPUT = "exit", PROMPT = ">"; std::cout << "Function is defined on interval [" << spline->min_defined() << ", " << spline->max_defined() << "]." << std::endl << "Nodes are:" << std::endl << std::endl << spline->nodes_printer << std::endl << "Interpolation starts. To quit program, " << "type: '" << EXIT_INPUT << "'. " << std::endl; std::string input; bool show_message = true; while(true) { if (show_message) { std::cout << "Enter value you want to interpolate:" << std::endl; } else { show_message = true; } std::cout << PROMPT; std::getline(std::cin, input); if (EXIT_INPUT == input) { return; } if ("nodes" == input) { std::cout << spline->nodes_printer; continue; } std::stringstream s_stream(input); double x; if (!(s_stream >> x) || !s_stream.eof()) { std::cout << "Input is not a number." << std::endl; continue; } if (!(*spline)[x]) { std::cout << "Value " << x << " is not in domain of the spline." << std::endl << "Spline is defined on interval [" << spline->min_defined() << ", " << spline->max_defined() << "]." << std::endl; continue; } std::cout << "spline(" << x << ")=" << (*spline)(x) << std::endl; show_message = false; } } int main(int argc, char * argv[]) { function_data data = std::make_pair( function_ptr(new function()), std::unique_ptr<second_derivatives>(new second_derivatives()) ); if (argc == 1) { // reading from console: try { std::cout << "Enter data for nodes and second derivatives." << std::endl << "In every row, enter one node and it's" << " functional value, separated by blanks." << std::endl << "After entering data for all nodes, enter empty line," << " and after that," << std::endl << "enter values of second derivatives " << "in first and last node, separated by blanks." << std::endl; std::cin >> data; } catch (std::exception & e) { std::cout << "Error in input." << std::endl; return EXIT_FAILURE; } } else if (argc == 2) { // reading from file (speeds up testing!): std::ifstream input(argv[1]); if (!input.good()) { input.close(); std::cout << "File does not exist." << std::endl; return EXIT_FAILURE; } try { input >> data; } catch (std::exception & e) { input.close(); std::cout << "File is badly formated." << std::endl; return EXIT_FAILURE; } input.close(); } else { // bad arguments std::cout << "Program doesn't work with more than 1 argument." << std::endl; return EXIT_FAILURE; } try { run_interpolation( std::move(spline_ptr(new CubicSpline( std::move(data.first), data.second->first, data.second->second ))) ); data.first = nullptr; } catch (std::runtime_error & e){ std::cout << e.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cout << "Error in program." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
24.821839
72
0.611253
tbukic
722ddf61e7b1087a84fcfaaa46ec96d86a796161
949
cpp
C++
src/lib/base/Fitness.cpp
cantordust/cortex
0afe4b8c8c3e1b103541188301c3f445ee5d165d
[ "MIT" ]
2
2017-07-04T03:17:15.000Z
2017-07-04T22:38:59.000Z
src/lib/base/Fitness.cpp
cantordust/cortex
0afe4b8c8c3e1b103541188301c3f445ee5d165d
[ "MIT" ]
1
2017-07-04T03:31:54.000Z
2017-07-04T22:38:48.000Z
src/lib/base/Fitness.cpp
cantordust/cortex
0afe4b8c8c3e1b103541188301c3f445ee5d165d
[ "MIT" ]
null
null
null
#include "Param.hpp" #include "Fitness.hpp" namespace Cortex { Fitness::Fitness(Config& _cfg) : cfg(_cfg), eff(Eff::Undef) { stat.ema_coeff = cfg.fit.ema.coeff; stat.window_size = std::floor(2.0 / stat.ema_coeff) - 1; } void Fitness::set_abs(const real _abs_fit) { if (_abs_fit > stat.abs) { eff = Eff::Inc; } else if (_abs_fit < stat.abs) { eff = Eff::Dec; } else { eff = Eff::Undef; } stat.add(_abs_fit); feedback(); } void Fitness::feedback() { switch (cfg.mutation.opt) { case Opt::Anneal: for (auto&& param : params) { param.get().anneal(stat.abs); } break; case Opt::Trend: for (auto&& param : params) { param.get().set_trend(eff); } break; default: break; } /// Increase the SD if we haven't made any progress if (progress() <= 0.5) { for (auto&& param : params) { param.get().inc_sd(); } } params.clear(); } }
14.164179
58
0.56902
cantordust
722e9b544c4e21eba7406114aaf8cc67e51f89b9
1,238
cpp
C++
src/cgi-calculatepi.cpp
fdiblen/cpp2wasm
1f4424ee586225ddee6680adaf8274031b4bd559
[ "Apache-2.0" ]
null
null
null
src/cgi-calculatepi.cpp
fdiblen/cpp2wasm
1f4424ee586225ddee6680adaf8274031b4bd559
[ "Apache-2.0" ]
null
null
null
src/cgi-calculatepi.cpp
fdiblen/cpp2wasm
1f4424ee586225ddee6680adaf8274031b4bd559
[ "Apache-2.0" ]
null
null
null
// this C++ snippet is stored as src/cgi-calculatepi.hpp #include <string> #include <iostream> #include <nlohmann/json.hpp> // this C++ code snippet is later referred to as <<algorithm>> #include <iostream> #include <math.h> #include "calculatepi.hpp" #define SEED 35791246 namespace pirng { PiCalculate::PiCalculate(double niter) : niter(niter) {} // Function to calculate PI double PiCalculate::calculate() { srand(SEED); double x, y; int i, count = 0; double z; std::cout << "Iterations : " << niter << std::endl; for ( i = 0; i < niter; i++) { x = (double)rand()/RAND_MAX; y = (double)rand()/RAND_MAX; z = x*x + y*y; if (z <= 1) count++; } return (double)count/niter*4; }; } // namespace pirng int main(int argc, char *argv[]) { std::cout << "Content-type: application/json" << std::endl << std::endl; // Retrieve niter from request body nlohmann::json request(nlohmann::json::parse(std::cin)); double niter = request["niter"]; // Calculate PI pirng::PiCalculate pifinder(niter); double pi = pifinder.calculate(); // Assemble response nlohmann::json response; response["niter"] = niter; response["pi"] = pi; std::cout << response.dump(2) << std::endl; return 0; }
21.344828
74
0.64378
fdiblen
722fc6fdde7ffe26c6b78f9b759ae10974128a59
2,968
cpp
C++
Trimming/ImageInfo.cpp
AinoMegumi/TokidolRankingOCREngine
225bf6fe328aa4dcd653bf095aff88632c9bac96
[ "MIT" ]
null
null
null
Trimming/ImageInfo.cpp
AinoMegumi/TokidolRankingOCREngine
225bf6fe328aa4dcd653bf095aff88632c9bac96
[ "MIT" ]
null
null
null
Trimming/ImageInfo.cpp
AinoMegumi/TokidolRankingOCREngine
225bf6fe328aa4dcd653bf095aff88632c9bac96
[ "MIT" ]
null
null
null
#include "ImageInfo.hpp" #include "HttpException.hpp" #include <filesystem> ImageInfo::ImageInfo(const std::string& FilePath) { try { if (!std::filesystem::exists(FilePath)) throw HttpException(404); this->image = cv::imread(FilePath, 1); if (this->image.empty()) throw HttpException(); } catch (const HttpException& hex) { throw hex; } catch (...) { throw HttpException(500); } } ImageInfo::ImageInfo(const cv::Mat& imagedata, const RECT& rc) { try { if (rc.left < 0 || rc.left > imagedata.cols) throw std::out_of_range("left is out of image.\n" + std::to_string(rc.left) + "-" + std::to_string(imagedata.rows)); if (rc.right < 0 || rc.right > imagedata.cols) throw std::out_of_range("right is out of image.\n" + std::to_string(rc.right) + "-" + std::to_string(imagedata.rows)); if (rc.top < 0 || rc.top > imagedata.rows) throw std::out_of_range("top is out of range.\n" + std::to_string(rc.top) + "-" + std::to_string(imagedata.cols)); if (rc.bottom < 0 || rc.bottom > imagedata.rows) throw std::out_of_range("bottom is out of range.\n" + std::to_string(rc.bottom) + "-" + std::to_string(imagedata.cols)); if (rc.right < rc.left) throw std::runtime_error("left is over right"); if (rc.bottom < rc.top) throw std::runtime_error("bottom is over top"); cv::Rect roi(cv::Point(rc.left, rc.top), cv::Size(rc.right - rc.left, rc.bottom - rc.top)); this->image = imagedata(roi); } catch (const std::out_of_range& o) { throw HttpException(400, o.what()); } catch (const std::runtime_error& r) { throw HttpException(400, r.what()); } } ImageInfo::ImageInfo(cv::Mat&& imagedata) : image(std::move(imagedata)) {} ImageInfo ImageInfo::operator ~ () { return ImageInfo(~this->image); } ImageInfo ImageInfo::trim(const RECT rc) const { return ImageInfo(this->image, rc); } ImageInfo ImageInfo::ToGrayScale() const { cv::Mat dest; cv::cvtColor(this->image, dest, cv::COLOR_RGB2GRAY); return ImageInfo(std::move(dest)); } ImageInfo ImageInfo::Binarization() const { const double threshold = 100.0; const double maxValue = 255.0; cv::Mat dest; cv::threshold(this->image, dest, threshold, maxValue, cv::THRESH_BINARY); return ImageInfo(std::move(dest)); } ImageInfo ImageInfo::InvertColor() const { cv::Mat dest; cv::bitwise_not(this->image, dest); return ImageInfo(std::move(dest)); } ImageInfo ImageInfo::Resize(const double Ratio) const { cv::Mat dest; cv::resize(this->image, dest, cv::Size(), Ratio, Ratio); return ImageInfo(std::move(dest)); } cv::Mat& ImageInfo::ref() { return this->image; } const cv::Mat& ImageInfo::ref() const { return this->image; } cv::Size ImageInfo::GetSize() const { return cv::Size(this->image.cols, this->image.rows); } void ImageInfo::WriteOut(const std::string& FileName) const { if (std::filesystem::exists(FileName.c_str())) return; cv::imwrite(FileName, this->image); } void ImageInfo::View(const std::string& WindowName) const { cv::imshow(WindowName, this->image); }
34.511628
171
0.685984
AinoMegumi
7232718585b49ce58577ade9572f732a47f3b927
1,657
cpp
C++
P009-PalindromeNumber/P009-PalindromeNumber/main.cpp
rlan/LeetCode
0521e27097a01a0a2ba2af30f3185d8bb5e3e227
[ "MIT" ]
null
null
null
P009-PalindromeNumber/P009-PalindromeNumber/main.cpp
rlan/LeetCode
0521e27097a01a0a2ba2af30f3185d8bb5e3e227
[ "MIT" ]
null
null
null
P009-PalindromeNumber/P009-PalindromeNumber/main.cpp
rlan/LeetCode
0521e27097a01a0a2ba2af30f3185d8bb5e3e227
[ "MIT" ]
null
null
null
// // LeetCode // Algorithm 9 Palindrome Number // // Created by Rick Lan on 3/30/17. // See LICENSE // #include <iostream> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x >= 0) { long long save = x; long long mag2 = 0; while (x) { int digit = x % 10; mag2 = mag2 * 10 + digit; x = x / 10; } return (save == mag2); } else { return false; } } }; int main(int argc, const char * argv[]) { Solution solution; int x; x = 0; cout << x << ": " << solution.isPalindrome(x) << endl; x = 121; cout << x << ": " << solution.isPalindrome(x) << endl; x = -121; cout << x << ": " << solution.isPalindrome(x) << endl; x = 321; cout << x << ": " << solution.isPalindrome(x) << endl; x = -321; cout << x << ": " << solution.isPalindrome(x) << endl; x = 9999; cout << x << ": " << solution.isPalindrome(x) << endl; x = -9999; cout << x << ": " << solution.isPalindrome(x) << endl; x = 1987667891; cout << x << ": " << solution.isPalindrome(x) << endl; x = -1987667891; cout << x << ": " << solution.isPalindrome(x) << endl; x = 2147447412; cout << x << ": " << solution.isPalindrome(x) << endl; x = -2147447412; cout << x << ": " << solution.isPalindrome(x) << endl; x = -2147483648; cout << x << ": " << solution.isPalindrome(x) << endl; x = 1563847412; cout << x << ": " << solution.isPalindrome(x) << endl; /* Input: -2147447412 Output: true Expected: false -2147483648 */ return 0; }
26.301587
75
0.494267
rlan
72353b7b4849861f1ec9f35c08f48f96e2c7a150
282
cpp
C++
Pbinfo/Puteri3.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
7
2019-01-06T19:10:14.000Z
2021-10-16T06:41:23.000Z
Pbinfo/Puteri3.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
null
null
null
Pbinfo/Puteri3.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
6
2019-01-06T19:17:30.000Z
2020-02-12T22:29:17.000Z
#include <iostream> using namespace std; #include <iostream> using namespace std; int f(int n, int p){ if(n){ if(n%2==1) cout<<p<<" "; f(n/2, p*2); } } int main() { int n, p; cin>>n; f(n, 1); return 0; } int main(){ return 0; }
9.096774
32
0.475177
Al3x76
7236aee6f6ec5ed4b01cdfdbae4afa800c4f3f66
3,280
hpp
C++
src/menu/livechat/livechat_cmd.hpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
6
2019-06-11T20:09:01.000Z
2021-05-28T01:18:27.000Z
src/menu/livechat/livechat_cmd.hpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
7
2019-06-14T20:28:31.000Z
2020-08-11T14:51:03.000Z
src/menu/livechat/livechat_cmd.hpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
1
2020-11-07T05:28:23.000Z
2020-11-07T05:28:23.000Z
// Copyright © 2020 Niventill // This file is licensed under ISC License. See "LICENSE" in the top level directory for more info. #ifndef LCCMD_HPP_INCLUDED #define LCCMD_HPP_INCLUDED //standard libraries #include <string> #include <string_view> namespace LCCommand { void CheckCommandInput(const std::string &line); void PreCheckCommandInput(const std::string &line, bool &isAutoJoin); void Reconnect(const std::string_view line); void Quit(const std::string_view line); void StartTimer(const std::string_view linee); void SetNick(const std::string &line); void SetTrack(const std::string_view line); void SetTimer(const std::string_view line); void AddNickname(const std::string_view line); void DelNickname(const std::string_view line); void SetMoney(const std::string &line); void SetCourses(const std::string &line); void SetLoadingTime(const std::string_view line); void Reset(const std::string_view line); void HardReset(const std::string_view line); void FindTransfers(const std::string_view line); void FindWord(const std::string &line); void OpenConfig(const std::string_view line); void OpenConsoleLog(const std::string_view line); void OpenLogusLog(const std::string_view line); void Timestamp(const std::string_view line); void TimestampBeep(const std::string_view line); void RenderEngine(const std::string_view line); void RenderEngineBeep(const std::string_view line); void ClearChat(const std::string_view line); void ClearChatBeep(const std::string_view line); void SetMax(const std::string &line); void SetMin(const std::string &line); void SetRefresh(const std::string &line); void SetDynamicRefresh(const std::string_view line); void SetDynamicRefreshBeep(const std::string_view line); void AutoReconnect(const std::string_view line, bool &isAutoJoin); void AutoReconnectBeep(const std::string_view line); } // namespace LCCommand namespace LCCmdEvent { bool Reconnect(const std::string_view line); bool Quit(const std::string_view line); bool StartTimer(const std::string_view linee); bool SetNick(const std::string_view line); bool SetTrack(const std::string_view line); bool SetTimer(const std::string_view line); bool AddNickname(const std::string_view line); bool DelNickname(const std::string_view line); bool SetMoney(const std::string_view line); bool SetCourses(const std::string_view line); bool SetLoadingTime(const std::string_view line); bool Reset(const std::string_view line); bool HardReset(const std::string_view line); bool FindTransfers(const std::string_view line); bool FindWord(const std::string_view line); bool OpenConfig(const std::string_view line); bool OpenConsoleLog(const std::string_view line); bool OpenLogusLog(const std::string_view line); bool Timestamp(const std::string_view line); bool RenderEngine(const std::string_view line); bool ClearChat(const std::string_view line); bool SetMax(const std::string_view line); bool SetMin(const std::string_view line); bool SetRefresh(const std::string_view line); bool SetDynamicRefresh(const std::string_view line); bool AutoReconnect(const std::string_view line); bool CheckCommandEvents(const std::string_view line); } // namespace LCCmdEvent #endif
40
99
0.767988
DarXe
7237a84aa0f26f11fa821252ca68ca07e6386805
2,078
cc
C++
bindings/builtin/symbolizer.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
null
null
null
bindings/builtin/symbolizer.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
null
null
null
bindings/builtin/symbolizer.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
null
null
null
#include <iostream> #ifndef _WIN32 #include <signal.h> #endif // _WIN32 #include <sstream> #include "debug/backtrace.h" #include "debug/resolver.h" #include "estl/string_view.h" static std::unique_ptr<reindexer::debug::TraceResolver> resolver{nullptr}; struct cgoTracebackArg { uintptr_t context; uintptr_t sigContext; uintptr_t* buf; uintptr_t max; }; struct cgoSymbolizerArg { uintptr_t pc; const char* file; uintptr_t lineno; const char* func; uintptr_t entry; uintptr_t more; uintptr_t data; }; extern "C" void cgoSymbolizer(cgoSymbolizerArg* arg) { if (!resolver) resolver = reindexer::debug::TraceResolver::New(); // Leak it! auto* te = new reindexer::debug::TraceEntry(arg->pc); if (resolver->Resolve(*te)) { arg->file = te->srcFile_.data(); arg->func = te->funcName_.data(); arg->lineno = te->srcLine_; } } #ifdef _WIN32 extern "C" void cgoSignalsInit() {} #else // !_WIN32 static struct sigaction oldsa[32]; static void cgoSighandler(int sig, siginfo_t* info, void* ucontext) { reindexer::debug::print_crash_query(std::cout); if (sig < 32) { struct sigaction &old = oldsa[sig]; if (old.sa_flags & SA_SIGINFO) { (old.sa_sigaction)(sig, info, ucontext); } else { (old.sa_handler)(sig); } } else { std::exit(-1); } } extern "C" void cgoSignalsInit() { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = cgoSighandler; sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO; sigaction(SIGSEGV, &sa, &oldsa[SIGSEGV]); sigaction(SIGABRT, &sa, &oldsa[SIGABRT]); sigaction(SIGBUS, &sa, &oldsa[SIGBUS]); } #endif // _WIN32 extern "C" void cgoTraceback(cgoTracebackArg* arg) { reindexer::string_view method; void* addrlist[64] = {}; if (arg->context != 0) { arg->buf[0] = 0; return; } uintptr_t addrlen = reindexer::debug::backtrace_internal(addrlist, sizeof(addrlist) / sizeof(addrlist[0]), reinterpret_cast<void*>(arg->context), method); if (addrlen > 3) memcpy(arg->buf, addrlist + 3, std::min(addrlen - 3, arg->max) * sizeof(void*)); }
25.036145
107
0.674687
SolovyovAlexander
72392a72adb54165350e4aa1c868b60090ffcdb7
2,521
cpp
C++
Chapter_3_Problem_Solving_Paradigms/Greedy/kattis_andrewant.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_3_Problem_Solving_Paradigms/Greedy/kattis_andrewant.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_3_Problem_Solving_Paradigms/Greedy/kattis_andrewant.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
/**Kattis - andrewant * If we imagine the line as being infinitely long, eventually we reach a point where we have 2 * groups of ants: a left walking group on the left on a right walking group. Now observe that * since 2 ants never cross, it means that the order of the ants at this stage is the same as the * order of ants at the start. As such, the right-most left walking ant is the kth ant at the start, * where the ants are ordered from left to right and there are k left walking ants. Similarly, the * left-most right walking ant is the k+1th ant at the start. These 2 ants are the only candidates * for the longest standing ant. * * Time: O(n log n), Space: O(n) */ #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; int l, n, max_n; vector<int> ants; // initial positions of the ants int main() { while (cin >> l >> n) { int num_moving_left = 0; max_n = 0; int longest_moving_left = -1, longest_moving_right = -1; ants.clear(); for (int i = 0; i < n; i++) { int x; char dir; cin >> x >> dir; ants.emplace_back(x); num_moving_left += (dir == 'L'); if (dir == 'L') { if (longest_moving_left == -1) { longest_moving_left = x; } else { longest_moving_left = max(longest_moving_left, x); } } else if (dir == 'R') { if (longest_moving_right == -1) { longest_moving_right = l - x; } else { longest_moving_right = max(longest_moving_right, l - x); } } } sort(ants.begin(), ants.end()); if (longest_moving_left == longest_moving_right) { printf("The last ant will fall down in %d seconds - started at %d and %d.\n", longest_moving_left, ants[num_moving_left - 1], ants[num_moving_left]); } else if (longest_moving_left > longest_moving_right) { printf("The last ant will fall down in %d seconds - started at %d.\n", longest_moving_left, ants[num_moving_left - 1]); } else { printf("The last ant will fall down in %d seconds - started at %d.\n", longest_moving_right, ants[num_moving_left]); } } return 0; }
41.327869
100
0.575169
BrandonTang89
5cf9af244805d5fd3ca60471488613bc152ea208
1,847
hpp
C++
include/tribalscript/libraries/libraries.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
include/tribalscript/libraries/libraries.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
1
2021-07-24T16:29:11.000Z
2021-07-26T20:00:17.000Z
include/tribalscript/libraries/libraries.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
/** * Copyright 2021 Robert MacGregor * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <tribalscript/libraries/string.hpp> #include <tribalscript/libraries/math.hpp> #include <tribalscript/libraries/core.hpp> #include <tribalscript/libraries/simset.hpp> #include <tribalscript/libraries/simgroup.hpp> #include <tribalscript/libraries/scriptobject.hpp> #include <tribalscript/libraries/fileobject.hpp> namespace TribalScript { static void registerAllLibraries(Interpreter* interpreter) { registerStringLibrary(interpreter); registerMathLibrary(interpreter); registerCoreLibrary(interpreter); registerSimSetLibrary(interpreter); registerSimGroupLibrary(interpreter); registerScriptObjectLibrary(interpreter); registerFileObjectLibrary(interpreter); } }
48.605263
207
0.777477
Ragora
cf01771bccdb23495a3cad033a0212f0a9195a90
6,146
cpp
C++
lib/data_base.cpp
titouanlacombe/DCLP-Projet
80fe4b8468ee8a9ab5cc8ab5a7dabf759973afd0
[ "MIT" ]
null
null
null
lib/data_base.cpp
titouanlacombe/DCLP-Projet
80fe4b8468ee8a9ab5cc8ab5a7dabf759973afd0
[ "MIT" ]
null
null
null
lib/data_base.cpp
titouanlacombe/DCLP-Projet
80fe4b8468ee8a9ab5cc8ab5a7dabf759973afd0
[ "MIT" ]
1
2021-04-15T16:45:21.000Z
2021-04-15T16:45:21.000Z
#include "data_base.h" #include "mylog.h" #define CMP_FILE_NAME "/Companies.csv" #define JOB_FILE_NAME "/Jobs.csv" #define WRK_FILE_NAME "/Workers.csv" #define CMP_FIRST_LINE "Name,Zip code,email" #define JOB_FIRST_LINE "Title,Skills,Company" #define WRK_FIRST_LINE "First name,Last name,email,Zip code,Skills,Co-workers,Company" void load(std::string folder) { if (!path_exist(folder)) system(("mkdir -p " + folder).c_str()); std::ifstream cmp_file, job_file, wrk_file; cmp_file.open("./" + folder + CMP_FILE_NAME); job_file.open("./" + folder + JOB_FILE_NAME); wrk_file.open("./" + folder + WRK_FILE_NAME); //------------------------COMPANIES-------------------------- std::string line, it, it2; std::getline(cmp_file, line); if (line != CMP_FIRST_LINE) { cmp_file.close(); std::ofstream new_file; new_file.open("./" + folder + CMP_FILE_NAME); new_file << CMP_FIRST_LINE << "\n"; new_file.close(); } else { std::getline(cmp_file, line); while (!line.empty()) { mygetline(line, it, ','); // name std::string name = it; mygetline(line, it, ','); // zip_code std::string zip_code = it; mygetline(line, it); // email std::string email = it; new Company(name, zip_code, email); std::getline(cmp_file, line); } } //------------------------JOBS-------------------------- std::getline(job_file, line); if (line != JOB_FIRST_LINE) { job_file.close(); std::ofstream new_file; new_file.open("./" + folder + JOB_FILE_NAME); new_file << JOB_FIRST_LINE << "\n"; new_file.close(); } else { std::getline(job_file, line); while (!line.empty()) { mygetline(line, it, ','); // title std::string title = it; Job* j = new Job(title, NULL); mygetline(line, it, ','); // skills while (mygetline(it, it2, ';')) j->add_skill(it2); mygetline(line, it); // company j->company = get_company(it); std::getline(job_file, line); } } //------------------------WORKERS-------------------------- List<std::string> co_workers_names; // first line workers std::getline(wrk_file, line); if (line != WRK_FIRST_LINE) { wrk_file.close(); std::ofstream new_file; new_file.open("./" + folder + WRK_FILE_NAME); new_file << WRK_FIRST_LINE << "\n"; new_file.close(); } else { std::getline(wrk_file, line); while (!line.empty()) { mygetline(line, it, ','); // first name std::string first_name = it; mygetline(line, it, ','); // last name std::string last_name = it; mygetline(line, it, ','); // email std::string email = it; Worker* w = new Worker(first_name, last_name, email); mygetline(line, it, ','); // zip code w->set_zip_code(it); mygetline(line, it, ','); // skills while (mygetline(it, it2, ';')) w->add_skill(it2); mygetline(line, it, ','); // co_workers co_workers_names.addlast(new std::string(it)); mygetline(line, it); // company w->set_company(get_company(it)); std::getline(wrk_file, line); } } // Linking co_workers auto workers = get_workers(); if (workers) { std::string tmp_str; auto wrk_it = workers->first(); auto id_it = co_workers_names.first(); while (wrk_it != workers->end()) { if (!(* *id_it).empty()) { tmp_str = * *id_it; while (mygetline(tmp_str, it, ';')) (*wrk_it)->co_workers.addlast(get_worker(it)); } wrk_it++; id_it++; } } co_workers_names.delete_data(); cmp_file.close(); job_file.close(); wrk_file.close(); } void save(std::string folder) { if (!path_exist(folder)) system(("mkdir -p " + folder).c_str()); std::ofstream cmp_file, job_file, wrk_file; cmp_file.open("./" + folder + CMP_FILE_NAME); job_file.open("./" + folder + JOB_FILE_NAME); wrk_file.open("./" + folder + WRK_FILE_NAME); //------------------------WORKERS-------------------------- wrk_file << WRK_FIRST_LINE << "\n"; auto workers = get_workers(); if (workers) { auto wrk_it = workers->first(); while (wrk_it != workers->end()) { // first name,last name,email,zip code wrk_file << (*wrk_it)->first_name << "," << (*wrk_it)->last_name << "," << (*wrk_it)->email << "," << (*wrk_it)->zip_code << ","; // Skills auto skl_it2 = (*wrk_it)->skills.first(); while (skl_it2 != (*wrk_it)->skills.last()) { wrk_file << * *skl_it2 << ";"; skl_it2++; } if (skl_it2 != (*wrk_it)->skills.end()) wrk_file << * *skl_it2; wrk_file << ","; // co_workers auto coll_it = (*wrk_it)->co_workers.first(); while (coll_it != (*wrk_it)->co_workers.last()) { wrk_file << (*coll_it)->first_name << " " << (*coll_it)->last_name << ";"; coll_it++; } if (coll_it != (*wrk_it)->co_workers.end()) wrk_file << (*coll_it)->first_name << " " << (*coll_it)->last_name; wrk_file << ","; // company if ((*wrk_it)->employed()) wrk_file << (*wrk_it)->company->name; wrk_file << "\n"; wrk_it++; } } //------------------------JOBS-------------------------- job_file << JOB_FIRST_LINE << "\n"; auto jobs = get_jobs(); if (jobs) { auto job_it = jobs->first(); while (job_it != jobs->end()) { // title job_file << (*job_it)->title << ","; // Skills auto skl_it = (*job_it)->skills.first(); while (skl_it != (*job_it)->skills.last()) { job_file << * *skl_it << ";"; skl_it++; } if (skl_it != (*job_it)->skills.end()) job_file << * *skl_it; job_file << ","; // Company job_file << (*job_it)->company->name << "\n"; job_it++; } } //------------------------COMPANIES-------------------------- cmp_file << CMP_FIRST_LINE << "\n"; auto companies = get_companies(); if (companies) { auto cmp_it = companies->first(); while (cmp_it != companies->end()) { Company* c = *cmp_it; // name,zip code,email cmp_file << c->name << "," << c->zip_code << "," << c->email << "\n"; cmp_it++; delete c; } } wrk_file.close(); job_file.close(); cmp_file.close(); if (workers) { workers->delete_data(); delete workers; } if (jobs) { jobs->delete_data(); delete jobs; } if (companies) { companies->delete_data(); delete companies; } }
22.932836
114
0.5685
titouanlacombe
cf0341f3c79b5a19a8495c5319ce729e08218e98
415
hpp
C++
include/svgpp/policy/xml/fwd.hpp
RichardCory/svgpp
801e0142c61c88cf2898da157fb96dc04af1b8b0
[ "BSL-1.0" ]
428
2015-01-05T17:13:54.000Z
2022-03-31T08:25:47.000Z
include/svgpp/policy/xml/fwd.hpp
andrew2015/svgpp
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
[ "BSL-1.0" ]
61
2015-01-08T14:32:27.000Z
2021-12-06T16:55:11.000Z
include/svgpp/policy/xml/fwd.hpp
andrew2015/svgpp
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
[ "BSL-1.0" ]
90
2015-05-19T04:56:46.000Z
2022-03-26T16:42:50.000Z
// Copyright Oleg Maximenko 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://github.com/svgpp/svgpp for library home page. #pragma once namespace svgpp { namespace policy { namespace xml { template<class T> struct attribute_iterator; template<class T> struct element_iterator; }}}
21.842105
61
0.754217
RichardCory
cf054f5fed552a130c636bc86f2ac9fa777d4eed
7,541
cpp
C++
xfile/XFileReader.cpp
ryutorion/DirectX11ShaderProgrammingBook
2407dafec283bac2f195bcdf48ffae024f819d80
[ "MIT" ]
2
2021-01-12T13:40:45.000Z
2021-01-12T23:55:22.000Z
xfile/XFileReader.cpp
ryutorion/DirectX11ShaderProgrammingBook
2407dafec283bac2f195bcdf48ffae024f819d80
[ "MIT" ]
null
null
null
xfile/XFileReader.cpp
ryutorion/DirectX11ShaderProgrammingBook
2407dafec283bac2f195bcdf48ffae024f819d80
[ "MIT" ]
null
null
null
#include "XFileReader.h" #include <utility> #include "XFileMesh.h" namespace { constexpr uint32_t XFileMagic = 'x' | ('o' << 8) | ('f' << 16) | (' ' << 24); constexpr uint32_t XFileFormatBinary = 'b' | ('i' << 8) | ('n' << 16) | (' ' << 24); constexpr uint32_t XFileFormatText = 't' | ('x' << 8) | ('t' << 16) | (' ' << 24); constexpr uint32_t XFileFormatCompressed = 'c' | ('m' << 8) | ('p' << 16) | (' ' << 24); constexpr uint32_t XFileFormatFloatBits32 = '0' | ('0' << 8) | ('3' << 16) | ('2' << 24); constexpr uint32_t XFileFormatFloatBits64 = '0' | ('0' << 8) | ('6' << 16) | ('4' << 24); std::istream & operator>>(std::istream & in, xfile::TokenType & token) { if(in.eof()) { token = xfile::TokenType::None; return in; } int16_t t; in.read(reinterpret_cast<char *>(&t), sizeof(t)); switch(static_cast<xfile::TokenType>(t)) { case xfile::TokenType::Name: case xfile::TokenType::String: case xfile::TokenType::Integer: case xfile::TokenType::GUID: case xfile::TokenType::IntegerList: case xfile::TokenType::FloatList: case xfile::TokenType::OpenBrace: case xfile::TokenType::CloseBrace: case xfile::TokenType::OpenParen: case xfile::TokenType::CloseParen: case xfile::TokenType::OpenBracket: case xfile::TokenType::CloseBracket: case xfile::TokenType::OpenAngle: case xfile::TokenType::CloseAngle: case xfile::TokenType::Dot: case xfile::TokenType::Comma: case xfile::TokenType::SemiColon: case xfile::TokenType::Template: case xfile::TokenType::Word: case xfile::TokenType::DoubleWord: case xfile::TokenType::Float: case xfile::TokenType::Double: case xfile::TokenType::Char: case xfile::TokenType::UnsignedChar: case xfile::TokenType::SignedWord: case xfile::TokenType::SignedDoubleWord: case xfile::TokenType::Void: case xfile::TokenType::StringPointer: case xfile::TokenType::Unicode: case xfile::TokenType::CString: case xfile::TokenType::Array: token = static_cast<xfile::TokenType>(t); break; default: if(in.eof()) { token = xfile::TokenType::None; } else { token = xfile::TokenType::Error; } break; } return in; } } namespace xfile { XFileReader::XFileReader(const char * p_file_path) { open(p_file_path); } XFileReader::~XFileReader() { close(); } bool XFileReader::open(const char * p_file_path) { if(mFin.is_open()) { return false; } mFin.open(p_file_path, std::ios::in | std::ios::binary); if(!mFin) { return false; } uint32_t magic; mFin.read(reinterpret_cast<char *>(&magic), sizeof(magic)); if(magic != XFileMagic) { return false; } // ドキュメントではバージョンは0302となっているが, // DirectX 9シェーダプログラミングブックのバージョンは0303のため // いったんバージョンは無視する uint32_t version; mFin.read(reinterpret_cast<char *>(&version), sizeof(version)); uint32_t format; mFin.read(reinterpret_cast<char *>(&format), sizeof(format)); switch(format) { case XFileFormatBinary: mFormat = Format::Binary; break; case XFileFormatText: mFormat = Format::Text; break; case XFileFormatCompressed: mFormat = Format::Compressed; break; default: return false; } uint32_t float_format; mFin.read(reinterpret_cast<char *>(&float_format), sizeof(float_format)); switch(float_format) { case XFileFormatFloatBits32: mFloatFormat = FloatFormat::Bits32; break; case XFileFormatFloatBits64: mFloatFormat = FloatFormat::Bits64; break; default: return false; } return true; } bool XFileReader::read(XFile & xfile) { if(!readNextTokenType()) { return false; } while(true) { XFileObject object; if(!readObject(object)) { break; } if(object.name.compare("Mesh") == 0) { XFileMesh mesh; if(!mesh.setup(object)) { return false; } xfile.meshes.emplace_back(std::move(mesh)); } if(!readNextTokenType()) { return false; } if(mNextTokenType == TokenType::None) { break; } } return true; } bool XFileReader::close() { if(mFin.is_open()) { mFin.close(); } return true; } bool XFileReader::readObject(XFileObject & object) { if(mNextTokenType == TokenType::Name) { if(!readName(object.name)) { return false; } if(!readNextTokenType()) { return false; } } else { return false; } if(mNextTokenType == TokenType::Name) { if(!readName(object.optionalName)) { return false; } if(!readNextTokenType()) { return false; } } if(mNextTokenType != TokenType::OpenBrace) { return false; } if(!readNextTokenType()) { return false; } while(mNextTokenType != TokenType::CloseBrace) { XFileData data; switch(mNextTokenType) { case TokenType::Name: data.dataType = DataType::Object; data.object.reset(new XFileObject); if(!readObject(*data.object)) { return false; } break; case TokenType::IntegerList: if(!readIntegerList(data)) { return false; } break; case TokenType::FloatList: if(!readFloatList(data)) { return false; } break; case TokenType::String: if(!readString(data)) { return false; } break; default: return false; } object.dataArray.emplace_back(std::move(data)); if(!readNextTokenType()) { return false; } } return true; } bool XFileReader::readNextTokenType() { mFin >> mNextTokenType; if(mNextTokenType == TokenType::Error) { return false; } return true; } bool XFileReader::readName(std::string & s) { uint32_t length; mFin.read(reinterpret_cast<char *>(&length), sizeof(length)); s.resize(length); mFin.read(s.data(), length); return true; } bool XFileReader::readGUID() { uint32_t data1; mFin.read(reinterpret_cast<char *>(&data1), sizeof(data1)); uint16_t data2; mFin.read(reinterpret_cast<char *>(&data2), sizeof(data2)); uint16_t data3; mFin.read(reinterpret_cast<char *>(&data3), sizeof(data3)); uint8_t data4[8]; mFin.read(reinterpret_cast<char *>(data4), sizeof(data4)); return true; } bool XFileReader::readIntegerList(XFileData & data) { uint32_t count; mFin.read(reinterpret_cast<char *>(&count), sizeof(count)); data.dataType = DataType::Integer; data.numberList.resize(count); mFin.read(reinterpret_cast<char *>(data.numberList.data()), sizeof(uint32_t) * count); return true; } bool XFileReader::readFloatList(XFileData & data) { uint32_t count; mFin.read(reinterpret_cast<char *>(&count), sizeof(count)); if(mFloatFormat == FloatFormat::Bits32) { data.dataType = DataType::Float; data.floatList.resize(count); mFin.read(reinterpret_cast<char *>(data.floatList.data()), sizeof(float) * count); } else if(mFloatFormat == FloatFormat::Bits64) { data.dataType = DataType::Double; data.doubleList.resize(count); mFin.read(reinterpret_cast<char *>(data.doubleList.data()), sizeof(double) * count); } else { return false; } return true; } bool XFileReader::readString(XFileData & data) { uint32_t count; mFin.read(reinterpret_cast<char *>(&count), sizeof(count)); std::string s(count, '\0'); mFin.read(reinterpret_cast<char *>(s.data()), count); if(!readNextTokenType()) { return false; } if(mNextTokenType != TokenType::Comma && mNextTokenType != TokenType::SemiColon) { return false; } data.dataType = DataType::String; data.stringList.emplace_back(std::move(s)); return true; } }
19.536269
90
0.645936
ryutorion
cf06c8504f2a049772631c08e8411b6afc6deb4a
2,691
cpp
C++
device/src/startup/initialise-interrupts-stack.cpp
micro-os-plus/architecture-cortexm-xpack
3d0aa622dbaea7571f5e1858a5ac2b05d71ca132
[ "MIT" ]
null
null
null
device/src/startup/initialise-interrupts-stack.cpp
micro-os-plus/architecture-cortexm-xpack
3d0aa622dbaea7571f5e1858a5ac2b05d71ca132
[ "MIT" ]
1
2021-02-04T17:24:27.000Z
2021-02-05T11:06:10.000Z
device/src/startup/initialise-interrupts-stack.cpp
micro-os-plus/architecture-cortexm-xpack
3d0aa622dbaea7571f5e1858a5ac2b05d71ca132
[ "MIT" ]
1
2021-02-15T09:28:46.000Z
2021-02-15T09:28:46.000Z
/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2021 Liviu Ionescu. * * 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. */ #if (!(defined(__APPLE__) || defined(__linux__) || defined(__unix__))) \ || defined(__DOXYGEN__) // ---------------------------------------------------------------------------- #if defined(HAVE_MICRO_OS_PLUS_CONFIG_H) #include <micro-os-plus/config.h> #endif // HAVE_MICRO_OS_PLUS_CONFIG_H // ---------------------------------------------------------------------------- #if defined(MICRO_OS_PLUS_INCLUDE_RTOS) // ---------------------------------------------------------------------------- #include <micro-os-plus/startup/hooks.h> #include <micro-os-plus/rtos.h> // ---------------------------------------------------------------------------- using namespace micro_os_plus; // ---------------------------------------------------------------------------- void micro_os_plus_startup_initialize_interrupts_stack (void* stack_begin_address, size_t stack_size_bytes) { trace::printf ("%s(%p,%u)\n", __func__, stack_begin_address, stack_size_bytes); rtos::interrupts::stack ()->set ( static_cast<rtos::thread::stack::element_t*> (stack_begin_address), stack_size_bytes); } // ---------------------------------------------------------------------------- #endif // defined(MICRO_OS_PLUS_INCLUDE_RTOS) // ---------------------------------------------------------------------------- #endif // ! Unix // ----------------------------------------------------------------------------
36.863014
79
0.550725
micro-os-plus
cf0a164c35b7feaf4045eff4eacae23095ce71db
9,338
cpp
C++
libkeksbot/mensa.cpp
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
2
2015-01-17T00:18:29.000Z
2015-09-16T17:26:03.000Z
libkeksbot/mensa.cpp
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
11
2015-01-30T23:24:49.000Z
2017-12-10T15:48:23.000Z
libkeksbot/mensa.cpp
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
4
2016-02-29T17:45:51.000Z
2017-12-08T18:03:02.000Z
#include "mensa.h" #include "logging.h" #include "server.h" #include <curl/curl.h> #include <rapidjson/document.h> #include <chrono> using namespace std::literals::chrono_literals; void RoundToDay(struct tm* time) { assert(time != NULL); time->tm_sec = 0; time->tm_min = 0; time->tm_hour = 0; } static const char* const weekday[] = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}; void WriteTime(std::ostream& out, time_t time) { struct tm localnow; localtime_r(&time, &localnow); out << weekday[localnow.tm_wday] << ". " << localnow.tm_mday << "." << (localnow.tm_mon + 1) << "." << (localnow.tm_year % 100); } Mensa::Mensa(const Configs& cfg) : multiHandle(curl_multi_init()), updating(false) { cfg.GetValue("menuurl", menuurl); cfg.GetValue("metaurl", metaurl); cfg.GetValue("login", login); cfg.GetValue("canteen", canteen); cfg.GetValue("ad", ad); std::string rawlines; cfg.GetValue("lines", rawlines); std::istringstream sstr(rawlines); std::string newline; while(std::getline(sstr, newline, ',')) lines.insert(newline); } Mensa::~Mensa() { curl_multi_cleanup(multiHandle); } void Mensa::OnEvent(Server& srv, const std::string& event, const std::string& origin, const std::vector<std::string>& params) { if(params.size() == 0) throw std::logic_error("OnEvent should only be called for SENDMSG"); int offset = 0; if(params.size() > 1 && !params[1].empty()) { std::stringstream sstr(params[1]); sstr >> offset; if(sstr.fail()) { srv.SendMsg(params[0], "Error: " + params[1] + " is not a number"); return; } } auto now = std::chrono::steady_clock::now(); // No error handling, I don't care about overflow in time_t if(now - lastupdate >= 1min) { originBuf.insert(QueuedResponse(&srv, origin, params[0], offset)); if(!updating) QueryMenuUpdate(); } else SendMenu(srv, origin, params[0], offset); } void Mensa::AddSelectDescriptors(fd_set& inSet, fd_set& outSet, fd_set& excSet, int& maxFD) { int max = 0; curl_multi_fdset(multiHandle, &inSet, &outSet, &excSet, &max); maxFD = std::max(maxFD, max); } bool Mensa::UpdateMeta(rapidjson::Value& val) { if(!val.IsObject() || val.IsNull()) return true; rapidjson::Value::ConstMemberIterator canteenjs = val.FindMember(canteen.c_str()); if(canteenjs == val.MemberEnd() || !canteenjs->value.IsObject() || canteenjs->value.IsNull()) return true; rapidjson::Value::ConstMemberIterator linesjs=canteenjs->value.FindMember("lines"); if(linesjs == canteenjs->value.MemberEnd() || !linesjs->value.IsObject() || linesjs->value.IsNull()) return true; for(rapidjson::Value::ConstMemberIterator i = linesjs->value.MemberBegin(); i != linesjs->value.MemberEnd(); ++i) { if(!i->value.IsString() || !i->name.IsString()) continue; lineMap[i->name.GetString()] = i->value.GetString(); Log(LOG_DEBUG, "Updated line name for %s(%s)", i->name.GetString(), i->value.GetString()); } return false; } bool Mensa::UpdateMenu(rapidjson::Value& val) { if(!val.IsObject() || val.IsNull()) return true; menu = val; return false; } void Mensa::SelectDescriptors(fd_set& inSet, fd_set& outSet, fd_set& excSet) { int running; curl_multi_perform(multiHandle, &running); struct CURLMsg* msg; int msgnum; bool hasfinished = false; while((msg = curl_multi_info_read(multiHandle, &msgnum))) { hasfinished = true; CURL* handle = msg->easy_handle; Log(LOG_DEBUG, "Result of curl request: %ld", static_cast<long>(msg->data.result)); curl_multi_remove_handle(multiHandle, handle); curl_easy_cleanup(handle); } if(hasfinished && !running) { bool err = false; doc.Parse(metabuf.c_str()); if(doc.IsObject() && doc.HasMember("mensa")) err = UpdateMeta(doc["mensa"]); doc.Parse(menubuf.c_str()); if(doc.IsObject() && doc.HasMember(canteen.c_str())) err = err || UpdateMenu(doc[canteen.c_str()]); if(err) { for(std::set<QueuedResponse>::iterator it = originBuf.begin(); it != originBuf.end(); ++it) it->srv->SendMsg(it->channel, "Error while receiving json"); } else { for(std::set<QueuedResponse>::iterator it = originBuf.begin(); it != originBuf.end(); ++it) SendMenu(*it->srv, it->origin, it->channel, it->offset); } originBuf.clear(); lastupdate = std::chrono::steady_clock::now(); updating = false; } } void Mensa::RegisterCurlHandle(const std::string& url, std::string& buffer) { buffer = std::string(); CURL* handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &Mensa::PushData); curl_easy_setopt(handle, CURLOPT_WRITEDATA, &buffer); curl_easy_setopt(handle, CURLOPT_USERAGENT, "$USERAGENTWITHMOZILLAGECKOSAFARIANDSHIT"); curl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_easy_setopt(handle, CURLOPT_USERPWD, login.c_str()); curl_multi_add_handle(multiHandle, handle); Log(LOG_DEBUG, "Requested url %s", url.c_str()); } void Mensa::QueryMenuUpdate() { updating = true; RegisterCurlHandle(menuurl, menubuf); RegisterCurlHandle(metaurl, metabuf); } size_t Mensa::PushData(char* data, size_t size, size_t nmemb, void* userdata) { std::string* buffer = static_cast<std::string*>(userdata); if(buffer != NULL) buffer->append(data, size*nmemb); return nmemb; } void Mensa::SendMenu(Server& srv, const std::string& origin, const std::string& channel, int offset) { time_t now = time(NULL); struct tm localnow; localtime_r(&now, &localnow); RoundToDay(&localnow); if(offset) localnow.tm_mday += offset; else if(localnow.tm_wday % 6 == 0) localnow.tm_mday += localnow.tm_wday?2:1; now = mktime(&localnow); std::stringstream sstr; sstr << now; std::string strnow(sstr.str()); if(!menu.HasMember(strnow.c_str())) { std::stringstream errmsg; errmsg << "Keine Daten vorhanden für "; WriteTime(errmsg, now); srv.SendMsg(channel, errmsg.str()); return; } rapidjson::Value& menunow = menu[strnow.c_str()]; if(!menunow.IsObject() || menunow.IsNull()) return; std::stringstream menumsg; menumsg << "Mensaeinheitsbrei am "; WriteTime(menumsg, now); srv.SendMsg(channel, menumsg.str()); for (rapidjson::Value::ConstMemberIterator itr = menunow.MemberBegin(); itr != menunow.MemberEnd(); ++itr) { if(!itr->name.IsString()) continue; std::string name = itr->name.GetString(); if(lines.count(name) != 0) SendLine(srv, channel, name, itr->value); else SendLineClosed(srv, channel, name, itr->value); } if (!ad.empty()) { auto additionalVariables = std::multimap<std::string, std::string>{ {"USER", origin}, {"CHAN", channel}, {"NICK", srv.GetNick()}, }; srv.SendMsg(channel, RandomReplace(ad, additionalVariables)); } } void Mensa::SendLineClosed(Server& srv, const std::string& origin, const std::string& line, const rapidjson::Value& value) { if(!value.IsArray() || value.Size() != 1) return; const rapidjson::Value& data = value[0]; if(!data.IsObject() || data.IsNull()) return; rapidjson::Value::ConstMemberIterator itr = data.FindMember("closing_end"); if(itr == data.MemberEnd() || !itr->value.IsInt64()) return; std::stringstream sstr; std::string linename = lineMap[line]; if(linename.empty()) linename = line; sstr << linename << ": Geschlossen bis "; WriteTime(sstr, itr->value.GetInt64()); itr = data.FindMember("closing_text"); if(itr != data.MemberEnd() && itr->value.IsString()) sstr << " (" << itr->value.GetString() << ")"; srv.SendMsg(origin, sstr.str()); } void Mensa::SendLine(Server& srv, const std::string& origin, const std::string& line, const rapidjson::Value& value) { if(!value.IsArray()) return; if(value.Size() == 0) return; std::string linename = lineMap[line]; if(linename.empty()) linename = line; /* Check first array element for special values */ const rapidjson::Value& firstElem = value[0]; if(firstElem.IsObject() && !firstElem.IsNull()) { if(firstElem.HasMember("closing_end")) { SendLineClosed(srv, origin, line, value); return; } rapidjson::Value::ConstMemberIterator itr = firstElem.FindMember("nodata"); if(itr != firstElem.MemberEnd() && itr->value.IsBool() && itr->value.GetBool()) { srv.SendMsg(origin, linename + ": Keine Daten vorhanden"); return; } } std::stringstream strstr; strstr.setf(std::ios_base::fixed); strstr.precision(2); strstr << linename << ": "; for(rapidjson::Value::ConstValueIterator it = value.Begin(); it != value.End(); ++it) { if(!it->IsObject() || it->IsNull()) continue; rapidjson::Value::ConstMemberIterator meal = it->FindMember("meal"); rapidjson::Value::ConstMemberIterator price_1 = it->FindMember("price_1"); if(meal == it->MemberEnd() || !meal->value.IsString() || price_1 == it->MemberEnd() || !price_1->value.IsNumber()) continue; double price = price_1->value.GetDouble(); // threshold if(price < 1.3) continue; strstr << meal->value.GetString(); rapidjson::Value::ConstMemberIterator dish = it->FindMember("dish"); if(dish != it->MemberEnd() && dish->value.IsString() && dish->value.GetStringLength() != 0) strstr << " " << dish->value.GetString(); strstr << " (" << price << "), "; } std::string str = strstr.str(); srv.SendMsg(origin, str.substr(0, str.size()-2)); }
26.083799
100
0.674663
cookiemon
cf101bd843476de0e311d28ff09d3ef9cca483f0
254
cpp
C++
TouchGFX/gui/src/mainscreen_screen/mainScreenView.cpp
xlord13/vescUserInterface
ff26bc1245ec35cb545042fe01ce3111c92ef80f
[ "MIT" ]
null
null
null
TouchGFX/gui/src/mainscreen_screen/mainScreenView.cpp
xlord13/vescUserInterface
ff26bc1245ec35cb545042fe01ce3111c92ef80f
[ "MIT" ]
null
null
null
TouchGFX/gui/src/mainscreen_screen/mainScreenView.cpp
xlord13/vescUserInterface
ff26bc1245ec35cb545042fe01ce3111c92ef80f
[ "MIT" ]
null
null
null
#include <gui/mainscreen_screen/mainScreenView.hpp> mainScreenView::mainScreenView() { } void mainScreenView::setupScreen() { mainScreenViewBase::setupScreen(); } void mainScreenView::tearDownScreen() { mainScreenViewBase::tearDownScreen(); }
15.875
51
0.76378
xlord13
cf10ef64377dbdf3d4f1bf31fdd15e807684e71a
9,555
hpp
C++
grammar/src/noun.hpp
Agapanthus/grammar
41f14c761174d8518e206b4c78fc4ddffd429d74
[ "MIT" ]
null
null
null
grammar/src/noun.hpp
Agapanthus/grammar
41f14c761174d8518e206b4c78fc4ddffd429d74
[ "MIT" ]
null
null
null
grammar/src/noun.hpp
Agapanthus/grammar
41f14c761174d8518e206b4c78fc4ddffd429d74
[ "MIT" ]
null
null
null
#pragma once #include "grammar.hpp" enum class NounType { Name, Noun, Numeral, Toponym, Incomplete, }; const static thread_local vector<string> nDeclSuffix = { "and", "ant", "at", "end", "et", "ent", "graph", "ist", "ik", "it", "loge", "nom", "ot", "soph", "urg"}; class Noun : public WithCases { // See // http://www.dietz-und-daf.de/GD_DkfA/Gramm-List.htm public: bool noPlural, noSingular; NounType type; Genus genus; Noun() : noPlural(false), noSingular(false) {} ////////////////////////////////////////////// string ns() const; // Tests if n is a nominative singular bool ns(const stringLower &n) const { for (const stringLower s : nominative.singular) if (s == n) return true; return false; } // Don't use this if you can have a dictionary string npWithoutDict(const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || nominative.plural.empty()) return npRules(forceArtificial); return nominative.plural[0]; } string np(const Dictionary &dict, bool forceArtificial = false) const; // Warning: This one is a little less robust than the test for the other // cases bool np(const Dictionary &dict, const stringLower &n) const { for (const stringLower s : nominative.plural) if (s == n) return true; if (nominative.plural.empty()) if (n == stringLower(np(dict))) return true; return false; } string gs(const Dictionary &dict, const bool forceArtificial = false) const { if (noSingular) return ""; if (forceArtificial || genitive.singular.empty()) return gsRules(forceArtificial); return genitive.singular[0]; } // TODO: quite vague test bool gs(const Dictionary &dict, const stringLower &test) const { if (noSingular) return false; for (const stringLower g : genitive.singular) { if (g == test) return true; } if (genitive.singular.empty()) { const string ns = stringLower(this->ns()); const bool m = genus.empty() || genus.m; const bool f = genus.empty() || genus.f; const bool n = genus.empty() || genus.n; if (isNDeclination()) { if (endsWith(ns, "e")) return ns + "n" == test; return ns + "en" == test; } else if ((n || m) && endsWithAny(ns, sibilants)) { return ns + "es" == test; } else if (test == stringLower(gs(dict))) { return true; } else if (ns == test || ns + "s" == test) { return true; } } return false; } string gp(const Dictionary &dict, const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || genitive.plural.empty()) return np(dict, false); return genitive.plural[0]; } bool gp(const Dictionary &dict, const stringLower &test) const { if (noPlural) return false; for (const stringLower g : genitive.plural) { if (g == test) return true; } if (genitive.plural.empty()) { return np(dict, test); } return false; } string ds(const bool forceArtificial = false) const { if (noSingular) return ""; if (forceArtificial || dative.singular.empty()) { const string ns = this->ns(); const bool m = genus.empty() || genus.m; if (m && endsWithAny(ns, nDeclSuffix)) { return ns + "en"; } else if (endsWithAny(ns, {"er", "ar", "är", "eur", "ier", "or"})) { return ns; } if (isNDeclination()) { if (endsWith(ns, "e")) { // missing: Bauer, Herr, Nachbar, Ungar... return ns + "n"; } else if (!endsWithAny(ns, vocals) && !endsWith(ns, "n")) { return ns + "en"; } } return ns; } return dative.singular[0]; } bool ds(const stringLower &test) const { if (noSingular) return ""; for (const stringLower g : dative.singular) { if (g == test) return true; } if (dative.singular.empty()) { return ds() == test; } return false; } string dp(const Dictionary &dict, const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || dative.plural.empty()) { const string np = this->np(dict, false); if (endsWithAny(np, {"e", "er", "el", "erl"}) && !endsWithAny(np, {"ae"})) return np + "n"; return np; } return dative.plural[0]; } bool dp(const Dictionary &dict, const stringLower &test) const { if (noPlural) return false; for (const stringLower g : dative.plural) { if (g == test) return true; } if (dative.plural.empty()) { const string np = this->np(dict); if (endsWithAny(np, {"e", "er", "el", "erl"}) && !endsWithAny(np, {"ae"})) { if (!endsWith(test, "n")) return false; } return this->np(dict, test); } return false; } string as(const bool forceArtificial = false) const { if (noSingular) return ""; if (forceArtificial || accusative.singular.empty()) { return ds(); } return accusative.singular[0]; } bool as(const stringLower &test) const { if (noSingular) return ""; for (const stringLower g : accusative.singular) { if (g == test) return true; } if (accusative.singular.empty()) { return as() == test; } return false; } string ap(const Dictionary &dict, const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || accusative.plural.empty()) return np(dict, false); return accusative.plural[0]; } bool ap(const Dictionary &dict, const stringLower test) const { if (noPlural) return false; for (const stringLower g : accusative.plural) { if (g == test) return true; } if (accusative.plural.empty()) { return np(dict, test); } return false; } //////////////////////////////////////////////////////////////////////////// bool isNDeclination(bool forceArtificial = false) const; string npRules(const bool forceArtificial = false) const; string gsRules(const bool forceArtificial = false) const; bool nullArticle() const { // TODO return false; } //////////////////////////////////////////////////////////////////////////// string get(const Cases &c, bool plural, const Dictionary &dict, bool fa = false) const { switch (c) { case Cases::Nominative: return !plural ? ns() : np(dict, fa); break; case Cases::Genitive: return !plural ? gs(dict, fa) : gp(dict, fa); break; case Cases::Dative: return !plural ? ds(fa) : dp(dict, fa); break; case Cases::Accusative: return !plural ? as(fa) : ap(dict, fa); break; } } bool test(const Cases &c, bool plural, const Dictionary &dict, const string &t) const { switch (c) { case Cases::Nominative: return !plural ? ns(t) : np(dict, t); break; case Cases::Genitive: return !plural ? gs(dict, t) : gp(dict, t); break; case Cases::Dative: return !plural ? ds(t) : dp(dict, t); break; case Cases::Accusative: return !plural ? as(t) : ap(dict, t); break; } } bool predefined(const Cases &c, bool plural) const { if (plural) return !cases[size_t(c)].plural.empty() && !cases[size_t(c)].plural[0].empty(); else return !cases[size_t(c)].singular.empty() && !cases[size_t(c)].singular[0].empty(); } //////////////////////////////////////////////////////////////////////////// void serialize(ostream &out) const { WithCases::serialize(out); genus.serialize(out); out << noSingular << " " << noPlural << " " << (int)type << " "; } void deserialize(istream &in) { WithCases::deserialize(in); genus.deserialize(in); int temp; in >> noSingular >> noPlural >> temp; type = (NounType)temp; } void buildMap(map<string, vector<Word>> &dict) const { Word me({this, WordType::Noun}); nominative.buildMap(me, dict); } };
30.04717
80
0.480167
Agapanthus
cf15f637599c1af1537245c942f98a31735e493a
8,582
cc
C++
code/render/coregraphics/vk/vkshaderserver.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
code/render/coregraphics/vk/vkshaderserver.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
code/render/coregraphics/vk/vkshaderserver.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
//------------------------------------------------------------------------------ // vkshaderserver.cc // (C) 2016-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "render/stdneb.h" #include "vkshaderserver.h" #include "effectfactory.h" #include "coregraphics/shaderpool.h" #include "vkgraphicsdevice.h" #include "vkshaderpool.h" #include "vkshader.h" using namespace Resources; using namespace CoreGraphics; namespace Vulkan { __ImplementClass(Vulkan::VkShaderServer, 'VKSS', Base::ShaderServerBase); __ImplementSingleton(Vulkan::VkShaderServer); //------------------------------------------------------------------------------ /** */ VkShaderServer::VkShaderServer() { __ConstructSingleton; } //------------------------------------------------------------------------------ /** */ VkShaderServer::~VkShaderServer() { __DestructSingleton; } //------------------------------------------------------------------------------ /** */ bool VkShaderServer::Open() { n_assert(!this->IsOpen()); // create anyfx factory this->factory = n_new(AnyFX::EffectFactory); ShaderServerBase::Open(); auto func = [](uint32_t& val, IndexT i) -> void { val = i; }; this->texture2DPool.SetSetupFunc(func); this->texture2DPool.Resize(MAX_2D_TEXTURES); this->texture2DMSPool.SetSetupFunc(func); this->texture2DMSPool.Resize(MAX_2D_MS_TEXTURES); this->texture3DPool.SetSetupFunc(func); this->texture3DPool.Resize(MAX_3D_TEXTURES); this->textureCubePool.SetSetupFunc(func); this->textureCubePool.Resize(MAX_CUBE_TEXTURES); this->texture2DArrayPool.SetSetupFunc(func); this->texture2DArrayPool.Resize(MAX_2D_ARRAY_TEXTURES); // create shader state for textures, and fetch variables ShaderId shader = VkShaderServer::Instance()->GetShader("shd:shared.fxb"_atm); this->texture2DTextureVar = ShaderGetResourceSlot(shader, "Textures2D"); this->texture2DMSTextureVar = ShaderGetResourceSlot(shader, "Textures2DMS"); this->texture2DArrayTextureVar = ShaderGetResourceSlot(shader, "Textures2DArray"); this->textureCubeTextureVar = ShaderGetResourceSlot(shader, "TexturesCube"); this->texture3DTextureVar = ShaderGetResourceSlot(shader, "Textures3D"); this->tableLayout = ShaderGetResourcePipeline(shader); this->ticksCbo = CoreGraphics::GetGraphicsConstantBuffer(MainThreadConstantBuffer); this->cboSlot = ShaderGetResourceSlot(shader, "PerTickParams"); this->resourceTables.Resize(CoreGraphics::GetNumBufferedFrames()); IndexT i; for (i = 0; i < this->resourceTables.Size(); i++) { this->resourceTables[i] = ShaderCreateResourceTable(shader, NEBULA_TICK_GROUP); // fill up all slots with placeholders IndexT j; for (j = 0; j < MAX_2D_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], {CoreGraphics::White2D, this->texture2DTextureVar, j, CoreGraphics::SamplerId::Invalid(), false}); for (j = 0; j < MAX_2D_MS_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::White2D, this->texture2DMSTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); for (j = 0; j < MAX_3D_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::White3D, this->texture3DTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); for (j = 0; j < MAX_CUBE_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::WhiteCube, this->textureCubeTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); for (j = 0; j < MAX_2D_ARRAY_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::White2DArray, this->texture2DArrayTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); ResourceTableCommitChanges(this->resourceTables[i]); } this->normalBufferTextureVar = ShaderGetConstantBinding(shader, "NormalBuffer"); this->depthBufferTextureVar = ShaderGetConstantBinding(shader, "DepthBuffer"); this->specularBufferTextureVar = ShaderGetConstantBinding(shader, "SpecularBuffer"); this->albedoBufferTextureVar = ShaderGetConstantBinding(shader, "AlbedoBuffer"); this->emissiveBufferTextureVar = ShaderGetConstantBinding(shader, "EmissiveBuffer"); this->lightBufferTextureVar = ShaderGetConstantBinding(shader, "LightBuffer"); this->environmentMapVar = ShaderGetConstantBinding(shader, "EnvironmentMap"); this->irradianceMapVar = ShaderGetConstantBinding(shader, "IrradianceMap"); this->numEnvMipsVar = ShaderGetConstantBinding(shader, "NumEnvMips"); return true; } //------------------------------------------------------------------------------ /** */ void VkShaderServer::Close() { n_assert(this->IsOpen()); n_delete(this->factory); IndexT i; for (i = 0; i < this->resourceTables.Size(); i++) { DestroyResourceTable(this->resourceTables[i]); } ShaderServerBase::Close(); } //------------------------------------------------------------------------------ /** */ uint32_t VkShaderServer::RegisterTexture(const CoreGraphics::TextureId& tex, bool depth, CoreGraphics::TextureType type) { uint32_t idx; IndexT var; switch (type) { case Texture2D: n_assert(!this->texture2DPool.IsFull()); idx = this->texture2DPool.Alloc(); var = this->texture2DTextureVar; break; case Texture2DArray: n_assert(!this->texture2DArrayPool.IsFull()); idx = this->texture2DArrayPool.Alloc(); var = this->texture2DArrayTextureVar; break; case Texture3D: n_assert(!this->texture3DPool.IsFull()); idx = this->texture3DPool.Alloc(); var = this->texture3DTextureVar; break; case TextureCube: n_assert(!this->textureCubePool.IsFull()); idx = this->textureCubePool.Alloc(); var = this->textureCubeTextureVar; break; } ResourceTableTexture info; info.tex = tex; info.index = idx; info.sampler = SamplerId::Invalid(); info.isDepth = false; info.slot = var; // update textures for all tables IndexT i; for (i = 0; i < this->resourceTables.Size(); i++) { ResourceTableSetTexture(this->resourceTables[i], info); } return idx; } //------------------------------------------------------------------------------ /** */ void VkShaderServer::UnregisterTexture(const uint32_t id, const CoreGraphics::TextureType type) { switch (type) { case Texture2D: this->texture2DPool.Free(id); break; case Texture2DArray: this->texture2DArrayPool.Free(id); break; case Texture3D: this->texture3DPool.Free(id); break; case TextureCube: this->textureCubePool.Free(id); break; } } //------------------------------------------------------------------------------ /** */ void VkShaderServer::SetGlobalEnvironmentTextures(const CoreGraphics::TextureId& env, const CoreGraphics::TextureId& irr, const SizeT numMips) { this->tickParams.EnvironmentMap = CoreGraphics::TextureGetBindlessHandle(env); this->tickParams.IrradianceMap = CoreGraphics::TextureGetBindlessHandle(irr); this->tickParams.NumEnvMips = numMips; } //------------------------------------------------------------------------------ /** */ void VkShaderServer::SetupGBufferConstants() { this->tickParams.NormalBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("NormalBuffer")); this->tickParams.DepthBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("ZBuffer")); this->tickParams.SpecularBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("SpecularBuffer")); this->tickParams.AlbedoBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("AlbedoBuffer")); this->tickParams.EmissiveBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("EmissiveBuffer")); this->tickParams.LightBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("LightBuffer")); } //------------------------------------------------------------------------------ /** */ void VkShaderServer::BeforeView() { // just allocate the memory this->cboOffset = CoreGraphics::AllocateGraphicsConstantBufferMemory(MainThreadConstantBuffer, sizeof(Shared::PerTickParams)); IndexT bufferedFrameIndex = GetBufferedFrameIndex(); // update resource table ResourceTableSetConstantBuffer(this->resourceTables[bufferedFrameIndex], { this->ticksCbo, this->cboSlot, 0, false, false, sizeof(Shared::PerTickParams), (SizeT)this->cboOffset }); ResourceTableCommitChanges(this->resourceTables[bufferedFrameIndex]); } //------------------------------------------------------------------------------ /** */ void VkShaderServer::AfterView() { // update the constant buffer with the data accumulated in this frame CoreGraphics::SetGraphicsConstants(MainThreadConstantBuffer, this->cboOffset, this->tickParams); } } // namespace Vulkan
33.787402
181
0.677231
Nechrito
cf1c6c7306e07fb8241178d2c27e97f9aa7d7ffe
285
hpp
C++
examples/wifi/GUI/aboutwindow.hpp
balsini/metasim
e20a2313b18bb943d766dc1ecf3c61cf28d956f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
examples/wifi/GUI/aboutwindow.hpp
balsini/metasim
e20a2313b18bb943d766dc1ecf3c61cf28d956f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
examples/wifi/GUI/aboutwindow.hpp
balsini/metasim
e20a2313b18bb943d766dc1ecf3c61cf28d956f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#ifndef ABOUTWINDOW_H #define ABOUTWINDOW_H #include <QWidget> namespace Ui { class AboutWindow; } class AboutWindow : public QWidget { Q_OBJECT public: explicit AboutWindow(QWidget *parent = 0); ~AboutWindow(); private: Ui::AboutWindow *ui; }; #endif // ABOUTWINDOW_H
12.391304
44
0.722807
balsini
cf1cd214b161e28649c4865764e7856ce5965c86
2,468
cpp
C++
share/crts/plugins/Filters/fileOut.cpp
xywzwd/VT-Wireless
ec42e742e2be26310df4b25cef9cea873896890b
[ "MIT" ]
6
2019-01-05T08:30:32.000Z
2022-03-10T08:19:57.000Z
share/crts/plugins/Filters/fileOut.cpp
xywzwd/VT-Wireless
ec42e742e2be26310df4b25cef9cea873896890b
[ "MIT" ]
4
2019-10-18T14:31:04.000Z
2020-10-16T16:52:30.000Z
share/crts/plugins/Filters/fileOut.cpp
xywzwd/VT-Wireless
ec42e742e2be26310df4b25cef9cea873896890b
[ "MIT" ]
5
2017-05-12T21:24:18.000Z
2022-03-10T08:20:02.000Z
#include <stdio.h> #include <string.h> #include <string> #include "crts/debug.h" #include "crts/Filter.hpp" #include "crts/crts.hpp" // for: FILE *crtsOut class FileOut : public CRTSFilter { public: FileOut(int argc, const char **argv); ~FileOut(void); ssize_t write(void *buffer, size_t bufferLen, uint32_t channelNum); private: FILE *file; }; // This is called if the user ran something like: // // crts_radio -f file [ --help ] // // static void usage(void) { char name[64]; fprintf(crtsOut, "Usage: %s [ OUT_FILENAME ]\n" "\n" " The option OUT_FILENAME is optional. The default\n" " output file is something like stdout.\n" "\n" "\n" , CRTS_BASENAME(name, 64)); throw ""; // This is how return an error from a C++ constructor // the module loader with catch this throw. } FileOut::FileOut(int argc, const char **argv): file(0) { const char *filename = 0; DSPEW(); if(argc > 1 || (argc == 1 && argv[0][0] == '-')) usage(); else if(argc == 1) filename = argv[0]; if(filename) { file = fopen(filename, "a"); if(!file) { std::string str("fopen(\""); str += filename; str += "\", \"a\") failed"; // This is how return an error from a C++ constructor // the module loader with catch this throw. throw str; } INFO("opened file: %s", filename); } else file = crtsOut; // like stdout but not polluted by libuhd DSPEW(); } FileOut::~FileOut(void) { if(file && file != crtsOut) fclose(file); file = 0; DSPEW(); } ssize_t FileOut::write(void *buffer, size_t len, uint32_t channelNum) { DASSERT(buffer, ""); DASSERT(len, ""); // This filter is a sink, the end of the line, so we do not call // writePush(). We write no matter what channel it is. errno = 0; size_t ret = fwrite(buffer, 1, len, file); if(ret != len && errno == EINTR) { // One more try, because we where interrupted errno = 0; ret += fwrite(buffer, 1, len - ret, file); } if(ret != len) NOTICE("fwrite(,1,%zu,) only wrote %zu bytes", len, ret); fflush(file); return ret; } // Define the module loader stuff to make one of these class objects. CRTSFILTER_MAKE_MODULE(FileOut)
21.275862
75
0.552269
xywzwd
cf2141384bbe6594f49112aa14701485cb584e07
490
cpp
C++
44_StackInheritance/src/Stack.cpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
44_StackInheritance/src/Stack.cpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
44_StackInheritance/src/Stack.cpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
#include "Stack.h" #include <iostream> Stack::Stack() : sp(256) { } Stack::~Stack() { } void Stack::push(int i) { if (full()) { std::cout << "Element '" << i << "' could not be pushed. Stack full!" << std::endl; return; } s[--sp] = i; } int Stack::pop() { if (empty()) { std::cout << "Stack Empty! Following pops are not from stack!" << std::endl; } return s[sp++]; } bool Stack::empty() { return sp == 256; } bool Stack::full() { return sp == 0; }
16.333333
86
0.528571
jonixis
cf295c30acc4633c02fafae8a08e9d396738b3dc
2,129
cpp
C++
FireWok/main.cpp
davidkron/AECE
83b0f288b84b16755df2e5a0d5d401f0e9a7dceb
[ "MIT" ]
null
null
null
FireWok/main.cpp
davidkron/AECE
83b0f288b84b16755df2e5a0d5d401f0e9a7dceb
[ "MIT" ]
null
null
null
FireWok/main.cpp
davidkron/AECE
83b0f288b84b16755df2e5a0d5d401f0e9a7dceb
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <iostream> #include <Engine.hpp> using namespace sf; class AECEWrapper { std::map<std::string, std::unique_ptr<sf::Music>> _songs; std::unique_ptr<AECE::Engine> _engine; public: AECEWrapper() { std::unique_ptr<sf::Music> music = std::make_unique<sf::Music>(); music->openFromFile("Songs/Alan_Walker_Fade.ogg"); auto song = AECE::SongWithAef("Songs/Alan_Walker_Fade.ogg", "Songs/Alan_Walker_Fade.aef", "Fade", music->getDuration().asMicroseconds()); std::vector<AECE::SongWithAef> songsWithAef; songsWithAef.push_back(song); _songs["Fade"] = std::move(music); _engine = std::make_unique<AECE::Engine>(songsWithAef, [=](std::string song) { _songs[song]->play(); }, [=](std::string song) { return _songs[song]->getPlayingOffset().asMicroseconds(); } ); } void Play(std::string song) { _engine->StartPlaying(song); } std::vector<AECE::AudioEvent> QueryEvents() { return _engine->QueryEvents(); } }; int main() { RenderWindow window(VideoMode(200, 200), "SFML works!"); CircleShape shape(100.f); shape.setFillColor(Color::Green); AECEWrapper engine; engine.Play("Fade"); window.setFramerateLimit(30); while (window.isOpen()) { Event event; if (shape.getFillColor() == Color::Red) shape.setFillColor(Color::Green); while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if (event.type == sf::Event::EventType::KeyPressed){ if (event.key.code == sf::Keyboard::Key::Up) shape.setFillColor(Color::Red); } } for (auto &event : engine.QueryEvents()) { shape.setFillColor(Color::Red); } window.clear(); window.draw(shape); window.display(); } return 0; }
28.386667
132
0.554251
davidkron
cf3595135ad0cb907b7de4544f4d0ae1780bd08f
5,298
cpp
C++
libcornet/poller.cpp
pioneer19/libcornet
9eb91629d8f9a6793b28af10a3535bfba0cc24ca
[ "Apache-2.0" ]
1
2020-07-25T06:39:24.000Z
2020-07-25T06:39:24.000Z
libcornet/poller.cpp
pioneer19/libcornet
9eb91629d8f9a6793b28af10a3535bfba0cc24ca
[ "Apache-2.0" ]
1
2020-07-25T05:32:10.000Z
2020-07-25T05:32:10.000Z
libcornet/poller.cpp
pioneer19/libcornet
9eb91629d8f9a6793b28af10a3535bfba0cc24ca
[ "Apache-2.0" ]
1
2020-07-25T05:28:54.000Z
2020-07-25T05:28:54.000Z
/* * Copyright 2020 Alex Syrnikov <pioneer19@post.cz> * SPDX-License-Identifier: Apache-2.0 * * This file is part of libcornet (https://github.com/pioneer19/libcornet). */ #include <libcornet/poller.hpp> #include <unistd.h> #include <cstdio> #include <string> #include <array> #include <algorithm> #include <system_error> #include <libcornet/tcp_socket.hpp> #include <libcornet/async_file.hpp> #include <libcornet/net_uring.hpp> namespace pioneer19::cornet { Poller::Poller() { m_poller_fd = epoll_create1( EPOLL_CLOEXEC ); if( m_poller_fd == -1 ) { throw std::system_error(errno, std::system_category() , "failed epoll_create1() in Poller constructor" ); } } Poller::Poller( Poller&& other ) noexcept { m_poller_fd = other.m_poller_fd; other.m_poller_fd = -1; } Poller& Poller::operator=( Poller&& other ) noexcept { if( this != &other ) { close(); std::swap( m_poller_fd, other.m_poller_fd ); } return *this; } void Poller::close() { if( m_poller_fd != -1 ) ::close( m_poller_fd ); m_poller_fd = -1; } void Poller::run() { int timeout_ms = -1; // -1 is infinite timeout for epoll_wait while( true) { constexpr uint32_t EVENT_BATCH_SIZE = 16; epoll_event events[ EVENT_BATCH_SIZE ]; if( m_stop ) break; int res = epoll_wait( m_poller_fd, events, EVENT_BATCH_SIZE, timeout_ms ); timeout_ms = -1; if( m_stop ) break; if( res == -1 ) { if( errno == EINTR ) continue; throw std::system_error(errno, std::system_category() , std::string( "failed epoll_wait on epoll socket " ) + std::to_string( m_poller_fd )); } for( uint32_t i = 0; i < static_cast<uint32_t>(res); ++i ) { auto& curr_event = events[i]; auto* poller_cb = reinterpret_cast<PollerCb*>(curr_event.data.ptr); // printf( "epoll_wait for poller_cb %p got events %s\n" // , (void*)poller_cb, events_string( curr_event.events ).c_str() ); poller_cb->add_reference(); poller_cb->events_mask = curr_event.events; } /* * current_event.data.ptr - pointer to poller_cb. * to eliminate removing poller_cb with socket delete until poller not * finished it's processing, poller holds reference to poller_cb * (in this case poller_cb will be cleared, but not removed) */ for( uint32_t i = 0; i < static_cast<uint32_t>(res); ++i ) { auto& curr_event = events[i]; if( curr_event.data.ptr == nullptr ) continue; auto poller_cb = reinterpret_cast<PollerCb*>( curr_event.data.ptr ); poller_cb->process_event(); PollerCb::rm_reference( poller_cb ); } #if USE_IO_URING uint32_t queue_size = NetUring::instance().process_requests(); if( queue_size != 0 ) timeout_ms = 0; #endif } } int Poller::add_fd( int fd, PollerCb* poller_cb, uint32_t mask ) { epoll_event event = {}; event.events = mask; event.data.ptr = poller_cb; return epoll_ctl( m_poller_fd, EPOLL_CTL_ADD, fd, &event); } void Poller::add_socket( const TcpSocket& socket, PollerCb* poller_cb, uint32_t mask ) { if( add_fd( socket.fd(), poller_cb, mask ) == -1 ) { throw std::system_error(errno, std::system_category() , std::string( "failed epoll_ctl add socket " ) + std::to_string(socket.fd()) ); } } void Poller::add_file( const AsyncFile& async_file, PollerCb* poller_cb, uint32_t mask ) { if( add_fd( async_file.fd(), poller_cb, mask ) == -1 ) { throw std::system_error(errno, std::system_category() , std::string( "failed epoll_ctl add async file " ) + std::to_string(async_file.fd()) ); } } std::string Poller::events_string( uint32_t events_mask ) { constexpr std::array<uint32_t,10> event_types = {EPOLLIN, EPOLLOUT, EPOLLRDHUP, EPOLLPRI, EPOLLERR, EPOLLHUP, EPOLLET ,EPOLLONESHOT, EPOLLWAKEUP, EPOLLEXCLUSIVE }; constexpr std::array<const char*,10> event_print_types = { "IN", "OUT", "RDHUP", "PRI", "ERR", "HUP", "ET" ,"ONESHOT", "WAKEUP", "EXCLUSIVE" }; static_assert( event_types.size() == event_print_types.size() , "event_types.size != event_print_types.size" ); bool first = true; std::string events_string; for( uint32_t i = 0; i < event_types.size(); ++i ) { if( events_mask & event_types[i] ) { if( !first ) events_string += ", "; events_string += event_print_types[i]; first = false; } } return events_string; } void Poller::run_on_signal( int signum, std::function<void()> func ) { if( !m_signal_processor ) m_signal_processor = std::make_unique<SignalProcessor>( *this ); m_signal_processor->add_signal_handler( signum, std::move(func) ); } }
29.764045
89
0.579464
pioneer19
cf4020ea3144e9c12d48e9a6a38ccb966d4b29b4
1,187
cpp
C++
OpenCLFilterPipeline/Camera.cpp
SebGrenier/OpenCLFilterPipeline
dbdf08142f211cc4ba6d08fbf07c22ecd6bb872b
[ "MIT" ]
null
null
null
OpenCLFilterPipeline/Camera.cpp
SebGrenier/OpenCLFilterPipeline
dbdf08142f211cc4ba6d08fbf07c22ecd6bb872b
[ "MIT" ]
null
null
null
OpenCLFilterPipeline/Camera.cpp
SebGrenier/OpenCLFilterPipeline
dbdf08142f211cc4ba6d08fbf07c22ecd6bb872b
[ "MIT" ]
null
null
null
#include "Camera.h" Camera::Camera() : _center_x(0) , _center_y(0) , _width(1) , _height(1) , _zoom_level(1) { } Camera::~Camera() { } void Camera::Translate(double x, double y) { _center_x += x; _center_y += y; } void Camera::Zoom(const double factor) { _width = _width * factor; _height = _height * factor; _zoom_level *= factor; } void Camera::Set(double center_x, double center_y, double width, double height, double zoom_level) { _center_x = center_x; _center_y = center_y; _width = width; _height = height; _zoom_level = zoom_level; } double Camera::Left() const { return _center_x - _width / 2.0; } double Camera::Right() const { return _center_x + _width / 2.0; } double Camera::Top() const { return _center_y + _height / 2.0; } double Camera::Bottom() const { return _center_y - _height / 2.0; } void Camera::Fit(const double width, const double height, double center_x, double center_y) { _center_x = center_x; _center_y = center_y; _zoom_level = 1.0; double aspect_ratio = _width / _height; if (height > width) { _height = height; _width = _height * aspect_ratio; } else { _width = width; _height = _width / aspect_ratio; } }
15.826667
98
0.679023
SebGrenier
cf41fb617b797f032de6c6762a62b0931599fef8
513
hpp
C++
bsengine/src/bstorm/math_util.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/math_util.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/math_util.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> namespace bstorm { template <typename T> T constrain(const T& v, const T& min, const T& max) { return std::min(std::max<T>(v, min), max); } inline int NextPow2(int x) { if (x < 0) return 0; --x; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; } template <class T> void hash_combine(std::size_t& seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } }
16.548387
63
0.528265
At-sushi
cf4a71baaf7976e390f64e029a2d37d997c783ea
1,240
cpp
C++
src/dx12/render/details/CommandQueue.cpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
src/dx12/render/details/CommandQueue.cpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
src/dx12/render/details/CommandQueue.cpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
#include "CommandQueue.hpp" #include "Exceptions.hpp" #include "../Context.hpp" using namespace winapi; namespace render { CommandQueue::CommandQueue(D3D12_COMMAND_LIST_TYPE type) { D3D12_COMMAND_QUEUE_DESC desc = { .Type = type, .Flags = D3D12_COMMAND_QUEUE_FLAG_NONE, .NodeMask = 1, }; ThrowIfFailed(g_context->device->CreateCommandQueue(&desc, IID_PPV_ARGS(&command_queue))); ThrowIfFailed(g_context->device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); } void CommandQueue::Execute(winapi::ComPtr<ID3D12GraphicsCommandList>& command_list) { command_queue->ExecuteCommandLists(1, (ID3D12CommandList* const *)&command_list); } void CommandQueue::ExecuteSync(winapi::ComPtr<ID3D12GraphicsCommandList>& command_list) { Execute(command_list); Signal(); WaitIdle(); } void CommandQueue::WaitForFenceValue(uint64_t fence_value) { if (fence_value == 0) { return; } if (fence->GetCompletedValue() >= fence_value) { return; } fence->SetEventOnCompletion(fence_value, fence_event.handle); fence_event.Wait(INFINITE); } void CommandQueue::WaitIdle() { WaitForFenceValue(fence_counter); } uint64_t CommandQueue::Signal() { command_queue->Signal(fence, ++fence_counter); return fence_counter; } }
24.8
95
0.766129
log0div0
cf4b260e9a191301a714383ab17f9a1ca0499c56
12,355
hpp
C++
tests/python_to_cpp/python_to_11l/tokenizer.hpp
11l-lang/_11l_to_cpp
60306c270d51f2876bff868d7f897ff4c395d39f
[ "MIT" ]
9
2019-11-03T23:38:55.000Z
2022-01-08T07:49:26.000Z
tests/python_to_cpp/python_to_11l/tokenizer.hpp
11l-lang/_11l_to_cpp
60306c270d51f2876bff868d7f897ff4c395d39f
[ "MIT" ]
null
null
null
tests/python_to_cpp/python_to_11l/tokenizer.hpp
11l-lang/_11l_to_cpp
60306c270d51f2876bff868d7f897ff4c395d39f
[ "MIT" ]
2
2019-11-16T14:16:01.000Z
2020-11-16T14:34:48.000Z
auto keywords = create_array({u"False"_S, u"await"_S, u"else"_S, u"import"_S, u"pass"_S, u"None"_S, u"break"_S, u"except"_S, u"in"_S, u"raise"_S, u"True"_S, u"class"_S, u"finally"_S, u"is"_S, u"return"_S, u"and"_S, u"continue"_S, u"for"_S, u"lambda"_S, u"try"_S, u"as"_S, u"def"_S, u"from"_S, u"nonlocal"_S, u"while"_S, u"assert"_S, u"del"_S, u"global"_S, u"not"_S, u"with"_S, u"async"_S, u"elif"_S, u"if"_S, u"or"_S, u"yield"_S}); auto operators = create_array({u"+"_S, u"-"_S, u"*"_S, u"**"_S, u"/"_S, u"//"_S, u"%"_S, u"@"_S, u"<<"_S, u">>"_S, u"&"_S, u"|"_S, u"^"_S, u"~"_S, u"<"_S, u">"_S, u"<="_S, u">="_S, u"=="_S, u"!="_S}); auto delimiters = create_array({u"("_S, u")"_S, u"["_S, u"]"_S, u"{"_S, u"}"_S, u","_S, u":"_S, u"."_S, u";"_S, u"@"_S, u"="_S, u"->"_S, u"+="_S, u"-="_S, u"*="_S, u"/="_S, u"//="_S, u"%="_S, u"@="_S, u"&="_S, u"|="_S, u"^="_S, u">>="_S, u"<<="_S, u"**="_S}); auto operators_and_delimiters = sorted(operators + delimiters, [](const auto &x){return x.len();}, true); class Error { public: String message; int pos; int end; template <typename T1, typename T2> Error(const T1 &message, const T2 &pos) : message(message), pos(pos), end(pos) { } }; class Token { public: enum class Category { NAME, KEYWORD, CONSTANT, OPERATOR_OR_DELIMITER, NUMERIC_LITERAL, STRING_LITERAL, INDENT, DEDENT, STATEMENT_SEPARATOR }; int start; int end; Category category; template <typename T1, typename T2, typename T3> Token(const T1 &start, const T2 &end, const T3 &category) : start(start), end(end), category(category) { } auto __repr__() { return String(start); } template <typename T1> auto value(const T1 &source) { return source[range_el(start, end)]; } template <typename T1> auto to_str(const T1 &source) { return u"Token("_S & String(category) & u", \""_S & (value(source)) & u"\")"_S; } }; template <typename T1> auto tokenize(const T1 &source, Array<int>* const newline_chars = nullptr, Array<ivec2>* const comments = nullptr) { Array<Token> tokens; Array<int> indentation_levels; Array<Tuple<Char, int>> nesting_elements; auto begin_of_line = true; auto expected_an_indented_block = false; auto i = 0; while (i < source.len()) { if (begin_of_line) { begin_of_line = false; auto linestart = i; auto indentation_level = 0; while (i < source.len()) { if (source[i] == u' ') indentation_level++; else if (source[i] == u'\t') indentation_level += 8; else break; i++; } if (i == source.len()) break; if (in(source[i], u"\r\n#"_S)) continue; auto prev_indentation_level = !indentation_levels.empty() ? indentation_levels.last() : 0; if (expected_an_indented_block) { if (!(indentation_level > prev_indentation_level)) throw Error(u"expected an indented block"_S, i); } if (indentation_level == prev_indentation_level) { if (!tokens.empty()) tokens.append(Token(linestart - 1, linestart, Token::Category::STATEMENT_SEPARATOR)); } else if (indentation_level > prev_indentation_level) { if (!expected_an_indented_block) throw Error(u"unexpected indent"_S, i); expected_an_indented_block = false; indentation_levels.append(indentation_level); tokens.append(Token(linestart, i, Token::Category::INDENT)); } else while (true) { indentation_levels.pop(); tokens.append(Token(i, i, Token::Category::DEDENT)); auto level = !indentation_levels.empty() ? indentation_levels.last() : 0; if (level == indentation_level) break; if (level < indentation_level) throw Error(u"unindent does not match any outer indentation level"_S, i); } } auto ch = source[i]; if (in(ch, u" \t"_S)) i++; else if (in(ch, u"\r\n"_S)) { if (newline_chars != nullptr) newline_chars->append(i); i++; if (ch == u'\r' && source[range_el(i, i + 1)] == u'\n') i++; if (nesting_elements.empty()) begin_of_line = true; } else if (ch == u'#') { auto comment_start = i; i++; while (i < source.len() && !in(source[i], u"\r\n"_S)) i++; if (comments != nullptr) comments->append(make_tuple(comment_start, i)); } else { expected_an_indented_block = ch == u':'; auto operator_or_delimiter = u""_S; for (auto &&op : tokenizer::operators_and_delimiters) if (source[range_el(i, i + op.len())] == op) { if (op == u'.' && source[range_el(i + 1, i + 2)].is_digit()) break; operator_or_delimiter = op; break; } auto lexem_start = i; i++; Token::Category category; if (operator_or_delimiter != u"") { i = lexem_start + operator_or_delimiter.len(); category = TYPE_RM_REF(category)::OPERATOR_OR_DELIMITER; if (in(ch, u"([{"_S)) nesting_elements.append(make_tuple(ch, lexem_start)); else if (in(ch, u")]}"_S)) { if (nesting_elements.empty() || _get<0>(nesting_elements.last()) != ([&](const auto &a){return a == u')' ? u'('_C : a == u']' ? u'['_C : a == u'}' ? u'{'_C : throw KeyError(a);}(ch))) throw Error(u"there is no corresponding opening parenthesis/bracket/brace for `"_S & ch & u"`"_S, lexem_start); nesting_elements.pop(); } else if (ch == u';') category = TYPE_RM_REF(category)::STATEMENT_SEPARATOR; } else if (in(ch, make_tuple(u"\""_S, u"'"_S)) || (in(ch, u"rRbB"_S) && in(source[range_el(i, i + 1)], make_tuple(u"\""_S, u"'"_S)))) { String ends; if (in(ch, u"rRbB"_S)) ends = in(source[range_el(i, i + 3)], make_tuple(u"\"\"\""_S, u"'''"_S)) ? source[range_el(i, i + 3)] : source[i]; else { i--; ends = in(source[range_el(i, i + 3)], make_tuple(u"\"\"\""_S, u"'''"_S)) ? source[range_el(i, i + 3)] : ch; } i += ends.len(); while (true) { if (i == source.len()) throw Error(u"unclosed string literal"_S, lexem_start); if (source[i] == u'\\') { i++; if (i == source.len()) continue; } else if (source[range_el(i, i + ends.len())] == ends) { i += ends.len(); break; } i++; } category = TYPE_RM_REF(category)::STRING_LITERAL; } else if (ch.is_alpha() || ch == u'_') { while (i < source.len()) { ch = source[i]; if (!(ch.is_alpha() || ch == u'_' || in(ch, range_ee(u'0'_C, u'9'_C)) || ch == u'?')) break; i++; } if (in(source[range_el(lexem_start, i)], tokenizer::keywords)) { if (in(source[range_el(lexem_start, i)], make_tuple(u"None"_S, u"False"_S, u"True"_S))) category = TYPE_RM_REF(category)::CONSTANT; else category = TYPE_RM_REF(category)::KEYWORD; } else category = TYPE_RM_REF(category)::NAME; } else if ((in(ch, u"-+"_S) && in(source[range_el(i, i + 1)], range_ee(u'0'_C, u'9'_C))) || in(ch, range_ee(u'0'_C, u'9'_C)) || (ch == u'.' && in(source[range_el(i, i + 1)], range_ee(u'0'_C, u'9'_C)))) { if (in(ch, u"-+"_S)) { assert(false); ch = source[i + 1]; } else i--; auto is_hex = ch == u'0' && in(source[range_el(i + 1, i + 2)], make_tuple(u"x"_S, u"X"_S)); auto is_oct = ch == u'0' && in(source[range_el(i + 1, i + 2)], make_tuple(u"o"_S, u"O"_S)); auto is_bin = ch == u'0' && in(source[range_el(i + 1, i + 2)], make_tuple(u"b"_S, u"B"_S)); if (is_hex || is_oct || is_bin) i += 2; auto start = i; i++; if (is_hex) while (i < source.len() && (in(source[i], range_ee(u'0'_C, u'9'_C)) || in(source[i], range_ee(u'a'_C, u'f'_C)) || in(source[i], range_ee(u'A'_C, u'F'_C)) || source[i] == u'_')) i++; else if (is_oct) while (i < source.len() && (in(source[i], range_ee(u'0'_C, u'7'_C)) || source[i] == u'_')) i++; else if (is_bin) while (i < source.len() && in(source[i], u"01_"_S)) i++; else { while (i < source.len() && (in(source[i], range_ee(u'0'_C, u'9'_C)) || in(source[i], u"_.eE"_S))) { if (in(source[i], u"eE"_S)) { if (in(source[range_el(i + 1, i + 2)], u"-+"_S)) i++; } i++; } if (in(source[range_el(i, i + 1)], make_tuple(u"j"_S, u"J"_S))) i++; if (in(u'_'_C, source[range_el(start, i)]) && !(in(u'.'_C, source[range_el(start, i)]))) { auto number = source[range_el(start, i)].replace(u"_"_S, u""_S); auto number_with_separators = u""_S; auto j = number.len(); while (j > 3) { number_with_separators = u"_"_S & number[range_el(j - 3, j)] & number_with_separators; j -= 3; } number_with_separators = number[range_el(0, j)] & number_with_separators; if (source[range_el(start, i)] != number_with_separators) throw Error(u"digit separator in this number is located in the wrong place (should be: "_S & number_with_separators & u")"_S, start); } } category = TYPE_RM_REF(category)::NUMERIC_LITERAL; } else if (ch == u'\\') { if (!in(source[i], u"\r\n"_S)) throw Error(u"only new line character allowed after backslash"_S, i); if (source[i] == u'\r') i++; if (source[i] == u'\n') i++; continue; } else throw Error(u"unexpected character "_S & ch, lexem_start); tokens.append(Token(lexem_start, i, category)); } } if (!nesting_elements.empty()) throw Error(u"there is no corresponding closing parenthesis/bracket/brace for `"_S & _get<0>(nesting_elements.last()) & u"`"_S, _get<1>(nesting_elements.last())); if (expected_an_indented_block) throw Error(u"expected an indented block"_S, i); while (!indentation_levels.empty()) { tokens.append(Token(i, i, Token::Category::DEDENT)); indentation_levels.pop(); } return tokens; }
41.459732
432
0.456091
11l-lang
cf4c74936fb769e9fc0476356a63f2f46774d048
18,687
hpp
C++
core/src/cogs/gui/scroll_pane.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
5
2019-02-08T15:59:14.000Z
2022-01-22T19:12:33.000Z
core/src/cogs/gui/scroll_pane.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
1
2019-12-03T03:11:34.000Z
2019-12-03T03:11:34.000Z
core/src/cogs/gui/scroll_pane.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
null
null
null
// // Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC // // Status: Good, MayNeedCleanup #ifndef COGS_HEADER_GUI_SCROLL_PANE #define COGS_HEADER_GUI_SCROLL_PANE #include "cogs/gui/pane.hpp" #include "cogs/gui/label.hpp" #include "cogs/gui/grid.hpp" #include "cogs/gui/scroll_bar.hpp" #include "cogs/gui/native_container_pane.hpp" #include "cogs/sync/transactable.hpp" namespace cogs { namespace gui { /// @ingroup GUI /// @brief A scrollable GUI outer pane, providing a view of an inner pane. /// Inner pane should have a minimum size, under which size the need for a scroll bar is incurred class scroll_pane : public pane, protected virtual pane_container { private: class scroll_bar_info { public: rcref<scroll_bar> m_scrollBar; rcref<override_bounds_frame> m_frame; volatile transactable<scroll_bar_state> m_state; volatile double m_position = 0; volatile boolean m_canAutoFade; delegated_dependency_property<double> m_positionProperty; delegated_dependency_property<bool, io::permission::write> m_canAutoFadeProperty; delegated_dependency_property<scroll_bar_state, io::permission::read> m_stateProperty; scroll_bar_info(scroll_pane& scrollPane, dimension d) : m_scrollBar(rcnew(scroll_bar)({ .scrollDimension = d })), m_frame(rcnew(override_bounds_frame)), m_positionProperty(scrollPane, [this]() { return atomic::load(m_position); }, [this, &scrollPane](double d) { double newPos = d; double oldPos = atomic::exchange(m_position, newPos); if (oldPos != newPos) { m_positionProperty.changed(); scrollPane.scrolled(); } m_positionProperty.set_complete(); }), m_canAutoFadeProperty(scrollPane, [this, &scrollPane](bool b) { boolean oldValue = m_canAutoFade.exchange(b); if (oldValue != b && scrollPane.m_shouldAutoFadeScrollBar) scrollPane.recompose(); m_canAutoFadeProperty.set_complete(); }), m_stateProperty(scrollPane, [this]() { return *(m_state.begin_read()); }) { m_scrollBar->prepend_frame(m_frame); scrollPane.pane::nest_last(m_scrollBar); m_stateProperty.bind_to(m_scrollBar->get_state_property()); m_positionProperty.bind(m_scrollBar->get_position_property(), true); m_canAutoFadeProperty.bind_from(m_scrollBar->get_can_auto_fade_property()); scrollPane.m_shouldAutoFadeScrollBarProperty.bind_to(m_scrollBar->get_should_auto_fade_property()); } }; bool m_hasScrollBar[2]; placement<scroll_bar_info> m_scrollBarInfo[2]; rcref<override_bounds_frame> m_contentFrame; rcref<override_bounds_frame> m_clippingFrame; rcref<override_bounds_frame> m_cornerFrame; rcref<container_pane> m_contentPane; rcref<native_container_pane> m_clippingPane; // using a native pane ensures clipping of platform dependent pane children (i.e. OS buttons, etc.) rcref<container_pane> m_cornerPane; range m_calculatedRange; std::optional<size> m_calculatedDefaultSize; bool m_hideInactiveScrollBar; volatile boolean m_shouldAutoFadeScrollBar; delegated_dependency_property<bool> m_shouldAutoFadeScrollBarProperty; bool has_scroll_bar(dimension d) const { return m_hasScrollBar[(int)d]; } scroll_bar_info& get_scroll_bar_info(dimension d) { COGS_ASSERT(has_scroll_bar(d)); return m_scrollBarInfo[(int)d].get(); } const scroll_bar_info& get_scroll_bar_info(dimension d) const { COGS_ASSERT(has_scroll_bar(d)); return m_scrollBarInfo[(int)d].get(); } void scrolled() { point oldOrigin = m_contentFrame->get_position(); point oldScrollPosition = -oldOrigin; double hScrollPosition = has_scroll_bar(dimension::horizontal) ? atomic::load(get_scroll_bar_info(dimension::horizontal).m_position) : 0.0; double vScrollPosition = has_scroll_bar(dimension::vertical) ? atomic::load(get_scroll_bar_info(dimension::vertical).m_position) : 0.0; point newScrollPosition(hScrollPosition, vScrollPosition); if (oldScrollPosition != newScrollPosition) { m_contentFrame->get_position() = -newScrollPosition; cell::reshape(*m_contentFrame, m_contentFrame->get_fixed_size(), oldOrigin); } } bool use_scroll_bar_auto_fade() const { if (!m_shouldAutoFadeScrollBar) return false; dimension d = dimension::vertical; if (!has_scroll_bar(d)) d = !d; return get_scroll_bar_info(d).m_canAutoFade; } public: enum dimensions { horizontal = 0x01, // 01 vertical = 0x02, // 10 both = 0x03 // 11 }; // The behavior of scroll_pane varies depending on the input device. // Mode A: For traditional mouse-based input, scroll bars are always shown (though can optionally be hidden when inactive). // Mode B: For touch screen, or if scrolling is otherwise provided by a device, scroll bars are displayed overlaying // the content only when scrolling occurs, then fade. Drag/flick scrolling is always enabled in Mode B. // On MacOS, there is a user setting to dynamically switch between these modes. struct options { dimensions scrollDimensions = dimensions::both; bool hideInactiveScrollBar = true; bool shouldScrollBarAutoFade = true; // If false, scroll bars are always displayed in mode B. bool dragAndFlickScrolling = true; // If true, enables drag and flick scrolling in mode A. It's always enabled in mode B. frame_list frames; pane_list children; }; scroll_pane() : scroll_pane(options()) { } explicit scroll_pane(options&& o) : pane({ .frames = std::move(o.frames) }), m_contentFrame(rcnew(override_bounds_frame)), m_clippingFrame(rcnew(override_bounds_frame)), m_cornerFrame(rcnew(override_bounds_frame)), m_contentPane(rcnew(container_pane)({ .frames = {rcnew(unconstrained_frame)(alignment(0, 0)), m_contentFrame}, .children = {std::move(o.children)} })), m_clippingPane(rcnew(native_container_pane)({ .frames{m_clippingFrame}, .children{m_contentPane} })), m_cornerPane(rcnew(container_pane)({ .frames{m_cornerFrame} })), m_hideInactiveScrollBar(o.hideInactiveScrollBar), m_shouldAutoFadeScrollBar(o.shouldScrollBarAutoFade), m_shouldAutoFadeScrollBarProperty(*this, [this]() { return m_shouldAutoFadeScrollBar; }, [this](bool b) { bool oldValue = m_shouldAutoFadeScrollBar.exchange(b); if (oldValue != b) m_shouldAutoFadeScrollBarProperty.changed(); m_shouldAutoFadeScrollBarProperty.set_complete(); }) { // TBD: dragAndFlickScrolling // TODO: May need to address what happens when a native control is offscreen when drawn, and backing buffer is unavailable //m_contentPane->set_compositing_behavior(compositing_behavior::buffer_self_and_children); pane::nest_last(m_clippingPane); pane::nest_last(m_cornerPane); m_hasScrollBar[(int)dimension::horizontal] = ((int)o.scrollDimensions & (int)dimensions::horizontal) != 0; if (m_hasScrollBar[(int)dimension::horizontal]) nested_rcnew(&get_scroll_bar_info(dimension::horizontal), *get_desc())(*this, dimension::horizontal); m_hasScrollBar[(int)dimension::vertical] = ((int)o.scrollDimensions & (int)dimensions::vertical) != 0; if (m_hasScrollBar[(int)dimension::vertical]) nested_rcnew(&get_scroll_bar_info(dimension::vertical), *get_desc())(*this, dimension::vertical); } ~scroll_pane() { if (m_hasScrollBar[(int)dimension::horizontal]) m_scrollBarInfo[(int)dimension::horizontal].destruct(); if (m_hasScrollBar[(int)dimension::vertical]) m_scrollBarInfo[(int)dimension::vertical].destruct(); } virtual range get_range() const { return m_calculatedRange; } virtual std::optional<size> get_default_size() const { return m_calculatedDefaultSize; } using pane_container::nest; virtual void nest_last(const rcref<pane>& child) { m_contentPane->nest_last(child); } virtual void nest_first(const rcref<pane>& child) { m_contentPane->nest_first(child); } virtual void nest_before(const rcref<pane>& beforeThis, const rcref<pane>& child) { m_contentPane->nest_before(beforeThis, child); } virtual void nest_after(const rcref<pane>& afterThis, const rcref<pane>& child) { m_contentPane->nest_after(afterThis, child); } // Nests a pane to be rendered at the intersection of 2 visible scroll bars. // If no corner pane is specified, the scroll_pane's background color is used. void nest_corner(const rcref<pane>&child) { nest_corner_last(child); } void nest_corner_last(const rcref<pane>& child) { m_cornerPane->nest_last(child); } void nest_corner_first(const rcref<pane>& child) { m_cornerPane->nest_first(child); } void nest_corner_before(const rcref<pane>& beforeThis, const rcref<pane>& child) { m_cornerPane->nest_before(beforeThis, child); } void nest_corner_after(const rcref<pane>& afterThis, const rcref<pane>& child) { m_cornerPane->nest_after(afterThis, child); } virtual void calculate_range() { pane::calculate_range(); // recalculate scroll bar widths, in case dimensions for the scrollbars were just recalculated as well for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) { auto& sbinfo = get_scroll_bar_info(d); COGS_ASSERT(sbinfo.m_scrollBar->get_frame_default_size().has_value()); sbinfo.m_frame->get_fixed_size(!d) = (*sbinfo.m_scrollBar->get_frame_default_size())[!d]; } } m_calculatedRange.set_min(0, 0); m_calculatedRange.clear_max(); // default to size of contents m_calculatedDefaultSize = m_contentPane->get_default_size(); bool autoFade = use_scroll_bar_auto_fade(); if (m_calculatedDefaultSize.has_value() && !m_hideInactiveScrollBar && !autoFade) { for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) (*m_calculatedDefaultSize)[!d] += get_scroll_bar_info(d).m_frame->get_fixed_size(!d); } } // Limit max size to max size of contents range contentRange = m_contentPane->get_range(); for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (contentRange.has_max(!d)) { m_calculatedRange.set_max(!d, contentRange.get_max(!d)); if (has_scroll_bar(!!d) && !autoFade) m_calculatedRange.get_max(!d) += (*get_scroll_bar_info(d).m_scrollBar->get_frame_default_size())[!d]; } if (!has_scroll_bar(!d)) { m_calculatedRange.set_min(!d, contentRange.get_min(!d)); if (!m_hideInactiveScrollBar && has_scroll_bar(!!d) && !autoFade) m_calculatedRange.get_min(!d) += (*get_scroll_bar_info(d).m_scrollBar->get_frame_default_size())[!d]; } } } virtual propose_size_result propose_size( const size& sz, const range& r = range::make_unbounded(), const std::optional<dimension>& resizeDimension = std::nullopt, sizing_mask = all_sizing_types) const { propose_size_result result; range r2 = get_range() & r; if (r2.is_empty()) result.set_empty(); else { size newSize = r2.limit(sz); range contentRange = m_contentFrame->get_range(); constexpr dimension d = dimension::horizontal; // If we are not hiding inactive scroll bars or are showing scroll bars over content (auto fade), use as is if (!use_scroll_bar_auto_fade() && m_hideInactiveScrollBar) { if (has_scroll_bar(d)) { if (contentRange.has_max(!d) && newSize[!d] > contentRange.get_max(!d) && newSize[d] >= contentRange.get_min(d)) newSize[!d] = contentRange.get_max(!d); } else { double min = contentRange.get_min(d); if (newSize[!d] < contentRange.get_min(!d)) min += get_scroll_bar_info(!d).m_frame->get_fixed_size(d); if (newSize[d] < min) newSize[d] = min; } if (has_scroll_bar(!d)) { if (contentRange.has_max(d) && newSize[d] > contentRange.get_max(d) && newSize[!d] >= contentRange.get_min(!d)) newSize[d] = contentRange.get_max(d); } else { double min = contentRange.get_min(!d); if (newSize[d] < contentRange.get_min(d)) min += get_scroll_bar_info(d).m_frame->get_fixed_size(!d); if (newSize[!d] < min) newSize[!d] = min; } } result.set(newSize); result.set_relative_to(sz, get_primary_flow_dimension(), resizeDimension); } return result; } virtual void reshape(const bounds& b, const point& oldOrigin = point(0, 0)) { range contentRange = m_contentFrame->get_range(); bounds visibleBounds = b; point contentOldOrigin = m_contentFrame->get_position(); std::optional<size> contentDefaultSizeOpt = m_contentFrame->get_default_size(); size contentDefaultSize = contentDefaultSizeOpt.has_value() ? *contentDefaultSizeOpt : size(0, 0); bounds contentBounds(contentOldOrigin, contentDefaultSize); // limit contentBounds to visibleBounds, but may still have greater min size contentBounds.get_size() = contentRange.limit(visibleBounds.get_size()); bool autoFade = use_scroll_bar_auto_fade(); auto reduce_content_bounds = [&](dimension d) { if (!autoFade) visibleBounds.get_size()[d] -= get_scroll_bar_info(!d).m_frame->get_fixed_size()[d]; if (visibleBounds.get_size()[d] < contentBounds.get_size()[d]) { contentBounds.get_size()[d] = visibleBounds.get_size()[d]; if (contentBounds.get_size()[d] < contentRange.get_min()[d]) contentBounds.get_size()[d] = contentRange.get_min()[d]; } }; bool showScrollBar[2]; if (!m_hideInactiveScrollBar) { // If not auto-hide, always include them. showScrollBar[(int)dimension::horizontal] = has_scroll_bar(dimension::horizontal); showScrollBar[(int)dimension::vertical] = has_scroll_bar(dimension::vertical); if (showScrollBar[(int)dimension::horizontal]) reduce_content_bounds(dimension::vertical); if (showScrollBar[(int)dimension::vertical]) reduce_content_bounds(dimension::horizontal); } else { showScrollBar[(int)dimension::horizontal] = false; showScrollBar[(int)dimension::vertical] = false; bool hasBothScrollBars = has_scroll_bar(dimension::horizontal) && has_scroll_bar(dimension::vertical); if (!hasBothScrollBars) { // If auto-hide and only 1 dimension... dimension d = has_scroll_bar(dimension::horizontal) ? (dimension)0 : (dimension)1; if (contentBounds.get_size()[d] > visibleBounds.get_size()[d]) { showScrollBar[(int)d] = true; reduce_content_bounds(!d); } } else { int neededPrevDimension = 0; // 1 = yes, -1 = new, 0 not checked yet dimension d = dimension::horizontal; // doesn't matter which dimension is used first, it's symetrical for (;;) { showScrollBar[(int)d] = (contentBounds.get_size()[d] > visibleBounds.get_size()[d]); if (contentBounds.get_size()[d] > visibleBounds.get_size()[d]) { showScrollBar[(int)d] = true; reduce_content_bounds(!d); if (neededPrevDimension == 1) break; neededPrevDimension = 1; } else if (neededPrevDimension != 0) break; else neededPrevDimension = -1; d = !d; //continue; } } } for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) { contentBounds.get_position()[d] += oldOrigin[d]; double pos = 0; if (showScrollBar[i]) { double thumbSize = visibleBounds.get_size()[d]; double max = contentBounds.get_size()[d]; pos = -(contentBounds.get_position()[d]); double maxPos = max; maxPos -= thumbSize; if (pos > maxPos) { pos = maxPos; contentBounds.get_position()[d] = -pos; } else if (pos < 0) { pos = 0; contentBounds.get_position()[d] = 0; } get_scroll_bar_info(d).m_frame->get_position()[!d] = b.get_size()[!d]; get_scroll_bar_info(d).m_frame->get_position()[!d] -= get_scroll_bar_info(d).m_frame->get_fixed_size()[!d]; get_scroll_bar_info(d).m_state.set(scroll_bar_state(max, thumbSize)); } else { contentBounds.get_position()[d] = 0; get_scroll_bar_info(d).m_state.set(scroll_bar_state(0, 0)); } atomic::store(get_scroll_bar_info(d).m_position, pos); get_scroll_bar_info(d).m_frame->get_fixed_size()[d] = b.get_size()[d]; get_scroll_bar_info(d).m_stateProperty.changed(); get_scroll_bar_info(d).m_positionProperty.changed(); } } bool showBothScrollBars = showScrollBar[(int)dimension::horizontal] && showScrollBar[(int)dimension::vertical]; if (showBothScrollBars) { double vScrollBarWidth = get_scroll_bar_info(dimension::vertical).m_frame->get_fixed_width(); double hScrollBarHeight = get_scroll_bar_info(dimension::horizontal).m_frame->get_fixed_height(); get_scroll_bar_info(dimension::horizontal).m_frame->get_fixed_width() -= vScrollBarWidth; get_scroll_bar_info(dimension::vertical).m_frame->get_fixed_height() -= hScrollBarHeight; m_cornerFrame->get_bounds() = bounds( point( get_scroll_bar_info(dimension::vertical).m_frame->get_position().get_x(), get_scroll_bar_info(dimension::horizontal).m_frame->get_position().get_y()), size( vScrollBarWidth, hScrollBarHeight)); } std::optional<size> opt = m_contentFrame->propose_size_best(contentBounds.get_size()); contentBounds.get_size() = opt.has_value() ? *opt : size(0, 0); m_contentFrame->get_bounds() = contentBounds; m_clippingFrame->get_bounds() = contentBounds & visibleBounds; // clip to smaller of content and visible bounds for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) { if (get_scroll_bar_info(d).m_scrollBar->is_hidden() == showScrollBar[i]) get_scroll_bar_info(d).m_scrollBar->show_or_hide(showScrollBar[i]); } } if (m_cornerPane->is_hidden() == showBothScrollBars) m_cornerPane->show_or_hide(showBothScrollBars); bool visible = (m_clippingFrame->get_bounds().get_width() != 0 && m_clippingFrame->get_bounds().get_height() != 0); if (m_clippingPane->is_hidden() == visible) m_clippingPane->show_or_hide(visible); pane::reshape(b, oldOrigin); } virtual bool wheel_moving(double distance, const point& pt, const ui::modifier_keys_state& modifiers) { // Give child pane first chance to intercept it if (!pane::wheel_moving(distance, pt, modifiers)) { dimension scrollDimension = dimension::horizontal; if (has_scroll_bar(dimension::vertical)) // If shift is held, scroll horizontally { if (!has_scroll_bar(dimension::horizontal) || !modifiers.get_key(ui::modifier_key::shift_key)) scrollDimension = dimension::vertical; } else if (!has_scroll_bar(dimension::horizontal)) return false; get_scroll_bar_info(scrollDimension).m_scrollBar->scroll(distance); } return true; } virtual rcref<dependency_property<bool> > get_should_auto_fade_scroll_bar_property() { return get_self_rcref(&m_shouldAutoFadeScrollBarProperty); } }; } } #endif
33.015901
148
0.716059
cogmine
cf4e821f115e3cfd6d94bfd773d302b790d4f29f
417
cpp
C++
C++/octalToDecimal.cpp
neontuts/code-snippets
cdc5d9e482a716015f3a43a4843d02521e1231f1
[ "MIT" ]
null
null
null
C++/octalToDecimal.cpp
neontuts/code-snippets
cdc5d9e482a716015f3a43a4843d02521e1231f1
[ "MIT" ]
null
null
null
C++/octalToDecimal.cpp
neontuts/code-snippets
cdc5d9e482a716015f3a43a4843d02521e1231f1
[ "MIT" ]
null
null
null
/* Write a program to convert octal to decimal. For Example : (100)₈ ---> (64)₁₀ */ #include <iostream> using namespace std; int octalToDecimal(int n) { int ans = 0; int x = 1; while (n > 0) { int y = n % 10; ans += x *y; x *= 8; n /= 10; } return ans; } int main() { int octal; cout<<"Enter the octal : "; cin>>octal; cout<<octalToDecimal(octal)<<endl; return 0; }
12.264706
46
0.541966
neontuts
cf531c57b1fa79a7d73b5badbf1fed15e2fd4904
486
cpp
C++
src/commandHistory.cpp
rainstormstudio/AsciiEditor
ea6a089cd1edf087cb086295ad6268af0ed37c65
[ "MIT" ]
1
2020-08-06T02:43:50.000Z
2020-08-06T02:43:50.000Z
src/commandHistory.cpp
rainstormstudio/AsciiEditor
ea6a089cd1edf087cb086295ad6268af0ed37c65
[ "MIT" ]
null
null
null
src/commandHistory.cpp
rainstormstudio/AsciiEditor
ea6a089cd1edf087cb086295ad6268af0ed37c65
[ "MIT" ]
null
null
null
#include "commandHistory.hpp" CommandHistory::CommandHistory() { commands = std::stack<std::shared_ptr<Command>>(); } void CommandHistory::push(std::shared_ptr<Command> command) { commands.emplace(command); } std::shared_ptr<Command> CommandHistory::pop() { if (commands.empty()) { return nullptr; } std::shared_ptr<Command> command = commands.top(); commands.pop(); return command; } int CommandHistory::size() const { return commands.size(); }
23.142857
61
0.679012
rainstormstudio